summaryrefslogtreecommitdiff
path: root/utils
diff options
context:
space:
mode:
authorNicolas Pennequin <nicolas.pennequin@free.fr>2008-07-11 16:51:25 +0000
committerNicolas Pennequin <nicolas.pennequin@free.fr>2008-07-11 16:51:25 +0000
commitca5bb76d2b8f65aa97e50b633f828c1deb241526 (patch)
tree453a1b2de3a0dc0d0b2f7080d10d033bf8fbcdf1 /utils
parent141774be48940d56e3ad4dbf451d245b61d4f8b2 (diff)
downloadrockbox-ca5bb76d2b8f65aa97e50b633f828c1deb241526.tar.gz
rockbox-ca5bb76d2b8f65aa97e50b633f828c1deb241526.zip
Delete the svn:executable property and set svn:eol-style to native for all those text files.
git-svn-id: svn://svn.rockbox.org/rockbox/trunk@18012 a1c6a512-1295-4272-9138-f99709370657
Diffstat (limited to 'utils')
-rw-r--r--[-rwxr-xr-x]utils/zenutils/CMakeLists.txt26
-rw-r--r--[-rwxr-xr-x]utils/zenutils/COPYING0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/CMakeLists.txt6
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/CMakeLists.txt28
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/AUTHORS0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BENCHMARKS0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BUGS0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/CONTRIBUTORS0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING.LIB0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/ChangeLog0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/INSTALL0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/NEWS0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.DLL0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.WIN320
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/api.h0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/beecrypt.h0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.c0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.h0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.c0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.h0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfishopt.h0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.c0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.h0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/gnu.h0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.c0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.h0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.c0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.h0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/memchunk.h0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.c0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.h0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpnumber.h0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpopt.h0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/rsa.h0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.c0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.h0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1opt.h0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/win.h0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/getpot-c++-1.1.17/getpot/GetPot0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/getpot-c++-1.1.17/getpot/LPGL.txt0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/getpot-c++-1.1.17/getpot/README0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/getpot-c++-1.1.17/getpot/getpot.hpp4870
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/CMakeLists.txt40
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.cpp1022
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.h174
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.cpp934
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.h240
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.cpp766
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.h168
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.cpp1384
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.h266
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.cpp358
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.h116
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/ImportDirectory.h2278
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/MzHeader.cpp1168
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/MzHeader.h296
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/PeFile.cpp338
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/PeFile.h902
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/PeHeader.cpp180
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/PeHeader.h5370
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/PeLib.h54
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/PeLibAux.cpp550
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/PeLibAux.h1768
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/PeLibInc.h64
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/RelocationsDirectory.cpp422
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/RelocationsDirectory.h140
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/ResourceDirectory.cpp2994
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/ResourceDirectory.h1470
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/TlsDirectory.h608
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/buffer/InputBuffer.cpp116
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/buffer/InputBuffer.h104
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/buffer/OutputBuffer.cpp82
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/buffer/OutputBuffer.h102
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/changelog.txt640
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/license.htm68
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/pelib-0.9/pelib/readme.txt86
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/CMakeLists.txt38
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/ChangeLog1710
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/FAQ678
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/INDEX102
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/Makefile308
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/Makefile.in308
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/README250
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/adler32.c298
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/algorithm.txt418
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/compress.c158
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/configure918
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/crc32.c846
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/crc32.h882
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/deflate.c3472
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/deflate.h662
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/example.c1130
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/gzio.c2052
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/infback.c1246
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/inffast.c636
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/inffast.h22
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/inffixed.h188
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/inflate.c2736
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/inflate.h230
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/inftrees.c658
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/inftrees.h110
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/make_vms.com922
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/minigzip.c644
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/trees.c2438
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/trees.h256
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/uncompr.c122
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/zconf.h664
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/zconf.in.h664
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/zlib.3318
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/zlib.h2714
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/zutil.c636
-rw-r--r--[-rwxr-xr-x]utils/zenutils/libraries/zlib123/zlib/zutil.h538
-rw-r--r--[-rwxr-xr-x]utils/zenutils/notes.txt154
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/CMakeLists.txt12
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/firmware_extract/CMakeLists.txt6
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/firmware_extract/main.cpp486
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/firmware_make/CMakeLists.txt6
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/firmware_make/main.cpp522
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/shared/CMakeLists.txt32
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/shared/cenc.cpp666
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/shared/cenc.h58
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/shared/crypt.cpp182
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/shared/crypt.h60
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/shared/file.cpp212
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/shared/file.h72
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/shared/firmware.cpp774
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/shared/firmware.h184
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/shared/pe.cpp256
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/shared/pe.h284
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/shared/shared.cpp0
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/shared/updater.cpp302
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/shared/updater.h64
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/shared/utils.cpp422
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/shared/utils.h136
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/update_extract/CMakeLists.txt6
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/update_extract/main.cpp558
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/update_patch/CMakeLists.txt6
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/update_patch/main.cpp818
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/zen_crypt/CMakeLists.txt8
-rw-r--r--[-rwxr-xr-x]utils/zenutils/source/zen_crypt/main.cpp1374
142 files changed, 33915 insertions, 33915 deletions
diff --git a/utils/zenutils/CMakeLists.txt b/utils/zenutils/CMakeLists.txt
index 32798747cd..0983d394a7 100755..100644
--- a/utils/zenutils/CMakeLists.txt
+++ b/utils/zenutils/CMakeLists.txt
@@ -1,13 +1,13 @@
1PROJECT(zenutils) 1PROJECT(zenutils)
2 2
3SET(EXECUTABLE_OUTPUT_PATH ${zenutils_SOURCE_DIR}/bin/${CMAKE_SYSTEM_NAME}) 3SET(EXECUTABLE_OUTPUT_PATH ${zenutils_SOURCE_DIR}/bin/${CMAKE_SYSTEM_NAME})
4 4
5SUBDIRS(source libraries) 5SUBDIRS(source libraries)
6 6
7INCLUDE_DIRECTORIES( 7INCLUDE_DIRECTORIES(
8 ${zenutils_SOURCE_DIR}/libraries/beecrypt-4.1.2 8 ${zenutils_SOURCE_DIR}/libraries/beecrypt-4.1.2
9 ${zenutils_SOURCE_DIR}/libraries/getpot-c++-1.1.17 9 ${zenutils_SOURCE_DIR}/libraries/getpot-c++-1.1.17
10 ${zenutils_SOURCE_DIR}/libraries/pelib-0.9 10 ${zenutils_SOURCE_DIR}/libraries/pelib-0.9
11 ${zenutils_SOURCE_DIR}/libraries/zlib123 11 ${zenutils_SOURCE_DIR}/libraries/zlib123
12 ${zenutils_SOURCE_DIR}/source/shared 12 ${zenutils_SOURCE_DIR}/source/shared
13) 13)
diff --git a/utils/zenutils/COPYING b/utils/zenutils/COPYING
index d511905c16..d511905c16 100755..100644
--- a/utils/zenutils/COPYING
+++ b/utils/zenutils/COPYING
diff --git a/utils/zenutils/libraries/CMakeLists.txt b/utils/zenutils/libraries/CMakeLists.txt
index 19297d7a2e..82f5824c81 100755..100644
--- a/utils/zenutils/libraries/CMakeLists.txt
+++ b/utils/zenutils/libraries/CMakeLists.txt
@@ -1,3 +1,3 @@
1ADD_SUBDIRECTORY(beecrypt-4.1.2) 1ADD_SUBDIRECTORY(beecrypt-4.1.2)
2ADD_SUBDIRECTORY(pelib-0.9) 2ADD_SUBDIRECTORY(pelib-0.9)
3ADD_SUBDIRECTORY(zlib123) 3ADD_SUBDIRECTORY(zlib123)
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/CMakeLists.txt b/utils/zenutils/libraries/beecrypt-4.1.2/CMakeLists.txt
index 83836af99d..7044ec090a 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/CMakeLists.txt
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/CMakeLists.txt
@@ -1,14 +1,14 @@
1PROJECT(beecrypt) 1PROJECT(beecrypt)
2 2
3# source files for beecrypt 3# source files for beecrypt
4SET(beecrypt_srcs 4SET(beecrypt_srcs
5 beecrypt/blockmode.c 5 beecrypt/blockmode.c
6 beecrypt/blowfish.c 6 beecrypt/blowfish.c
7 beecrypt/endianness.c 7 beecrypt/endianness.c
8 beecrypt/hmac.c 8 beecrypt/hmac.c
9 beecrypt/hmacsha1.c 9 beecrypt/hmacsha1.c
10 beecrypt/mp.c 10 beecrypt/mp.c
11 beecrypt/sha1.c 11 beecrypt/sha1.c
12) 12)
13 13
14ADD_LIBRARY(beecrypt ${beecrypt_srcs}) 14ADD_LIBRARY(beecrypt ${beecrypt_srcs})
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/AUTHORS b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/AUTHORS
index 878abf5a3f..878abf5a3f 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/AUTHORS
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/AUTHORS
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BENCHMARKS b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BENCHMARKS
index 7919f340db..7919f340db 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BENCHMARKS
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BENCHMARKS
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BUGS b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BUGS
index 577c5adac5..577c5adac5 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BUGS
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BUGS
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/CONTRIBUTORS b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/CONTRIBUTORS
index 7f61011475..7f61011475 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/CONTRIBUTORS
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/CONTRIBUTORS
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING
index a6d7d0188a..a6d7d0188a 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING.LIB b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING.LIB
index 223ede7de3..223ede7de3 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING.LIB
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING.LIB
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/ChangeLog b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/ChangeLog
index e69de29bb2..e69de29bb2 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/ChangeLog
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/ChangeLog
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/INSTALL b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/INSTALL
index bca44d042e..bca44d042e 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/INSTALL
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/INSTALL
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/NEWS b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/NEWS
index 6c6bbd0175..6c6bbd0175 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/NEWS
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/NEWS
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README
index d875372c39..d875372c39 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.DLL b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.DLL
index 2131f87ce2..2131f87ce2 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.DLL
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.DLL
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.WIN32 b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.WIN32
index 411116fea2..411116fea2 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.WIN32
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.WIN32
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/api.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/api.h
index f5ef7ff04a..f5ef7ff04a 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/api.h
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/api.h
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/beecrypt.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/beecrypt.h
index a4c8780d03..a4c8780d03 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/beecrypt.h
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/beecrypt.h
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.c
index cfccd43337..cfccd43337 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.c
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.c
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.h
index 4f21b81f65..4f21b81f65 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.h
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.h
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.c
index a8b801e6ec..a8b801e6ec 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.c
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.c
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.h
index 1d95ddb4f2..1d95ddb4f2 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.h
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.h
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfishopt.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfishopt.h
index f38db94b52..f38db94b52 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfishopt.h
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfishopt.h
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.c
index 8a0999b63e..8a0999b63e 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.c
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.c
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.h
index e136aa59f9..e136aa59f9 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.h
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.h
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/gnu.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/gnu.h
index 18386ef997..18386ef997 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/gnu.h
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/gnu.h
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.c
index c28770a05b..c28770a05b 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.c
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.c
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.h
index 709bb079f0..709bb079f0 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.h
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.h
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.c
index f201a45f0f..f201a45f0f 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.c
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.c
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.h
index 207f5df37f..207f5df37f 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.h
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.h
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/memchunk.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/memchunk.h
index 4778b7ca89..4778b7ca89 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/memchunk.h
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/memchunk.h
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.c
index 82d272c17a..82d272c17a 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.c
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.c
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.h
index 57a3e6c502..57a3e6c502 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.h
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.h
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpnumber.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpnumber.h
index f42e82a80f..f42e82a80f 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpnumber.h
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpnumber.h
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpopt.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpopt.h
index 7ba66bb5f9..7ba66bb5f9 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpopt.h
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpopt.h
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/rsa.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/rsa.h
index dbb0e45412..dbb0e45412 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/rsa.h
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/rsa.h
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.c
index fe7c2cd8b4..fe7c2cd8b4 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.c
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.c
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.h
index a35c917fdd..a35c917fdd 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.h
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.h
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1opt.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1opt.h
index 62ea87718f..62ea87718f 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1opt.h
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1opt.h
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/win.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/win.h
index d578085c29..d578085c29 100755..100644
--- a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/win.h
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/win.h
diff --git a/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/GetPot b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/GetPot
index 0663880990..0663880990 100755..100644
--- a/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/GetPot
+++ b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/GetPot
diff --git a/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/LPGL.txt b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/LPGL.txt
index b1e3f5a263..b1e3f5a263 100755..100644
--- a/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/LPGL.txt
+++ b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/LPGL.txt
diff --git a/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/README b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/README
index 3d55352a6b..3d55352a6b 100755..100644
--- a/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/README
+++ b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/README
diff --git a/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/getpot.hpp b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/getpot.hpp
index fe820c91a2..9986d17893 100755..100644
--- a/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/getpot.hpp
+++ b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/getpot.hpp
@@ -1,2435 +1,2435 @@
1// -*- c++ -*- 1// -*- c++ -*-
2// GetPot Version $$Version$$ $$Date$$ 2// GetPot Version $$Version$$ $$Date$$
3// 3//
4// WEBSITE: http://getpot.sourceforge.net 4// WEBSITE: http://getpot.sourceforge.net
5// 5//
6// NOTE: The LPGL License for this library is only valid in case that 6// NOTE: The LPGL License for this library is only valid in case that
7// it is not used for the production or development of applications 7// it is not used for the production or development of applications
8// dedicated to military industry. This is what the author calls 8// dedicated to military industry. This is what the author calls
9// the 'unofficial peace version of the LPGL'. 9// the 'unofficial peace version of the LPGL'.
10// 10//
11// This library is free software; you can redistribute it and/or modify 11// This library is free software; you can redistribute it and/or modify
12// it under the terms of the GNU Lesser General Public License as 12// it under the terms of the GNU Lesser General Public License as
13// published by the Free Software Foundation; either version 2.1 of the 13// published by the Free Software Foundation; either version 2.1 of the
14// License, or (at your option) any later version. 14// License, or (at your option) any later version.
15// 15//
16// This library is distributed in the hope that it will be useful, but 16// This library is distributed in the hope that it will be useful, but
17// WITHOUT ANY WARRANTY; without even the implied warranty of 17// WITHOUT ANY WARRANTY; without even the implied warranty of
18// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 18// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19// Lesser General Public License for more details. 19// Lesser General Public License for more details.
20// 20//
21// You should have received a copy of the GNU Lesser General Public 21// You should have received a copy of the GNU Lesser General Public
22// License along with this library; if not, write to the Free Software 22// License along with this library; if not, write to the Free Software
23// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 23// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
24// USA 24// USA
25// 25//
26// (C) 2001-2005 Frank R. Schaefer <fschaef@users.sf.net> 26// (C) 2001-2005 Frank R. Schaefer <fschaef@users.sf.net>
27//========================================================================== 27//==========================================================================
28 28
29#ifndef __include_guard_GETPOT_H__ 29#ifndef __include_guard_GETPOT_H__
30#define __include_guard_GETPOT_H__ 30#define __include_guard_GETPOT_H__
31 31
32#if defined(WIN32) || defined(SOLARIS_RAW) || (__GNUC__ == 2) || defined(__HP_aCC) 32#if defined(WIN32) || defined(SOLARIS_RAW) || (__GNUC__ == 2) || defined(__HP_aCC)
33#define strtok_r(a, b, c) strtok(a, b) 33#define strtok_r(a, b, c) strtok(a, b)
34#endif // WINDOWS or SOLARIS or gcc 2.* or HP aCC 34#endif // WINDOWS or SOLARIS or gcc 2.* or HP aCC
35 35
36extern "C" { 36extern "C" {
37// leave the 'extern C' to make it 100% sure to work - 37// leave the 'extern C' to make it 100% sure to work -
38// expecially with older distributions of header files. 38// expecially with older distributions of header files.
39#ifndef WIN32 39#ifndef WIN32
40// this is necessary (depending on OS) 40// this is necessary (depending on OS)
41#include <ctype.h> 41#include <ctype.h>
42#endif 42#endif
43#include <stdio.h> 43#include <stdio.h>
44#include <stdarg.h> 44#include <stdarg.h>
45#include <assert.h> 45#include <assert.h>
46} 46}
47#include <cmath> 47#include <cmath>
48#include <string> 48#include <string>
49#include <vector> 49#include <vector>
50#include <algorithm> 50#include <algorithm>
51 51
52#include <fstream> 52#include <fstream>
53#include <iostream> // not every compiler distribution includes <iostream> 53#include <iostream> // not every compiler distribution includes <iostream>
54// // with <fstream> 54// // with <fstream>
55 55
56typedef std::vector<std::string> STRING_VECTOR; 56typedef std::vector<std::string> STRING_VECTOR;
57 57
58#define victorate(TYPE, VARIABLE, ITERATOR) \ 58#define victorate(TYPE, VARIABLE, ITERATOR) \
59 std::vector<TYPE>::const_iterator ITERATOR = (VARIABLE).begin(); \ 59 std::vector<TYPE>::const_iterator ITERATOR = (VARIABLE).begin(); \
60 for(; (ITERATOR) != (VARIABLE).end(); (ITERATOR)++) 60 for(; (ITERATOR) != (VARIABLE).end(); (ITERATOR)++)
61 61
62 62
63class GetPot { 63class GetPot {
64 //-------- 64 //--------
65 inline void __basic_initialization(); 65 inline void __basic_initialization();
66public: 66public:
67 // (*) constructors, destructor, assignment operator ----------------------- 67 // (*) constructors, destructor, assignment operator -----------------------
68 inline GetPot(); 68 inline GetPot();
69 inline GetPot(const GetPot&); 69 inline GetPot(const GetPot&);
70 inline GetPot(const int argc_, char** argv_, 70 inline GetPot(const int argc_, char** argv_,
71 const char* FieldSeparator=0x0); 71 const char* FieldSeparator=0x0);
72 inline GetPot(const char* FileName, 72 inline GetPot(const char* FileName,
73 const char* CommentStart=0x0, const char* CommentEnd=0x0, 73 const char* CommentStart=0x0, const char* CommentEnd=0x0,
74 const char* FieldSeparator=0x0); 74 const char* FieldSeparator=0x0);
75 inline ~GetPot(); 75 inline ~GetPot();
76 inline GetPot& operator=(const GetPot&); 76 inline GetPot& operator=(const GetPot&);
77 77
78 78
79 // (*) absorbing contents of another GetPot object 79 // (*) absorbing contents of another GetPot object
80 inline void absorb(const GetPot& That); 80 inline void absorb(const GetPot& That);
81 // -- for ufo detection: recording requested arguments, options etc. 81 // -- for ufo detection: recording requested arguments, options etc.
82 inline void clear_requests(); 82 inline void clear_requests();
83 inline void disable_request_recording() { __request_recording_f = false; } 83 inline void disable_request_recording() { __request_recording_f = false; }
84 inline void enable_request_recording() { __request_recording_f = true; } 84 inline void enable_request_recording() { __request_recording_f = true; }
85 85
86 // (*) direct access to command line arguments ----------------------------- 86 // (*) direct access to command line arguments -----------------------------
87 inline const std::string operator[](unsigned Idx) const; 87 inline const std::string operator[](unsigned Idx) const;
88 inline int get(unsigned Idx, int Default) const; 88 inline int get(unsigned Idx, int Default) const;
89 inline double get(unsigned Idx, const double& Default) const; 89 inline double get(unsigned Idx, const double& Default) const;
90 inline const std::string get(unsigned Idx, const char* Default) const; 90 inline const std::string get(unsigned Idx, const char* Default) const;
91 inline unsigned size() const; 91 inline unsigned size() const;
92 92
93 // (*) flags --------------------------------------------------------------- 93 // (*) flags ---------------------------------------------------------------
94 inline bool options_contain(const char* FlagList) const; 94 inline bool options_contain(const char* FlagList) const;
95 inline bool argument_contains(unsigned Idx, const char* FlagList) const; 95 inline bool argument_contains(unsigned Idx, const char* FlagList) const;
96 96
97 // (*) variables ----------------------------------------------------------- 97 // (*) variables -----------------------------------------------------------
98 // -- scalar values 98 // -- scalar values
99 inline int operator()(const char* VarName, int Default) const; 99 inline int operator()(const char* VarName, int Default) const;
100 inline double operator()(const char* VarName, const double& Default) const; 100 inline double operator()(const char* VarName, const double& Default) const;
101 inline const std::string operator()(const char* VarName, const char* Default) const; 101 inline const std::string operator()(const char* VarName, const char* Default) const;
102 // -- vectors 102 // -- vectors
103 inline int operator()(const char* VarName, int Default, unsigned Idx) const; 103 inline int operator()(const char* VarName, int Default, unsigned Idx) const;
104 inline double operator()(const char* VarName, const double& Default, unsigned Idx) const; 104 inline double operator()(const char* VarName, const double& Default, unsigned Idx) const;
105 inline const std::string operator()(const char* VarName, const char* Default, unsigned Idx) const; 105 inline const std::string operator()(const char* VarName, const char* Default, unsigned Idx) const;
106 106
107 // -- setting variables 107 // -- setting variables
108 // i) from outside of GetPot (considering prefix etc.) 108 // i) from outside of GetPot (considering prefix etc.)
109 // ii) from inside, use '__set_variable()' below 109 // ii) from inside, use '__set_variable()' below
110 inline void set(const char* VarName, const char* Value, const bool Requested = true); 110 inline void set(const char* VarName, const char* Value, const bool Requested = true);
111 inline void set(const char* VarName, const double& Value, const bool Requested = true); 111 inline void set(const char* VarName, const double& Value, const bool Requested = true);
112 inline void set(const char* VarName, const int Value, const bool Requested = true); 112 inline void set(const char* VarName, const int Value, const bool Requested = true);
113 113
114 inline unsigned vector_variable_size(const char* VarName) const; 114 inline unsigned vector_variable_size(const char* VarName) const;
115 inline STRING_VECTOR get_variable_names() const; 115 inline STRING_VECTOR get_variable_names() const;
116 inline STRING_VECTOR get_section_names() const; 116 inline STRING_VECTOR get_section_names() const;
117 117
118 118
119 // (*) cursor oriented functions ------------------------------------------- 119 // (*) cursor oriented functions -------------------------------------------
120 inline void set_prefix(const char* Prefix) { prefix = std::string(Prefix); } 120 inline void set_prefix(const char* Prefix) { prefix = std::string(Prefix); }
121 inline bool search_failed() const { return search_failed_f; } 121 inline bool search_failed() const { return search_failed_f; }
122 122
123 // -- enable/disable search for an option in loop 123 // -- enable/disable search for an option in loop
124 inline void disable_loop() { search_loop_f = false; } 124 inline void disable_loop() { search_loop_f = false; }
125 inline void enable_loop() { search_loop_f = true; } 125 inline void enable_loop() { search_loop_f = true; }
126 126
127 // -- reset cursor to position '1' 127 // -- reset cursor to position '1'
128 inline void reset_cursor(); 128 inline void reset_cursor();
129 inline void init_multiple_occurrence(); 129 inline void init_multiple_occurrence();
130 130
131 // -- search for a certain option and set cursor to position 131 // -- search for a certain option and set cursor to position
132 inline bool search(const char* option); 132 inline bool search(const char* option);
133 inline bool search(unsigned No, const char* P, ...); 133 inline bool search(unsigned No, const char* P, ...);
134 // -- get argument at cursor++ 134 // -- get argument at cursor++
135 inline int next(int Default); 135 inline int next(int Default);
136 inline double next(const double& Default); 136 inline double next(const double& Default);
137 inline const std::string next(const char* Default); 137 inline const std::string next(const char* Default);
138 // -- search for option and get argument at cursor++ 138 // -- search for option and get argument at cursor++
139 inline int follow(int Default, const char* Option); 139 inline int follow(int Default, const char* Option);
140 inline double follow(const double& Default, const char* Option); 140 inline double follow(const double& Default, const char* Option);
141 inline const std::string follow(const char* Default, const char* Option); 141 inline const std::string follow(const char* Default, const char* Option);
142 // -- search for one of the given options and get argument that follows it 142 // -- search for one of the given options and get argument that follows it
143 inline int follow(int Default, unsigned No, const char* Option, ...); 143 inline int follow(int Default, unsigned No, const char* Option, ...);
144 inline double follow(const double& Default, unsigned No, const char* Option, ...); 144 inline double follow(const double& Default, unsigned No, const char* Option, ...);
145 inline const std::string follow(const char* Default, unsigned No, const char* Option, ...); 145 inline const std::string follow(const char* Default, unsigned No, const char* Option, ...);
146 // -- lists of nominuses following an option 146 // -- lists of nominuses following an option
147 inline std::vector<std::string> nominus_followers(const char* Option); 147 inline std::vector<std::string> nominus_followers(const char* Option);
148 inline std::vector<std::string> nominus_followers(unsigned No, ...); 148 inline std::vector<std::string> nominus_followers(unsigned No, ...);
149 149
150 // -- directly followed arguments 150 // -- directly followed arguments
151 inline int direct_follow(int Default, const char* Option); 151 inline int direct_follow(int Default, const char* Option);
152 inline double direct_follow(const double& Default, const char* Option); 152 inline double direct_follow(const double& Default, const char* Option);
153 inline const std::string direct_follow(const char* Default, const char* Option); 153 inline const std::string direct_follow(const char* Default, const char* Option);
154 154
155 inline std::vector<std::string> string_tails(const char* StartString); 155 inline std::vector<std::string> string_tails(const char* StartString);
156 inline std::vector<int> int_tails(const char* StartString, const int Default = 1); 156 inline std::vector<int> int_tails(const char* StartString, const int Default = 1);
157 inline std::vector<double> double_tails(const char* StartString, const double Default = 1.0); 157 inline std::vector<double> double_tails(const char* StartString, const double Default = 1.0);
158 158
159 // (*) nominus arguments --------------------------------------------------- 159 // (*) nominus arguments ---------------------------------------------------
160 inline STRING_VECTOR nominus_vector() const; 160 inline STRING_VECTOR nominus_vector() const;
161 inline unsigned nominus_size() const { return static_cast<unsigned int>(idx_nominus.size()); } 161 inline unsigned nominus_size() const { return static_cast<unsigned int>(idx_nominus.size()); }
162 inline std::string next_nominus(); 162 inline std::string next_nominus();
163 163
164 // (*) unidentified flying objects ----------------------------------------- 164 // (*) unidentified flying objects -----------------------------------------
165 inline STRING_VECTOR unidentified_arguments(unsigned Number, const char* Known, ...) const; 165 inline STRING_VECTOR unidentified_arguments(unsigned Number, const char* Known, ...) const;
166 inline STRING_VECTOR unidentified_arguments(const STRING_VECTOR& Knowns) const; 166 inline STRING_VECTOR unidentified_arguments(const STRING_VECTOR& Knowns) const;
167 inline STRING_VECTOR unidentified_arguments() const; 167 inline STRING_VECTOR unidentified_arguments() const;
168 168
169 inline STRING_VECTOR unidentified_options(unsigned Number, const char* Known, ...) const; 169 inline STRING_VECTOR unidentified_options(unsigned Number, const char* Known, ...) const;
170 inline STRING_VECTOR unidentified_options(const STRING_VECTOR& Knowns) const; 170 inline STRING_VECTOR unidentified_options(const STRING_VECTOR& Knowns) const;
171 inline STRING_VECTOR unidentified_options() const; 171 inline STRING_VECTOR unidentified_options() const;
172 172
173 inline std::string unidentified_flags(const char* Known, 173 inline std::string unidentified_flags(const char* Known,
174 int ArgumentNumber /* =-1 */) const; 174 int ArgumentNumber /* =-1 */) const;
175 175
176 inline STRING_VECTOR unidentified_variables(unsigned Number, const char* Known, ...) const; 176 inline STRING_VECTOR unidentified_variables(unsigned Number, const char* Known, ...) const;
177 inline STRING_VECTOR unidentified_variables(const STRING_VECTOR& Knowns) const; 177 inline STRING_VECTOR unidentified_variables(const STRING_VECTOR& Knowns) const;
178 inline STRING_VECTOR unidentified_variables() const; 178 inline STRING_VECTOR unidentified_variables() const;
179 179
180 inline STRING_VECTOR unidentified_sections(unsigned Number, const char* Known, ...) const; 180 inline STRING_VECTOR unidentified_sections(unsigned Number, const char* Known, ...) const;
181 inline STRING_VECTOR unidentified_sections(const STRING_VECTOR& Knowns) const; 181 inline STRING_VECTOR unidentified_sections(const STRING_VECTOR& Knowns) const;
182 inline STRING_VECTOR unidentified_sections() const; 182 inline STRING_VECTOR unidentified_sections() const;
183 183
184 inline STRING_VECTOR unidentified_nominuses(unsigned Number, const char* Known, ...) const; 184 inline STRING_VECTOR unidentified_nominuses(unsigned Number, const char* Known, ...) const;
185 inline STRING_VECTOR unidentified_nominuses(const STRING_VECTOR& Knowns) const; 185 inline STRING_VECTOR unidentified_nominuses(const STRING_VECTOR& Knowns) const;
186 inline STRING_VECTOR unidentified_nominuses() const; 186 inline STRING_VECTOR unidentified_nominuses() const;
187 187
188 // (*) output -------------------------------------------------------------- 188 // (*) output --------------------------------------------------------------
189 inline int print() const; 189 inline int print() const;
190 190
191private: 191private:
192 // (*) Type Declaration ---------------------------------------------------- 192 // (*) Type Declaration ----------------------------------------------------
193 struct variable { 193 struct variable {
194 //----------- 194 //-----------
195 // Variable to be specified on the command line or in input files. 195 // Variable to be specified on the command line or in input files.
196 // (i.e. of the form var='12 312 341') 196 // (i.e. of the form var='12 312 341')
197 197
198 // -- constructors, destructors, assignment operator 198 // -- constructors, destructors, assignment operator
199 variable(); 199 variable();
200 variable(const variable&); 200 variable(const variable&);
201 variable(const char* Name, const char* Value, const char* FieldSeparator); 201 variable(const char* Name, const char* Value, const char* FieldSeparator);
202 ~variable(); 202 ~variable();
203 variable& operator=(const variable& That); 203 variable& operator=(const variable& That);
204 204
205 void take(const char* Value, const char* FieldSeparator); 205 void take(const char* Value, const char* FieldSeparator);
206 206
207 // -- get a specific element in the string vector 207 // -- get a specific element in the string vector
208 // (return 0 if not present) 208 // (return 0 if not present)
209 const std::string* get_element(unsigned Idx) const; 209 const std::string* get_element(unsigned Idx) const;
210 210
211 // -- data memebers 211 // -- data memebers
212 std::string name; // identifier of variable 212 std::string name; // identifier of variable
213 STRING_VECTOR value; // value of variable stored in vector 213 STRING_VECTOR value; // value of variable stored in vector
214 std::string original; // value of variable as given on command line 214 std::string original; // value of variable as given on command line
215 }; 215 };
216 216
217 // (*) member variables -------------------------------------------------------------- 217 // (*) member variables --------------------------------------------------------------
218 std::string prefix; // prefix automatically added in queries 218 std::string prefix; // prefix automatically added in queries
219 std::string section; // (for dollar bracket parsing) 219 std::string section; // (for dollar bracket parsing)
220 STRING_VECTOR section_list; // list of all parsed sections 220 STRING_VECTOR section_list; // list of all parsed sections
221 // -- argument vector 221 // -- argument vector
222 STRING_VECTOR argv; // vector of command line arguments stored as strings 222 STRING_VECTOR argv; // vector of command line arguments stored as strings
223 unsigned cursor; // cursor for argv 223 unsigned cursor; // cursor for argv
224 bool search_loop_f; // shall search start at beginning after 224 bool search_loop_f; // shall search start at beginning after
225 // // reaching end of arg array ? 225 // // reaching end of arg array ?
226 bool search_failed_f; // flag indicating a failed search() operation 226 bool search_failed_f; // flag indicating a failed search() operation
227 // // (e.g. next() functions react with 'missed') 227 // // (e.g. next() functions react with 'missed')
228 228
229 // -- nominus vector 229 // -- nominus vector
230 int nominus_cursor; // cursor for nominus_pointers 230 int nominus_cursor; // cursor for nominus_pointers
231 std::vector<unsigned> idx_nominus; // indecies of 'no minus' arguments 231 std::vector<unsigned> idx_nominus; // indecies of 'no minus' arguments
232 232
233 // -- variables 233 // -- variables
234 // (arguments of the form "variable=value") 234 // (arguments of the form "variable=value")
235 std::vector<variable> variables; 235 std::vector<variable> variables;
236 236
237 // -- comment delimiters 237 // -- comment delimiters
238 std::string _comment_start; 238 std::string _comment_start;
239 std::string _comment_end; 239 std::string _comment_end;
240 240
241 // -- field separator (separating elements of a vector) 241 // -- field separator (separating elements of a vector)
242 std::string _field_separator; 242 std::string _field_separator;
243 243
244 // -- some functions return a char pointer to a temporarily existing string 244 // -- some functions return a char pointer to a temporarily existing string
245 // this container makes them 'available' until the getpot object is destroyed. 245 // this container makes them 'available' until the getpot object is destroyed.
246 std::vector<char*> __internal_string_container; 246 std::vector<char*> __internal_string_container;
247 247
248 // -- keeping track about arguments that are requested, so that the UFO detection 248 // -- keeping track about arguments that are requested, so that the UFO detection
249 // can be simplified 249 // can be simplified
250 STRING_VECTOR _requested_arguments; 250 STRING_VECTOR _requested_arguments;
251 STRING_VECTOR _requested_variables; 251 STRING_VECTOR _requested_variables;
252 STRING_VECTOR _requested_sections; 252 STRING_VECTOR _requested_sections;
253 253
254 bool __request_recording_f; // speed: request recording can be turned off 254 bool __request_recording_f; // speed: request recording can be turned off
255 255
256 // -- if an argument is requested record it and the 'tag' the section branch to which 256 // -- if an argument is requested record it and the 'tag' the section branch to which
257 // it belongs. Caution: both functions mark the sections as 'tagged'. 257 // it belongs. Caution: both functions mark the sections as 'tagged'.
258 void __record_argument_request(const std::string& Arg); 258 void __record_argument_request(const std::string& Arg);
259 void __record_variable_request(const std::string& Arg); 259 void __record_variable_request(const std::string& Arg);
260 260
261 // (*) helper functions ---------------------------------------------------- 261 // (*) helper functions ----------------------------------------------------
262 // set variable from inside GetPot (no prefix considered) 262 // set variable from inside GetPot (no prefix considered)
263 inline void __set_variable(const char* VarName, const char* Value); 263 inline void __set_variable(const char* VarName, const char* Value);
264 264
265 // -- produce three basic data vectors: 265 // -- produce three basic data vectors:
266 // - argument vector 266 // - argument vector
267 // - nominus vector 267 // - nominus vector
268 // - variable dictionary 268 // - variable dictionary
269 inline void __parse_argument_vector(const STRING_VECTOR& ARGV); 269 inline void __parse_argument_vector(const STRING_VECTOR& ARGV);
270 270
271 // -- helpers for argument list processing 271 // -- helpers for argument list processing
272 // * search for a variable in 'variables' array 272 // * search for a variable in 'variables' array
273 inline const variable* __find_variable(const char*) const; 273 inline const variable* __find_variable(const char*) const;
274 // * support finding directly followed arguments 274 // * support finding directly followed arguments
275 inline const char* __match_starting_string(const char* StartString); 275 inline const char* __match_starting_string(const char* StartString);
276 // * support search for flags in a specific argument 276 // * support search for flags in a specific argument
277 inline bool __check_flags(const std::string& Str, const char* FlagList) const; 277 inline bool __check_flags(const std::string& Str, const char* FlagList) const;
278 // * type conversion if possible 278 // * type conversion if possible
279 inline int __convert_to_type(const std::string& String, int Default) const; 279 inline int __convert_to_type(const std::string& String, int Default) const;
280 inline double __convert_to_type(const std::string& String, double Default) const; 280 inline double __convert_to_type(const std::string& String, double Default) const;
281 // * prefix extraction 281 // * prefix extraction
282 const std::string __get_remaining_string(const std::string& String, 282 const std::string __get_remaining_string(const std::string& String,
283 const std::string& Start) const; 283 const std::string& Start) const;
284 // * search for a specific string 284 // * search for a specific string
285 inline bool __search_string_vector(const STRING_VECTOR& Vec, 285 inline bool __search_string_vector(const STRING_VECTOR& Vec,
286 const std::string& Str) const; 286 const std::string& Str) const;
287 287
288 // -- helpers to parse input file 288 // -- helpers to parse input file
289 // create an argument vector based on data found in an input file, i.e.: 289 // create an argument vector based on data found in an input file, i.e.:
290 // 1) delete comments (in between '_comment_start' '_comment_end') 290 // 1) delete comments (in between '_comment_start' '_comment_end')
291 // 2) contract assignment expressions, such as 291 // 2) contract assignment expressions, such as
292 // my-variable = '007 J. B.' 292 // my-variable = '007 J. B.'
293 // into 293 // into
294 // my-variable='007 J. B.' 294 // my-variable='007 J. B.'
295 // 3) interprete sections like '[../my-section]' etc. 295 // 3) interprete sections like '[../my-section]' etc.
296 inline void __skip_whitespace(std::istream& istr); 296 inline void __skip_whitespace(std::istream& istr);
297 inline const std::string __get_next_token(std::istream& istr); 297 inline const std::string __get_next_token(std::istream& istr);
298 inline const std::string __get_string(std::istream& istr); 298 inline const std::string __get_string(std::istream& istr);
299 inline const std::string __get_until_closing_bracket(std::istream& istr); 299 inline const std::string __get_until_closing_bracket(std::istream& istr);
300 300
301 inline STRING_VECTOR __read_in_stream(std::istream& istr); 301 inline STRING_VECTOR __read_in_stream(std::istream& istr);
302 inline STRING_VECTOR __read_in_file(const char* FileName); 302 inline STRING_VECTOR __read_in_file(const char* FileName);
303 inline std::string __process_section_label(const std::string& Section, 303 inline std::string __process_section_label(const std::string& Section,
304 STRING_VECTOR& section_stack); 304 STRING_VECTOR& section_stack);
305 305
306 // -- dollar bracket expressions 306 // -- dollar bracket expressions
307 std::string __DBE_expand_string(const std::string str); 307 std::string __DBE_expand_string(const std::string str);
308 std::string __DBE_expand(const std::string str); 308 std::string __DBE_expand(const std::string str);
309 const GetPot::variable* __DBE_get_variable(const std::string str); 309 const GetPot::variable* __DBE_get_variable(const std::string str);
310 STRING_VECTOR __DBE_get_expr_list(const std::string str, const unsigned ExpectedNumber); 310 STRING_VECTOR __DBE_get_expr_list(const std::string str, const unsigned ExpectedNumber);
311 311
312 std::string __double2string(const double& Value) const { 312 std::string __double2string(const double& Value) const {
313 // -- converts a double integer into a string 313 // -- converts a double integer into a string
314 char* tmp = new char[128]; 314 char* tmp = new char[128];
315#ifndef WIN32 315#ifndef WIN32
316 snprintf(tmp, (int)sizeof(char)*128, "%e", Value); 316 snprintf(tmp, (int)sizeof(char)*128, "%e", Value);
317#else 317#else
318 _snprintf(tmp, sizeof(char)*128, "%e", Value); 318 _snprintf(tmp, sizeof(char)*128, "%e", Value);
319#endif 319#endif
320 std::string result(tmp); 320 std::string result(tmp);
321 delete [] tmp; 321 delete [] tmp;
322 return result; 322 return result;
323 } 323 }
324 324
325 std::string __int2string(const int& Value) const { 325 std::string __int2string(const int& Value) const {
326 // -- converts an integer into a string 326 // -- converts an integer into a string
327 char* tmp = new char[128]; 327 char* tmp = new char[128];
328#ifndef WIN32 328#ifndef WIN32
329 snprintf(tmp, (int)sizeof(char)*128, "%i", Value); 329 snprintf(tmp, (int)sizeof(char)*128, "%i", Value);
330#else 330#else
331 _snprintf(tmp, sizeof(char)*128, "%i", Value); 331 _snprintf(tmp, sizeof(char)*128, "%i", Value);
332#endif 332#endif
333 std::string result(tmp); 333 std::string result(tmp);
334 delete [] tmp; 334 delete [] tmp;
335 return result; 335 return result;
336 } 336 }
337 337
338 STRING_VECTOR __get_section_tree(const std::string& FullPath) { 338 STRING_VECTOR __get_section_tree(const std::string& FullPath) {
339 // -- cuts a variable name into a tree of sub-sections. this is requested for recording 339 // -- cuts a variable name into a tree of sub-sections. this is requested for recording
340 // requested sections when dealing with 'ufo' detection. 340 // requested sections when dealing with 'ufo' detection.
341 STRING_VECTOR result; 341 STRING_VECTOR result;
342 const char* Start = FullPath.c_str(); 342 const char* Start = FullPath.c_str();
343 343
344 for(char *p = (char*)Start; *p ; p++) { 344 for(char *p = (char*)Start; *p ; p++) {
345 if( *p == '/' ) { 345 if( *p == '/' ) {
346 *p = '\0'; // set terminating zero for convinience 346 *p = '\0'; // set terminating zero for convinience
347 const std::string Section = Start; 347 const std::string Section = Start;
348 *p = '/'; // reset slash at place 348 *p = '/'; // reset slash at place
349 result.push_back(Section); 349 result.push_back(Section);
350 } 350 }
351 } 351 }
352 352
353 return result; 353 return result;
354 } 354 }
355}; 355};
356 356
357 357
358/////////////////////////////////////////////////////////////////////////////// 358///////////////////////////////////////////////////////////////////////////////
359// (*) constructors, destructor, assignment operator 359// (*) constructors, destructor, assignment operator
360//............................................................................. 360//.............................................................................
361// 361//
362inline void 362inline void
363GetPot::__basic_initialization() 363GetPot::__basic_initialization()
364{ 364{
365 cursor = 0; nominus_cursor = -1; 365 cursor = 0; nominus_cursor = -1;
366 search_failed_f = true; search_loop_f = true; 366 search_failed_f = true; search_loop_f = true;
367 prefix = ""; section = ""; 367 prefix = ""; section = "";
368 368
369 // automatic request recording for later ufo detection 369 // automatic request recording for later ufo detection
370 __request_recording_f = true; 370 __request_recording_f = true;
371 371
372 // comment start and end strings 372 // comment start and end strings
373 _comment_start = std::string("#"); 373 _comment_start = std::string("#");
374 _comment_end = std::string("\n"); 374 _comment_end = std::string("\n");
375 375
376 // default: separate vector elements by whitespaces 376 // default: separate vector elements by whitespaces
377 _field_separator = " \t\n"; 377 _field_separator = " \t\n";
378} 378}
379 379
380inline 380inline
381GetPot::GetPot() 381GetPot::GetPot()
382{ 382{
383 __basic_initialization(); 383 __basic_initialization();
384 384
385 STRING_VECTOR _apriori_argv; 385 STRING_VECTOR _apriori_argv;
386 _apriori_argv.push_back(std::string("Empty")); 386 _apriori_argv.push_back(std::string("Empty"));
387 __parse_argument_vector(_apriori_argv); 387 __parse_argument_vector(_apriori_argv);
388} 388}
389 389
390inline 390inline
391GetPot::GetPot(const int argc_, char ** argv_, 391GetPot::GetPot(const int argc_, char ** argv_,
392 const char* FieldSeparator /* =0x0 */) 392 const char* FieldSeparator /* =0x0 */)
393 // leave 'char**' non-const to honor less capable compilers ... 393 // leave 'char**' non-const to honor less capable compilers ...
394{ 394{
395 // TODO: Ponder over the problem when the argument list is of size = 0. 395 // TODO: Ponder over the problem when the argument list is of size = 0.
396 // This is 'sabotage', but it can still occur if the user specifies 396 // This is 'sabotage', but it can still occur if the user specifies
397 // it himself. 397 // it himself.
398 assert(argc_ >= 1); 398 assert(argc_ >= 1);
399 __basic_initialization(); 399 __basic_initialization();
400 400
401 // if specified -> overwrite default string 401 // if specified -> overwrite default string
402 if( FieldSeparator ) _field_separator = std::string(FieldSeparator); 402 if( FieldSeparator ) _field_separator = std::string(FieldSeparator);
403 403
404 // -- make an internal copy of the argument list: 404 // -- make an internal copy of the argument list:
405 STRING_VECTOR _apriori_argv; 405 STRING_VECTOR _apriori_argv;
406 // -- for the sake of clarity: we do want to include the first argument in the argument vector ! 406 // -- for the sake of clarity: we do want to include the first argument in the argument vector !
407 // it will not be a nominus argument, though. This gives us a minimun vector size of one 407 // it will not be a nominus argument, though. This gives us a minimun vector size of one
408 // which facilitates error checking in many functions. Also the user will be able to 408 // which facilitates error checking in many functions. Also the user will be able to
409 // retrieve the name of his application by "get[0]" 409 // retrieve the name of his application by "get[0]"
410 _apriori_argv.push_back(std::string(argv_[0])); 410 _apriori_argv.push_back(std::string(argv_[0]));
411 int i=1; 411 int i=1;
412 for(; i<argc_; ++i) { 412 for(; i<argc_; ++i) {
413 std::string tmp(argv_[i]); // recall the problem with temporaries, 413 std::string tmp(argv_[i]); // recall the problem with temporaries,
414 _apriori_argv.push_back(tmp); // reference counting in arguement lists ... 414 _apriori_argv.push_back(tmp); // reference counting in arguement lists ...
415 } 415 }
416 __parse_argument_vector(_apriori_argv); 416 __parse_argument_vector(_apriori_argv);
417} 417}
418 418
419 419
420inline 420inline
421GetPot::GetPot(const char* FileName, 421GetPot::GetPot(const char* FileName,
422 const char* CommentStart /* = 0x0 */, const char* CommentEnd /* = 0x0 */, 422 const char* CommentStart /* = 0x0 */, const char* CommentEnd /* = 0x0 */,
423 const char* FieldSeparator/* = 0x0 */) 423 const char* FieldSeparator/* = 0x0 */)
424{ 424{
425 __basic_initialization(); 425 __basic_initialization();
426 426
427 // if specified -> overwrite default strings 427 // if specified -> overwrite default strings
428 if( CommentStart ) _comment_start = std::string(CommentStart); 428 if( CommentStart ) _comment_start = std::string(CommentStart);
429 if( CommentEnd ) _comment_end = std::string(CommentEnd); 429 if( CommentEnd ) _comment_end = std::string(CommentEnd);
430 if( FieldSeparator ) _field_separator = FieldSeparator; 430 if( FieldSeparator ) _field_separator = FieldSeparator;
431 431
432 STRING_VECTOR _apriori_argv; 432 STRING_VECTOR _apriori_argv;
433 // -- file name is element of argument vector, however, it is not parsed for 433 // -- file name is element of argument vector, however, it is not parsed for
434 // variable assignments or nominuses. 434 // variable assignments or nominuses.
435 _apriori_argv.push_back(std::string(FileName)); 435 _apriori_argv.push_back(std::string(FileName));
436 436
437 STRING_VECTOR args = __read_in_file(FileName); 437 STRING_VECTOR args = __read_in_file(FileName);
438 _apriori_argv.insert(_apriori_argv.begin()+1, args.begin(), args.end()); 438 _apriori_argv.insert(_apriori_argv.begin()+1, args.begin(), args.end());
439 __parse_argument_vector(_apriori_argv); 439 __parse_argument_vector(_apriori_argv);
440} 440}
441 441
442inline 442inline
443GetPot::GetPot(const GetPot& That) 443GetPot::GetPot(const GetPot& That)
444{ GetPot::operator=(That); } 444{ GetPot::operator=(That); }
445 445
446inline 446inline
447GetPot::~GetPot() 447GetPot::~GetPot()
448{ 448{
449 // may be some return strings had to be created, delete now ! 449 // may be some return strings had to be created, delete now !
450 victorate(char*, __internal_string_container, it) 450 victorate(char*, __internal_string_container, it)
451 delete [] *it; 451 delete [] *it;
452} 452}
453 453
454inline GetPot& 454inline GetPot&
455GetPot::operator=(const GetPot& That) 455GetPot::operator=(const GetPot& That)
456{ 456{
457 if (&That == this) return *this; 457 if (&That == this) return *this;
458 458
459 _comment_start = That._comment_start; 459 _comment_start = That._comment_start;
460 _comment_end = That._comment_end; 460 _comment_end = That._comment_end;
461 argv = That.argv; 461 argv = That.argv;
462 variables = That.variables; 462 variables = That.variables;
463 prefix = That.prefix; 463 prefix = That.prefix;
464 464
465 cursor = That.cursor; 465 cursor = That.cursor;
466 nominus_cursor = That.nominus_cursor; 466 nominus_cursor = That.nominus_cursor;
467 search_failed_f = That.search_failed_f; 467 search_failed_f = That.search_failed_f;
468 468
469 idx_nominus = That.idx_nominus; 469 idx_nominus = That.idx_nominus;
470 search_loop_f = That.search_loop_f; 470 search_loop_f = That.search_loop_f;
471 471
472 return *this; 472 return *this;
473} 473}
474 474
475 475
476inline void 476inline void
477GetPot::absorb(const GetPot& That) 477GetPot::absorb(const GetPot& That)
478{ 478{
479 if (&That == this) return; 479 if (&That == this) return;
480 480
481 STRING_VECTOR __tmp(That.argv); 481 STRING_VECTOR __tmp(That.argv);
482 482
483 __tmp.erase(__tmp.begin()); 483 __tmp.erase(__tmp.begin());
484 484
485 __parse_argument_vector(__tmp); 485 __parse_argument_vector(__tmp);
486} 486}
487 487
488inline void 488inline void
489GetPot::clear_requests() 489GetPot::clear_requests()
490{ 490{
491 _requested_arguments.erase(_requested_arguments.begin(), _requested_arguments.end()); 491 _requested_arguments.erase(_requested_arguments.begin(), _requested_arguments.end());
492 _requested_variables.erase(_requested_variables.begin(), _requested_variables.end()); 492 _requested_variables.erase(_requested_variables.begin(), _requested_variables.end());
493 _requested_sections.erase(_requested_sections.begin(), _requested_sections.end()); 493 _requested_sections.erase(_requested_sections.begin(), _requested_sections.end());
494} 494}
495 495
496inline void 496inline void
497GetPot::__parse_argument_vector(const STRING_VECTOR& ARGV) 497GetPot::__parse_argument_vector(const STRING_VECTOR& ARGV)
498{ 498{
499 if( ARGV.size() == 0 ) return; 499 if( ARGV.size() == 0 ) return;
500 500
501 // build internal databases: 501 // build internal databases:
502 // 1) array with no-minus arguments (usually used as filenames) 502 // 1) array with no-minus arguments (usually used as filenames)
503 // 2) variable assignments: 503 // 2) variable assignments:
504 // 'variable name' '=' number | string 504 // 'variable name' '=' number | string
505 STRING_VECTOR section_stack; 505 STRING_VECTOR section_stack;
506 STRING_VECTOR::const_iterator it = ARGV.begin(); 506 STRING_VECTOR::const_iterator it = ARGV.begin();
507 507
508 508
509 section = ""; 509 section = "";
510 510
511 // -- do not parse the first argument, so that it is not interpreted a s a nominus or so. 511 // -- do not parse the first argument, so that it is not interpreted a s a nominus or so.
512 argv.push_back(*it); 512 argv.push_back(*it);
513 ++it; 513 ++it;
514 514
515 // -- loop over remaining arguments 515 // -- loop over remaining arguments
516 unsigned i=1; 516 unsigned i=1;
517 for(; it != ARGV.end(); ++it, ++i) { 517 for(; it != ARGV.end(); ++it, ++i) {
518 std::string arg = *it; 518 std::string arg = *it;
519 519
520 if( arg.length() == 0 ) continue; 520 if( arg.length() == 0 ) continue;
521 521
522 // -- [section] labels 522 // -- [section] labels
523 if( arg.length() > 1 && arg[0] == '[' && arg[arg.length()-1] == ']' ) { 523 if( arg.length() > 1 && arg[0] == '[' && arg[arg.length()-1] == ']' ) {
524 524
525 // (*) sections are considered 'requested arguments' 525 // (*) sections are considered 'requested arguments'
526 if( __request_recording_f ) _requested_arguments.push_back(arg); 526 if( __request_recording_f ) _requested_arguments.push_back(arg);
527 527
528 const std::string Name = __DBE_expand_string(arg.substr(1, arg.length()-2)); 528 const std::string Name = __DBE_expand_string(arg.substr(1, arg.length()-2));
529 section = __process_section_label(Name, section_stack); 529 section = __process_section_label(Name, section_stack);
530 // new section --> append to list of sections 530 // new section --> append to list of sections
531 if( find(section_list.begin(), section_list.end(), section) == section_list.end() ) 531 if( find(section_list.begin(), section_list.end(), section) == section_list.end() )
532 if( section.length() != 0 ) section_list.push_back(section); 532 if( section.length() != 0 ) section_list.push_back(section);
533 argv.push_back(arg); 533 argv.push_back(arg);
534 } 534 }
535 else { 535 else {
536 arg = section + __DBE_expand_string(arg); 536 arg = section + __DBE_expand_string(arg);
537 argv.push_back(arg); 537 argv.push_back(arg);
538 } 538 }
539 539
540 // -- separate array for nominus arguments 540 // -- separate array for nominus arguments
541 if( arg[0] != '-' ) idx_nominus.push_back(unsigned(i)); 541 if( arg[0] != '-' ) idx_nominus.push_back(unsigned(i));
542 542
543 // -- variables: does arg contain a '=' operator ? 543 // -- variables: does arg contain a '=' operator ?
544 const char* p = arg.c_str(); 544 const char* p = arg.c_str();
545 for(; *p ; p++) { 545 for(; *p ; p++) {
546 if( *p == '=' ) { 546 if( *p == '=' ) {
547 // (*) record for later ufo detection 547 // (*) record for later ufo detection
548 // arguments carriying variables are always treated as 'requested' arguments. 548 // arguments carriying variables are always treated as 'requested' arguments.
549 // as a whole! That is 'x=4712' is considered a requested argument. 549 // as a whole! That is 'x=4712' is considered a requested argument.
550 // 550 //
551 // unrequested variables have to be detected with the ufo-variable 551 // unrequested variables have to be detected with the ufo-variable
552 // detection routine. 552 // detection routine.
553 if( __request_recording_f ) _requested_arguments.push_back(arg); 553 if( __request_recording_f ) _requested_arguments.push_back(arg);
554 554
555 // set terminating 'zero' to treat first part as single string 555 // set terminating 'zero' to treat first part as single string
556 // => arg (from start to 'p') = Name of variable 556 // => arg (from start to 'p') = Name of variable
557 // p+1 (until terminating zero) = value of variable 557 // p+1 (until terminating zero) = value of variable
558 char* o = (char*)p++; 558 char* o = (char*)p++;
559 *o = '\0'; // set temporary terminating zero 559 *o = '\0'; // set temporary terminating zero
560 // __set_variable(...) 560 // __set_variable(...)
561 // calls __find_variable(...) which registers the search 561 // calls __find_variable(...) which registers the search
562 // temporarily disable this 562 // temporarily disable this
563 const bool tmp = __request_recording_f; 563 const bool tmp = __request_recording_f;
564 __request_recording_f = false; 564 __request_recording_f = false;
565 __set_variable(arg.c_str(), p); // v-name = c_str() bis 'p', value = rest 565 __set_variable(arg.c_str(), p); // v-name = c_str() bis 'p', value = rest
566 __request_recording_f = tmp; 566 __request_recording_f = tmp;
567 *o = '='; // reset the original '=' 567 *o = '='; // reset the original '='
568 break; 568 break;
569 } 569 }
570 } 570 }
571 } 571 }
572} 572}
573 573
574 574
575inline STRING_VECTOR 575inline STRING_VECTOR
576GetPot::__read_in_file(const char* FileName) 576GetPot::__read_in_file(const char* FileName)
577{ 577{
578 std::ifstream i(FileName); 578 std::ifstream i(FileName);
579 if( ! i ) return STRING_VECTOR(); 579 if( ! i ) return STRING_VECTOR();
580 // argv[0] == the filename of the file that was read in 580 // argv[0] == the filename of the file that was read in
581 return __read_in_stream(i); 581 return __read_in_stream(i);
582} 582}
583 583
584inline STRING_VECTOR 584inline STRING_VECTOR
585GetPot::__read_in_stream(std::istream& istr) 585GetPot::__read_in_stream(std::istream& istr)
586{ 586{
587 STRING_VECTOR brute_tokens; 587 STRING_VECTOR brute_tokens;
588 while(istr) { 588 while(istr) {
589 __skip_whitespace(istr); 589 __skip_whitespace(istr);
590 590
591 const std::string Token = __get_next_token(istr); 591 const std::string Token = __get_next_token(istr);
592 if( Token.length() == 0 || Token[0] == EOF) break; 592 if( Token.length() == 0 || Token[0] == EOF) break;
593 brute_tokens.push_back(Token); 593 brute_tokens.push_back(Token);
594 } 594 }
595 595
596 // -- reduce expressions of token1'='token2 to a single 596 // -- reduce expressions of token1'='token2 to a single
597 // string 'token1=token2' 597 // string 'token1=token2'
598 // -- copy everything into 'argv' 598 // -- copy everything into 'argv'
599 // -- arguments preceded by something like '[' name ']' (section) 599 // -- arguments preceded by something like '[' name ']' (section)
600 // produce a second copy of each argument with a prefix '[name]argument' 600 // produce a second copy of each argument with a prefix '[name]argument'
601 unsigned i1 = 0; 601 unsigned i1 = 0;
602 unsigned i2 = 1; 602 unsigned i2 = 1;
603 unsigned i3 = 2; 603 unsigned i3 = 2;
604 604
605 STRING_VECTOR arglist; 605 STRING_VECTOR arglist;
606 while( i1 < brute_tokens.size() ) { 606 while( i1 < brute_tokens.size() ) {
607 const std::string& SRef = brute_tokens[i1]; 607 const std::string& SRef = brute_tokens[i1];
608 // 1) concatinate 'abcdef' '=' 'efgasdef' to 'abcdef=efgasdef' 608 // 1) concatinate 'abcdef' '=' 'efgasdef' to 'abcdef=efgasdef'
609 // note: java.lang.String: substring(a,b) = from a to b-1 609 // note: java.lang.String: substring(a,b) = from a to b-1
610 // C++ string: substr(a,b) = from a to a + b 610 // C++ string: substr(a,b) = from a to a + b
611 if( i2 < brute_tokens.size() && brute_tokens[i2] == "=" ) { 611 if( i2 < brute_tokens.size() && brute_tokens[i2] == "=" ) {
612 if( i3 >= brute_tokens.size() ) 612 if( i3 >= brute_tokens.size() )
613 arglist.push_back(brute_tokens[i1] + brute_tokens[i2]); 613 arglist.push_back(brute_tokens[i1] + brute_tokens[i2]);
614 else 614 else
615 arglist.push_back(brute_tokens[i1] + brute_tokens[i2] + brute_tokens[i3]); 615 arglist.push_back(brute_tokens[i1] + brute_tokens[i2] + brute_tokens[i3]);
616 i1 = i3+1; i2 = i3+2; i3 = i3+3; 616 i1 = i3+1; i2 = i3+2; i3 = i3+3;
617 continue; 617 continue;
618 } 618 }
619 else { 619 else {
620 arglist.push_back(SRef); 620 arglist.push_back(SRef);
621 i1=i2; i2=i3; i3++; 621 i1=i2; i2=i3; i3++;
622 } 622 }
623 } 623 }
624 return arglist; 624 return arglist;
625} 625}
626 626
627inline void 627inline void
628GetPot::__skip_whitespace(std::istream& istr) 628GetPot::__skip_whitespace(std::istream& istr)
629 // find next non-whitespace while deleting comments 629 // find next non-whitespace while deleting comments
630{ 630{
631 int tmp = istr.get(); 631 int tmp = istr.get();
632 do { 632 do {
633 // -- search a non whitespace 633 // -- search a non whitespace
634 while( isspace(tmp) ) { 634 while( isspace(tmp) ) {
635 tmp = istr.get(); 635 tmp = istr.get();
636 if( ! istr ) return; 636 if( ! istr ) return;
637 } 637 }
638 638
639 // -- look if characters match the comment starter string 639 // -- look if characters match the comment starter string
640 const std::istream::pos_type Pos = istr.tellg(); 640 const std::istream::pos_type Pos = istr.tellg();
641 unsigned i=0; 641 unsigned i=0;
642 for(; i<_comment_start.length() ; ++i) { 642 for(; i<_comment_start.length() ; ++i) {
643 if( tmp != _comment_start[i] ) { 643 if( tmp != _comment_start[i] ) {
644// HACK: The following line throws off msvc8: 644// HACK: The following line throws off msvc8:
645// istr.seekg(Pos); 645// istr.seekg(Pos);
646 // -- one step more backwards, since 'tmp' already at non-whitespace 646 // -- one step more backwards, since 'tmp' already at non-whitespace
647 istr.unget(); 647 istr.unget();
648 return; 648 return;
649 } 649 }
650 tmp = istr.get(); 650 tmp = istr.get();
651 if( ! istr ) { istr.unget(); return; } 651 if( ! istr ) { istr.unget(); return; }
652 } 652 }
653 // 'tmp' contains last character of _comment_starter 653 // 'tmp' contains last character of _comment_starter
654 654
655 // -- comment starter found -> search for comment ender 655 // -- comment starter found -> search for comment ender
656 unsigned match_no=0; 656 unsigned match_no=0;
657 while(1+1 == 2) { 657 while(1+1 == 2) {
658 tmp = istr.get(); 658 tmp = istr.get();
659 if( ! istr ) { istr.unget(); return; } 659 if( ! istr ) { istr.unget(); return; }
660 660
661 if( tmp == _comment_end[match_no] ) { 661 if( tmp == _comment_end[match_no] ) {
662 match_no++; 662 match_no++;
663 if( match_no == _comment_end.length() ) { 663 if( match_no == _comment_end.length() ) {
664 istr.unget(); 664 istr.unget();
665 break; // shuffle more whitespace, end of comment found 665 break; // shuffle more whitespace, end of comment found
666 } 666 }
667 } 667 }
668 else 668 else
669 match_no = 0; 669 match_no = 0;
670 } 670 }
671 671
672 tmp = istr.get(); 672 tmp = istr.get();
673 673
674 } while( istr ); 674 } while( istr );
675 istr.unget(); 675 istr.unget();
676} 676}
677 677
678inline const std::string 678inline const std::string
679GetPot::__get_next_token(std::istream& istr) 679GetPot::__get_next_token(std::istream& istr)
680 // get next concatinates string token. consider quotes that embrace 680 // get next concatinates string token. consider quotes that embrace
681 // whitespaces 681 // whitespaces
682{ 682{
683 std::string token; 683 std::string token;
684 int tmp = 0; 684 int tmp = 0;
685 int last_letter = 0; 685 int last_letter = 0;
686 while(1+1 == 2) { 686 while(1+1 == 2) {
687 last_letter = tmp; tmp = istr.get(); 687 last_letter = tmp; tmp = istr.get();
688 if( tmp == EOF 688 if( tmp == EOF
689 || ((tmp == ' ' || tmp == '\t' || tmp == '\n') && last_letter != '\\') ) { 689 || ((tmp == ' ' || tmp == '\t' || tmp == '\n') && last_letter != '\\') ) {
690 return token; 690 return token;
691 } 691 }
692 else if( tmp == '\'' && last_letter != '\\' ) { 692 else if( tmp == '\'' && last_letter != '\\' ) {
693 // QUOTES: un-backslashed quotes => it's a string 693 // QUOTES: un-backslashed quotes => it's a string
694 token += __get_string(istr); 694 token += __get_string(istr);
695 continue; 695 continue;
696 } 696 }
697 else if( tmp == '{' && last_letter == '$') { 697 else if( tmp == '{' && last_letter == '$') {
698 token += '{' + __get_until_closing_bracket(istr); 698 token += '{' + __get_until_closing_bracket(istr);
699 continue; 699 continue;
700 } 700 }
701 else if( tmp == '$' && last_letter == '\\') { 701 else if( tmp == '$' && last_letter == '\\') {
702 token += tmp; tmp = 0; // so that last_letter will become = 0, not '$'; 702 token += tmp; tmp = 0; // so that last_letter will become = 0, not '$';
703 continue; 703 continue;
704 } 704 }
705 else if( tmp == '\\' && last_letter != '\\') 705 else if( tmp == '\\' && last_letter != '\\')
706 continue; // don't append un-backslashed backslashes 706 continue; // don't append un-backslashed backslashes
707 token += tmp; 707 token += tmp;
708 } 708 }
709} 709}
710 710
711inline const std::string 711inline const std::string
712GetPot::__get_string(std::istream& istr) 712GetPot::__get_string(std::istream& istr)
713 // parse input until next matching ' 713 // parse input until next matching '
714{ 714{
715 std::string str; 715 std::string str;
716 int tmp = 0; 716 int tmp = 0;
717 int last_letter = 0; 717 int last_letter = 0;
718 while(1 + 1 == 2) { 718 while(1 + 1 == 2) {
719 last_letter = tmp; tmp = istr.get(); 719 last_letter = tmp; tmp = istr.get();
720 if( tmp == EOF) return str; 720 if( tmp == EOF) return str;
721 // un-backslashed quotes => it's the end of the string 721 // un-backslashed quotes => it's the end of the string
722 else if( tmp == '\'' && last_letter != '\\') return str; 722 else if( tmp == '\'' && last_letter != '\\') return str;
723 else if( tmp == '\\' && last_letter != '\\') continue; // don't append 723 else if( tmp == '\\' && last_letter != '\\') continue; // don't append
724 724
725 str += tmp; 725 str += tmp;
726 } 726 }
727} 727}
728 728
729inline const std::string 729inline const std::string
730GetPot::__get_until_closing_bracket(std::istream& istr) 730GetPot::__get_until_closing_bracket(std::istream& istr)
731 // parse input until next matching } 731 // parse input until next matching }
732{ 732{
733 std::string str = ""; 733 std::string str = "";
734 int tmp = 0; 734 int tmp = 0;
735 int last_letter = 0; 735 int last_letter = 0;
736 int brackets = 1; 736 int brackets = 1;
737 while(1 + 1 == 2) { 737 while(1 + 1 == 2) {
738 last_letter = tmp; tmp = istr.get(); 738 last_letter = tmp; tmp = istr.get();
739 if( tmp == EOF) return str; 739 if( tmp == EOF) return str;
740 else if( tmp == '{' && last_letter == '$') brackets += 1; 740 else if( tmp == '{' && last_letter == '$') brackets += 1;
741 else if( tmp == '}') { 741 else if( tmp == '}') {
742 brackets -= 1; 742 brackets -= 1;
743 // un-backslashed brackets => it's the end of the string 743 // un-backslashed brackets => it's the end of the string
744 if( brackets == 0) return str + '}'; 744 if( brackets == 0) return str + '}';
745 else if( tmp == '\\' && last_letter != '\\') 745 else if( tmp == '\\' && last_letter != '\\')
746 continue; // do not append an unbackslashed backslash 746 continue; // do not append an unbackslashed backslash
747 } 747 }
748 str += tmp; 748 str += tmp;
749 } 749 }
750} 750}
751 751
752inline std::string 752inline std::string
753GetPot::__process_section_label(const std::string& Section, 753GetPot::__process_section_label(const std::string& Section,
754 STRING_VECTOR& section_stack) 754 STRING_VECTOR& section_stack)
755{ 755{
756 std::string sname = Section; 756 std::string sname = Section;
757 // 1) subsection of actual section ('./' prefix) 757 // 1) subsection of actual section ('./' prefix)
758 if( sname.length() >= 2 && sname.substr(0, 2) == "./" ) { 758 if( sname.length() >= 2 && sname.substr(0, 2) == "./" ) {
759 sname = sname.substr(2); 759 sname = sname.substr(2);
760 } 760 }
761 // 2) subsection of parent section ('../' prefix) 761 // 2) subsection of parent section ('../' prefix)
762 else if( sname.length() >= 3 && sname.substr(0, 3) == "../" ) { 762 else if( sname.length() >= 3 && sname.substr(0, 3) == "../" ) {
763 do { 763 do {
764 if( section_stack.end() != section_stack.begin() ) 764 if( section_stack.end() != section_stack.begin() )
765 section_stack.pop_back(); 765 section_stack.pop_back();
766 sname = sname.substr(3); 766 sname = sname.substr(3);
767 } while( sname.substr(0, 3) == "../" ); 767 } while( sname.substr(0, 3) == "../" );
768 } 768 }
769 // 3) subsection of the root-section 769 // 3) subsection of the root-section
770 else { 770 else {
771 section_stack.erase(section_stack.begin(), section_stack.end()); 771 section_stack.erase(section_stack.begin(), section_stack.end());
772 // [] => back to root section 772 // [] => back to root section
773 } 773 }
774 774
775 if( sname != "" ) { 775 if( sname != "" ) {
776 // parse section name for 'slashes' 776 // parse section name for 'slashes'
777 unsigned i=0; 777 unsigned i=0;
778 while( i < sname.length() ) { 778 while( i < sname.length() ) {
779 if( sname[i] == '/' ) { 779 if( sname[i] == '/' ) {
780 section_stack.push_back(sname.substr(0,i)); 780 section_stack.push_back(sname.substr(0,i));
781 if( i+1 < sname.length()-1 ) 781 if( i+1 < sname.length()-1 )
782 sname = sname.substr(i+1); 782 sname = sname.substr(i+1);
783 i = 0; 783 i = 0;
784 } 784 }
785 else 785 else
786 ++i; 786 ++i;
787 } 787 }
788 section_stack.push_back(sname); 788 section_stack.push_back(sname);
789 } 789 }
790 std::string section = ""; 790 std::string section = "";
791 if( section_stack.size() != 0 ) { 791 if( section_stack.size() != 0 ) {
792 victorate(std::string, section_stack, it) 792 victorate(std::string, section_stack, it)
793 section += *it + "/"; 793 section += *it + "/";
794 } 794 }
795 return section; 795 return section;
796} 796}
797 797
798 798
799// convert string to DOUBLE, if not possible return Default 799// convert string to DOUBLE, if not possible return Default
800inline double 800inline double
801GetPot::__convert_to_type(const std::string& String, double Default) const 801GetPot::__convert_to_type(const std::string& String, double Default) const
802{ 802{
803 double tmp; 803 double tmp;
804 if( sscanf(String.c_str(),"%lf", &tmp) != 1 ) return Default; 804 if( sscanf(String.c_str(),"%lf", &tmp) != 1 ) return Default;
805 return tmp; 805 return tmp;
806} 806}
807 807
808// convert string to INT, if not possible return Default 808// convert string to INT, if not possible return Default
809inline int 809inline int
810GetPot::__convert_to_type(const std::string& String, int Default) const 810GetPot::__convert_to_type(const std::string& String, int Default) const
811{ 811{
812 // NOTE: intermediate results may be floating points, so that the string 812 // NOTE: intermediate results may be floating points, so that the string
813 // may look like 2.0e1 (i.e. float format) => use float conversion 813 // may look like 2.0e1 (i.e. float format) => use float conversion
814 // in any case. 814 // in any case.
815 return (int)__convert_to_type(String, (double)Default); 815 return (int)__convert_to_type(String, (double)Default);
816} 816}
817 817
818////////////////////////////////////////////////////////////////////////////// 818//////////////////////////////////////////////////////////////////////////////
819// (*) cursor oriented functions 819// (*) cursor oriented functions
820//............................................................................. 820//.............................................................................
821inline const std::string 821inline const std::string
822GetPot::__get_remaining_string(const std::string& String, const std::string& Start) const 822GetPot::__get_remaining_string(const std::string& String, const std::string& Start) const
823 // Checks if 'String' begins with 'Start' and returns the remaining String. 823 // Checks if 'String' begins with 'Start' and returns the remaining String.
824 // Returns None if String does not begin with Start. 824 // Returns None if String does not begin with Start.
825{ 825{
826 if( Start == "" ) return String; 826 if( Start == "" ) return String;
827 // note: java.lang.String: substring(a,b) = from a to b-1 827 // note: java.lang.String: substring(a,b) = from a to b-1
828 // C++ string: substr(a,b) = from a to a + b 828 // C++ string: substr(a,b) = from a to a + b
829 if( String.find(Start) == 0 ) return String.substr(Start.length()); 829 if( String.find(Start) == 0 ) return String.substr(Start.length());
830 else return ""; 830 else return "";
831} 831}
832 832
833// -- search for a certain argument and set cursor to position 833// -- search for a certain argument and set cursor to position
834inline bool 834inline bool
835GetPot::search(const char* Option) 835GetPot::search(const char* Option)
836{ 836{
837 unsigned OldCursor = cursor; 837 unsigned OldCursor = cursor;
838 const std::string SearchTerm = prefix + Option; 838 const std::string SearchTerm = prefix + Option;
839 839
840 // (*) record requested arguments for later ufo detection 840 // (*) record requested arguments for later ufo detection
841 __record_argument_request(SearchTerm); 841 __record_argument_request(SearchTerm);
842 842
843 if( OldCursor >= argv.size() ) OldCursor = static_cast<unsigned int>(argv.size()) - 1; 843 if( OldCursor >= argv.size() ) OldCursor = static_cast<unsigned int>(argv.size()) - 1;
844 search_failed_f = true; 844 search_failed_f = true;
845 845
846 // (*) first loop from cursor position until end 846 // (*) first loop from cursor position until end
847 unsigned c = cursor; 847 unsigned c = cursor;
848 for(; c < argv.size(); c++) { 848 for(; c < argv.size(); c++) {
849 if( argv[c] == SearchTerm ) 849 if( argv[c] == SearchTerm )
850 { cursor = c; search_failed_f = false; return true; } 850 { cursor = c; search_failed_f = false; return true; }
851 } 851 }
852 if( ! search_loop_f ) return false; 852 if( ! search_loop_f ) return false;
853 853
854 // (*) second loop from 0 to old cursor position 854 // (*) second loop from 0 to old cursor position
855 for(c = 1; c < OldCursor; c++) { 855 for(c = 1; c < OldCursor; c++) {
856 if( argv[c] == SearchTerm ) 856 if( argv[c] == SearchTerm )
857 { cursor = c; search_failed_f = false; return true; } 857 { cursor = c; search_failed_f = false; return true; }
858 } 858 }
859 // in case nothing is found the cursor stays where it was 859 // in case nothing is found the cursor stays where it was
860 return false; 860 return false;
861} 861}
862 862
863 863
864inline bool 864inline bool
865GetPot::search(unsigned No, const char* P, ...) 865GetPot::search(unsigned No, const char* P, ...)
866{ 866{
867 // (*) recording the requested arguments happens in subroutine 'search' 867 // (*) recording the requested arguments happens in subroutine 'search'
868 if( No == 0 ) return false; 868 if( No == 0 ) return false;
869 869
870 // search for the first argument 870 // search for the first argument
871 if( search(P) == true ) return true; 871 if( search(P) == true ) return true;
872 872
873 // start interpreting variable argument list 873 // start interpreting variable argument list
874 va_list ap; 874 va_list ap;
875 va_start(ap, P); 875 va_start(ap, P);
876 unsigned i = 1; 876 unsigned i = 1;
877 for(; i < No; ++i) { 877 for(; i < No; ++i) {
878 char* Opt = va_arg(ap, char *); 878 char* Opt = va_arg(ap, char *);
879 if( search(Opt) == true ) break; 879 if( search(Opt) == true ) break;
880 } 880 }
881 881
882 if( i < No ) { 882 if( i < No ) {
883 ++i; 883 ++i;
884 // loop was left before end of array --> hit but 884 // loop was left before end of array --> hit but
885 // make sure that the rest of the search terms is marked 885 // make sure that the rest of the search terms is marked
886 // as requested. 886 // as requested.
887 for(; i < No; ++i) { 887 for(; i < No; ++i) {
888 char* Opt = va_arg(ap, char *); 888 char* Opt = va_arg(ap, char *);
889 // (*) record requested arguments for later ufo detection 889 // (*) record requested arguments for later ufo detection
890 __record_argument_request(Opt); 890 __record_argument_request(Opt);
891 } 891 }
892 va_end(ap); 892 va_end(ap);
893 return true; 893 return true;
894 } 894 }
895 895
896 va_end(ap); 896 va_end(ap);
897 // loop was left normally --> no hit 897 // loop was left normally --> no hit
898 return false; 898 return false;
899} 899}
900 900
901inline void 901inline void
902GetPot::reset_cursor() 902GetPot::reset_cursor()
903{ search_failed_f = false; cursor = 0; } 903{ search_failed_f = false; cursor = 0; }
904 904
905inline void 905inline void
906GetPot::init_multiple_occurrence() 906GetPot::init_multiple_occurrence()
907{ disable_loop(); reset_cursor(); } 907{ disable_loop(); reset_cursor(); }
908/////////////////////////////////////////////////////////////////////////////// 908///////////////////////////////////////////////////////////////////////////////
909// (*) direct access to command line arguments 909// (*) direct access to command line arguments
910//............................................................................. 910//.............................................................................
911// 911//
912inline const std::string 912inline const std::string
913GetPot::operator[](unsigned idx) const 913GetPot::operator[](unsigned idx) const
914{ return idx < argv.size() ? argv[idx] : ""; } 914{ return idx < argv.size() ? argv[idx] : ""; }
915 915
916inline int 916inline int
917GetPot::get(unsigned Idx, int Default) const 917GetPot::get(unsigned Idx, int Default) const
918{ 918{
919 if( Idx >= argv.size() ) return Default; 919 if( Idx >= argv.size() ) return Default;
920 return __convert_to_type(argv[Idx], Default); 920 return __convert_to_type(argv[Idx], Default);
921} 921}
922 922
923inline double 923inline double
924GetPot::get(unsigned Idx, const double& Default) const 924GetPot::get(unsigned Idx, const double& Default) const
925{ 925{
926 if( Idx >= argv.size() ) return Default; 926 if( Idx >= argv.size() ) return Default;
927 return __convert_to_type(argv[Idx], Default); 927 return __convert_to_type(argv[Idx], Default);
928} 928}
929 929
930inline const std::string 930inline const std::string
931GetPot::get(unsigned Idx, const char* Default) const 931GetPot::get(unsigned Idx, const char* Default) const
932{ 932{
933 if( Idx >= argv.size() ) return Default; 933 if( Idx >= argv.size() ) return Default;
934 else return argv[Idx]; 934 else return argv[Idx];
935} 935}
936 936
937inline unsigned 937inline unsigned
938GetPot::size() const 938GetPot::size() const
939{ return static_cast<unsigned int>(argv.size()); } 939{ return static_cast<unsigned int>(argv.size()); }
940 940
941 941
942// -- next() function group 942// -- next() function group
943inline int 943inline int
944GetPot::next(int Default) 944GetPot::next(int Default)
945{ 945{
946 if( search_failed_f ) return Default; 946 if( search_failed_f ) return Default;
947 cursor++; 947 cursor++;
948 if( cursor >= argv.size() ) 948 if( cursor >= argv.size() )
949 { cursor = static_cast<unsigned int>(argv.size()); return Default; } 949 { cursor = static_cast<unsigned int>(argv.size()); return Default; }
950 950
951 // (*) record requested argument for later ufo detection 951 // (*) record requested argument for later ufo detection
952 __record_argument_request(argv[cursor]); 952 __record_argument_request(argv[cursor]);
953 953
954 const std::string Remain = __get_remaining_string(argv[cursor], prefix); 954 const std::string Remain = __get_remaining_string(argv[cursor], prefix);
955 955
956 return Remain != "" ? __convert_to_type(Remain, Default) : Default; 956 return Remain != "" ? __convert_to_type(Remain, Default) : Default;
957} 957}
958 958
959inline double 959inline double
960GetPot::next(const double& Default) 960GetPot::next(const double& Default)
961{ 961{
962 if( search_failed_f ) return Default; 962 if( search_failed_f ) return Default;
963 cursor++; 963 cursor++;
964 964
965 if( cursor >= argv.size() ) 965 if( cursor >= argv.size() )
966 { cursor = static_cast<unsigned int>(argv.size()); return Default; } 966 { cursor = static_cast<unsigned int>(argv.size()); return Default; }
967 967
968 // (*) record requested argument for later ufo detection 968 // (*) record requested argument for later ufo detection
969 __record_argument_request(argv[cursor]); 969 __record_argument_request(argv[cursor]);
970 970
971 std::string Remain = __get_remaining_string(argv[cursor], prefix); 971 std::string Remain = __get_remaining_string(argv[cursor], prefix);
972 972
973 return Remain != "" ? __convert_to_type(Remain, Default) : Default; 973 return Remain != "" ? __convert_to_type(Remain, Default) : Default;
974} 974}
975 975
976inline const std::string 976inline const std::string
977GetPot::next(const char* Default) 977GetPot::next(const char* Default)
978{ 978{
979 if( search_failed_f ) return Default; 979 if( search_failed_f ) return Default;
980 cursor++; 980 cursor++;
981 981
982 if( cursor >= argv.size() ) 982 if( cursor >= argv.size() )
983 { cursor = static_cast<unsigned int>(argv.size()); return Default; } 983 { cursor = static_cast<unsigned int>(argv.size()); return Default; }
984 984
985 // (*) record requested argument for later ufo detection 985 // (*) record requested argument for later ufo detection
986 __record_argument_request(argv[cursor]); 986 __record_argument_request(argv[cursor]);
987 987
988 const std::string Remain = __get_remaining_string(argv[cursor], prefix); 988 const std::string Remain = __get_remaining_string(argv[cursor], prefix);
989 989
990 if( Remain == "" ) return Default; 990 if( Remain == "" ) return Default;
991 991
992 992
993 // (*) function returns a pointer to a char array (inside Remain) 993 // (*) function returns a pointer to a char array (inside Remain)
994 // this array will be deleted, though after this function call. 994 // this array will be deleted, though after this function call.
995 // To ensure propper functioning, create a copy inside *this 995 // To ensure propper functioning, create a copy inside *this
996 // object and only delete it, when *this is deleted. 996 // object and only delete it, when *this is deleted.
997 char* result = new char[Remain.length()+1]; 997 char* result = new char[Remain.length()+1];
998 strncpy(result, Remain.c_str(), Remain.length()+1); 998 strncpy(result, Remain.c_str(), Remain.length()+1);
999 999
1000 // store the created string internally, delete if when object deleted 1000 // store the created string internally, delete if when object deleted
1001 __internal_string_container.push_back(result); 1001 __internal_string_container.push_back(result);
1002 1002
1003 return result; 1003 return result;
1004} 1004}
1005 1005
1006// -- follow() function group 1006// -- follow() function group
1007// distinct option to be searched for 1007// distinct option to be searched for
1008inline int 1008inline int
1009GetPot::follow(int Default, const char* Option) 1009GetPot::follow(int Default, const char* Option)
1010{ 1010{
1011 // (*) record requested of argument is entirely handled in 'search()' and 'next()' 1011 // (*) record requested of argument is entirely handled in 'search()' and 'next()'
1012 if( search(Option) == false ) return Default; 1012 if( search(Option) == false ) return Default;
1013 return next(Default); 1013 return next(Default);
1014} 1014}
1015 1015
1016inline double 1016inline double
1017GetPot::follow(const double& Default, const char* Option) 1017GetPot::follow(const double& Default, const char* Option)
1018{ 1018{
1019 // (*) record requested of argument is entirely handled in 'search()' and 'next()' 1019 // (*) record requested of argument is entirely handled in 'search()' and 'next()'
1020 if( search(Option) == false ) return Default; 1020 if( search(Option) == false ) return Default;
1021 return next(Default); 1021 return next(Default);
1022} 1022}
1023 1023
1024inline const std::string 1024inline const std::string
1025GetPot::follow(const char* Default, const char* Option) 1025GetPot::follow(const char* Default, const char* Option)
1026{ 1026{
1027 // (*) record requested of argument is entirely handled in 'search()' and 'next()' 1027 // (*) record requested of argument is entirely handled in 'search()' and 'next()'
1028 if( search(Option) == false ) return Default; 1028 if( search(Option) == false ) return Default;
1029 return next(Default); 1029 return next(Default);
1030} 1030}
1031 1031
1032// -- second follow() function group 1032// -- second follow() function group
1033// multiple option to be searched for 1033// multiple option to be searched for
1034inline int 1034inline int
1035GetPot::follow(int Default, unsigned No, const char* P, ...) 1035GetPot::follow(int Default, unsigned No, const char* P, ...)
1036{ 1036{
1037 // (*) record requested of argument is entirely handled in 'search()' and 'next()' 1037 // (*) record requested of argument is entirely handled in 'search()' and 'next()'
1038 if( No == 0 ) return Default; 1038 if( No == 0 ) return Default;
1039 if( search(P) == true ) return next(Default); 1039 if( search(P) == true ) return next(Default);
1040 1040
1041 va_list ap; 1041 va_list ap;
1042 va_start(ap, P); 1042 va_start(ap, P);
1043 unsigned i=1; 1043 unsigned i=1;
1044 for(; i<No; ++i) { 1044 for(; i<No; ++i) {
1045 char* Opt = va_arg(ap, char *); 1045 char* Opt = va_arg(ap, char *);
1046 if( search(Opt) == true ) { 1046 if( search(Opt) == true ) {
1047 va_end(ap); 1047 va_end(ap);
1048 return next(Default); 1048 return next(Default);
1049 } 1049 }
1050 } 1050 }
1051 va_end(ap); 1051 va_end(ap);
1052 return Default; 1052 return Default;
1053} 1053}
1054 1054
1055inline double 1055inline double
1056GetPot::follow(const double& Default, unsigned No, const char* P, ...) 1056GetPot::follow(const double& Default, unsigned No, const char* P, ...)
1057{ 1057{
1058 // (*) record requested of argument is entirely handled in 'search()' and 'next()' 1058 // (*) record requested of argument is entirely handled in 'search()' and 'next()'
1059 if( No == 0 ) return Default; 1059 if( No == 0 ) return Default;
1060 if( search(P) == true ) return next(Default); 1060 if( search(P) == true ) return next(Default);
1061 1061
1062 va_list ap; 1062 va_list ap;
1063 va_start(ap, P); 1063 va_start(ap, P);
1064 for(unsigned i=1; i<No; ++i) { 1064 for(unsigned i=1; i<No; ++i) {
1065 char* Opt = va_arg(ap, char *); 1065 char* Opt = va_arg(ap, char *);
1066 if( search(Opt) == true ) { 1066 if( search(Opt) == true ) {
1067 va_end(ap); 1067 va_end(ap);
1068 return next(Default); 1068 return next(Default);
1069 } 1069 }
1070 } 1070 }
1071 va_end(ap); 1071 va_end(ap);
1072 return Default; 1072 return Default;
1073} 1073}
1074 1074
1075inline const std::string 1075inline const std::string
1076GetPot::follow(const char* Default, unsigned No, const char* P, ...) 1076GetPot::follow(const char* Default, unsigned No, const char* P, ...)
1077{ 1077{
1078 // (*) record requested of argument is entirely handled in 'search()' and 'next()' 1078 // (*) record requested of argument is entirely handled in 'search()' and 'next()'
1079 if( No == 0 ) return Default; 1079 if( No == 0 ) return Default;
1080 if( search(P) == true ) return next(Default); 1080 if( search(P) == true ) return next(Default);
1081 1081
1082 va_list ap; 1082 va_list ap;
1083 va_start(ap, P); 1083 va_start(ap, P);
1084 unsigned i=1; 1084 unsigned i=1;
1085 for(; i<No; ++i) { 1085 for(; i<No; ++i) {
1086 char* Opt = va_arg(ap, char *); 1086 char* Opt = va_arg(ap, char *);
1087 if( search(Opt) == true ) { 1087 if( search(Opt) == true ) {
1088 va_end(ap); 1088 va_end(ap);
1089 return next(Default); 1089 return next(Default);
1090 } 1090 }
1091 } 1091 }
1092 va_end(ap); 1092 va_end(ap);
1093 return Default; 1093 return Default;
1094} 1094}
1095 1095
1096 1096
1097/////////////////////////////////////////////////////////////////////////////// 1097///////////////////////////////////////////////////////////////////////////////
1098// (*) lists of nominus following an option 1098// (*) lists of nominus following an option
1099//............................................................................. 1099//.............................................................................
1100// 1100//
1101inline std::vector<std::string> 1101inline std::vector<std::string>
1102GetPot::nominus_followers(const char* Option) 1102GetPot::nominus_followers(const char* Option)
1103{ 1103{
1104 std::vector<std::string> result_list; 1104 std::vector<std::string> result_list;
1105 if( search(Option) == false ) return result_list; 1105 if( search(Option) == false ) return result_list;
1106 while( 1 + 1 == 2 ) { 1106 while( 1 + 1 == 2 ) {
1107 ++cursor; 1107 ++cursor;
1108 if( cursor >= argv.size() ) { 1108 if( cursor >= argv.size() ) {
1109 cursor = argv.size() - 1; 1109 cursor = argv.size() - 1;
1110 return result_list; 1110 return result_list;
1111 } 1111 }
1112 if( argv[cursor].length() >= 1 ) { 1112 if( argv[cursor].length() >= 1 ) {
1113 if( argv[cursor][0] == '-' ) { 1113 if( argv[cursor][0] == '-' ) {
1114 return result_list; 1114 return result_list;
1115 } 1115 }
1116 // -- record for later ufo-detection 1116 // -- record for later ufo-detection
1117 __record_argument_request(argv[cursor]); 1117 __record_argument_request(argv[cursor]);
1118 // -- append to the result list 1118 // -- append to the result list
1119 result_list.push_back(argv[cursor]); 1119 result_list.push_back(argv[cursor]);
1120 } 1120 }
1121 } 1121 }
1122} 1122}
1123 1123
1124inline std::vector<std::string> 1124inline std::vector<std::string>
1125GetPot::nominus_followers(unsigned No, ...) 1125GetPot::nominus_followers(unsigned No, ...)
1126{ 1126{
1127 std::vector<std::string> result_list; 1127 std::vector<std::string> result_list;
1128 // (*) record requested of argument is entirely handled in 'search()' 1128 // (*) record requested of argument is entirely handled in 'search()'
1129 // and 'nominus_followers()' 1129 // and 'nominus_followers()'
1130 if( No == 0 ) return result_list; 1130 if( No == 0 ) return result_list;
1131 1131
1132 va_list ap; 1132 va_list ap;
1133 va_start(ap, No); 1133 va_start(ap, No);
1134 for(unsigned i=0; i<No; ++i) { 1134 for(unsigned i=0; i<No; ++i) {
1135 char* Option = va_arg(ap, char *); 1135 char* Option = va_arg(ap, char *);
1136 std::vector<std::string> tmp = nominus_followers(Option); 1136 std::vector<std::string> tmp = nominus_followers(Option);
1137 result_list.insert(result_list.end(), tmp.begin(), tmp.end()); 1137 result_list.insert(result_list.end(), tmp.begin(), tmp.end());
1138 1138
1139 // std::cerr << "option = '" << Option << "'" << std::endl; 1139 // std::cerr << "option = '" << Option << "'" << std::endl;
1140 // std::cerr << "length = " << tmp.size() << std::endl; 1140 // std::cerr << "length = " << tmp.size() << std::endl;
1141 // std::cerr << "new result list = <"; 1141 // std::cerr << "new result list = <";
1142 // for(std::vector<std::string>::const_iterator it = result_list.begin(); 1142 // for(std::vector<std::string>::const_iterator it = result_list.begin();
1143 // it != result_list.end(); ++it) 1143 // it != result_list.end(); ++it)
1144 // std::cerr << *it << ", "; 1144 // std::cerr << *it << ", ";
1145 // std::cerr << ">\n"; 1145 // std::cerr << ">\n";
1146 } 1146 }
1147 va_end(ap); 1147 va_end(ap);
1148 return result_list; 1148 return result_list;
1149} 1149}
1150 1150
1151 1151
1152/////////////////////////////////////////////////////////////////////////////// 1152///////////////////////////////////////////////////////////////////////////////
1153// (*) directly connected options 1153// (*) directly connected options
1154//............................................................................. 1154//.............................................................................
1155// 1155//
1156inline int 1156inline int
1157GetPot::direct_follow(int Default, const char* Option) 1157GetPot::direct_follow(int Default, const char* Option)
1158{ 1158{
1159 const char* FollowStr = __match_starting_string(Option); 1159 const char* FollowStr = __match_starting_string(Option);
1160 if( FollowStr == 0x0 ) return Default; 1160 if( FollowStr == 0x0 ) return Default;
1161 1161
1162 // (*) record requested of argument for later ufo-detection 1162 // (*) record requested of argument for later ufo-detection
1163 __record_argument_request(std::string(Option) + FollowStr); 1163 __record_argument_request(std::string(Option) + FollowStr);
1164 1164
1165 if( ++cursor >= static_cast<unsigned int>(argv.size()) ) cursor = static_cast<unsigned int>(argv.size()); 1165 if( ++cursor >= static_cast<unsigned int>(argv.size()) ) cursor = static_cast<unsigned int>(argv.size());
1166 return __convert_to_type(FollowStr, Default); 1166 return __convert_to_type(FollowStr, Default);
1167} 1167}
1168 1168
1169inline double 1169inline double
1170GetPot::direct_follow(const double& Default, const char* Option) 1170GetPot::direct_follow(const double& Default, const char* Option)
1171{ 1171{
1172 const char* FollowStr = __match_starting_string(Option); 1172 const char* FollowStr = __match_starting_string(Option);
1173 if( FollowStr == 0 ) return Default; 1173 if( FollowStr == 0 ) return Default;
1174 1174
1175 // (*) record requested of argument for later ufo-detection 1175 // (*) record requested of argument for later ufo-detection
1176 __record_argument_request(std::string(Option) + FollowStr); 1176 __record_argument_request(std::string(Option) + FollowStr);
1177 1177
1178 if( ++cursor >= static_cast<unsigned int>(argv.size()) ) cursor = static_cast<unsigned int>(argv.size()); 1178 if( ++cursor >= static_cast<unsigned int>(argv.size()) ) cursor = static_cast<unsigned int>(argv.size());
1179 return __convert_to_type(FollowStr, Default); 1179 return __convert_to_type(FollowStr, Default);
1180} 1180}
1181 1181
1182inline const std::string 1182inline const std::string
1183GetPot::direct_follow(const char* Default, const char* Option) 1183GetPot::direct_follow(const char* Default, const char* Option)
1184{ 1184{
1185 if( search_failed_f ) return Default; 1185 if( search_failed_f ) return Default;
1186 const char* FollowStr = __match_starting_string(Option); 1186 const char* FollowStr = __match_starting_string(Option);
1187 if( FollowStr == 0 ) return Default; 1187 if( FollowStr == 0 ) return Default;
1188 1188
1189 // (*) record requested of argument for later ufo-detection 1189 // (*) record requested of argument for later ufo-detection
1190 if( FollowStr ) __record_argument_request(std::string(Option) + FollowStr); 1190 if( FollowStr ) __record_argument_request(std::string(Option) + FollowStr);
1191 1191
1192 if( ++cursor >= static_cast<unsigned int>(argv.size()) ) cursor = static_cast<unsigned int>(argv.size()); 1192 if( ++cursor >= static_cast<unsigned int>(argv.size()) ) cursor = static_cast<unsigned int>(argv.size());
1193 return std::string(FollowStr); 1193 return std::string(FollowStr);
1194} 1194}
1195 1195
1196inline std::vector<std::string> 1196inline std::vector<std::string>
1197GetPot::string_tails(const char* StartString) 1197GetPot::string_tails(const char* StartString)
1198{ 1198{
1199 std::vector<std::string> result; 1199 std::vector<std::string> result;
1200 const unsigned N = static_cast<unsigned int>(strlen(StartString)); 1200 const unsigned N = static_cast<unsigned int>(strlen(StartString));
1201 1201
1202 std::vector<std::string>::iterator it = argv.begin(); 1202 std::vector<std::string>::iterator it = argv.begin();
1203 1203
1204 unsigned idx = 0; 1204 unsigned idx = 0;
1205 while( it != argv.end() ) { 1205 while( it != argv.end() ) {
1206 // (*) does start string match the given option? 1206 // (*) does start string match the given option?
1207 // NO -> goto next option 1207 // NO -> goto next option
1208 if( strncmp(StartString, (*it).c_str(), N) != 0) { ++it; ++idx; continue; } 1208 if( strncmp(StartString, (*it).c_str(), N) != 0) { ++it; ++idx; continue; }
1209 1209
1210 // append the found tail to the result vector 1210 // append the found tail to the result vector
1211 result.push_back((*it).substr(N)); 1211 result.push_back((*it).substr(N));
1212 1212
1213 // adapt the nominus vector 1213 // adapt the nominus vector
1214 std::vector<unsigned>::iterator nit = idx_nominus.begin(); 1214 std::vector<unsigned>::iterator nit = idx_nominus.begin();
1215 for(; nit != idx_nominus.end(); ++nit) { 1215 for(; nit != idx_nominus.end(); ++nit) {
1216 if( *nit == idx ) { 1216 if( *nit == idx ) {
1217 idx_nominus.erase(nit); 1217 idx_nominus.erase(nit);
1218 for(; nit != idx_nominus.end(); ++nit) *nit -= 1; 1218 for(; nit != idx_nominus.end(); ++nit) *nit -= 1;
1219 break; 1219 break;
1220 } 1220 }
1221 } 1221 }
1222 1222
1223 // erase the found option 1223 // erase the found option
1224 argv.erase(it); 1224 argv.erase(it);
1225 1225
1226 // 100% safe solution: set iterator back to the beginning. 1226 // 100% safe solution: set iterator back to the beginning.
1227 // (normally, 'it--' would be enough, but who knows how the 1227 // (normally, 'it--' would be enough, but who knows how the
1228 // iterator is implemented and .erase() definitely invalidates 1228 // iterator is implemented and .erase() definitely invalidates
1229 // the current iterator position. 1229 // the current iterator position.
1230 if( argv.empty() ) break; 1230 if( argv.empty() ) break;
1231 it = argv.begin(); 1231 it = argv.begin();
1232 } 1232 }
1233 cursor = 0; 1233 cursor = 0;
1234 nominus_cursor = -1; 1234 nominus_cursor = -1;
1235 return result; 1235 return result;
1236} 1236}
1237 1237
1238inline std::vector<int> 1238inline std::vector<int>
1239GetPot::int_tails(const char* StartString, const int Default /* = -1 */) 1239GetPot::int_tails(const char* StartString, const int Default /* = -1 */)
1240{ 1240{
1241 std::vector<int> result; 1241 std::vector<int> result;
1242 const unsigned N = static_cast<unsigned int>(strlen(StartString)); 1242 const unsigned N = static_cast<unsigned int>(strlen(StartString));
1243 1243
1244 std::vector<std::string>::iterator it = argv.begin(); 1244 std::vector<std::string>::iterator it = argv.begin();
1245 1245
1246 unsigned idx = 0; 1246 unsigned idx = 0;
1247 while( it != argv.end() ) { 1247 while( it != argv.end() ) {
1248 // (*) does start string match the given option? 1248 // (*) does start string match the given option?
1249 // NO -> goto next option 1249 // NO -> goto next option
1250 if( strncmp(StartString, (*it).c_str(), N) != 0) { ++it; ++idx; continue; } 1250 if( strncmp(StartString, (*it).c_str(), N) != 0) { ++it; ++idx; continue; }
1251 1251
1252 // append the found tail to the result vector 1252 // append the found tail to the result vector
1253 result.push_back(__convert_to_type((*it).substr(N), Default)); 1253 result.push_back(__convert_to_type((*it).substr(N), Default));
1254 1254
1255 // adapt the nominus vector 1255 // adapt the nominus vector
1256 std::vector<unsigned>::iterator nit = idx_nominus.begin(); 1256 std::vector<unsigned>::iterator nit = idx_nominus.begin();
1257 for(; nit != idx_nominus.end(); ++nit) { 1257 for(; nit != idx_nominus.end(); ++nit) {
1258 if( *nit == idx ) { 1258 if( *nit == idx ) {
1259 idx_nominus.erase(nit); 1259 idx_nominus.erase(nit);
1260 for(; nit != idx_nominus.end(); ++nit) *nit -= 1; 1260 for(; nit != idx_nominus.end(); ++nit) *nit -= 1;
1261 break; 1261 break;
1262 } 1262 }
1263 } 1263 }
1264 1264
1265 // erase the found option 1265 // erase the found option
1266 argv.erase(it); 1266 argv.erase(it);
1267 1267
1268 // 100% safe solution: set iterator back to the beginning. 1268 // 100% safe solution: set iterator back to the beginning.
1269 // (normally, 'it--' would be enough, but who knows how the 1269 // (normally, 'it--' would be enough, but who knows how the
1270 // iterator is implemented and .erase() definitely invalidates 1270 // iterator is implemented and .erase() definitely invalidates
1271 // the current iterator position. 1271 // the current iterator position.
1272 if( argv.empty() ) break; 1272 if( argv.empty() ) break;
1273 it = argv.begin(); 1273 it = argv.begin();
1274 } 1274 }
1275 cursor = 0; 1275 cursor = 0;
1276 nominus_cursor = -1; 1276 nominus_cursor = -1;
1277 return result; 1277 return result;
1278} 1278}
1279 1279
1280inline std::vector<double> 1280inline std::vector<double>
1281GetPot::double_tails(const char* StartString, 1281GetPot::double_tails(const char* StartString,
1282 const double Default /* = -1.0 */) 1282 const double Default /* = -1.0 */)
1283{ 1283{
1284 std::vector<double> result; 1284 std::vector<double> result;
1285 const unsigned N = static_cast<unsigned int>(strlen(StartString)); 1285 const unsigned N = static_cast<unsigned int>(strlen(StartString));
1286 1286
1287 std::vector<std::string>::iterator it = argv.begin(); 1287 std::vector<std::string>::iterator it = argv.begin();
1288 unsigned idx = 0; 1288 unsigned idx = 0;
1289 while( it != argv.end() ) { 1289 while( it != argv.end() ) {
1290 // (*) does start string match the given option? 1290 // (*) does start string match the given option?
1291 // NO -> goto next option 1291 // NO -> goto next option
1292 if( strncmp(StartString, (*it).c_str(), N) != 0) { ++it; ++idx; continue; } 1292 if( strncmp(StartString, (*it).c_str(), N) != 0) { ++it; ++idx; continue; }
1293 1293
1294 // append the found tail to the result vector 1294 // append the found tail to the result vector
1295 result.push_back(__convert_to_type((*it).substr(N), Default)); 1295 result.push_back(__convert_to_type((*it).substr(N), Default));
1296 1296
1297 // adapt the nominus vector 1297 // adapt the nominus vector
1298 std::vector<unsigned>::iterator nit = idx_nominus.begin(); 1298 std::vector<unsigned>::iterator nit = idx_nominus.begin();
1299 for(; nit != idx_nominus.end(); ++nit) { 1299 for(; nit != idx_nominus.end(); ++nit) {
1300 if( *nit == idx ) { 1300 if( *nit == idx ) {
1301 idx_nominus.erase(nit); 1301 idx_nominus.erase(nit);
1302 for(; nit != idx_nominus.end(); ++nit) *nit -= 1; 1302 for(; nit != idx_nominus.end(); ++nit) *nit -= 1;
1303 break; 1303 break;
1304 } 1304 }
1305 } 1305 }
1306 1306
1307 // erase the found option 1307 // erase the found option
1308 argv.erase(it); 1308 argv.erase(it);
1309 1309
1310 // 100% safe solution: set iterator back to the beginning. 1310 // 100% safe solution: set iterator back to the beginning.
1311 // (normally, 'it--' would be enough, but who knows how the 1311 // (normally, 'it--' would be enough, but who knows how the
1312 // iterator is implemented and .erase() definitely invalidates 1312 // iterator is implemented and .erase() definitely invalidates
1313 // the current iterator position. 1313 // the current iterator position.
1314 if( argv.empty() ) break; 1314 if( argv.empty() ) break;
1315 it = argv.begin(); 1315 it = argv.begin();
1316 } 1316 }
1317 cursor = 0; 1317 cursor = 0;
1318 nominus_cursor = -1; 1318 nominus_cursor = -1;
1319 return result; 1319 return result;
1320} 1320}
1321 1321
1322 1322
1323 1323
1324 1324
1325 1325
1326inline const char* 1326inline const char*
1327GetPot::__match_starting_string(const char* StartString) 1327GetPot::__match_starting_string(const char* StartString)
1328 // pointer to the place where the string after 1328 // pointer to the place where the string after
1329 // the match inside the found argument starts. 1329 // the match inside the found argument starts.
1330 // 0 no argument matches the starting string. 1330 // 0 no argument matches the starting string.
1331{ 1331{
1332 const unsigned N = static_cast<unsigned int>(strlen(StartString)); 1332 const unsigned N = static_cast<unsigned int>(strlen(StartString));
1333 unsigned OldCursor = cursor; 1333 unsigned OldCursor = cursor;
1334 1334
1335 if( OldCursor >= static_cast<unsigned int>(argv.size()) ) OldCursor = static_cast<unsigned int>(argv.size()) - 1; 1335 if( OldCursor >= static_cast<unsigned int>(argv.size()) ) OldCursor = static_cast<unsigned int>(argv.size()) - 1;
1336 search_failed_f = true; 1336 search_failed_f = true;
1337 1337
1338 // (*) first loop from cursor position until end 1338 // (*) first loop from cursor position until end
1339 unsigned c = cursor; 1339 unsigned c = cursor;
1340 for(; c < argv.size(); c++) { 1340 for(; c < argv.size(); c++) {
1341 if( strncmp(StartString, argv[c].c_str(), N) == 0) 1341 if( strncmp(StartString, argv[c].c_str(), N) == 0)
1342 { cursor = c; search_failed_f = false; return &(argv[c].c_str()[N]); } 1342 { cursor = c; search_failed_f = false; return &(argv[c].c_str()[N]); }
1343 } 1343 }
1344 1344
1345 if( ! search_loop_f ) return false; 1345 if( ! search_loop_f ) return false;
1346 1346
1347 // (*) second loop from 0 to old cursor position 1347 // (*) second loop from 0 to old cursor position
1348 for(c = 1; c < OldCursor; c++) { 1348 for(c = 1; c < OldCursor; c++) {
1349 if( strncmp(StartString, argv[c].c_str(), N) == 0) 1349 if( strncmp(StartString, argv[c].c_str(), N) == 0)
1350 { cursor = c; search_failed_f = false; return &(argv[c].c_str()[N]); } 1350 { cursor = c; search_failed_f = false; return &(argv[c].c_str()[N]); }
1351 } 1351 }
1352 return 0; 1352 return 0;
1353} 1353}
1354 1354
1355/////////////////////////////////////////////////////////////////////////////// 1355///////////////////////////////////////////////////////////////////////////////
1356// (*) search for flags 1356// (*) search for flags
1357//............................................................................. 1357//.............................................................................
1358// 1358//
1359inline bool 1359inline bool
1360GetPot::options_contain(const char* FlagList) const 1360GetPot::options_contain(const char* FlagList) const
1361{ 1361{
1362 // go through all arguments that start with a '-' (but not '--') 1362 // go through all arguments that start with a '-' (but not '--')
1363 std::string str; 1363 std::string str;
1364 STRING_VECTOR::const_iterator it = argv.begin(); 1364 STRING_VECTOR::const_iterator it = argv.begin();
1365 for(; it != argv.end(); ++it) { 1365 for(; it != argv.end(); ++it) {
1366 str = __get_remaining_string(*it, prefix); 1366 str = __get_remaining_string(*it, prefix);
1367 1367
1368 if( str.length() >= 2 && str[0] == '-' && str[1] != '-' ) 1368 if( str.length() >= 2 && str[0] == '-' && str[1] != '-' )
1369 if( __check_flags(str, FlagList) ) return true; 1369 if( __check_flags(str, FlagList) ) return true;
1370 } 1370 }
1371 return false; 1371 return false;
1372} 1372}
1373 1373
1374inline bool 1374inline bool
1375GetPot::argument_contains(unsigned Idx, const char* FlagList) const 1375GetPot::argument_contains(unsigned Idx, const char* FlagList) const
1376{ 1376{
1377 if( Idx >= argv.size() ) return false; 1377 if( Idx >= argv.size() ) return false;
1378 1378
1379 // (*) record requested of argument for later ufo-detection 1379 // (*) record requested of argument for later ufo-detection
1380 // an argument that is checked for flags is considered to be 'requested' 1380 // an argument that is checked for flags is considered to be 'requested'
1381 ((GetPot*)this)->__record_argument_request(argv[Idx]); 1381 ((GetPot*)this)->__record_argument_request(argv[Idx]);
1382 1382
1383 if( prefix == "" ) 1383 if( prefix == "" )
1384 // search argument for any flag in flag list 1384 // search argument for any flag in flag list
1385 return __check_flags(argv[Idx], FlagList); 1385 return __check_flags(argv[Idx], FlagList);
1386 1386
1387 // if a prefix is set, then the argument index is the index 1387 // if a prefix is set, then the argument index is the index
1388 // inside the 'namespace' 1388 // inside the 'namespace'
1389 // => only check list of arguments that start with prefix 1389 // => only check list of arguments that start with prefix
1390 unsigned no_matches = 0; 1390 unsigned no_matches = 0;
1391 unsigned i=0; 1391 unsigned i=0;
1392 for(; i<argv.size(); ++i) { 1392 for(; i<argv.size(); ++i) {
1393 const std::string Remain = __get_remaining_string(argv[i], prefix); 1393 const std::string Remain = __get_remaining_string(argv[i], prefix);
1394 if( Remain != "") { 1394 if( Remain != "") {
1395 no_matches += 1; 1395 no_matches += 1;
1396 if( no_matches == Idx) 1396 if( no_matches == Idx)
1397 return __check_flags(Remain, FlagList); 1397 return __check_flags(Remain, FlagList);
1398 } 1398 }
1399 } 1399 }
1400 // no argument in this namespace 1400 // no argument in this namespace
1401 return false; 1401 return false;
1402} 1402}
1403 1403
1404inline bool 1404inline bool
1405GetPot::__check_flags(const std::string& Str, const char* FlagList) const 1405GetPot::__check_flags(const std::string& Str, const char* FlagList) const
1406{ 1406{
1407 const char* p=FlagList; 1407 const char* p=FlagList;
1408 for(; *p != '\0' ; p++) 1408 for(; *p != '\0' ; p++)
1409 if( Str.find(*p) != std::string::npos ) return true; // found something 1409 if( Str.find(*p) != std::string::npos ) return true; // found something
1410 return false; 1410 return false;
1411} 1411}
1412 1412
1413/////////////////////////////////////////////////////////////////////////////// 1413///////////////////////////////////////////////////////////////////////////////
1414// (*) nominus arguments 1414// (*) nominus arguments
1415inline STRING_VECTOR 1415inline STRING_VECTOR
1416GetPot::nominus_vector() const 1416GetPot::nominus_vector() const
1417 // return vector of nominus arguments 1417 // return vector of nominus arguments
1418{ 1418{
1419 STRING_VECTOR nv; 1419 STRING_VECTOR nv;
1420 std::vector<unsigned>::const_iterator it = idx_nominus.begin(); 1420 std::vector<unsigned>::const_iterator it = idx_nominus.begin();
1421 for(; it != idx_nominus.end(); ++it) { 1421 for(; it != idx_nominus.end(); ++it) {
1422 nv.push_back(argv[*it]); 1422 nv.push_back(argv[*it]);
1423 1423
1424 // (*) record for later ufo-detection 1424 // (*) record for later ufo-detection
1425 // when a nominus vector is requested, the entire set of nominus arguments are 1425 // when a nominus vector is requested, the entire set of nominus arguments are
1426 // tagged as 'requested' 1426 // tagged as 'requested'
1427 ((GetPot*)this)->__record_argument_request(argv[*it]); 1427 ((GetPot*)this)->__record_argument_request(argv[*it]);
1428 } 1428 }
1429 return nv; 1429 return nv;
1430} 1430}
1431 1431
1432inline std::string 1432inline std::string
1433GetPot::next_nominus() 1433GetPot::next_nominus()
1434{ 1434{
1435 if( nominus_cursor < int(idx_nominus.size()) - 1 ) { 1435 if( nominus_cursor < int(idx_nominus.size()) - 1 ) {
1436 const std::string Tmp = argv[idx_nominus[++nominus_cursor]]; 1436 const std::string Tmp = argv[idx_nominus[++nominus_cursor]];
1437 1437
1438 // (*) record for later ufo-detection 1438 // (*) record for later ufo-detection
1439 __record_argument_request(Tmp); 1439 __record_argument_request(Tmp);
1440 1440
1441 // -- cannot use the Tmp variable, since it is temporary and c_str() will return a pointer 1441 // -- cannot use the Tmp variable, since it is temporary and c_str() will return a pointer
1442 // to something that does no longer exist. 1442 // to something that does no longer exist.
1443 return Tmp; 1443 return Tmp;
1444 } 1444 }
1445 return std::string(""); 1445 return std::string("");
1446} 1446}
1447 1447
1448/////////////////////////////////////////////////////////////////////////////// 1448///////////////////////////////////////////////////////////////////////////////
1449// (*) variables 1449// (*) variables
1450//............................................................................. 1450//.............................................................................
1451// 1451//
1452inline int 1452inline int
1453GetPot::operator()(const char* VarName, int Default) const 1453GetPot::operator()(const char* VarName, int Default) const
1454{ 1454{
1455 // (*) recording of requested variables happens in '__find_variable()' 1455 // (*) recording of requested variables happens in '__find_variable()'
1456 const variable* sv = __find_variable(VarName); 1456 const variable* sv = __find_variable(VarName);
1457 if( sv == 0 ) return Default; 1457 if( sv == 0 ) return Default;
1458 return __convert_to_type(sv->original, Default); 1458 return __convert_to_type(sv->original, Default);
1459} 1459}
1460 1460
1461inline double 1461inline double
1462GetPot::operator()(const char* VarName, const double& Default) const 1462GetPot::operator()(const char* VarName, const double& Default) const
1463{ 1463{
1464 // (*) recording of requested variables happens in '__find_variable()' 1464 // (*) recording of requested variables happens in '__find_variable()'
1465 const variable* sv = __find_variable(VarName); 1465 const variable* sv = __find_variable(VarName);
1466 if( sv == 0 ) return Default; 1466 if( sv == 0 ) return Default;
1467 return __convert_to_type(sv->original, Default); 1467 return __convert_to_type(sv->original, Default);
1468} 1468}
1469 1469
1470inline const std::string 1470inline const std::string
1471GetPot::operator()(const char* VarName, const char* Default) const 1471GetPot::operator()(const char* VarName, const char* Default) const
1472{ 1472{
1473 // (*) recording of requested variables happens in '__find_variable()' 1473 // (*) recording of requested variables happens in '__find_variable()'
1474 const variable* sv = __find_variable(VarName); 1474 const variable* sv = __find_variable(VarName);
1475 if( sv == 0 ) return Default; 1475 if( sv == 0 ) return Default;
1476 // -- returning a c_str() pointer is OK here, since the variable remains existant, 1476 // -- returning a c_str() pointer is OK here, since the variable remains existant,
1477 // while 'sv' of course is delete at the end of the function. 1477 // while 'sv' of course is delete at the end of the function.
1478 return sv->original; 1478 return sv->original;
1479} 1479}
1480 1480
1481inline int 1481inline int
1482GetPot::operator()(const char* VarName, int Default, unsigned Idx) const 1482GetPot::operator()(const char* VarName, int Default, unsigned Idx) const
1483{ 1483{
1484 // (*) recording of requested variables happens in '__find_variable()' 1484 // (*) recording of requested variables happens in '__find_variable()'
1485 const variable* sv = __find_variable(VarName); 1485 const variable* sv = __find_variable(VarName);
1486 if( sv == 0 ) return Default; 1486 if( sv == 0 ) return Default;
1487 const std::string* element = sv->get_element(Idx); 1487 const std::string* element = sv->get_element(Idx);
1488 if( element == 0 ) return Default; 1488 if( element == 0 ) return Default;
1489 return __convert_to_type(*element, Default); 1489 return __convert_to_type(*element, Default);
1490} 1490}
1491 1491
1492inline double 1492inline double
1493GetPot::operator()(const char* VarName, const double& Default, unsigned Idx) const 1493GetPot::operator()(const char* VarName, const double& Default, unsigned Idx) const
1494{ 1494{
1495 // (*) recording of requested variables happens in '__find_variable()' 1495 // (*) recording of requested variables happens in '__find_variable()'
1496 const variable* sv = __find_variable(VarName); 1496 const variable* sv = __find_variable(VarName);
1497 if( sv == 0 ) return Default; 1497 if( sv == 0 ) return Default;
1498 const std::string* element = sv->get_element(Idx); 1498 const std::string* element = sv->get_element(Idx);
1499 if( element == 0 ) return Default; 1499 if( element == 0 ) return Default;
1500 return __convert_to_type(*element, Default); 1500 return __convert_to_type(*element, Default);
1501} 1501}
1502 1502
1503inline const std::string 1503inline const std::string
1504GetPot::operator()(const char* VarName, const char* Default, unsigned Idx) const 1504GetPot::operator()(const char* VarName, const char* Default, unsigned Idx) const
1505{ 1505{
1506 // (*) recording of requested variables happens in '__find_variable()' 1506 // (*) recording of requested variables happens in '__find_variable()'
1507 const variable* sv = __find_variable(VarName); 1507 const variable* sv = __find_variable(VarName);
1508 if( sv == 0 ) return Default; 1508 if( sv == 0 ) return Default;
1509 const std::string* element = sv->get_element(Idx); 1509 const std::string* element = sv->get_element(Idx);
1510 if( element == 0 ) return Default; 1510 if( element == 0 ) return Default;
1511 return *element; 1511 return *element;
1512} 1512}
1513 1513
1514inline void 1514inline void
1515GetPot::__record_argument_request(const std::string& Name) 1515GetPot::__record_argument_request(const std::string& Name)
1516{ 1516{
1517 if( ! __request_recording_f ) return; 1517 if( ! __request_recording_f ) return;
1518 1518
1519 // (*) record requested variable for later ufo detection 1519 // (*) record requested variable for later ufo detection
1520 _requested_arguments.push_back(Name); 1520 _requested_arguments.push_back(Name);
1521 1521
1522 // (*) record considered section for ufo detection 1522 // (*) record considered section for ufo detection
1523 STRING_VECTOR STree = __get_section_tree(Name); 1523 STRING_VECTOR STree = __get_section_tree(Name);
1524 victorate(std::string, STree, it) 1524 victorate(std::string, STree, it)
1525 if( find(_requested_sections.begin(), _requested_sections.end(), *it) == _requested_sections.end() ) 1525 if( find(_requested_sections.begin(), _requested_sections.end(), *it) == _requested_sections.end() )
1526 if( section.length() != 0 ) _requested_sections.push_back(*it); 1526 if( section.length() != 0 ) _requested_sections.push_back(*it);
1527} 1527}
1528 1528
1529inline void 1529inline void
1530GetPot::__record_variable_request(const std::string& Name) 1530GetPot::__record_variable_request(const std::string& Name)
1531{ 1531{
1532 if( ! __request_recording_f ) return; 1532 if( ! __request_recording_f ) return;
1533 1533
1534 // (*) record requested variable for later ufo detection 1534 // (*) record requested variable for later ufo detection
1535 _requested_variables.push_back(Name); 1535 _requested_variables.push_back(Name);
1536 1536
1537 // (*) record considered section for ufo detection 1537 // (*) record considered section for ufo detection
1538 STRING_VECTOR STree = __get_section_tree(Name); 1538 STRING_VECTOR STree = __get_section_tree(Name);
1539 victorate(std::string, STree, it) 1539 victorate(std::string, STree, it)
1540 if( find(_requested_sections.begin(), _requested_sections.end(), *it) == _requested_sections.end() ) 1540 if( find(_requested_sections.begin(), _requested_sections.end(), *it) == _requested_sections.end() )
1541 if( section.length() != 0 ) _requested_sections.push_back(*it); 1541 if( section.length() != 0 ) _requested_sections.push_back(*it);
1542} 1542}
1543 1543
1544// (*) following functions are to be used from 'outside', after getpot has parsed its 1544// (*) following functions are to be used from 'outside', after getpot has parsed its
1545// arguments => append an argument in the argument vector that reflects the addition 1545// arguments => append an argument in the argument vector that reflects the addition
1546inline void 1546inline void
1547GetPot::__set_variable(const char* VarName, const char* Value) 1547GetPot::__set_variable(const char* VarName, const char* Value)
1548{ 1548{
1549 const GetPot::variable* Var = __find_variable(VarName); 1549 const GetPot::variable* Var = __find_variable(VarName);
1550 if( Var == 0 ) variables.push_back(variable(VarName, Value, _field_separator.c_str())); 1550 if( Var == 0 ) variables.push_back(variable(VarName, Value, _field_separator.c_str()));
1551 else ((GetPot::variable*)Var)->take(Value, _field_separator.c_str()); 1551 else ((GetPot::variable*)Var)->take(Value, _field_separator.c_str());
1552} 1552}
1553 1553
1554inline void 1554inline void
1555GetPot::set(const char* VarName, const char* Value, const bool Requested /* = yes */) 1555GetPot::set(const char* VarName, const char* Value, const bool Requested /* = yes */)
1556{ 1556{
1557 const std::string Arg = prefix + std::string(VarName) + std::string("=") + std::string(Value); 1557 const std::string Arg = prefix + std::string(VarName) + std::string("=") + std::string(Value);
1558 argv.push_back(Arg); 1558 argv.push_back(Arg);
1559 __set_variable(VarName, Value); 1559 __set_variable(VarName, Value);
1560 1560
1561 // if user does not specify the variable as 'not being requested' it will be 1561 // if user does not specify the variable as 'not being requested' it will be
1562 // considered amongst the requested variables 1562 // considered amongst the requested variables
1563 if( Requested ) __record_variable_request(Arg); 1563 if( Requested ) __record_variable_request(Arg);
1564} 1564}
1565 1565
1566inline void 1566inline void
1567GetPot::set(const char* VarName, const double& Value, const bool Requested /* = yes */) 1567GetPot::set(const char* VarName, const double& Value, const bool Requested /* = yes */)
1568{ __set_variable(VarName, __double2string(Value).c_str()); } 1568{ __set_variable(VarName, __double2string(Value).c_str()); }
1569 1569
1570inline void 1570inline void
1571GetPot::set(const char* VarName, const int Value, const bool Requested /* = yes */) 1571GetPot::set(const char* VarName, const int Value, const bool Requested /* = yes */)
1572{ __set_variable(VarName, __int2string(Value).c_str()); } 1572{ __set_variable(VarName, __int2string(Value).c_str()); }
1573 1573
1574 1574
1575inline unsigned 1575inline unsigned
1576GetPot::vector_variable_size(const char* VarName) const 1576GetPot::vector_variable_size(const char* VarName) const
1577{ 1577{
1578 const variable* sv = __find_variable(VarName); 1578 const variable* sv = __find_variable(VarName);
1579 if( sv == 0 ) return 0; 1579 if( sv == 0 ) return 0;
1580 return static_cast<unsigned int>(sv->value.size()); 1580 return static_cast<unsigned int>(sv->value.size());
1581} 1581}
1582 1582
1583inline STRING_VECTOR 1583inline STRING_VECTOR
1584GetPot::get_variable_names() const 1584GetPot::get_variable_names() const
1585{ 1585{
1586 STRING_VECTOR result; 1586 STRING_VECTOR result;
1587 std::vector<GetPot::variable>::const_iterator it = variables.begin(); 1587 std::vector<GetPot::variable>::const_iterator it = variables.begin();
1588 for(; it != variables.end(); ++it) { 1588 for(; it != variables.end(); ++it) {
1589 const std::string Tmp = __get_remaining_string((*it).name, prefix); 1589 const std::string Tmp = __get_remaining_string((*it).name, prefix);
1590 if( Tmp != "" ) result.push_back(Tmp); 1590 if( Tmp != "" ) result.push_back(Tmp);
1591 } 1591 }
1592 return result; 1592 return result;
1593} 1593}
1594 1594
1595inline STRING_VECTOR 1595inline STRING_VECTOR
1596GetPot::get_section_names() const 1596GetPot::get_section_names() const
1597{ return section_list; } 1597{ return section_list; }
1598 1598
1599inline const GetPot::variable* 1599inline const GetPot::variable*
1600GetPot::__find_variable(const char* VarName) const 1600GetPot::__find_variable(const char* VarName) const
1601{ 1601{
1602 const std::string Name = prefix + VarName; 1602 const std::string Name = prefix + VarName;
1603 1603
1604 // (*) record requested variable for later ufo detection 1604 // (*) record requested variable for later ufo detection
1605 ((GetPot*)this)->__record_variable_request(Name); 1605 ((GetPot*)this)->__record_variable_request(Name);
1606 1606
1607 std::vector<variable>::const_iterator it = variables.begin(); 1607 std::vector<variable>::const_iterator it = variables.begin();
1608 for(; it != variables.end(); ++it) { 1608 for(; it != variables.end(); ++it) {
1609 if( (*it).name == Name ) return &(*it); 1609 if( (*it).name == Name ) return &(*it);
1610 } 1610 }
1611 return 0; 1611 return 0;
1612} 1612}
1613 1613
1614/////////////////////////////////////////////////////////////////////////////// 1614///////////////////////////////////////////////////////////////////////////////
1615// (*) ouput (basically for debugging reasons 1615// (*) ouput (basically for debugging reasons
1616//............................................................................. 1616//.............................................................................
1617// 1617//
1618inline int 1618inline int
1619GetPot::print() const 1619GetPot::print() const
1620{ 1620{
1621 std::cout << "argc = " << static_cast<unsigned int>(argv.size()) << std::endl; 1621 std::cout << "argc = " << static_cast<unsigned int>(argv.size()) << std::endl;
1622 STRING_VECTOR::const_iterator it = argv.begin(); 1622 STRING_VECTOR::const_iterator it = argv.begin();
1623 for(; it != argv.end(); ++it) 1623 for(; it != argv.end(); ++it)
1624 std::cout << *it << std::endl; 1624 std::cout << *it << std::endl;
1625 std::cout << std::endl; 1625 std::cout << std::endl;
1626 return 1; 1626 return 1;
1627} 1627}
1628 1628
1629// (*) dollar bracket expressions (DBEs) ------------------------------------ 1629// (*) dollar bracket expressions (DBEs) ------------------------------------
1630// 1630//
1631// 1) Entry Function: __DBE_expand_string() 1631// 1) Entry Function: __DBE_expand_string()
1632// Takes a string such as 1632// Takes a string such as
1633// 1633//
1634// "${+ ${x} ${y}} Subject-${& ${section} ${subsection}}: ${title}" 1634// "${+ ${x} ${y}} Subject-${& ${section} ${subsection}}: ${title}"
1635// 1635//
1636// calls __DBE_expand() for each of the expressions 1636// calls __DBE_expand() for each of the expressions
1637// 1637//
1638// ${+ ${x} ${y}} 1638// ${+ ${x} ${y}}
1639// ${& ${section} ${subsection}} 1639// ${& ${section} ${subsection}}
1640// ${Title} 1640// ${Title}
1641// 1641//
1642// and returns the string 1642// and returns the string
1643// 1643//
1644// "4711 Subject-1.01: Mit den Clowns kamen die Schwaene" 1644// "4711 Subject-1.01: Mit den Clowns kamen die Schwaene"
1645// 1645//
1646// assuming that 1646// assuming that
1647// x = "4699" 1647// x = "4699"
1648// y = "12" 1648// y = "12"
1649// section = "1." 1649// section = "1."
1650// subsection = "01" 1650// subsection = "01"
1651// title = "Mit den Clowns kamen die Schwaene" 1651// title = "Mit den Clowns kamen die Schwaene"
1652// 1652//
1653// 2) __DBE_expand(): 1653// 2) __DBE_expand():
1654// 1654//
1655// checks for the command, i.e. the 'sign' that follows '${' 1655// checks for the command, i.e. the 'sign' that follows '${'
1656// divides the argument list into sub-expressions using 1656// divides the argument list into sub-expressions using
1657// __DBE_get_expr_list() 1657// __DBE_get_expr_list()
1658// 1658//
1659// ${+ ${x} ${y}} -> "${x}" "${y}" 1659// ${+ ${x} ${y}} -> "${x}" "${y}"
1660// ${& ${section} ${subsection}} -> "${section}" "${subsection}" 1660// ${& ${section} ${subsection}} -> "${section}" "${subsection}"
1661// ${Title} -> Nothing, variable expansion 1661// ${Title} -> Nothing, variable expansion
1662// 1662//
1663// 3) __DBE_expression_list(): 1663// 3) __DBE_expression_list():
1664// 1664//
1665// builds a vector of unbracketed whitespace separated strings, i.e. 1665// builds a vector of unbracketed whitespace separated strings, i.e.
1666// 1666//
1667// " ${Number}.a ${: Das Marmorbild} AB-${& Author= ${Eichendorf}-1870}" 1667// " ${Number}.a ${: Das Marmorbild} AB-${& Author= ${Eichendorf}-1870}"
1668// 1668//
1669// is split into a vector 1669// is split into a vector
1670// 1670//
1671// [0] ${Number}.a 1671// [0] ${Number}.a
1672// [1] ${: Das Marmorbild} 1672// [1] ${: Das Marmorbild}
1673// [2] AB-${& Author= ${Eichendorf}}-1870 1673// [2] AB-${& Author= ${Eichendorf}}-1870
1674// 1674//
1675// Each sub-expression is expanded using expand(). 1675// Each sub-expression is expanded using expand().
1676//--------------------------------------------------------------------------- 1676//---------------------------------------------------------------------------
1677inline std::string 1677inline std::string
1678GetPot::__DBE_expand_string(const std::string str) 1678GetPot::__DBE_expand_string(const std::string str)
1679{ 1679{
1680 // Parses for closing operators '${ }' and expands them letting 1680 // Parses for closing operators '${ }' and expands them letting
1681 // white spaces and other letters as they are. 1681 // white spaces and other letters as they are.
1682 std::string new_string = ""; 1682 std::string new_string = "";
1683 unsigned open_brackets = 0; 1683 unsigned open_brackets = 0;
1684 unsigned first = 0; 1684 unsigned first = 0;
1685 unsigned i = 0; 1685 unsigned i = 0;
1686 for(; i<str.size(); ++i) { 1686 for(; i<str.size(); ++i) {
1687 if( i < str.size() - 2 && str.substr(i, 2) == "${" ) { 1687 if( i < str.size() - 2 && str.substr(i, 2) == "${" ) {
1688 if( open_brackets == 0 ) first = i+2; 1688 if( open_brackets == 0 ) first = i+2;
1689 open_brackets++; 1689 open_brackets++;
1690 } 1690 }
1691 else if( str[i] == '}' && open_brackets > 0) { 1691 else if( str[i] == '}' && open_brackets > 0) {
1692 open_brackets -= 1; 1692 open_brackets -= 1;
1693 if( open_brackets == 0 ) { 1693 if( open_brackets == 0 ) {
1694 const std::string Replacement = __DBE_expand(str.substr(first, i - first)); 1694 const std::string Replacement = __DBE_expand(str.substr(first, i - first));
1695 new_string += Replacement; 1695 new_string += Replacement;
1696 } 1696 }
1697 } 1697 }
1698 else if( open_brackets == 0 ) 1698 else if( open_brackets == 0 )
1699 new_string += str[i]; 1699 new_string += str[i];
1700 } 1700 }
1701 return new_string; 1701 return new_string;
1702} 1702}
1703 1703
1704inline STRING_VECTOR 1704inline STRING_VECTOR
1705GetPot::__DBE_get_expr_list(const std::string str_, const unsigned ExpectedNumber) 1705GetPot::__DBE_get_expr_list(const std::string str_, const unsigned ExpectedNumber)
1706 // ensures that the resulting vector has the expected number 1706 // ensures that the resulting vector has the expected number
1707 // of arguments, but they may contain an error message 1707 // of arguments, but they may contain an error message
1708{ 1708{
1709 std::string str = str_; 1709 std::string str = str_;
1710 // Separates expressions by non-bracketed whitespaces, expands them 1710 // Separates expressions by non-bracketed whitespaces, expands them
1711 // and puts them into a list. 1711 // and puts them into a list.
1712 1712
1713 unsigned i=0; 1713 unsigned i=0;
1714 // (1) eat initial whitespaces 1714 // (1) eat initial whitespaces
1715 for(; i < str.size(); ++i) 1715 for(; i < str.size(); ++i)
1716 if( ! isspace(str[i]) ) break; 1716 if( ! isspace(str[i]) ) break;
1717 1717
1718 STRING_VECTOR expr_list; 1718 STRING_VECTOR expr_list;
1719 unsigned open_brackets = 0; 1719 unsigned open_brackets = 0;
1720 std::vector<unsigned> start_idx; 1720 std::vector<unsigned> start_idx;
1721 unsigned start_new_string = i; 1721 unsigned start_new_string = i;
1722 unsigned l = static_cast<unsigned int>(str.size()); 1722 unsigned l = static_cast<unsigned int>(str.size());
1723 1723
1724 // (2) search for ${ } expressions ... 1724 // (2) search for ${ } expressions ...
1725 while( i < l ) { 1725 while( i < l ) {
1726 const char letter = str[i]; 1726 const char letter = str[i];
1727 // whitespace -> end of expression 1727 // whitespace -> end of expression
1728 if( isspace(letter) && open_brackets == 0) { 1728 if( isspace(letter) && open_brackets == 0) {
1729 expr_list.push_back(str.substr(start_new_string, i - start_new_string)); 1729 expr_list.push_back(str.substr(start_new_string, i - start_new_string));
1730 bool no_breakout_f = true; 1730 bool no_breakout_f = true;
1731 for(++i; i < l ; ++i) { 1731 for(++i; i < l ; ++i) {
1732 if( ! isspace(str[i]) ) 1732 if( ! isspace(str[i]) )
1733 { no_breakout_f = false; start_new_string = i; break; } 1733 { no_breakout_f = false; start_new_string = i; break; }
1734 } 1734 }
1735 if( no_breakout_f ) { 1735 if( no_breakout_f ) {
1736 // end of expression list 1736 // end of expression list
1737 if( expr_list.size() < ExpectedNumber ) { 1737 if( expr_list.size() < ExpectedNumber ) {
1738 const std::string pre_tmp("<< ${ }: missing arguments>>"); 1738 const std::string pre_tmp("<< ${ }: missing arguments>>");
1739 STRING_VECTOR tmp(ExpectedNumber - expr_list.size(), pre_tmp); 1739 STRING_VECTOR tmp(ExpectedNumber - expr_list.size(), pre_tmp);
1740 expr_list.insert(expr_list.end(), tmp.begin(), tmp.end()); 1740 expr_list.insert(expr_list.end(), tmp.begin(), tmp.end());
1741 } 1741 }
1742 return expr_list; 1742 return expr_list;
1743 } 1743 }
1744 } 1744 }
1745 1745
1746 // dollar-bracket expression 1746 // dollar-bracket expression
1747 if( str.length() >= i+2 && str.substr(i, 2) == "${" ) { 1747 if( str.length() >= i+2 && str.substr(i, 2) == "${" ) {
1748 open_brackets++; 1748 open_brackets++;
1749 start_idx.push_back(i+2); 1749 start_idx.push_back(i+2);
1750 } 1750 }
1751 else if( letter == '}' && open_brackets > 0) { 1751 else if( letter == '}' && open_brackets > 0) {
1752 int start = start_idx[start_idx.size()-1]; 1752 int start = start_idx[start_idx.size()-1];
1753 start_idx.pop_back(); 1753 start_idx.pop_back();
1754 const std::string Replacement = __DBE_expand(str.substr(start, i-start)); 1754 const std::string Replacement = __DBE_expand(str.substr(start, i-start));
1755 if( start - 3 < (int)0) 1755 if( start - 3 < (int)0)
1756 str = Replacement + str.substr(i+1); 1756 str = Replacement + str.substr(i+1);
1757 else 1757 else
1758 str = str.substr(0, start-2) + Replacement + str.substr(i+1); 1758 str = str.substr(0, start-2) + Replacement + str.substr(i+1);
1759 l = static_cast<unsigned int>(str.size()); 1759 l = static_cast<unsigned int>(str.size());
1760 i = start + static_cast<unsigned int>(Replacement.size()) - 3; 1760 i = start + static_cast<unsigned int>(Replacement.size()) - 3;
1761 open_brackets--; 1761 open_brackets--;
1762 } 1762 }
1763 ++i; 1763 ++i;
1764 } 1764 }
1765 1765
1766 // end of expression list 1766 // end of expression list
1767 expr_list.push_back(str.substr(start_new_string, i-start_new_string)); 1767 expr_list.push_back(str.substr(start_new_string, i-start_new_string));
1768 1768
1769 if( expr_list.size() < ExpectedNumber ) { 1769 if( expr_list.size() < ExpectedNumber ) {
1770 const std::string pre_tmp("<< ${ }: missing arguments>>"); 1770 const std::string pre_tmp("<< ${ }: missing arguments>>");
1771 STRING_VECTOR tmp(ExpectedNumber - expr_list.size(), pre_tmp); 1771 STRING_VECTOR tmp(ExpectedNumber - expr_list.size(), pre_tmp);
1772 expr_list.insert(expr_list.end(), tmp.begin(), tmp.end()); 1772 expr_list.insert(expr_list.end(), tmp.begin(), tmp.end());
1773 } 1773 }
1774 1774
1775 return expr_list; 1775 return expr_list;
1776} 1776}
1777 1777
1778inline const GetPot::variable* 1778inline const GetPot::variable*
1779GetPot::__DBE_get_variable(std::string VarName) 1779GetPot::__DBE_get_variable(std::string VarName)
1780{ 1780{
1781 static GetPot::variable ev; 1781 static GetPot::variable ev;
1782 std::string secure_Prefix = prefix; 1782 std::string secure_Prefix = prefix;
1783 1783
1784 prefix = section; 1784 prefix = section;
1785 // (1) first search in currently active section 1785 // (1) first search in currently active section
1786 const GetPot::variable* var = __find_variable(VarName.c_str()); 1786 const GetPot::variable* var = __find_variable(VarName.c_str());
1787 if( var != 0 ) { prefix = secure_Prefix; return var; } 1787 if( var != 0 ) { prefix = secure_Prefix; return var; }
1788 1788
1789 // (2) search in root name space 1789 // (2) search in root name space
1790 prefix = ""; 1790 prefix = "";
1791 var = __find_variable(VarName.c_str()); 1791 var = __find_variable(VarName.c_str());
1792 if( var != 0 ) { prefix = secure_Prefix; return var; } 1792 if( var != 0 ) { prefix = secure_Prefix; return var; }
1793 1793
1794 prefix = secure_Prefix; 1794 prefix = secure_Prefix;
1795 1795
1796 // error occured => variable name == "" 1796 // error occured => variable name == ""
1797 char* tmp = new char[VarName.length() + 25]; 1797 char* tmp = new char[VarName.length() + 25];
1798#ifndef WIN32 1798#ifndef WIN32
1799 snprintf(tmp, (int)sizeof(char)*(VarName.length() + 25), 1799 snprintf(tmp, (int)sizeof(char)*(VarName.length() + 25),
1800#else 1800#else
1801 _snprintf(tmp, sizeof(char)*(VarName.length() + 25), 1801 _snprintf(tmp, sizeof(char)*(VarName.length() + 25),
1802#endif 1802#endif
1803 "<<${ } variable '%s' undefined>>", VarName.c_str()); 1803 "<<${ } variable '%s' undefined>>", VarName.c_str());
1804 ev.name = ""; 1804 ev.name = "";
1805 ev.original = std::string(tmp); 1805 ev.original = std::string(tmp);
1806 delete [] tmp; 1806 delete [] tmp;
1807 return &ev; 1807 return &ev;
1808} 1808}
1809 1809
1810inline std::string 1810inline std::string
1811GetPot::__DBE_expand(const std::string expr) 1811GetPot::__DBE_expand(const std::string expr)
1812{ 1812{
1813 // ${: } pure text 1813 // ${: } pure text
1814 if( expr[0] == ':' ) 1814 if( expr[0] == ':' )
1815 return expr.substr(1); 1815 return expr.substr(1);
1816 1816
1817 // ${& expr expr ... } text concatination 1817 // ${& expr expr ... } text concatination
1818 else if( expr[0] == '&' ) { 1818 else if( expr[0] == '&' ) {
1819 const STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 1); 1819 const STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 1);
1820 1820
1821 STRING_VECTOR::const_iterator it = A.begin(); 1821 STRING_VECTOR::const_iterator it = A.begin();
1822 std::string result = *it++; 1822 std::string result = *it++;
1823 for(; it != A.end(); ++it) result += *it; 1823 for(; it != A.end(); ++it) result += *it;
1824 1824
1825 return result; 1825 return result;
1826 } 1826 }
1827 1827
1828 // ${<-> expr expr expr} text replacement 1828 // ${<-> expr expr expr} text replacement
1829 else if( expr.length() >= 3 && expr.substr(0, 3) == "<->" ) { 1829 else if( expr.length() >= 3 && expr.substr(0, 3) == "<->" ) {
1830 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(3), 3); 1830 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(3), 3);
1831 std::string::size_type tmp = 0; 1831 std::string::size_type tmp = 0;
1832 const std::string::size_type L = A[1].length(); 1832 const std::string::size_type L = A[1].length();
1833 while( (tmp = A[0].find(A[1])) != std::string::npos ) { 1833 while( (tmp = A[0].find(A[1])) != std::string::npos ) {
1834 A[0].replace(tmp, L, A[2]); 1834 A[0].replace(tmp, L, A[2]);
1835 } 1835 }
1836 return A[0]; 1836 return A[0];
1837 } 1837 }
1838 // ${+ ...}, ${- ...}, ${* ...}, ${/ ...} expressions 1838 // ${+ ...}, ${- ...}, ${* ...}, ${/ ...} expressions
1839 else if( expr[0] == '+' ) { 1839 else if( expr[0] == '+' ) {
1840 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2); 1840 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
1841 STRING_VECTOR::const_iterator it = A.begin(); 1841 STRING_VECTOR::const_iterator it = A.begin();
1842 double result = __convert_to_type(*it++, 0.0); 1842 double result = __convert_to_type(*it++, 0.0);
1843 for(; it != A.end(); ++it) 1843 for(; it != A.end(); ++it)
1844 result += __convert_to_type(*it, 0.0); 1844 result += __convert_to_type(*it, 0.0);
1845 1845
1846 return __double2string(result); 1846 return __double2string(result);
1847 } 1847 }
1848 else if( expr[0] == '-' ) { 1848 else if( expr[0] == '-' ) {
1849 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2); 1849 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
1850 STRING_VECTOR::const_iterator it = A.begin(); 1850 STRING_VECTOR::const_iterator it = A.begin();
1851 double result = __convert_to_type(*it++, 0.0); 1851 double result = __convert_to_type(*it++, 0.0);
1852 for(; it != A.end(); ++it) 1852 for(; it != A.end(); ++it)
1853 result -= __convert_to_type(*it, 0.0); 1853 result -= __convert_to_type(*it, 0.0);
1854 1854
1855 return __double2string(result); 1855 return __double2string(result);
1856 } 1856 }
1857 else if( expr[0] == '*' ) { 1857 else if( expr[0] == '*' ) {
1858 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2); 1858 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
1859 STRING_VECTOR::const_iterator it = A.begin(); 1859 STRING_VECTOR::const_iterator it = A.begin();
1860 double result = __convert_to_type(*it++, 0.0); 1860 double result = __convert_to_type(*it++, 0.0);
1861 for(; it != A.end(); ++it) 1861 for(; it != A.end(); ++it)
1862 result *= __convert_to_type(*it, 0.0); 1862 result *= __convert_to_type(*it, 0.0);
1863 1863
1864 return __double2string(result); 1864 return __double2string(result);
1865 } 1865 }
1866 else if( expr[0] == '/' ) { 1866 else if( expr[0] == '/' ) {
1867 1867
1868 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2); 1868 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
1869 STRING_VECTOR::const_iterator it = A.begin(); 1869 STRING_VECTOR::const_iterator it = A.begin();
1870 double result = __convert_to_type(*it++, 0.0); 1870 double result = __convert_to_type(*it++, 0.0);
1871 if( result == 0 ) return "0.0"; 1871 if( result == 0 ) return "0.0";
1872 for(; it != A.end(); ++it) { 1872 for(; it != A.end(); ++it) {
1873 const double Q = __convert_to_type(*it, 0.0); 1873 const double Q = __convert_to_type(*it, 0.0);
1874 if( Q == 0.0 ) return "0.0"; 1874 if( Q == 0.0 ) return "0.0";
1875 result /= Q; 1875 result /= Q;
1876 } 1876 }
1877 return __double2string(result); 1877 return __double2string(result);
1878 } 1878 }
1879 1879
1880 // ${^ ... } power expressions 1880 // ${^ ... } power expressions
1881 else if( expr[0] == '^' ) { 1881 else if( expr[0] == '^' ) {
1882 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2); 1882 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
1883 STRING_VECTOR::const_iterator it = A.begin(); 1883 STRING_VECTOR::const_iterator it = A.begin();
1884 double result = __convert_to_type(*it++, 0.0); 1884 double result = __convert_to_type(*it++, 0.0);
1885 for(; it != A.end(); ++it) 1885 for(; it != A.end(); ++it)
1886 result = pow(result, __convert_to_type(*it, 0.0)); 1886 result = pow(result, __convert_to_type(*it, 0.0));
1887 return __double2string(result); 1887 return __double2string(result);
1888 } 1888 }
1889 1889
1890 // ${== } ${<= } ${>= } comparisons (return the number of the first 'match' 1890 // ${== } ${<= } ${>= } comparisons (return the number of the first 'match'
1891 else if( expr.length() >= 2 && 1891 else if( expr.length() >= 2 &&
1892 ( expr.substr(0,2) == "==" || expr.substr(0,2) == ">=" || 1892 ( expr.substr(0,2) == "==" || expr.substr(0,2) == ">=" ||
1893 expr.substr(0,2) == "<=" || expr[0] == '>' || expr[0] == '<')) { 1893 expr.substr(0,2) == "<=" || expr[0] == '>' || expr[0] == '<')) {
1894 // differentiate between two and one sign operators 1894 // differentiate between two and one sign operators
1895 unsigned op = 0; 1895 unsigned op = 0;
1896 enum { EQ, GEQ, LEQ, GT, LT }; 1896 enum { EQ, GEQ, LEQ, GT, LT };
1897 if ( expr.substr(0, 2) == "==" ) op = EQ; 1897 if ( expr.substr(0, 2) == "==" ) op = EQ;
1898 else if ( expr.substr(0, 2) == ">=" ) op = GEQ; 1898 else if ( expr.substr(0, 2) == ">=" ) op = GEQ;
1899 else if ( expr.substr(0, 2) == "<=" ) op = LEQ; 1899 else if ( expr.substr(0, 2) == "<=" ) op = LEQ;
1900 else if ( expr[0] == '>' ) op = GT; 1900 else if ( expr[0] == '>' ) op = GT;
1901 else /* "<" */ op = LT; 1901 else /* "<" */ op = LT;
1902 1902
1903 STRING_VECTOR a; 1903 STRING_VECTOR a;
1904 if ( op == GT || op == LT ) a = __DBE_get_expr_list(expr.substr(1), 2); 1904 if ( op == GT || op == LT ) a = __DBE_get_expr_list(expr.substr(1), 2);
1905 else a = __DBE_get_expr_list(expr.substr(2), 2); 1905 else a = __DBE_get_expr_list(expr.substr(2), 2);
1906 1906
1907 std::string x_orig = a[0]; 1907 std::string x_orig = a[0];
1908 double x = __convert_to_type(x_orig, 1e37); 1908 double x = __convert_to_type(x_orig, 1e37);
1909 unsigned i = 1; 1909 unsigned i = 1;
1910 1910
1911 STRING_VECTOR::const_iterator y_orig = a.begin(); 1911 STRING_VECTOR::const_iterator y_orig = a.begin();
1912 for(y_orig++; y_orig != a.end(); y_orig++) { 1912 for(y_orig++; y_orig != a.end(); y_orig++) {
1913 double y = __convert_to_type(*y_orig, 1e37); 1913 double y = __convert_to_type(*y_orig, 1e37);
1914 1914
1915 // set the strings as reference if one wasn't a number 1915 // set the strings as reference if one wasn't a number
1916 if ( x == 1e37 || y == 1e37 ) { 1916 if ( x == 1e37 || y == 1e37 ) {
1917 // it's a string comparison 1917 // it's a string comparison
1918 if( (op == EQ && x_orig == *y_orig) || (op == GEQ && x_orig >= *y_orig) || 1918 if( (op == EQ && x_orig == *y_orig) || (op == GEQ && x_orig >= *y_orig) ||
1919 (op == LEQ && x_orig <= *y_orig) || (op == GT && x_orig > *y_orig) || 1919 (op == LEQ && x_orig <= *y_orig) || (op == GT && x_orig > *y_orig) ||
1920 (op == LT && x_orig < *y_orig) ) 1920 (op == LT && x_orig < *y_orig) )
1921 return __int2string(i); 1921 return __int2string(i);
1922 } 1922 }
1923 else { 1923 else {
1924 // it's a number comparison 1924 // it's a number comparison
1925 if( (op == EQ && x == y) || (op == GEQ && x >= y) || 1925 if( (op == EQ && x == y) || (op == GEQ && x >= y) ||
1926 (op == LEQ && x <= y) || (op == GT && x > y) || 1926 (op == LEQ && x <= y) || (op == GT && x > y) ||
1927 (op == LT && x < y) ) 1927 (op == LT && x < y) )
1928 return __int2string(i); 1928 return __int2string(i);
1929 } 1929 }
1930 ++i; 1930 ++i;
1931 } 1931 }
1932 1932
1933 // nothing fulfills the condition => return 0 1933 // nothing fulfills the condition => return 0
1934 return "0"; 1934 return "0";
1935 } 1935 }
1936 // ${?? expr expr} select 1936 // ${?? expr expr} select
1937 else if( expr.length() >= 2 && expr.substr(0, 2) == "??" ) { 1937 else if( expr.length() >= 2 && expr.substr(0, 2) == "??" ) {
1938 STRING_VECTOR a = __DBE_get_expr_list(expr.substr(2), 2); 1938 STRING_VECTOR a = __DBE_get_expr_list(expr.substr(2), 2);
1939 double x = __convert_to_type(a[0], 1e37); 1939 double x = __convert_to_type(a[0], 1e37);
1940 // last element is always the default argument 1940 // last element is always the default argument
1941 if( x == 1e37 || x < 0 || x >= a.size() - 1 ) return a[a.size()-1]; 1941 if( x == 1e37 || x < 0 || x >= a.size() - 1 ) return a[a.size()-1];
1942 1942
1943 // round x to closest integer 1943 // round x to closest integer
1944 return a[int(x+0.5)]; 1944 return a[int(x+0.5)];
1945 } 1945 }
1946 // ${? expr expr expr} if then else conditions 1946 // ${? expr expr expr} if then else conditions
1947 else if( expr[0] == '?' ) { 1947 else if( expr[0] == '?' ) {
1948 STRING_VECTOR a = __DBE_get_expr_list(expr.substr(1), 2); 1948 STRING_VECTOR a = __DBE_get_expr_list(expr.substr(1), 2);
1949 if( __convert_to_type(a[0], 0.0) == 1.0 ) return a[1]; 1949 if( __convert_to_type(a[0], 0.0) == 1.0 ) return a[1];
1950 else if( a.size() > 2 ) return a[2]; 1950 else if( a.size() > 2 ) return a[2];
1951 } 1951 }
1952 // ${! expr} maxro expansion 1952 // ${! expr} maxro expansion
1953 else if( expr[0] == '!' ) { 1953 else if( expr[0] == '!' ) {
1954 const GetPot::variable* Var = __DBE_get_variable(expr.substr(1)); 1954 const GetPot::variable* Var = __DBE_get_variable(expr.substr(1));
1955 // error 1955 // error
1956 if( Var->name == "" ) return std::string(Var->original); 1956 if( Var->name == "" ) return std::string(Var->original);
1957 1957
1958 const STRING_VECTOR A = __DBE_get_expr_list(Var->original, 2); 1958 const STRING_VECTOR A = __DBE_get_expr_list(Var->original, 2);
1959 return A[0]; 1959 return A[0];
1960 } 1960 }
1961 // ${@: } - string subscription 1961 // ${@: } - string subscription
1962 else if( expr.length() >= 2 && expr.substr(0,2) == "@:" ) { 1962 else if( expr.length() >= 2 && expr.substr(0,2) == "@:" ) {
1963 const STRING_VECTOR A = __DBE_get_expr_list(expr.substr(2), 2); 1963 const STRING_VECTOR A = __DBE_get_expr_list(expr.substr(2), 2);
1964 double x = __convert_to_type(A[1], 1e37); 1964 double x = __convert_to_type(A[1], 1e37);
1965 1965
1966 // last element is always the default argument 1966 // last element is always the default argument
1967 if( x == 1e37 || x < 0 || x >= A[0].size() - 1) 1967 if( x == 1e37 || x < 0 || x >= A[0].size() - 1)
1968 return "<<1st index out of range>>"; 1968 return "<<1st index out of range>>";
1969 1969
1970 if( A.size() > 2 ) { 1970 if( A.size() > 2 ) {
1971 double y = __convert_to_type(A[2], 1e37); 1971 double y = __convert_to_type(A[2], 1e37);
1972 if ( y != 1e37 && y > 0 && y <= A[0].size() - 1 && y > x ) 1972 if ( y != 1e37 && y > 0 && y <= A[0].size() - 1 && y > x )
1973 return A[0].substr(int(x+0.5), int(y+1.5) - int(x+0.5)); 1973 return A[0].substr(int(x+0.5), int(y+1.5) - int(x+0.5));
1974 else if( y == -1 ) 1974 else if( y == -1 )
1975 return A[0].substr(int(x+0.5)); 1975 return A[0].substr(int(x+0.5));
1976 return "<<2nd index out of range>>"; 1976 return "<<2nd index out of range>>";
1977 } 1977 }
1978 else { 1978 else {
1979 char* tmp = new char[2]; 1979 char* tmp = new char[2];
1980 tmp[0] = A[0][int(x+0.5)]; tmp[1] = '\0'; 1980 tmp[0] = A[0][int(x+0.5)]; tmp[1] = '\0';
1981 std::string result(tmp); 1981 std::string result(tmp);
1982 delete [] tmp; 1982 delete [] tmp;
1983 return result; 1983 return result;
1984 } 1984 }
1985 } 1985 }
1986 // ${@ } - vector subscription 1986 // ${@ } - vector subscription
1987 else if( expr[0] == '@' ) { 1987 else if( expr[0] == '@' ) {
1988 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2); 1988 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
1989 const GetPot::variable* Var = __DBE_get_variable(A[0]); 1989 const GetPot::variable* Var = __DBE_get_variable(A[0]);
1990 // error 1990 // error
1991 if( Var->name == "" ) { 1991 if( Var->name == "" ) {
1992 // make a copy of the string if an error occured 1992 // make a copy of the string if an error occured
1993 // (since the error variable is a static variable inside get_variable()) 1993 // (since the error variable is a static variable inside get_variable())
1994 return std::string(Var->original); 1994 return std::string(Var->original);
1995 } 1995 }
1996 1996
1997 double x = __convert_to_type(A[1], 1e37); 1997 double x = __convert_to_type(A[1], 1e37);
1998 1998
1999 // last element is always the default argument 1999 // last element is always the default argument
2000 if (x == 1e37 || x < 0 || x >= Var->value.size() ) 2000 if (x == 1e37 || x < 0 || x >= Var->value.size() )
2001 return "<<1st index out of range>>"; 2001 return "<<1st index out of range>>";
2002 2002
2003 if ( A.size() > 2) { 2003 if ( A.size() > 2) {
2004 double y = __convert_to_type(A[2], 1e37); 2004 double y = __convert_to_type(A[2], 1e37);
2005 int begin = int(x+0.5); 2005 int begin = int(x+0.5);
2006 int end = 0; 2006 int end = 0;
2007 if ( y != 1e37 && y > 0 && y <= Var->value.size() && y > x) 2007 if ( y != 1e37 && y > 0 && y <= Var->value.size() && y > x)
2008 end = int(y+1.5); 2008 end = int(y+1.5);
2009 else if( y == -1 ) 2009 else if( y == -1 )
2010 end = static_cast<unsigned int>(Var->value.size()); 2010 end = static_cast<unsigned int>(Var->value.size());
2011 else 2011 else
2012 return "<<2nd index out of range>>"; 2012 return "<<2nd index out of range>>";
2013 2013
2014 std::string result = *(Var->get_element(begin)); 2014 std::string result = *(Var->get_element(begin));
2015 int i = begin+1; 2015 int i = begin+1;
2016 for(; i < end; ++i) 2016 for(; i < end; ++i)
2017 result += std::string(" ") + *(Var->get_element(i)); 2017 result += std::string(" ") + *(Var->get_element(i));
2018 return result; 2018 return result;
2019 } 2019 }
2020 else 2020 else
2021 return *(Var->get_element(int(x+0.5))); 2021 return *(Var->get_element(int(x+0.5)));
2022 } 2022 }
2023 2023
2024 const STRING_VECTOR A = __DBE_get_expr_list(expr, 1); 2024 const STRING_VECTOR A = __DBE_get_expr_list(expr, 1);
2025 const GetPot::variable* B = __DBE_get_variable(A[0]); 2025 const GetPot::variable* B = __DBE_get_variable(A[0]);
2026 2026
2027 // make a copy of the string if an error occured 2027 // make a copy of the string if an error occured
2028 // (since the error variable is a static variable inside get_variable()) 2028 // (since the error variable is a static variable inside get_variable())
2029 if( B->name == "" ) return std::string(B->original); 2029 if( B->name == "" ) return std::string(B->original);
2030 // (psuggs@pobox.com mentioned to me the warning MSVC++6.0 produces 2030 // (psuggs@pobox.com mentioned to me the warning MSVC++6.0 produces
2031 // with: else return B->original (thanks)) 2031 // with: else return B->original (thanks))
2032 return B->original; 2032 return B->original;
2033} 2033}
2034 2034
2035 2035
2036/////////////////////////////////////////////////////////////////////////////// 2036///////////////////////////////////////////////////////////////////////////////
2037// (*) unidentified flying objects 2037// (*) unidentified flying objects
2038//............................................................................. 2038//.............................................................................
2039// 2039//
2040inline bool 2040inline bool
2041GetPot::__search_string_vector(const STRING_VECTOR& VecStr, const std::string& Str) const 2041GetPot::__search_string_vector(const STRING_VECTOR& VecStr, const std::string& Str) const
2042{ 2042{
2043 victorate(std::string, VecStr, itk) { 2043 victorate(std::string, VecStr, itk) {
2044 if( *itk == Str ) return true; 2044 if( *itk == Str ) return true;
2045 } 2045 }
2046 return false; 2046 return false;
2047} 2047}
2048 2048
2049inline STRING_VECTOR 2049inline STRING_VECTOR
2050GetPot::unidentified_arguments(unsigned Number, 2050GetPot::unidentified_arguments(unsigned Number,
2051 const char* KnownArgument1, ...) const 2051 const char* KnownArgument1, ...) const
2052{ 2052{
2053 STRING_VECTOR known_arguments; 2053 STRING_VECTOR known_arguments;
2054 2054
2055 // (1) create a vector of known arguments 2055 // (1) create a vector of known arguments
2056 if( Number == 0 ) return STRING_VECTOR(); 2056 if( Number == 0 ) return STRING_VECTOR();
2057 2057
2058 va_list ap; 2058 va_list ap;
2059 va_start(ap, KnownArgument1); 2059 va_start(ap, KnownArgument1);
2060 known_arguments.push_back(std::string(KnownArgument1)); 2060 known_arguments.push_back(std::string(KnownArgument1));
2061 unsigned i=1; 2061 unsigned i=1;
2062 for(; i<Number; ++i) 2062 for(; i<Number; ++i)
2063 known_arguments.push_back(std::string(va_arg(ap, char *))); 2063 known_arguments.push_back(std::string(va_arg(ap, char *)));
2064 va_end(ap); 2064 va_end(ap);
2065 2065
2066 return unidentified_arguments(known_arguments); 2066 return unidentified_arguments(known_arguments);
2067} 2067}
2068 2068
2069inline STRING_VECTOR 2069inline STRING_VECTOR
2070GetPot::unidentified_arguments() const 2070GetPot::unidentified_arguments() const
2071{ return unidentified_arguments(_requested_arguments); } 2071{ return unidentified_arguments(_requested_arguments); }
2072 2072
2073inline STRING_VECTOR 2073inline STRING_VECTOR
2074GetPot::unidentified_arguments(const STRING_VECTOR& Knowns) const 2074GetPot::unidentified_arguments(const STRING_VECTOR& Knowns) const
2075{ 2075{
2076 STRING_VECTOR ufos; 2076 STRING_VECTOR ufos;
2077 STRING_VECTOR::const_iterator it = argv.begin(); 2077 STRING_VECTOR::const_iterator it = argv.begin();
2078 ++it; // forget about argv[0] (application or filename) 2078 ++it; // forget about argv[0] (application or filename)
2079 for(; it != argv.end(); ++it) { 2079 for(; it != argv.end(); ++it) {
2080 // -- argument belongs to prefixed section ? 2080 // -- argument belongs to prefixed section ?
2081 const std::string arg = __get_remaining_string(*it, prefix); 2081 const std::string arg = __get_remaining_string(*it, prefix);
2082 if( arg == "" ) continue; 2082 if( arg == "" ) continue;
2083 2083
2084 // -- check if in list 2084 // -- check if in list
2085 if( __search_string_vector(Knowns, arg) == false) 2085 if( __search_string_vector(Knowns, arg) == false)
2086 ufos.push_back(*it); 2086 ufos.push_back(*it);
2087 } 2087 }
2088 return ufos; 2088 return ufos;
2089} 2089}
2090 2090
2091inline STRING_VECTOR 2091inline STRING_VECTOR
2092GetPot::unidentified_options(unsigned Number, 2092GetPot::unidentified_options(unsigned Number,
2093 const char* KnownOption1, ...) const 2093 const char* KnownOption1, ...) const
2094{ 2094{
2095 STRING_VECTOR known_options; 2095 STRING_VECTOR known_options;
2096 2096
2097 // (1) create a vector of known arguments 2097 // (1) create a vector of known arguments
2098 if( Number == 0 ) return STRING_VECTOR(); 2098 if( Number == 0 ) return STRING_VECTOR();
2099 2099
2100 va_list ap; 2100 va_list ap;
2101 va_start(ap, KnownOption1); 2101 va_start(ap, KnownOption1);
2102 known_options.push_back(std::string(KnownOption1)); 2102 known_options.push_back(std::string(KnownOption1));
2103 unsigned i=1; 2103 unsigned i=1;
2104 for(; i<Number; ++i) 2104 for(; i<Number; ++i)
2105 known_options.push_back(std::string(va_arg(ap, char *))); 2105 known_options.push_back(std::string(va_arg(ap, char *)));
2106 va_end(ap); 2106 va_end(ap);
2107 2107
2108 return unidentified_options(known_options); 2108 return unidentified_options(known_options);
2109} 2109}
2110 2110
2111inline STRING_VECTOR 2111inline STRING_VECTOR
2112GetPot::unidentified_options() const 2112GetPot::unidentified_options() const
2113{ 2113{
2114 // -- every option is an argument. 2114 // -- every option is an argument.
2115 // -- the set of requested arguments contains the set of requested options. 2115 // -- the set of requested arguments contains the set of requested options.
2116 // -- IF the set of requested arguments contains unrequested options, 2116 // -- IF the set of requested arguments contains unrequested options,
2117 // THEN they were requested as 'follow' and 'next' arguments and not as real options. 2117 // THEN they were requested as 'follow' and 'next' arguments and not as real options.
2118 // 2118 //
2119 // => it is not necessary to separate requested options from the list 2119 // => it is not necessary to separate requested options from the list
2120 STRING_VECTOR option_list; 2120 STRING_VECTOR option_list;
2121 victorate(std::string, _requested_arguments, it) { 2121 victorate(std::string, _requested_arguments, it) {
2122 const std::string arg = *it; 2122 const std::string arg = *it;
2123 if( arg.length() == 0 ) continue; 2123 if( arg.length() == 0 ) continue;
2124 if( arg[0] == '-' ) option_list.push_back(arg); 2124 if( arg[0] == '-' ) option_list.push_back(arg);
2125 } 2125 }
2126 return unidentified_options(option_list); 2126 return unidentified_options(option_list);
2127} 2127}
2128 2128
2129inline STRING_VECTOR 2129inline STRING_VECTOR
2130GetPot::unidentified_options(const STRING_VECTOR& Knowns) const 2130GetPot::unidentified_options(const STRING_VECTOR& Knowns) const
2131{ 2131{
2132 STRING_VECTOR ufos; 2132 STRING_VECTOR ufos;
2133 STRING_VECTOR::const_iterator it = argv.begin(); 2133 STRING_VECTOR::const_iterator it = argv.begin();
2134 ++it; // forget about argv[0] (application or filename) 2134 ++it; // forget about argv[0] (application or filename)
2135 for(; it != argv.end(); ++it) { 2135 for(; it != argv.end(); ++it) {
2136 // -- argument belongs to prefixed section ? 2136 // -- argument belongs to prefixed section ?
2137 const std::string arg = __get_remaining_string(*it, prefix); 2137 const std::string arg = __get_remaining_string(*it, prefix);
2138 if( arg == "" ) continue; 2138 if( arg == "" ) continue;
2139 2139
2140 // is argument really an option (starting with '-') ? 2140 // is argument really an option (starting with '-') ?
2141 if( arg.length() < 1 || arg[0] != '-' ) continue; 2141 if( arg.length() < 1 || arg[0] != '-' ) continue;
2142 2142
2143 if( __search_string_vector(Knowns, arg) == false) 2143 if( __search_string_vector(Knowns, arg) == false)
2144 ufos.push_back(*it); 2144 ufos.push_back(*it);
2145 } 2145 }
2146 2146
2147 return ufos; 2147 return ufos;
2148} 2148}
2149 2149
2150inline std::string 2150inline std::string
2151GetPot::unidentified_flags(const char* KnownFlagList, int ArgumentNumber=-1) const 2151GetPot::unidentified_flags(const char* KnownFlagList, int ArgumentNumber=-1) const
2152 // Two modes: 2152 // Two modes:
2153 // ArgumentNumber >= 0 check specific argument 2153 // ArgumentNumber >= 0 check specific argument
2154 // ArgumentNumber == -1 check all options starting with one '-' 2154 // ArgumentNumber == -1 check all options starting with one '-'
2155 // for flags 2155 // for flags
2156{ 2156{
2157 std::string ufos; 2157 std::string ufos;
2158 STRING_VECTOR known_arguments; 2158 STRING_VECTOR known_arguments;
2159 std::string KFL(KnownFlagList); 2159 std::string KFL(KnownFlagList);
2160 2160
2161 // (2) iteration over '-' arguments (options) 2161 // (2) iteration over '-' arguments (options)
2162 if( ArgumentNumber == -1 ) { 2162 if( ArgumentNumber == -1 ) {
2163 STRING_VECTOR::const_iterator it = argv.begin(); 2163 STRING_VECTOR::const_iterator it = argv.begin();
2164 ++it; // forget about argv[0] (application or filename) 2164 ++it; // forget about argv[0] (application or filename)
2165 for(; it != argv.end(); ++it) { 2165 for(; it != argv.end(); ++it) {
2166 // -- argument belongs to prefixed section ? 2166 // -- argument belongs to prefixed section ?
2167 const std::string arg = __get_remaining_string(*it, prefix); 2167 const std::string arg = __get_remaining_string(*it, prefix);
2168 if( arg == "" ) continue; 2168 if( arg == "" ) continue;
2169 2169
2170 // -- does arguments start with '-' (but not '--') 2170 // -- does arguments start with '-' (but not '--')
2171 if ( arg.length() < 2 ) continue; 2171 if ( arg.length() < 2 ) continue;
2172 else if( arg[0] != '-' ) continue; 2172 else if( arg[0] != '-' ) continue;
2173 else if( arg[1] == '-' ) continue; 2173 else if( arg[1] == '-' ) continue;
2174 2174
2175 // -- check out if flags inside option are contained in KnownFlagList 2175 // -- check out if flags inside option are contained in KnownFlagList
2176 const char* p=arg.c_str(); 2176 const char* p=arg.c_str();
2177 p++; // skip starting minus 2177 p++; // skip starting minus
2178 for(; *p != '\0' ; p++) 2178 for(; *p != '\0' ; p++)
2179 if( KFL.find(*p) == std::string::npos ) ufos += *p; 2179 if( KFL.find(*p) == std::string::npos ) ufos += *p;
2180 } 2180 }
2181 } 2181 }
2182 // (1) check specific argument 2182 // (1) check specific argument
2183 else { 2183 else {
2184 // -- only check arguments that start with prefix 2184 // -- only check arguments that start with prefix
2185 int no_matches = 0; 2185 int no_matches = 0;
2186 unsigned i=1; 2186 unsigned i=1;
2187 for(; i<argv.size(); ++i) { 2187 for(; i<argv.size(); ++i) {
2188 const std::string Remain = __get_remaining_string(argv[i], prefix); 2188 const std::string Remain = __get_remaining_string(argv[i], prefix);
2189 if( Remain != "") { 2189 if( Remain != "") {
2190 no_matches++; 2190 no_matches++;
2191 if( no_matches == ArgumentNumber) { 2191 if( no_matches == ArgumentNumber) {
2192 // -- the right argument number inside the section is found 2192 // -- the right argument number inside the section is found
2193 // => check it for flags 2193 // => check it for flags
2194 const char* p = Remain.c_str(); 2194 const char* p = Remain.c_str();
2195 p++; // skip starting minus 2195 p++; // skip starting minus
2196 for(; *p != '\0' ; p++) 2196 for(; *p != '\0' ; p++)
2197 if( KFL.find(*p) == std::string::npos ) ufos += *p; 2197 if( KFL.find(*p) == std::string::npos ) ufos += *p;
2198 return ufos; 2198 return ufos;
2199 } 2199 }
2200 } 2200 }
2201 } 2201 }
2202 } 2202 }
2203 return ufos; 2203 return ufos;
2204} 2204}
2205 2205
2206inline STRING_VECTOR 2206inline STRING_VECTOR
2207GetPot::unidentified_variables(unsigned Number, 2207GetPot::unidentified_variables(unsigned Number,
2208 const char* KnownVariable1, ...) const 2208 const char* KnownVariable1, ...) const
2209{ 2209{
2210 STRING_VECTOR known_variables; 2210 STRING_VECTOR known_variables;
2211 2211
2212 // create vector of known arguments 2212 // create vector of known arguments
2213 if( Number == 0 ) return STRING_VECTOR(); 2213 if( Number == 0 ) return STRING_VECTOR();
2214 2214
2215 va_list ap; 2215 va_list ap;
2216 va_start(ap, KnownVariable1); 2216 va_start(ap, KnownVariable1);
2217 known_variables.push_back(std::string(KnownVariable1)); 2217 known_variables.push_back(std::string(KnownVariable1));
2218 unsigned i=1; 2218 unsigned i=1;
2219 for(; i<Number; ++i) 2219 for(; i<Number; ++i)
2220 known_variables.push_back(std::string(va_arg(ap, char *))); 2220 known_variables.push_back(std::string(va_arg(ap, char *)));
2221 va_end(ap); 2221 va_end(ap);
2222 2222
2223 return unidentified_variables(known_variables); 2223 return unidentified_variables(known_variables);
2224} 2224}
2225 2225
2226inline STRING_VECTOR 2226inline STRING_VECTOR
2227GetPot::unidentified_variables(const STRING_VECTOR& Knowns) const 2227GetPot::unidentified_variables(const STRING_VECTOR& Knowns) const
2228{ 2228{
2229 STRING_VECTOR ufos; 2229 STRING_VECTOR ufos;
2230 2230
2231 victorate(GetPot::variable, variables, it) { 2231 victorate(GetPot::variable, variables, it) {
2232 // -- check if variable has specific prefix 2232 // -- check if variable has specific prefix
2233 const std::string var_name = __get_remaining_string((*it).name, prefix); 2233 const std::string var_name = __get_remaining_string((*it).name, prefix);
2234 if( var_name == "" ) continue; 2234 if( var_name == "" ) continue;
2235 2235
2236 // -- check if variable is known 2236 // -- check if variable is known
2237 if( __search_string_vector(Knowns, var_name) == false) 2237 if( __search_string_vector(Knowns, var_name) == false)
2238 ufos.push_back((*it).name); 2238 ufos.push_back((*it).name);
2239 } 2239 }
2240 return ufos; 2240 return ufos;
2241} 2241}
2242 2242
2243inline STRING_VECTOR 2243inline STRING_VECTOR
2244GetPot::unidentified_variables() const 2244GetPot::unidentified_variables() const
2245{ return unidentified_variables(_requested_variables); } 2245{ return unidentified_variables(_requested_variables); }
2246 2246
2247 2247
2248inline STRING_VECTOR 2248inline STRING_VECTOR
2249GetPot::unidentified_sections(unsigned Number, 2249GetPot::unidentified_sections(unsigned Number,
2250 const char* KnownSection1, ...) const 2250 const char* KnownSection1, ...) const
2251{ 2251{
2252 STRING_VECTOR known_sections; 2252 STRING_VECTOR known_sections;
2253 2253
2254 // (1) create a vector of known arguments 2254 // (1) create a vector of known arguments
2255 if( Number == 0 ) return STRING_VECTOR(); 2255 if( Number == 0 ) return STRING_VECTOR();
2256 2256
2257 va_list ap; 2257 va_list ap;
2258 va_start(ap, KnownSection1); 2258 va_start(ap, KnownSection1);
2259 known_sections.push_back(std::string(KnownSection1)); 2259 known_sections.push_back(std::string(KnownSection1));
2260 unsigned i=1; 2260 unsigned i=1;
2261 for(; i<Number; ++i) { 2261 for(; i<Number; ++i) {
2262 std::string tmp = std::string(va_arg(ap, char *)); 2262 std::string tmp = std::string(va_arg(ap, char *));
2263 if( tmp.length() == 0 ) continue; 2263 if( tmp.length() == 0 ) continue;
2264 if( tmp[tmp.length()-1] != '/' ) tmp += '/'; 2264 if( tmp[tmp.length()-1] != '/' ) tmp += '/';
2265 known_sections.push_back(tmp); 2265 known_sections.push_back(tmp);
2266 } 2266 }
2267 va_end(ap); 2267 va_end(ap);
2268 2268
2269 return unidentified_sections(known_sections); 2269 return unidentified_sections(known_sections);
2270} 2270}
2271 2271
2272inline STRING_VECTOR 2272inline STRING_VECTOR
2273GetPot::unidentified_sections() const 2273GetPot::unidentified_sections() const
2274{ return unidentified_sections(_requested_sections); } 2274{ return unidentified_sections(_requested_sections); }
2275 2275
2276inline STRING_VECTOR 2276inline STRING_VECTOR
2277GetPot::unidentified_sections(const STRING_VECTOR& Knowns) const 2277GetPot::unidentified_sections(const STRING_VECTOR& Knowns) const
2278{ 2278{
2279 STRING_VECTOR ufos; 2279 STRING_VECTOR ufos;
2280 2280
2281 victorate(std::string, section_list, it) { 2281 victorate(std::string, section_list, it) {
2282 // -- check if section conform to prefix 2282 // -- check if section conform to prefix
2283 const std::string sec_name = __get_remaining_string(*it, prefix); 2283 const std::string sec_name = __get_remaining_string(*it, prefix);
2284 if( sec_name == "" ) continue; 2284 if( sec_name == "" ) continue;
2285 2285
2286 // -- check if section is known 2286 // -- check if section is known
2287 if( __search_string_vector(Knowns, sec_name) == false ) 2287 if( __search_string_vector(Knowns, sec_name) == false )
2288 ufos.push_back(*it); 2288 ufos.push_back(*it);
2289 } 2289 }
2290 2290
2291 return ufos; 2291 return ufos;
2292} 2292}
2293 2293
2294 2294
2295inline STRING_VECTOR 2295inline STRING_VECTOR
2296GetPot::unidentified_nominuses(unsigned Number, const char* Known, ...) const 2296GetPot::unidentified_nominuses(unsigned Number, const char* Known, ...) const
2297{ 2297{
2298 STRING_VECTOR known_nominuses; 2298 STRING_VECTOR known_nominuses;
2299 2299
2300 // create vector of known arguments 2300 // create vector of known arguments
2301 if( Number == 0 ) return STRING_VECTOR(); 2301 if( Number == 0 ) return STRING_VECTOR();
2302 2302
2303 va_list ap; 2303 va_list ap;
2304 va_start(ap, Known); 2304 va_start(ap, Known);
2305 known_nominuses.push_back(std::string(Known)); 2305 known_nominuses.push_back(std::string(Known));
2306 unsigned i=1; 2306 unsigned i=1;
2307 for(; i<Number; ++i) { 2307 for(; i<Number; ++i) {
2308 std::string tmp = std::string(va_arg(ap, char *)); 2308 std::string tmp = std::string(va_arg(ap, char *));
2309 if( tmp.length() == 0 ) continue; 2309 if( tmp.length() == 0 ) continue;
2310 known_nominuses.push_back(tmp); 2310 known_nominuses.push_back(tmp);
2311 } 2311 }
2312 va_end(ap); 2312 va_end(ap);
2313 2313
2314 return unidentified_nominuses(known_nominuses); 2314 return unidentified_nominuses(known_nominuses);
2315} 2315}
2316 2316
2317inline STRING_VECTOR 2317inline STRING_VECTOR
2318GetPot::unidentified_nominuses() const { 2318GetPot::unidentified_nominuses() const {
2319 // -- every nominus is an argument. 2319 // -- every nominus is an argument.
2320 // -- the set of requested arguments contains the set of requested nominuss. 2320 // -- the set of requested arguments contains the set of requested nominuss.
2321 // -- IF the set of requested arguments contains unrequested nominuss, 2321 // -- IF the set of requested arguments contains unrequested nominuss,
2322 // THEN they were requested as 'follow' and 'next' arguments and not as real nominuses. 2322 // THEN they were requested as 'follow' and 'next' arguments and not as real nominuses.
2323 // 2323 //
2324 // => it is not necessary to separate requested nominus from the list 2324 // => it is not necessary to separate requested nominus from the list
2325 2325
2326 return unidentified_nominuses(_requested_arguments); 2326 return unidentified_nominuses(_requested_arguments);
2327} 2327}
2328 2328
2329inline STRING_VECTOR 2329inline STRING_VECTOR
2330GetPot::unidentified_nominuses(const STRING_VECTOR& Knowns) const 2330GetPot::unidentified_nominuses(const STRING_VECTOR& Knowns) const
2331{ 2331{
2332 STRING_VECTOR ufos; 2332 STRING_VECTOR ufos;
2333 2333
2334 // (2) iterate over all arguments 2334 // (2) iterate over all arguments
2335 STRING_VECTOR::const_iterator it = argv.begin(); 2335 STRING_VECTOR::const_iterator it = argv.begin();
2336 ++it; // forget about argv[0] (application or filename) 2336 ++it; // forget about argv[0] (application or filename)
2337 for(; it != argv.end(); ++it) { 2337 for(; it != argv.end(); ++it) {
2338 // -- check if nominus part of prefix 2338 // -- check if nominus part of prefix
2339 const std::string arg = __get_remaining_string(*it, prefix); 2339 const std::string arg = __get_remaining_string(*it, prefix);
2340 if( arg == "" ) continue; 2340 if( arg == "" ) continue;
2341 2341
2342 if( arg.length() < 1 ) continue; 2342 if( arg.length() < 1 ) continue;
2343 // option ? --> not a nomius 2343 // option ? --> not a nomius
2344 if( arg[0] == '-' ) continue; 2344 if( arg[0] == '-' ) continue;
2345 // section ? --> not a real nominus 2345 // section ? --> not a real nominus
2346 if( arg[0] == '[' && arg[arg.length()-1] == ']' ) continue; 2346 if( arg[0] == '[' && arg[arg.length()-1] == ']' ) continue;
2347 // variable definition ? --> not a real nominus 2347 // variable definition ? --> not a real nominus
2348 bool continue_f = false; 2348 bool continue_f = false;
2349 unsigned i=0; 2349 unsigned i=0;
2350 for(; i<arg.length() ; ++i) 2350 for(; i<arg.length() ; ++i)
2351 if( arg[i] == '=' ) { continue_f = true; break; } 2351 if( arg[i] == '=' ) { continue_f = true; break; }
2352 if( continue_f ) continue; 2352 if( continue_f ) continue;
2353 2353
2354 // real nominuses are compared with the given list 2354 // real nominuses are compared with the given list
2355 if( __search_string_vector(Knowns, arg) == false ) 2355 if( __search_string_vector(Knowns, arg) == false )
2356 ufos.push_back(*it); 2356 ufos.push_back(*it);
2357 } 2357 }
2358 return ufos; 2358 return ufos;
2359} 2359}
2360 2360
2361 2361
2362/////////////////////////////////////////////////////////////////////////////// 2362///////////////////////////////////////////////////////////////////////////////
2363// (*) variable class 2363// (*) variable class
2364//............................................................................. 2364//.............................................................................
2365// 2365//
2366inline 2366inline
2367GetPot::variable::variable() 2367GetPot::variable::variable()
2368{} 2368{}
2369 2369
2370inline 2370inline
2371GetPot::variable::variable(const variable& That) 2371GetPot::variable::variable(const variable& That)
2372{ 2372{
2373#ifdef WIN32 2373#ifdef WIN32
2374 operator=(That); 2374 operator=(That);
2375#else 2375#else
2376 GetPot::variable::operator=(That); 2376 GetPot::variable::operator=(That);
2377#endif 2377#endif
2378} 2378}
2379 2379
2380 2380
2381inline 2381inline
2382GetPot::variable::variable(const char* Name, const char* Value, const char* FieldSeparator) 2382GetPot::variable::variable(const char* Name, const char* Value, const char* FieldSeparator)
2383 : name(Name) 2383 : name(Name)
2384{ 2384{
2385 // make a copy of the 'Value' 2385 // make a copy of the 'Value'
2386 take(Value, FieldSeparator); 2386 take(Value, FieldSeparator);
2387} 2387}
2388 2388
2389inline const std::string* 2389inline const std::string*
2390GetPot::variable::get_element(unsigned Idx) const 2390GetPot::variable::get_element(unsigned Idx) const
2391{ if( Idx >= value.size() ) return 0; else return &(value[Idx]); } 2391{ if( Idx >= value.size() ) return 0; else return &(value[Idx]); }
2392 2392
2393inline void 2393inline void
2394GetPot::variable::take(const char* Value, const char* FieldSeparator) 2394GetPot::variable::take(const char* Value, const char* FieldSeparator)
2395{ 2395{
2396 original = std::string(Value); 2396 original = std::string(Value);
2397 2397
2398 // separate string by white space delimiters using 'strtok' 2398 // separate string by white space delimiters using 'strtok'
2399 // thread safe usage of strtok (no static members) 2399 // thread safe usage of strtok (no static members)
2400 char* spt = 0; 2400 char* spt = 0;
2401 // make a copy of the 'Value' 2401 // make a copy of the 'Value'
2402 char* copy = new char[strlen(Value)+1]; 2402 char* copy = new char[strlen(Value)+1];
2403 strcpy(copy, Value); 2403 strcpy(copy, Value);
2404 char* follow_token = strtok_r(copy, FieldSeparator, &spt); 2404 char* follow_token = strtok_r(copy, FieldSeparator, &spt);
2405 if( value.size() != 0 ) value.erase(value.begin(), value.end()); 2405 if( value.size() != 0 ) value.erase(value.begin(), value.end());
2406 while(follow_token != 0) { 2406 while(follow_token != 0) {
2407 value.push_back(std::string(follow_token)); 2407 value.push_back(std::string(follow_token));
2408 follow_token = strtok_r(NULL, FieldSeparator, &spt); 2408 follow_token = strtok_r(NULL, FieldSeparator, &spt);
2409 } 2409 }
2410 2410
2411 delete [] copy; 2411 delete [] copy;
2412} 2412}
2413 2413
2414inline 2414inline
2415GetPot::variable::~variable() 2415GetPot::variable::~variable()
2416{} 2416{}
2417 2417
2418inline GetPot::variable& 2418inline GetPot::variable&
2419GetPot::variable::operator=(const GetPot::variable& That) 2419GetPot::variable::operator=(const GetPot::variable& That)
2420{ 2420{
2421 if( &That != this) { 2421 if( &That != this) {
2422 name = That.name; 2422 name = That.name;
2423 value = That.value; 2423 value = That.value;
2424 original = That.original; 2424 original = That.original;
2425 } 2425 }
2426 return *this; 2426 return *this;
2427} 2427}
2428 2428
2429#undef victorate 2429#undef victorate
2430 2430
2431 2431
2432#endif // __include_guard_GETPOT_H__ 2432#endif // __include_guard_GETPOT_H__
2433 2433
2434 2434
2435 2435
diff --git a/utils/zenutils/libraries/pelib-0.9/CMakeLists.txt b/utils/zenutils/libraries/pelib-0.9/CMakeLists.txt
index 540fa99c8c..3cdb6e71ff 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/CMakeLists.txt
+++ b/utils/zenutils/libraries/pelib-0.9/CMakeLists.txt
@@ -1,20 +1,20 @@
1PROJECT(pelib) 1PROJECT(pelib)
2 2
3# source files for pelib 3# source files for pelib
4SET(pelib_srcs 4SET(pelib_srcs
5 pelib/BoundImportDirectory.cpp 5 pelib/BoundImportDirectory.cpp
6 pelib/ComHeaderDirectory.cpp 6 pelib/ComHeaderDirectory.cpp
7 pelib/DebugDirectory.cpp 7 pelib/DebugDirectory.cpp
8 pelib/ExportDirectory.cpp 8 pelib/ExportDirectory.cpp
9 pelib/IatDirectory.cpp 9 pelib/IatDirectory.cpp
10 pelib/MzHeader.cpp 10 pelib/MzHeader.cpp
11 pelib/PeFile.cpp 11 pelib/PeFile.cpp
12 pelib/PeHeader.cpp 12 pelib/PeHeader.cpp
13 pelib/PeLibAux.cpp 13 pelib/PeLibAux.cpp
14 pelib/RelocationsDirectory.cpp 14 pelib/RelocationsDirectory.cpp
15 pelib/ResourceDirectory.cpp 15 pelib/ResourceDirectory.cpp
16 pelib/buffer/InputBuffer.cpp 16 pelib/buffer/InputBuffer.cpp
17 pelib/buffer/OutputBuffer.cpp 17 pelib/buffer/OutputBuffer.cpp
18) 18)
19 19
20ADD_LIBRARY(pelib ${pelib_srcs}) 20ADD_LIBRARY(pelib ${pelib_srcs})
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.cpp
index 5b84931838..7c5ff74f0e 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.cpp
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.cpp
@@ -1,511 +1,511 @@
1/* 1/*
2* BoundImportDirectory.cpp - Part of the PeLib library. 2* BoundImportDirectory.cpp - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#include "PeLibInc.h" 13#include "PeLibInc.h"
14#include "BoundImportDirectory.h" 14#include "BoundImportDirectory.h"
15#include <numeric> 15#include <numeric>
16#include <set> 16#include <set>
17#include <map> 17#include <map>
18 18
19namespace PeLib 19namespace PeLib
20{ 20{
21 /** 21 /**
22 * Adds another bound import to the BoundImport directory. 22 * Adds another bound import to the BoundImport directory.
23 * @param strModuleName Name of the PE file which will be imported. 23 * @param strModuleName Name of the PE file which will be imported.
24 * @param dwTds Value of the TimeDateStamp of the bound import field. 24 * @param dwTds Value of the TimeDateStamp of the bound import field.
25 * @param wOmn Value of the OffsetModuleName of the bound import field. 25 * @param wOmn Value of the OffsetModuleName of the bound import field.
26 * @param wWfr Value of the NumberOfModuleForwarderRefs of the bound import field. 26 * @param wWfr Value of the NumberOfModuleForwarderRefs of the bound import field.
27 **/ 27 **/
28 int BoundImportDirectory::addBoundImport(const std::string& strModuleName, dword dwTds, word wOmn, word wWfr) 28 int BoundImportDirectory::addBoundImport(const std::string& strModuleName, dword dwTds, word wOmn, word wWfr)
29 { 29 {
30 for (unsigned int i=0;i<m_vIbd.size();i++) 30 for (unsigned int i=0;i<m_vIbd.size();i++)
31 { 31 {
32 if (isEqualNc(strModuleName, m_vIbd[i].strModuleName)) 32 if (isEqualNc(strModuleName, m_vIbd[i].strModuleName))
33 { 33 {
34 return ERROR_DUPLICATE_ENTRY; 34 return ERROR_DUPLICATE_ENTRY;
35 } 35 }
36 } 36 }
37 37
38 PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR ibidCurrent; 38 PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR ibidCurrent;
39 ibidCurrent.TimeDateStamp = dwTds; 39 ibidCurrent.TimeDateStamp = dwTds;
40 ibidCurrent.OffsetModuleName = wOmn; 40 ibidCurrent.OffsetModuleName = wOmn;
41 ibidCurrent.NumberOfModuleForwarderRefs = wWfr; 41 ibidCurrent.NumberOfModuleForwarderRefs = wWfr;
42 PELIB_IMAGE_BOUND_DIRECTORY ibdCurrent; 42 PELIB_IMAGE_BOUND_DIRECTORY ibdCurrent;
43 ibdCurrent.ibdDescriptor = ibidCurrent; 43 ibdCurrent.ibdDescriptor = ibidCurrent;
44 ibdCurrent.strModuleName = strModuleName; 44 ibdCurrent.strModuleName = strModuleName;
45 m_vIbd.push_back(ibdCurrent); 45 m_vIbd.push_back(ibdCurrent);
46 46
47 return NO_ERROR; 47 return NO_ERROR;
48 } 48 }
49 49
50 /** 50 /**
51 * Searches for the first instance of a module with the given modulename. 51 * Searches for the first instance of a module with the given modulename.
52 * @param strModuleName The name of a module. 52 * @param strModuleName The name of a module.
53 * @return The id of the module. 53 * @return The id of the module.
54 **/ 54 **/
55 int BoundImportDirectory::getModuleIndex(const std::string& strModuleName) const 55 int BoundImportDirectory::getModuleIndex(const std::string& strModuleName) const
56 { 56 {
57 std::vector<PELIB_IMAGE_BOUND_DIRECTORY>::const_iterator Iter = std::find_if(m_vIbd.begin(), m_vIbd.end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_BOUND_DIRECTORY::equal), strModuleName)); 57 std::vector<PELIB_IMAGE_BOUND_DIRECTORY>::const_iterator Iter = std::find_if(m_vIbd.begin(), m_vIbd.end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_BOUND_DIRECTORY::equal), strModuleName));
58 58
59 if (Iter == m_vIbd.end()) 59 if (Iter == m_vIbd.end())
60 { 60 {
61 return ERROR_ENTRY_NOT_FOUND; 61 return ERROR_ENTRY_NOT_FOUND;
62 } 62 }
63 63
64 return static_cast<int>(std::distance(m_vIbd.begin(), Iter)); 64 return static_cast<int>(std::distance(m_vIbd.begin(), Iter));
65 } 65 }
66 66
67 /** 67 /**
68 * @return Number of files in the current BoundImport directory. 68 * @return Number of files in the current BoundImport directory.
69 **/ 69 **/
70 unsigned int BoundImportDirectory::calcNumberOfModules() const 70 unsigned int BoundImportDirectory::calcNumberOfModules() const
71 { 71 {
72 return static_cast<unsigned int>(m_vIbd.size()); 72 return static_cast<unsigned int>(m_vIbd.size());
73 } 73 }
74 74
75 int BoundImportDirectory::read(InputBuffer& inpBuffer, unsigned char* data, unsigned int dwSize) 75 int BoundImportDirectory::read(InputBuffer& inpBuffer, unsigned char* data, unsigned int dwSize)
76 { 76 {
77 std::vector<PELIB_IMAGE_BOUND_DIRECTORY> currentDirectory; 77 std::vector<PELIB_IMAGE_BOUND_DIRECTORY> currentDirectory;
78 78
79 do 79 do
80 { 80 {
81 PELIB_IMAGE_BOUND_DIRECTORY ibdCurrent; 81 PELIB_IMAGE_BOUND_DIRECTORY ibdCurrent;
82 82
83 inpBuffer >> ibdCurrent.ibdDescriptor.TimeDateStamp; 83 inpBuffer >> ibdCurrent.ibdDescriptor.TimeDateStamp;
84 inpBuffer >> ibdCurrent.ibdDescriptor.OffsetModuleName; 84 inpBuffer >> ibdCurrent.ibdDescriptor.OffsetModuleName;
85 inpBuffer >> ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs; 85 inpBuffer >> ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs;
86 86
87 if (ibdCurrent.ibdDescriptor.TimeDateStamp == 0 && ibdCurrent.ibdDescriptor.OffsetModuleName == 0 && ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs == 0) break; 87 if (ibdCurrent.ibdDescriptor.TimeDateStamp == 0 && ibdCurrent.ibdDescriptor.OffsetModuleName == 0 && ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs == 0) break;
88 88
89 for (int i=0;i<ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs;i++) 89 for (int i=0;i<ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs;i++)
90 { 90 {
91 PELIB_IMAGE_BOUND_DIRECTORY currentForwarder; 91 PELIB_IMAGE_BOUND_DIRECTORY currentForwarder;
92 92
93 inpBuffer >> currentForwarder.ibdDescriptor.TimeDateStamp; 93 inpBuffer >> currentForwarder.ibdDescriptor.TimeDateStamp;
94 inpBuffer >> currentForwarder.ibdDescriptor.OffsetModuleName; 94 inpBuffer >> currentForwarder.ibdDescriptor.OffsetModuleName;
95 inpBuffer >> currentForwarder.ibdDescriptor.NumberOfModuleForwarderRefs; 95 inpBuffer >> currentForwarder.ibdDescriptor.NumberOfModuleForwarderRefs;
96 96
97 ibdCurrent.moduleForwarders.push_back(currentForwarder); 97 ibdCurrent.moduleForwarders.push_back(currentForwarder);
98 } 98 }
99 99
100 currentDirectory.push_back(ibdCurrent); 100 currentDirectory.push_back(ibdCurrent);
101 ibdCurrent.moduleForwarders.clear(); 101 ibdCurrent.moduleForwarders.clear();
102 } while (true); 102 } while (true);
103 103
104 for (unsigned int i=0;i<currentDirectory.size();i++) 104 for (unsigned int i=0;i<currentDirectory.size();i++)
105 { 105 {
106 dword wOmn = currentDirectory[i].ibdDescriptor.OffsetModuleName; 106 dword wOmn = currentDirectory[i].ibdDescriptor.OffsetModuleName;
107 if (wOmn > dwSize) 107 if (wOmn > dwSize)
108 { 108 {
109 return ERROR_INVALID_FILE; 109 return ERROR_INVALID_FILE;
110 } 110 }
111 111
112 currentDirectory[i].strModuleName = ""; 112 currentDirectory[i].strModuleName = "";
113 for (int k=0;data[wOmn + k] != 0 && k + wOmn < dwSize;k++) 113 for (int k=0;data[wOmn + k] != 0 && k + wOmn < dwSize;k++)
114 { 114 {
115 currentDirectory[i].strModuleName += data[wOmn + k]; 115 currentDirectory[i].strModuleName += data[wOmn + k];
116 } 116 }
117 117
118 for (unsigned int j=0;j<currentDirectory[i].moduleForwarders.size();j++) 118 for (unsigned int j=0;j<currentDirectory[i].moduleForwarders.size();j++)
119 { 119 {
120 dword wOmn = currentDirectory[i].moduleForwarders[j].ibdDescriptor.OffsetModuleName; 120 dword wOmn = currentDirectory[i].moduleForwarders[j].ibdDescriptor.OffsetModuleName;
121 121
122 if (wOmn > dwSize) 122 if (wOmn > dwSize)
123 { 123 {
124 return ERROR_INVALID_FILE; 124 return ERROR_INVALID_FILE;
125 } 125 }
126 126
127// m_vIbd[i].moduleForwarders[j].strModuleName.assign((char*)(&vBimpDir[wOmn])); 127// m_vIbd[i].moduleForwarders[j].strModuleName.assign((char*)(&vBimpDir[wOmn]));
128 currentDirectory[i].moduleForwarders[j].strModuleName = ""; 128 currentDirectory[i].moduleForwarders[j].strModuleName = "";
129 for (int k=0;data[wOmn + k] != 0 && k + wOmn < dwSize;k++) 129 for (int k=0;data[wOmn + k] != 0 && k + wOmn < dwSize;k++)
130 { 130 {
131 currentDirectory[i].moduleForwarders[j].strModuleName += data[wOmn + k]; 131 currentDirectory[i].moduleForwarders[j].strModuleName += data[wOmn + k];
132 } 132 }
133 } 133 }
134 } 134 }
135 135
136 std::swap(m_vIbd, currentDirectory); 136 std::swap(m_vIbd, currentDirectory);
137 137
138 return NO_ERROR; 138 return NO_ERROR;
139 } 139 }
140 140
141 /** 141 /**
142 * Reads the BoundImport directory from a PE file. 142 * Reads the BoundImport directory from a PE file.
143 * @param strModuleName The name of the PE file from which the BoundImport directory is read. 143 * @param strModuleName The name of the PE file from which the BoundImport directory is read.
144 * @param dwOffset The file offset where the BoundImport directory can be found (see #PeFile::PeHeader::getIDBoundImportRVA). 144 * @param dwOffset The file offset where the BoundImport directory can be found (see #PeFile::PeHeader::getIDBoundImportRVA).
145 * @param dwSize The size of the BoundImport directory (see #PeFile::PeHeader::getIDBoundImportSize). 145 * @param dwSize The size of the BoundImport directory (see #PeFile::PeHeader::getIDBoundImportSize).
146 **/ 146 **/
147 int BoundImportDirectory::read(const std::string& strModuleName, dword dwOffset, unsigned int uiSize) 147 int BoundImportDirectory::read(const std::string& strModuleName, dword dwOffset, unsigned int uiSize)
148 { 148 {
149 std::ifstream ifFile(strModuleName.c_str(), std::ios::binary); 149 std::ifstream ifFile(strModuleName.c_str(), std::ios::binary);
150 150
151 if (!ifFile) 151 if (!ifFile)
152 { 152 {
153 return ERROR_OPENING_FILE; 153 return ERROR_OPENING_FILE;
154 } 154 }
155 155
156 if (fileSize(ifFile) < dwOffset + uiSize) 156 if (fileSize(ifFile) < dwOffset + uiSize)
157 { 157 {
158 return ERROR_INVALID_FILE; 158 return ERROR_INVALID_FILE;
159 } 159 }
160 160
161 ifFile.seekg(dwOffset, std::ios::beg); 161 ifFile.seekg(dwOffset, std::ios::beg);
162 162
163 std::vector<unsigned char> vBimpDir(uiSize); 163 std::vector<unsigned char> vBimpDir(uiSize);
164 ifFile.read(reinterpret_cast<char*>(&vBimpDir[0]), uiSize); 164 ifFile.read(reinterpret_cast<char*>(&vBimpDir[0]), uiSize);
165 165
166 InputBuffer inpBuffer(vBimpDir); 166 InputBuffer inpBuffer(vBimpDir);
167 167
168 return read(inpBuffer, &vBimpDir[0], uiSize); 168 return read(inpBuffer, &vBimpDir[0], uiSize);
169 } 169 }
170 170
171 int BoundImportDirectory::read(unsigned char* pcBuffer, unsigned int uiSize) 171 int BoundImportDirectory::read(unsigned char* pcBuffer, unsigned int uiSize)
172 { 172 {
173 std::vector<unsigned char> vBimpDir(pcBuffer, pcBuffer + uiSize); 173 std::vector<unsigned char> vBimpDir(pcBuffer, pcBuffer + uiSize);
174 InputBuffer inpBuffer(vBimpDir); 174 InputBuffer inpBuffer(vBimpDir);
175 175
176 return read(inpBuffer, &vBimpDir[0], uiSize); 176 return read(inpBuffer, &vBimpDir[0], uiSize);
177 } 177 }
178 178
179 unsigned int BoundImportDirectory::totalModules() const 179 unsigned int BoundImportDirectory::totalModules() const
180 { 180 {
181 unsigned int modules = static_cast<unsigned int>(m_vIbd.size()); 181 unsigned int modules = static_cast<unsigned int>(m_vIbd.size());
182 182
183 for (unsigned int i=0;i<m_vIbd.size();i++) 183 for (unsigned int i=0;i<m_vIbd.size();i++)
184 { 184 {
185 modules += static_cast<unsigned int>(m_vIbd[i].moduleForwarders.size()); 185 modules += static_cast<unsigned int>(m_vIbd[i].moduleForwarders.size());
186 } 186 }
187 187
188 return modules; 188 return modules;
189 } 189 }
190 190
191 /** 191 /**
192 * Rebuilds the BoundImport directory. The rebuilded BoundImport directory can then be 192 * Rebuilds the BoundImport directory. The rebuilded BoundImport directory can then be
193 * written back to a PE file. 193 * written back to a PE file.
194 * @param vBuffer Buffer where the rebuilt BoundImport directory will be stored. 194 * @param vBuffer Buffer where the rebuilt BoundImport directory will be stored.
195 * @param fMakeValid If this flag is true a valid directory will be produced. 195 * @param fMakeValid If this flag is true a valid directory will be produced.
196 **/ 196 **/
197 void BoundImportDirectory::rebuild(std::vector<byte>& vBuffer, bool fMakeValid) const 197 void BoundImportDirectory::rebuild(std::vector<byte>& vBuffer, bool fMakeValid) const
198 { 198 {
199 std::map<std::string, word> filename_offsets; 199 std::map<std::string, word> filename_offsets;
200 200
201 OutputBuffer obBuffer(vBuffer); 201 OutputBuffer obBuffer(vBuffer);
202 202
203 word ulNameOffset = static_cast<word>((totalModules() + 1) * PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size()); 203 word ulNameOffset = static_cast<word>((totalModules() + 1) * PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size());
204 204
205 for (unsigned int i=0;i<m_vIbd.size();i++) 205 for (unsigned int i=0;i<m_vIbd.size();i++)
206 { 206 {
207 obBuffer << m_vIbd[i].ibdDescriptor.TimeDateStamp; 207 obBuffer << m_vIbd[i].ibdDescriptor.TimeDateStamp;
208 208
209 // Recalculate the offsets if a valid directory is wanted. 209 // Recalculate the offsets if a valid directory is wanted.
210 if (fMakeValid) 210 if (fMakeValid)
211 { 211 {
212 if (filename_offsets.find(m_vIbd[i].strModuleName) == filename_offsets.end()) 212 if (filename_offsets.find(m_vIbd[i].strModuleName) == filename_offsets.end())
213 { 213 {
214 filename_offsets[m_vIbd[i].strModuleName] = ulNameOffset; 214 filename_offsets[m_vIbd[i].strModuleName] = ulNameOffset;
215 obBuffer << ulNameOffset; 215 obBuffer << ulNameOffset;
216 ulNameOffset += static_cast<word>(m_vIbd[i].strModuleName.size() + 1); 216 ulNameOffset += static_cast<word>(m_vIbd[i].strModuleName.size() + 1);
217 } 217 }
218 else 218 else
219 { 219 {
220 obBuffer << filename_offsets[m_vIbd[i].strModuleName]; 220 obBuffer << filename_offsets[m_vIbd[i].strModuleName];
221 } 221 }
222 } 222 }
223 else // Otherwise just copy the old values into the buffer. 223 else // Otherwise just copy the old values into the buffer.
224 { 224 {
225 obBuffer << m_vIbd[i].ibdDescriptor.OffsetModuleName; 225 obBuffer << m_vIbd[i].ibdDescriptor.OffsetModuleName;
226 } 226 }
227 227
228 obBuffer << m_vIbd[i].ibdDescriptor.NumberOfModuleForwarderRefs; 228 obBuffer << m_vIbd[i].ibdDescriptor.NumberOfModuleForwarderRefs;
229 229
230 for (int j=0;j<calcNumberOfModuleForwarderRefs(i);j++) 230 for (int j=0;j<calcNumberOfModuleForwarderRefs(i);j++)
231 { 231 {
232 obBuffer << m_vIbd[i].moduleForwarders[j].ibdDescriptor.TimeDateStamp; 232 obBuffer << m_vIbd[i].moduleForwarders[j].ibdDescriptor.TimeDateStamp;
233 233
234 if (fMakeValid) 234 if (fMakeValid)
235 { 235 {
236 if (filename_offsets.find(m_vIbd[i].strModuleName) == filename_offsets.end()) 236 if (filename_offsets.find(m_vIbd[i].strModuleName) == filename_offsets.end())
237 { 237 {
238 filename_offsets[m_vIbd[i].moduleForwarders[j].strModuleName] = ulNameOffset; 238 filename_offsets[m_vIbd[i].moduleForwarders[j].strModuleName] = ulNameOffset;
239 obBuffer << ulNameOffset; 239 obBuffer << ulNameOffset;
240 ulNameOffset += static_cast<word>(m_vIbd[i].moduleForwarders[j].strModuleName.size() + 1); 240 ulNameOffset += static_cast<word>(m_vIbd[i].moduleForwarders[j].strModuleName.size() + 1);
241 } 241 }
242 else 242 else
243 { 243 {
244 obBuffer << filename_offsets[m_vIbd[i].moduleForwarders[j].strModuleName]; 244 obBuffer << filename_offsets[m_vIbd[i].moduleForwarders[j].strModuleName];
245 } 245 }
246 } 246 }
247 else // Otherwise just copy the old values into the buffer. 247 else // Otherwise just copy the old values into the buffer.
248 { 248 {
249 obBuffer << m_vIbd[i].moduleForwarders[j].ibdDescriptor.OffsetModuleName; 249 obBuffer << m_vIbd[i].moduleForwarders[j].ibdDescriptor.OffsetModuleName;
250 } 250 }
251 251
252 obBuffer << m_vIbd[i].moduleForwarders[j].ibdDescriptor.NumberOfModuleForwarderRefs; 252 obBuffer << m_vIbd[i].moduleForwarders[j].ibdDescriptor.NumberOfModuleForwarderRefs;
253 } 253 }
254 } 254 }
255 255
256 obBuffer << static_cast<dword>(0); 256 obBuffer << static_cast<dword>(0);
257 obBuffer << static_cast<word>(0); 257 obBuffer << static_cast<word>(0);
258 obBuffer << static_cast<word>(0); 258 obBuffer << static_cast<word>(0);
259 259
260 for (unsigned int i=0;i<m_vIbd.size();i++) 260 for (unsigned int i=0;i<m_vIbd.size();i++)
261 { 261 {
262 if (filename_offsets.find(m_vIbd[i].strModuleName) != filename_offsets.end()) 262 if (filename_offsets.find(m_vIbd[i].strModuleName) != filename_offsets.end())
263 { 263 {
264 obBuffer.add(getModuleName(i).c_str(), static_cast<unsigned long>(getModuleName(i).size() + 1)); 264 obBuffer.add(getModuleName(i).c_str(), static_cast<unsigned long>(getModuleName(i).size() + 1));
265 filename_offsets.erase(m_vIbd[i].strModuleName); 265 filename_offsets.erase(m_vIbd[i].strModuleName);
266 } 266 }
267 267
268 for (int j=0;j<calcNumberOfModuleForwarderRefs(i);j++) 268 for (int j=0;j<calcNumberOfModuleForwarderRefs(i);j++)
269 { 269 {
270 if (filename_offsets.find(getModuleName(i, j)) != filename_offsets.end()) 270 if (filename_offsets.find(getModuleName(i, j)) != filename_offsets.end())
271 { 271 {
272 obBuffer.add(getModuleName(i, j).c_str(), static_cast<unsigned long>(getModuleName(i, j).size() + 1)); 272 obBuffer.add(getModuleName(i, j).c_str(), static_cast<unsigned long>(getModuleName(i, j).size() + 1));
273 filename_offsets.erase(getModuleName(i, j)); 273 filename_offsets.erase(getModuleName(i, j));
274 } 274 }
275 } 275 }
276 } 276 }
277 } 277 }
278 278
279 /** 279 /**
280 * Removes all bound import files. 280 * Removes all bound import files.
281 **/ 281 **/
282 void BoundImportDirectory::clear() 282 void BoundImportDirectory::clear()
283 { 283 {
284 m_vIbd.clear(); 284 m_vIbd.clear();
285 } 285 }
286 286
287 /** 287 /**
288 * Removes a field specified by the parameter filename from the BoundImport directory. 288 * Removes a field specified by the parameter filename from the BoundImport directory.
289 * @param strModuleName Name of the file whose field will be removed from the BoundImport directory. 289 * @param strModuleName Name of the file whose field will be removed from the BoundImport directory.
290 **/ 290 **/
291 void BoundImportDirectory::removeBoundImport(const std::string& strModuleName) 291 void BoundImportDirectory::removeBoundImport(const std::string& strModuleName)
292 { 292 {
293 m_vIbd.erase(std::remove_if(m_vIbd.begin(), m_vIbd.end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_BOUND_DIRECTORY::equal), strModuleName)), m_vIbd.end()); 293 m_vIbd.erase(std::remove_if(m_vIbd.begin(), m_vIbd.end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_BOUND_DIRECTORY::equal), strModuleName)), m_vIbd.end());
294 } 294 }
295 295
296 /** 296 /**
297 * Returns the size of the rebuilt BoundImportDirectory. 297 * Returns the size of the rebuilt BoundImportDirectory.
298 * @return Size of the rebuilt BoundImportDirectory. 298 * @return Size of the rebuilt BoundImportDirectory.
299 **/ 299 **/
300 unsigned int BoundImportDirectory::size() const 300 unsigned int BoundImportDirectory::size() const
301 { 301 {
302 unsigned int size = PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size(); 302 unsigned int size = PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size();
303 303
304 std::set<std::string> filenames; 304 std::set<std::string> filenames;
305 305
306 for (unsigned int i = 0; i < m_vIbd.size(); i++) 306 for (unsigned int i = 0; i < m_vIbd.size(); i++)
307 { 307 {
308 filenames.insert(m_vIbd[i].strModuleName); 308 filenames.insert(m_vIbd[i].strModuleName);
309 309
310 size += PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size(); 310 size += PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size();
311 311
312 for (unsigned int j = 0; j < m_vIbd[i].moduleForwarders.size(); j++) 312 for (unsigned int j = 0; j < m_vIbd[i].moduleForwarders.size(); j++)
313 { 313 {
314 filenames.insert(m_vIbd[i].moduleForwarders[j].strModuleName); 314 filenames.insert(m_vIbd[i].moduleForwarders[j].strModuleName);
315 315
316 size += PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size(); 316 size += PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size();
317 } 317 }
318 } 318 }
319 319
320 for (std::set<std::string>::iterator iter = filenames.begin(); iter != filenames.end(); ++iter) 320 for (std::set<std::string>::iterator iter = filenames.begin(); iter != filenames.end(); ++iter)
321 { 321 {
322 size += static_cast<unsigned int>(iter->size()) + 1; 322 size += static_cast<unsigned int>(iter->size()) + 1;
323 } 323 }
324 324
325 return size; 325 return size;
326 } 326 }
327 327
328 /** 328 /**
329 * @param strFilename Name of the file. 329 * @param strFilename Name of the file.
330 * @param dwOffset File offset the bound importdirectory will be written to. 330 * @param dwOffset File offset the bound importdirectory will be written to.
331 * @param fMakeValid If this flag is true a valid directory will be produced. 331 * @param fMakeValid If this flag is true a valid directory will be produced.
332 **/ 332 **/
333 int BoundImportDirectory::write(const std::string& strFilename, dword dwOffset, bool fMakeValid) const 333 int BoundImportDirectory::write(const std::string& strFilename, dword dwOffset, bool fMakeValid) const
334 { 334 {
335 std::fstream ofFile(strFilename.c_str(), std::ios_base::in); 335 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
336 336
337 if (!ofFile) 337 if (!ofFile)
338 { 338 {
339 ofFile.clear(); 339 ofFile.clear();
340 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary); 340 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
341 } 341 }
342 else 342 else
343 { 343 {
344 ofFile.close(); 344 ofFile.close();
345 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary); 345 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
346 } 346 }
347 347
348 if (!ofFile) 348 if (!ofFile)
349 { 349 {
350 return ERROR_OPENING_FILE; 350 return ERROR_OPENING_FILE;
351 } 351 }
352 352
353 ofFile.seekp(dwOffset, std::ios::beg); 353 ofFile.seekp(dwOffset, std::ios::beg);
354 354
355 std::vector<unsigned char> vBuffer; 355 std::vector<unsigned char> vBuffer;
356 rebuild(vBuffer, fMakeValid); 356 rebuild(vBuffer, fMakeValid);
357 357
358 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<std::streamsize>(vBuffer.size())); 358 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<std::streamsize>(vBuffer.size()));
359 359
360 ofFile.close(); 360 ofFile.close();
361 361
362 return NO_ERROR; 362 return NO_ERROR;
363 } 363 }
364 364
365 /** 365 /**
366 * Retrieves the value of the TimeDateStamp value of a bound import field. 366 * Retrieves the value of the TimeDateStamp value of a bound import field.
367 * @param dwBidnr Number of the bound import field. 367 * @param dwBidnr Number of the bound import field.
368 * @return Value of the TimeDateStamp of the bound import field. 368 * @return Value of the TimeDateStamp of the bound import field.
369 **/ 369 **/
370 dword BoundImportDirectory::getTimeDateStamp(dword dwBidnr) const 370 dword BoundImportDirectory::getTimeDateStamp(dword dwBidnr) const
371 { 371 {
372 return m_vIbd[dwBidnr].ibdDescriptor.TimeDateStamp; 372 return m_vIbd[dwBidnr].ibdDescriptor.TimeDateStamp;
373 } 373 }
374 374
375 /** 375 /**
376 * Retrieves the value of the OffsetModuleName value of a bound import field. 376 * Retrieves the value of the OffsetModuleName value of a bound import field.
377 * @param dwBidnr Number of the bound import field. 377 * @param dwBidnr Number of the bound import field.
378 * @return Value of the OffsetModuleName of the bound import field. 378 * @return Value of the OffsetModuleName of the bound import field.
379 **/ 379 **/
380 word BoundImportDirectory::getOffsetModuleName(dword dwBidnr) const 380 word BoundImportDirectory::getOffsetModuleName(dword dwBidnr) const
381 { 381 {
382 return m_vIbd[dwBidnr].ibdDescriptor.OffsetModuleName; 382 return m_vIbd[dwBidnr].ibdDescriptor.OffsetModuleName;
383 } 383 }
384 384
385 /** 385 /**
386 * Retrieves the value of the NumberOfModuleForwarderRefs value of a bound import field. 386 * Retrieves the value of the NumberOfModuleForwarderRefs value of a bound import field.
387 * @param dwBidnr Number of the bound import field. 387 * @param dwBidnr Number of the bound import field.
388 * @return Value of the NumberOfModuleForwarderRefs of the bound import field. 388 * @return Value of the NumberOfModuleForwarderRefs of the bound import field.
389 **/ 389 **/
390 word BoundImportDirectory::getNumberOfModuleForwarderRefs(dword dwBidnr) const 390 word BoundImportDirectory::getNumberOfModuleForwarderRefs(dword dwBidnr) const
391 { 391 {
392 return m_vIbd[dwBidnr].ibdDescriptor.NumberOfModuleForwarderRefs; 392 return m_vIbd[dwBidnr].ibdDescriptor.NumberOfModuleForwarderRefs;
393 } 393 }
394 394
395 /** 395 /**
396 * Retrieves the value of the ModuleName value of a bound import field. 396 * Retrieves the value of the ModuleName value of a bound import field.
397 * @param dwBidnr Number of the bound import field. 397 * @param dwBidnr Number of the bound import field.
398 * @return Value of the ModuleName of the bound import field. 398 * @return Value of the ModuleName of the bound import field.
399 **/ 399 **/
400 std::string BoundImportDirectory::getModuleName(dword dwBidnr) const 400 std::string BoundImportDirectory::getModuleName(dword dwBidnr) const
401 { 401 {
402 return m_vIbd[dwBidnr].strModuleName; 402 return m_vIbd[dwBidnr].strModuleName;
403 } 403 }
404 404
405 /** 405 /**
406 * Changes the TimeDateStamp value of an existing bound import field. 406 * Changes the TimeDateStamp value of an existing bound import field.
407 * @param dwBidnr Number of the bound import field which will be changed. 407 * @param dwBidnr Number of the bound import field which will be changed.
408 * @param dwTds New value of the TimeDateStamp of the bound import field. 408 * @param dwTds New value of the TimeDateStamp of the bound import field.
409 **/ 409 **/
410 void BoundImportDirectory::setTimeDateStamp(dword dwBidnr, dword dwTds) 410 void BoundImportDirectory::setTimeDateStamp(dword dwBidnr, dword dwTds)
411 { 411 {
412 m_vIbd[dwBidnr].ibdDescriptor.TimeDateStamp = dwTds; 412 m_vIbd[dwBidnr].ibdDescriptor.TimeDateStamp = dwTds;
413 } 413 }
414 414
415 /** 415 /**
416 * Changes the OffsetModuleName value of an existing bound import field. 416 * Changes the OffsetModuleName value of an existing bound import field.
417 * @param dwBidnr Number of the bound import field which will be changed. 417 * @param dwBidnr Number of the bound import field which will be changed.
418 * @param wOmn New value of the OffsetModuleName of the bound import field. 418 * @param wOmn New value of the OffsetModuleName of the bound import field.
419 **/ 419 **/
420 void BoundImportDirectory::setOffsetModuleName(dword dwBidnr, word wOmn) 420 void BoundImportDirectory::setOffsetModuleName(dword dwBidnr, word wOmn)
421 { 421 {
422 m_vIbd[dwBidnr].ibdDescriptor.OffsetModuleName = wOmn; 422 m_vIbd[dwBidnr].ibdDescriptor.OffsetModuleName = wOmn;
423 } 423 }
424 424
425 /** 425 /**
426 * Changes the NumberOfModuleForwarderRefs value of an existing bound import field. 426 * Changes the NumberOfModuleForwarderRefs value of an existing bound import field.
427 * @param dwBidnr Number of the bound import field which will be changed. 427 * @param dwBidnr Number of the bound import field which will be changed.
428 * @param wMfr New value of the NumberOfModuleForwarderRefs of the bound import field. 428 * @param wMfr New value of the NumberOfModuleForwarderRefs of the bound import field.
429 **/ 429 **/
430 void BoundImportDirectory::setNumberOfModuleForwarderRefs(dword dwBidnr, word wMfr) 430 void BoundImportDirectory::setNumberOfModuleForwarderRefs(dword dwBidnr, word wMfr)
431 { 431 {
432 m_vIbd[dwBidnr].ibdDescriptor.NumberOfModuleForwarderRefs = wMfr; 432 m_vIbd[dwBidnr].ibdDescriptor.NumberOfModuleForwarderRefs = wMfr;
433 } 433 }
434 434
435 /** 435 /**
436 * Changes the ModuleName value of an existing bound import field. 436 * Changes the ModuleName value of an existing bound import field.
437 * @param dwBidnr Number of the bound import field which will be changed. 437 * @param dwBidnr Number of the bound import field which will be changed.
438 * @param strModuleName New value of the ModuleName of the bound import field. 438 * @param strModuleName New value of the ModuleName of the bound import field.
439 **/ 439 **/
440 void BoundImportDirectory::setModuleName(dword dwBidnr, const std::string& strModuleName) 440 void BoundImportDirectory::setModuleName(dword dwBidnr, const std::string& strModuleName)
441 { 441 {
442 m_vIbd[dwBidnr].strModuleName = strModuleName; 442 m_vIbd[dwBidnr].strModuleName = strModuleName;
443 } 443 }
444 444
445 dword BoundImportDirectory::getTimeDateStamp(dword dwBidnr, dword forwardedModule) const 445 dword BoundImportDirectory::getTimeDateStamp(dword dwBidnr, dword forwardedModule) const
446 { 446 {
447 return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.TimeDateStamp; 447 return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.TimeDateStamp;
448 } 448 }
449 449
450 word BoundImportDirectory::getOffsetModuleName(dword dwBidnr, dword forwardedModule) const 450 word BoundImportDirectory::getOffsetModuleName(dword dwBidnr, dword forwardedModule) const
451 { 451 {
452 return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.OffsetModuleName; 452 return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.OffsetModuleName;
453 } 453 }
454 454
455 word BoundImportDirectory::getNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule) const 455 word BoundImportDirectory::getNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule) const
456 { 456 {
457 return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.NumberOfModuleForwarderRefs; 457 return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.NumberOfModuleForwarderRefs;
458 } 458 }
459 459
460 std::string BoundImportDirectory::getModuleName(dword dwBidnr, dword forwardedModule) const 460 std::string BoundImportDirectory::getModuleName(dword dwBidnr, dword forwardedModule) const
461 { 461 {
462 return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].strModuleName; 462 return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].strModuleName;
463 } 463 }
464 464
465 void BoundImportDirectory::setTimeDateStamp(dword dwBidnr, dword forwardedModule, dword dwTds) 465 void BoundImportDirectory::setTimeDateStamp(dword dwBidnr, dword forwardedModule, dword dwTds)
466 { 466 {
467 m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.TimeDateStamp = dwTds; 467 m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.TimeDateStamp = dwTds;
468 } 468 }
469 469
470 void BoundImportDirectory::setOffsetModuleName(dword dwBidnr, dword forwardedModule, word wOmn) 470 void BoundImportDirectory::setOffsetModuleName(dword dwBidnr, dword forwardedModule, word wOmn)
471 { 471 {
472 m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.OffsetModuleName = wOmn; 472 m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.OffsetModuleName = wOmn;
473 } 473 }
474 474
475 void BoundImportDirectory::setNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule, word wMfr) 475 void BoundImportDirectory::setNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule, word wMfr)
476 { 476 {
477 m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.NumberOfModuleForwarderRefs = wMfr; 477 m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.NumberOfModuleForwarderRefs = wMfr;
478 } 478 }
479 479
480 void BoundImportDirectory::setModuleName(dword dwBidnr, dword forwardedModule, const std::string& strModuleName) 480 void BoundImportDirectory::setModuleName(dword dwBidnr, dword forwardedModule, const std::string& strModuleName)
481 { 481 {
482 m_vIbd[dwBidnr].moduleForwarders[forwardedModule].strModuleName = strModuleName; 482 m_vIbd[dwBidnr].moduleForwarders[forwardedModule].strModuleName = strModuleName;
483 } 483 }
484 484
485 word BoundImportDirectory::calcNumberOfModuleForwarderRefs(dword dwBidnr) const 485 word BoundImportDirectory::calcNumberOfModuleForwarderRefs(dword dwBidnr) const
486 { 486 {
487 return static_cast<word>(m_vIbd[dwBidnr].moduleForwarders.size()); 487 return static_cast<word>(m_vIbd[dwBidnr].moduleForwarders.size());
488 } 488 }
489 489
490 void BoundImportDirectory::addForwardedModule(dword dwBidnr, const std::string& name, dword timeStamp, word offsetModuleName, word forwardedModules) 490 void BoundImportDirectory::addForwardedModule(dword dwBidnr, const std::string& name, dword timeStamp, word offsetModuleName, word forwardedModules)
491 { 491 {
492 // XXX: Maybe test if there are already 0xFFFF forwarded modules. 492 // XXX: Maybe test if there are already 0xFFFF forwarded modules.
493 // XXX: Check for duplicate entries. Is it also necessary to check 493 // XXX: Check for duplicate entries. Is it also necessary to check
494 // non-forwarded entries and forwarded entries in other non-forwarded 494 // non-forwarded entries and forwarded entries in other non-forwarded
495 // entries? 495 // entries?
496 // XXX: Can forwarders forward recursively? 496 // XXX: Can forwarders forward recursively?
497 497
498 PELIB_IMAGE_BOUND_DIRECTORY ibdCurrent; 498 PELIB_IMAGE_BOUND_DIRECTORY ibdCurrent;
499 ibdCurrent.strModuleName = name; 499 ibdCurrent.strModuleName = name;
500 ibdCurrent.ibdDescriptor.TimeDateStamp = timeStamp; 500 ibdCurrent.ibdDescriptor.TimeDateStamp = timeStamp;
501 ibdCurrent.ibdDescriptor.OffsetModuleName = offsetModuleName; 501 ibdCurrent.ibdDescriptor.OffsetModuleName = offsetModuleName;
502 ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs = forwardedModules; 502 ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs = forwardedModules;
503 503
504 m_vIbd[dwBidnr].moduleForwarders.push_back(ibdCurrent); 504 m_vIbd[dwBidnr].moduleForwarders.push_back(ibdCurrent);
505 } 505 }
506 506
507 void BoundImportDirectory::removeForwardedModule(dword dwBidnr, word forwardedModule) 507 void BoundImportDirectory::removeForwardedModule(dword dwBidnr, word forwardedModule)
508 { 508 {
509 m_vIbd[dwBidnr].moduleForwarders.erase(m_vIbd[dwBidnr].moduleForwarders.begin() + forwardedModule); 509 m_vIbd[dwBidnr].moduleForwarders.erase(m_vIbd[dwBidnr].moduleForwarders.begin() + forwardedModule);
510 } 510 }
511} 511}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.h
index fd2bab56fd..142d78f710 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.h
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.h
@@ -1,87 +1,87 @@
1/* 1/*
2* BoundImportDirectory.h - Part of the PeLib library. 2* BoundImportDirectory.h - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#ifndef BOUNDIMPORTDIRECTORY_H 13#ifndef BOUNDIMPORTDIRECTORY_H
14#define BOUNDIMPORTDIRECTORY_H 14#define BOUNDIMPORTDIRECTORY_H
15 15
16#include "PeLibAux.h" 16#include "PeLibAux.h"
17 17
18namespace PeLib 18namespace PeLib
19{ 19{
20 /// Class that handles the BoundImport directory. 20 /// Class that handles the BoundImport directory.
21 /** 21 /**
22 * This class can read and modify the BoundImport directory table of a PE file. 22 * This class can read and modify the BoundImport directory table of a PE file.
23 **/ 23 **/
24 class BoundImportDirectory 24 class BoundImportDirectory
25 { 25 {
26 private: 26 private:
27 std::vector<PELIB_IMAGE_BOUND_DIRECTORY> m_vIbd; ///< Stores the individual BoundImport fields. 27 std::vector<PELIB_IMAGE_BOUND_DIRECTORY> m_vIbd; ///< Stores the individual BoundImport fields.
28 28
29 int read(InputBuffer& inpBuffer, unsigned char* data, unsigned int dwSize); 29 int read(InputBuffer& inpBuffer, unsigned char* data, unsigned int dwSize);
30 unsigned int totalModules() const; 30 unsigned int totalModules() const;
31 public: 31 public:
32 /// Adds another bound import. 32 /// Adds another bound import.
33 int addBoundImport(const std::string& strModuleName, dword dwTds, word dwOmn, word wWfr); // EXPORT 33 int addBoundImport(const std::string& strModuleName, dword dwTds, word dwOmn, word wWfr); // EXPORT
34 /// Identifies a module through it's name. 34 /// Identifies a module through it's name.
35 int getModuleIndex(const std::string& strModuleName) const; // EXPORT 35 int getModuleIndex(const std::string& strModuleName) const; // EXPORT
36 /// Returns the number of files in the BoundImport directory. 36 /// Returns the number of files in the BoundImport directory.
37 unsigned int calcNumberOfModules() const; // EXPORT 37 unsigned int calcNumberOfModules() const; // EXPORT
38 /// Reads the BoundImport directory table from a PE file. 38 /// Reads the BoundImport directory table from a PE file.
39 int read(const std::string& strFileName, dword dwOffset, unsigned int uiSize); // EXPORT 39 int read(const std::string& strFileName, dword dwOffset, unsigned int uiSize); // EXPORT
40 int read(unsigned char* pcBuffer, unsigned int uiSize); // EXPORT 40 int read(unsigned char* pcBuffer, unsigned int uiSize); // EXPORT
41 /// Rebuilds the BoundImport directory. 41 /// Rebuilds the BoundImport directory.
42 void rebuild(std::vector<byte>& vBuffer, bool fMakeValid = true) const; // EXPORT 42 void rebuild(std::vector<byte>& vBuffer, bool fMakeValid = true) const; // EXPORT
43 /// Empties the BoundImport directory. 43 /// Empties the BoundImport directory.
44 void clear(); // EXPORT 44 void clear(); // EXPORT
45 /// Removes a bound import. 45 /// Removes a bound import.
46 void removeBoundImport(const std::string& strModuleName); // EXPORT 46 void removeBoundImport(const std::string& strModuleName); // EXPORT
47 /// Returns the size of the BoundImport directory. 47 /// Returns the size of the BoundImport directory.
48 unsigned int size() const; // EXPORT 48 unsigned int size() const; // EXPORT
49 /// Writes the current bound import directory to a file. 49 /// Writes the current bound import directory to a file.
50 int write(const std::string& strFilename, dword dwOffset, bool fMakeValid = true) const; // EXPORT 50 int write(const std::string& strFilename, dword dwOffset, bool fMakeValid = true) const; // EXPORT
51 51
52 /// Retrieves the TimeDateStamp value of a bound import. 52 /// Retrieves the TimeDateStamp value of a bound import.
53 dword getTimeDateStamp(dword dwBidnr) const; // EXPORT 53 dword getTimeDateStamp(dword dwBidnr) const; // EXPORT
54 /// Retrieves the OffsetModuleName value of a bound import. 54 /// Retrieves the OffsetModuleName value of a bound import.
55 word getOffsetModuleName(dword dwBidnr) const; // EXPORT 55 word getOffsetModuleName(dword dwBidnr) const; // EXPORT
56 /// Retrieves the NumberOfModuleForwarderRefs value of a bound import. 56 /// Retrieves the NumberOfModuleForwarderRefs value of a bound import.
57 word getNumberOfModuleForwarderRefs(dword dwBidnr) const; // EXPORT 57 word getNumberOfModuleForwarderRefs(dword dwBidnr) const; // EXPORT
58 /// Retrieves the ModuleName value of a bound import. 58 /// Retrieves the ModuleName value of a bound import.
59 std::string getModuleName(dword dwBidnr) const; // EXPORT 59 std::string getModuleName(dword dwBidnr) const; // EXPORT
60 60
61 /// Updates the TimeDateStamp value of a bound import. 61 /// Updates the TimeDateStamp value of a bound import.
62 void setTimeDateStamp(dword dwBidnr, dword dwTds); // EXPORT 62 void setTimeDateStamp(dword dwBidnr, dword dwTds); // EXPORT
63 /// Updates the OffsetModuleName value of a bound import. 63 /// Updates the OffsetModuleName value of a bound import.
64 void setOffsetModuleName(dword dwBidnr, word wOmn); // EXPORT 64 void setOffsetModuleName(dword dwBidnr, word wOmn); // EXPORT
65 /// Updates the NumberOfModuleForwarderRefs value of a bound import. 65 /// Updates the NumberOfModuleForwarderRefs value of a bound import.
66 void setNumberOfModuleForwarderRefs(dword dwBidnr, word wMfr); // EXPORT 66 void setNumberOfModuleForwarderRefs(dword dwBidnr, word wMfr); // EXPORT
67 /// Updates the ModuleName value of a bound import. 67 /// Updates the ModuleName value of a bound import.
68 void setModuleName(dword dwBidnr, const std::string& strModuleName); // EXPORT 68 void setModuleName(dword dwBidnr, const std::string& strModuleName); // EXPORT
69 69
70 dword getTimeDateStamp(dword dwBidnr, dword forwardedModule) const; // EXPORT _module 70 dword getTimeDateStamp(dword dwBidnr, dword forwardedModule) const; // EXPORT _module
71 word getOffsetModuleName(dword dwBidnr, dword forwardedModule) const; // EXPORT _module 71 word getOffsetModuleName(dword dwBidnr, dword forwardedModule) const; // EXPORT _module
72 word getNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule) const; // EXPORT _module 72 word getNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule) const; // EXPORT _module
73 std::string getModuleName(dword dwBidnr, dword forwardedModule) const; // EXPORT _module 73 std::string getModuleName(dword dwBidnr, dword forwardedModule) const; // EXPORT _module
74 74
75 void setTimeDateStamp(dword dwBidnr, dword forwardedModule, dword dwTds); // EXPORT _module 75 void setTimeDateStamp(dword dwBidnr, dword forwardedModule, dword dwTds); // EXPORT _module
76 void setOffsetModuleName(dword dwBidnr, dword forwardedModule, word wOmn); // EXPORT _module 76 void setOffsetModuleName(dword dwBidnr, dword forwardedModule, word wOmn); // EXPORT _module
77 void setNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule, word wMfr); // EXPORT _module 77 void setNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule, word wMfr); // EXPORT _module
78 void setModuleName(dword dwBidnr, dword forwardedModule, const std::string& strModuleName); // EXPORT _module 78 void setModuleName(dword dwBidnr, dword forwardedModule, const std::string& strModuleName); // EXPORT _module
79 79
80 word calcNumberOfModuleForwarderRefs(dword dwBidnr) const; // EXPORT 80 word calcNumberOfModuleForwarderRefs(dword dwBidnr) const; // EXPORT
81 void addForwardedModule(dword dwBidnr, const std::string& name, dword timeStamp = 0, word offsetModuleName = 0, word forwardedModules = 0); // EXPORT 81 void addForwardedModule(dword dwBidnr, const std::string& name, dword timeStamp = 0, word offsetModuleName = 0, word forwardedModules = 0); // EXPORT
82 void removeForwardedModule(dword dwBidnr, word forwardedModule); // EXPORT 82 void removeForwardedModule(dword dwBidnr, word forwardedModule); // EXPORT
83 }; 83 };
84} 84}
85 85
86 86
87#endif 87#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.cpp
index 886348994e..fef12f4d8b 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.cpp
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.cpp
@@ -1,467 +1,467 @@
1/* 1/*
2* ComHeaderDirectory.cpp - Part of the PeLib library. 2* ComHeaderDirectory.cpp - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#include "PeLibInc.h" 13#include "PeLibInc.h"
14#include "ComHeaderDirectory.h" 14#include "ComHeaderDirectory.h"
15 15
16namespace PeLib 16namespace PeLib
17{ 17{
18 void ComHeaderDirectory::read(InputBuffer& inputbuffer) 18 void ComHeaderDirectory::read(InputBuffer& inputbuffer)
19 { 19 {
20 PELIB_IMAGE_COR20_HEADER ichCurr; 20 PELIB_IMAGE_COR20_HEADER ichCurr;
21 21
22 inputbuffer >> ichCurr.cb; 22 inputbuffer >> ichCurr.cb;
23 inputbuffer >> ichCurr.MajorRuntimeVersion; 23 inputbuffer >> ichCurr.MajorRuntimeVersion;
24 inputbuffer >> ichCurr.MinorRuntimeVersion; 24 inputbuffer >> ichCurr.MinorRuntimeVersion;
25 inputbuffer >> ichCurr.MetaData.VirtualAddress; 25 inputbuffer >> ichCurr.MetaData.VirtualAddress;
26 inputbuffer >> ichCurr.MetaData.Size; 26 inputbuffer >> ichCurr.MetaData.Size;
27 inputbuffer >> ichCurr.Flags; 27 inputbuffer >> ichCurr.Flags;
28 inputbuffer >> ichCurr.EntryPointToken; 28 inputbuffer >> ichCurr.EntryPointToken;
29 inputbuffer >> ichCurr.Resources.VirtualAddress; 29 inputbuffer >> ichCurr.Resources.VirtualAddress;
30 inputbuffer >> ichCurr.Resources.Size; 30 inputbuffer >> ichCurr.Resources.Size;
31 inputbuffer >> ichCurr.StrongNameSignature.VirtualAddress; 31 inputbuffer >> ichCurr.StrongNameSignature.VirtualAddress;
32 inputbuffer >> ichCurr.StrongNameSignature.Size; 32 inputbuffer >> ichCurr.StrongNameSignature.Size;
33 inputbuffer >> ichCurr.CodeManagerTable.VirtualAddress; 33 inputbuffer >> ichCurr.CodeManagerTable.VirtualAddress;
34 inputbuffer >> ichCurr.CodeManagerTable.Size; 34 inputbuffer >> ichCurr.CodeManagerTable.Size;
35 inputbuffer >> ichCurr.VTableFixups.VirtualAddress; 35 inputbuffer >> ichCurr.VTableFixups.VirtualAddress;
36 inputbuffer >> ichCurr.VTableFixups.Size; 36 inputbuffer >> ichCurr.VTableFixups.Size;
37 inputbuffer >> ichCurr.ExportAddressTableJumps.VirtualAddress; 37 inputbuffer >> ichCurr.ExportAddressTableJumps.VirtualAddress;
38 inputbuffer >> ichCurr.ExportAddressTableJumps.Size; 38 inputbuffer >> ichCurr.ExportAddressTableJumps.Size;
39 inputbuffer >> ichCurr.ManagedNativeHeader.VirtualAddress; 39 inputbuffer >> ichCurr.ManagedNativeHeader.VirtualAddress;
40 inputbuffer >> ichCurr.ManagedNativeHeader.Size; 40 inputbuffer >> ichCurr.ManagedNativeHeader.Size;
41 41
42 std::swap(ichCurr, m_ichComHeader); 42 std::swap(ichCurr, m_ichComHeader);
43 } 43 }
44 44
45 int ComHeaderDirectory::read(unsigned char* buffer, unsigned int buffersize) 45 int ComHeaderDirectory::read(unsigned char* buffer, unsigned int buffersize)
46 { 46 {
47 if (buffersize < PELIB_IMAGE_COR20_HEADER::size()) 47 if (buffersize < PELIB_IMAGE_COR20_HEADER::size())
48 { 48 {
49 return ERROR_INVALID_FILE; 49 return ERROR_INVALID_FILE;
50 } 50 }
51 51
52 std::vector<byte> vComDescDirectory(buffer, buffer + buffersize); 52 std::vector<byte> vComDescDirectory(buffer, buffer + buffersize);
53 53
54 InputBuffer ibBuffer(vComDescDirectory); 54 InputBuffer ibBuffer(vComDescDirectory);
55 read(ibBuffer); 55 read(ibBuffer);
56 return NO_ERROR; 56 return NO_ERROR;
57 } 57 }
58 58
59 /** 59 /**
60 * Reads a file's COM+ descriptor. 60 * Reads a file's COM+ descriptor.
61 * @param strFilename Name of the file. 61 * @param strFilename Name of the file.
62 * @param uiOffset File offset of the COM+ descriptor. 62 * @param uiOffset File offset of the COM+ descriptor.
63 * @param uiSize Size of the COM+ descriptor. 63 * @param uiSize Size of the COM+ descriptor.
64 **/ 64 **/
65 int ComHeaderDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize) 65 int ComHeaderDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize)
66 { 66 {
67 std::ifstream ifFile(strFilename.c_str(), std::ios::binary); 67 std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
68 unsigned int ulFileSize = fileSize(ifFile); 68 unsigned int ulFileSize = fileSize(ifFile);
69 69
70 if (!ifFile) 70 if (!ifFile)
71 { 71 {
72 return ERROR_OPENING_FILE; 72 return ERROR_OPENING_FILE;
73 } 73 }
74 74
75 if (ulFileSize < uiOffset + uiSize) 75 if (ulFileSize < uiOffset + uiSize)
76 { 76 {
77 return ERROR_INVALID_FILE; 77 return ERROR_INVALID_FILE;
78 } 78 }
79 79
80 ifFile.seekg(uiOffset, std::ios::beg); 80 ifFile.seekg(uiOffset, std::ios::beg);
81 81
82 std::vector<byte> vComDescDirectory(uiSize); 82 std::vector<byte> vComDescDirectory(uiSize);
83 ifFile.read(reinterpret_cast<char*>(&vComDescDirectory[0]), uiSize); 83 ifFile.read(reinterpret_cast<char*>(&vComDescDirectory[0]), uiSize);
84 84
85 InputBuffer ibBuffer(vComDescDirectory); 85 InputBuffer ibBuffer(vComDescDirectory);
86 read(ibBuffer); 86 read(ibBuffer);
87 return NO_ERROR; 87 return NO_ERROR;
88 } 88 }
89 89
90 /** 90 /**
91 * Rebuilds the current COM+ descriptor. 91 * Rebuilds the current COM+ descriptor.
92 * @param vBuffer Buffer where the COM+ descriptor will be written to. 92 * @param vBuffer Buffer where the COM+ descriptor will be written to.
93 **/ 93 **/
94 void ComHeaderDirectory::rebuild(std::vector<byte>& vBuffer) const 94 void ComHeaderDirectory::rebuild(std::vector<byte>& vBuffer) const
95 { 95 {
96 OutputBuffer obBuffer(vBuffer); 96 OutputBuffer obBuffer(vBuffer);
97 97
98 obBuffer << m_ichComHeader.cb; 98 obBuffer << m_ichComHeader.cb;
99 obBuffer << m_ichComHeader.MajorRuntimeVersion; 99 obBuffer << m_ichComHeader.MajorRuntimeVersion;
100 obBuffer << m_ichComHeader.MinorRuntimeVersion; 100 obBuffer << m_ichComHeader.MinorRuntimeVersion;
101 obBuffer << m_ichComHeader.MetaData.VirtualAddress; 101 obBuffer << m_ichComHeader.MetaData.VirtualAddress;
102 obBuffer << m_ichComHeader.MetaData.Size; 102 obBuffer << m_ichComHeader.MetaData.Size;
103 obBuffer << m_ichComHeader.Flags; 103 obBuffer << m_ichComHeader.Flags;
104 obBuffer << m_ichComHeader.EntryPointToken; 104 obBuffer << m_ichComHeader.EntryPointToken;
105 obBuffer << m_ichComHeader.Resources.VirtualAddress; 105 obBuffer << m_ichComHeader.Resources.VirtualAddress;
106 obBuffer << m_ichComHeader.Resources.Size; 106 obBuffer << m_ichComHeader.Resources.Size;
107 obBuffer << m_ichComHeader.StrongNameSignature.VirtualAddress; 107 obBuffer << m_ichComHeader.StrongNameSignature.VirtualAddress;
108 obBuffer << m_ichComHeader.StrongNameSignature.Size; 108 obBuffer << m_ichComHeader.StrongNameSignature.Size;
109 obBuffer << m_ichComHeader.CodeManagerTable.VirtualAddress; 109 obBuffer << m_ichComHeader.CodeManagerTable.VirtualAddress;
110 obBuffer << m_ichComHeader.CodeManagerTable.Size; 110 obBuffer << m_ichComHeader.CodeManagerTable.Size;
111 obBuffer << m_ichComHeader.VTableFixups.VirtualAddress; 111 obBuffer << m_ichComHeader.VTableFixups.VirtualAddress;
112 obBuffer << m_ichComHeader.VTableFixups.Size; 112 obBuffer << m_ichComHeader.VTableFixups.Size;
113 obBuffer << m_ichComHeader.ExportAddressTableJumps.VirtualAddress; 113 obBuffer << m_ichComHeader.ExportAddressTableJumps.VirtualAddress;
114 obBuffer << m_ichComHeader.ExportAddressTableJumps.Size; 114 obBuffer << m_ichComHeader.ExportAddressTableJumps.Size;
115 obBuffer << m_ichComHeader.ManagedNativeHeader.VirtualAddress; 115 obBuffer << m_ichComHeader.ManagedNativeHeader.VirtualAddress;
116 obBuffer << m_ichComHeader.ManagedNativeHeader.Size; 116 obBuffer << m_ichComHeader.ManagedNativeHeader.Size;
117 } 117 }
118 118
119 /** 119 /**
120 * @return Size in bytes. 120 * @return Size in bytes.
121 **/ 121 **/
122 unsigned int ComHeaderDirectory::size() const 122 unsigned int ComHeaderDirectory::size() const
123 { 123 {
124 return PELIB_IMAGE_COR20_HEADER::size(); 124 return PELIB_IMAGE_COR20_HEADER::size();
125 } 125 }
126 126
127 /** 127 /**
128 * @param strFilename Name of the file. 128 * @param strFilename Name of the file.
129 * @param dwOffset File offset the COM+ descriptor will be written to. 129 * @param dwOffset File offset the COM+ descriptor will be written to.
130 **/ 130 **/
131 int ComHeaderDirectory::write(const std::string& strFilename, unsigned int dwOffset) const 131 int ComHeaderDirectory::write(const std::string& strFilename, unsigned int dwOffset) const
132 { 132 {
133 std::fstream ofFile(strFilename.c_str(), std::ios_base::in); 133 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
134 134
135 if (!ofFile) 135 if (!ofFile)
136 { 136 {
137 ofFile.clear(); 137 ofFile.clear();
138 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary); 138 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
139 } 139 }
140 else 140 else
141 { 141 {
142 ofFile.close(); 142 ofFile.close();
143 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary); 143 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
144 } 144 }
145 145
146 if (!ofFile) 146 if (!ofFile)
147 { 147 {
148 return ERROR_OPENING_FILE; 148 return ERROR_OPENING_FILE;
149 } 149 }
150 150
151 ofFile.seekp(dwOffset, std::ios::beg); 151 ofFile.seekp(dwOffset, std::ios::beg);
152 152
153 std::vector<unsigned char> vBuffer; 153 std::vector<unsigned char> vBuffer;
154 rebuild(vBuffer); 154 rebuild(vBuffer);
155 155
156 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size())); 156 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
157 157
158 ofFile.close(); 158 ofFile.close();
159 159
160 return NO_ERROR; 160 return NO_ERROR;
161 } 161 }
162 162
163 /** 163 /**
164 * @return SizeOfHeader value of the current COM+ descriptor. 164 * @return SizeOfHeader value of the current COM+ descriptor.
165 **/ 165 **/
166 dword ComHeaderDirectory::getSizeOfHeader() const 166 dword ComHeaderDirectory::getSizeOfHeader() const
167 { 167 {
168 return m_ichComHeader.cb; 168 return m_ichComHeader.cb;
169 } 169 }
170 170
171 /** 171 /**
172 * @return MajorRuntimeVersion value of the current COM+ descriptor. 172 * @return MajorRuntimeVersion value of the current COM+ descriptor.
173 **/ 173 **/
174 word ComHeaderDirectory::getMajorRuntimeVersion() const 174 word ComHeaderDirectory::getMajorRuntimeVersion() const
175 { 175 {
176 return m_ichComHeader.MajorRuntimeVersion; 176 return m_ichComHeader.MajorRuntimeVersion;
177 } 177 }
178 178
179 /** 179 /**
180 * @return MinorRuntimeVersion value of the current COM+ descriptor. 180 * @return MinorRuntimeVersion value of the current COM+ descriptor.
181 **/ 181 **/
182 word ComHeaderDirectory::getMinorRuntimeVersion() const 182 word ComHeaderDirectory::getMinorRuntimeVersion() const
183 { 183 {
184 return m_ichComHeader.MinorRuntimeVersion; 184 return m_ichComHeader.MinorRuntimeVersion;
185 } 185 }
186 186
187 /** 187 /**
188 * @return MetaData (Virtual Address) value of the current COM+ descriptor. 188 * @return MetaData (Virtual Address) value of the current COM+ descriptor.
189 **/ 189 **/
190 dword ComHeaderDirectory::getMetaDataVa() const 190 dword ComHeaderDirectory::getMetaDataVa() const
191 { 191 {
192 return m_ichComHeader.MetaData.VirtualAddress; 192 return m_ichComHeader.MetaData.VirtualAddress;
193 } 193 }
194 194
195 /** 195 /**
196 * @return MetaData (Size) value of the current COM+ descriptor. 196 * @return MetaData (Size) value of the current COM+ descriptor.
197 **/ 197 **/
198 dword ComHeaderDirectory::getMetaDataSize() const 198 dword ComHeaderDirectory::getMetaDataSize() const
199 { 199 {
200 return m_ichComHeader.MetaData.Size; 200 return m_ichComHeader.MetaData.Size;
201 } 201 }
202 202
203 /** 203 /**
204 * @return Flags value of the current COM+ descriptor. 204 * @return Flags value of the current COM+ descriptor.
205 **/ 205 **/
206 dword ComHeaderDirectory::getFlags() const 206 dword ComHeaderDirectory::getFlags() const
207 { 207 {
208 return m_ichComHeader.Flags; 208 return m_ichComHeader.Flags;
209 } 209 }
210 210
211 /** 211 /**
212 * @return EntryPointToken value of the current COM+ descriptor. 212 * @return EntryPointToken value of the current COM+ descriptor.
213 **/ 213 **/
214 dword ComHeaderDirectory::getEntryPointToken() const 214 dword ComHeaderDirectory::getEntryPointToken() const
215 { 215 {
216 return m_ichComHeader.EntryPointToken; 216 return m_ichComHeader.EntryPointToken;
217 } 217 }
218 218
219 /** 219 /**
220 * @return Resources (Virtual Address) value of the current COM+ descriptor. 220 * @return Resources (Virtual Address) value of the current COM+ descriptor.
221 **/ 221 **/
222 dword ComHeaderDirectory::getResourcesVa() const 222 dword ComHeaderDirectory::getResourcesVa() const
223 { 223 {
224 return m_ichComHeader.Resources.VirtualAddress; 224 return m_ichComHeader.Resources.VirtualAddress;
225 } 225 }
226 226
227 /** 227 /**
228 * @return Resources (Size) value of the current COM+ descriptor. 228 * @return Resources (Size) value of the current COM+ descriptor.
229 **/ 229 **/
230 dword ComHeaderDirectory::getResourcesSize() 230 dword ComHeaderDirectory::getResourcesSize()
231 { 231 {
232 return m_ichComHeader.Resources.Size; 232 return m_ichComHeader.Resources.Size;
233 } 233 }
234 234
235 /** 235 /**
236 * @return StrongNameSignature (Virtual Address) value of the current COM+ descriptor. 236 * @return StrongNameSignature (Virtual Address) value of the current COM+ descriptor.
237 **/ 237 **/
238 dword ComHeaderDirectory::getStrongNameSignatureVa() const 238 dword ComHeaderDirectory::getStrongNameSignatureVa() const
239 { 239 {
240 return m_ichComHeader.StrongNameSignature.VirtualAddress; 240 return m_ichComHeader.StrongNameSignature.VirtualAddress;
241 } 241 }
242 242
243 /** 243 /**
244 * @return StrongNameSignature (Size) value of the current COM+ descriptor. 244 * @return StrongNameSignature (Size) value of the current COM+ descriptor.
245 **/ 245 **/
246 dword ComHeaderDirectory::getStrongNameSignagureSize() const 246 dword ComHeaderDirectory::getStrongNameSignagureSize() const
247 { 247 {
248 return m_ichComHeader.StrongNameSignature.Size; 248 return m_ichComHeader.StrongNameSignature.Size;
249 } 249 }
250 250
251 /** 251 /**
252 * @return CodeManagerTable (Virtual Address) value of the current COM+ descriptor. 252 * @return CodeManagerTable (Virtual Address) value of the current COM+ descriptor.
253 **/ 253 **/
254 dword ComHeaderDirectory::getCodeManagerTableVa() const 254 dword ComHeaderDirectory::getCodeManagerTableVa() const
255 { 255 {
256 return m_ichComHeader.CodeManagerTable.VirtualAddress; 256 return m_ichComHeader.CodeManagerTable.VirtualAddress;
257 } 257 }
258 258
259 /** 259 /**
260 * @return CodeManagerTable (Size) value of the current COM+ descriptor. 260 * @return CodeManagerTable (Size) value of the current COM+ descriptor.
261 **/ 261 **/
262 dword ComHeaderDirectory::getCodeManagerTableSize() const 262 dword ComHeaderDirectory::getCodeManagerTableSize() const
263 { 263 {
264 return m_ichComHeader.CodeManagerTable.Size; 264 return m_ichComHeader.CodeManagerTable.Size;
265 } 265 }
266 266
267 /** 267 /**
268 * @return VTableFixups (Virtual Address) value of the current COM+ descriptor. 268 * @return VTableFixups (Virtual Address) value of the current COM+ descriptor.
269 **/ 269 **/
270 dword ComHeaderDirectory::getVTableFixupsVa() const 270 dword ComHeaderDirectory::getVTableFixupsVa() const
271 { 271 {
272 return m_ichComHeader.VTableFixups.VirtualAddress; 272 return m_ichComHeader.VTableFixups.VirtualAddress;
273 } 273 }
274 274
275 /** 275 /**
276 * @return VTableFixups (Size) value of the current COM+ descriptor. 276 * @return VTableFixups (Size) value of the current COM+ descriptor.
277 **/ 277 **/
278 dword ComHeaderDirectory::getVTableFixupsSize() const 278 dword ComHeaderDirectory::getVTableFixupsSize() const
279 { 279 {
280 return m_ichComHeader.VTableFixups.Size; 280 return m_ichComHeader.VTableFixups.Size;
281 } 281 }
282 282
283 /** 283 /**
284 * @return ExportAddressTableJumps (Virtual Address) value of the current COM+ descriptor. 284 * @return ExportAddressTableJumps (Virtual Address) value of the current COM+ descriptor.
285 **/ 285 **/
286 dword ComHeaderDirectory::getExportAddressTableJumpsVa() const 286 dword ComHeaderDirectory::getExportAddressTableJumpsVa() const
287 { 287 {
288 return m_ichComHeader.ExportAddressTableJumps.VirtualAddress; 288 return m_ichComHeader.ExportAddressTableJumps.VirtualAddress;
289 } 289 }
290 290
291 /** 291 /**
292 * @return ExportAddressTableJumps (Size) value of the current COM+ descriptor. 292 * @return ExportAddressTableJumps (Size) value of the current COM+ descriptor.
293 **/ 293 **/
294 dword ComHeaderDirectory::getExportAddressTableJumpsSize() const 294 dword ComHeaderDirectory::getExportAddressTableJumpsSize() const
295 { 295 {
296 return m_ichComHeader.ExportAddressTableJumps.Size; 296 return m_ichComHeader.ExportAddressTableJumps.Size;
297 } 297 }
298 298
299 /** 299 /**
300 * @return ManagedNativeHeader (Virtual Address) value of the current COM+ descriptor. 300 * @return ManagedNativeHeader (Virtual Address) value of the current COM+ descriptor.
301 **/ 301 **/
302 dword ComHeaderDirectory::getManagedNativeHeaderVa() const 302 dword ComHeaderDirectory::getManagedNativeHeaderVa() const
303 { 303 {
304 return m_ichComHeader.ManagedNativeHeader.VirtualAddress; 304 return m_ichComHeader.ManagedNativeHeader.VirtualAddress;
305 } 305 }
306 306
307 /** 307 /**
308 * @return ManagedNativeHeader (Size) value of the current COM+ descriptor. 308 * @return ManagedNativeHeader (Size) value of the current COM+ descriptor.
309 **/ 309 **/
310 dword ComHeaderDirectory::getManagedNativeHeaderSize() const 310 dword ComHeaderDirectory::getManagedNativeHeaderSize() const
311 { 311 {
312 return m_ichComHeader.ManagedNativeHeader.Size; 312 return m_ichComHeader.ManagedNativeHeader.Size;
313 } 313 }
314 314
315 /** 315 /**
316 * @param dwValue New value for the current SizeOfHeader (cb) value. 316 * @param dwValue New value for the current SizeOfHeader (cb) value.
317 **/ 317 **/
318 void ComHeaderDirectory::setSizeOfHeader(dword dwValue) 318 void ComHeaderDirectory::setSizeOfHeader(dword dwValue)
319 { 319 {
320 m_ichComHeader.cb = dwValue; 320 m_ichComHeader.cb = dwValue;
321 } 321 }
322 322
323 /** 323 /**
324 * @param wValue New value for the current MajorRuntimeVersion value. 324 * @param wValue New value for the current MajorRuntimeVersion value.
325 **/ 325 **/
326 void ComHeaderDirectory::setMajorRuntimeVersion(word wValue) 326 void ComHeaderDirectory::setMajorRuntimeVersion(word wValue)
327 { 327 {
328 m_ichComHeader.MajorRuntimeVersion = wValue; 328 m_ichComHeader.MajorRuntimeVersion = wValue;
329 } 329 }
330 330
331 /** 331 /**
332 * @param wValue New value for the current MinorRuntimeVersion value. 332 * @param wValue New value for the current MinorRuntimeVersion value.
333 **/ 333 **/
334 void ComHeaderDirectory::setMinorRuntimeVersion(word wValue) 334 void ComHeaderDirectory::setMinorRuntimeVersion(word wValue)
335 { 335 {
336 m_ichComHeader.MinorRuntimeVersion = wValue; 336 m_ichComHeader.MinorRuntimeVersion = wValue;
337 } 337 }
338 338
339 /** 339 /**
340 * @param dwValue New value for the current MetaData (VirtualAddress) value. 340 * @param dwValue New value for the current MetaData (VirtualAddress) value.
341 **/ 341 **/
342 void ComHeaderDirectory::setMetaDataVa(dword dwValue) 342 void ComHeaderDirectory::setMetaDataVa(dword dwValue)
343 { 343 {
344 m_ichComHeader.MetaData.VirtualAddress = dwValue; 344 m_ichComHeader.MetaData.VirtualAddress = dwValue;
345 } 345 }
346 346
347 /** 347 /**
348 * @param dwValue New value for the current MetaData (Size) value. 348 * @param dwValue New value for the current MetaData (Size) value.
349 **/ 349 **/
350 void ComHeaderDirectory::setMetaDataSize(dword dwValue) 350 void ComHeaderDirectory::setMetaDataSize(dword dwValue)
351 { 351 {
352 m_ichComHeader.MetaData.Size = dwValue; 352 m_ichComHeader.MetaData.Size = dwValue;
353 } 353 }
354 354
355 /** 355 /**
356 * @param dwValue New value for the current Flags value. 356 * @param dwValue New value for the current Flags value.
357 **/ 357 **/
358 void ComHeaderDirectory::setFlags(dword dwValue) 358 void ComHeaderDirectory::setFlags(dword dwValue)
359 { 359 {
360 m_ichComHeader.Flags = dwValue; 360 m_ichComHeader.Flags = dwValue;
361 } 361 }
362 362
363 /** 363 /**
364 * @param dwValue New value for the current EntryPointToken value. 364 * @param dwValue New value for the current EntryPointToken value.
365 **/ 365 **/
366 void ComHeaderDirectory::setEntryPointToken(dword dwValue) 366 void ComHeaderDirectory::setEntryPointToken(dword dwValue)
367 { 367 {
368 m_ichComHeader.EntryPointToken = dwValue; 368 m_ichComHeader.EntryPointToken = dwValue;
369 } 369 }
370 370
371 /** 371 /**
372 * @param dwValue New value for the current Resources (VirtualAddress) value. 372 * @param dwValue New value for the current Resources (VirtualAddress) value.
373 **/ 373 **/
374 void ComHeaderDirectory::setResourcesVa(dword dwValue) 374 void ComHeaderDirectory::setResourcesVa(dword dwValue)
375 { 375 {
376 m_ichComHeader.Resources.VirtualAddress = dwValue; 376 m_ichComHeader.Resources.VirtualAddress = dwValue;
377 } 377 }
378 378
379 /** 379 /**
380 * @param dwValue New value for the current Resources (Size) value. 380 * @param dwValue New value for the current Resources (Size) value.
381 **/ 381 **/
382 void ComHeaderDirectory::setResourcesSize(dword dwValue) 382 void ComHeaderDirectory::setResourcesSize(dword dwValue)
383 { 383 {
384 m_ichComHeader.Resources.Size = dwValue; 384 m_ichComHeader.Resources.Size = dwValue;
385 } 385 }
386 386
387 /** 387 /**
388 * @param dwValue New value for the current StrongNameSignature (VirtualAddress) value. 388 * @param dwValue New value for the current StrongNameSignature (VirtualAddress) value.
389 **/ 389 **/
390 void ComHeaderDirectory::setStrongNameSignatureVa(dword dwValue) 390 void ComHeaderDirectory::setStrongNameSignatureVa(dword dwValue)
391 { 391 {
392 m_ichComHeader.StrongNameSignature.VirtualAddress = dwValue; 392 m_ichComHeader.StrongNameSignature.VirtualAddress = dwValue;
393 } 393 }
394 394
395 /** 395 /**
396 * @param dwValue New value for the current StrongNameSignature (Size) value. 396 * @param dwValue New value for the current StrongNameSignature (Size) value.
397 **/ 397 **/
398 void ComHeaderDirectory::setStrongNameSignagureSize(dword dwValue) 398 void ComHeaderDirectory::setStrongNameSignagureSize(dword dwValue)
399 { 399 {
400 m_ichComHeader.StrongNameSignature.Size = dwValue; 400 m_ichComHeader.StrongNameSignature.Size = dwValue;
401 } 401 }
402 402
403 /** 403 /**
404 * @param dwValue New value for the current CodeManagerTable (VirtualAddress) value. 404 * @param dwValue New value for the current CodeManagerTable (VirtualAddress) value.
405 **/ 405 **/
406 void ComHeaderDirectory::setCodeManagerTableVa(dword dwValue) 406 void ComHeaderDirectory::setCodeManagerTableVa(dword dwValue)
407 { 407 {
408 m_ichComHeader.CodeManagerTable.VirtualAddress = dwValue; 408 m_ichComHeader.CodeManagerTable.VirtualAddress = dwValue;
409 } 409 }
410 410
411 /** 411 /**
412 * @param dwValue New value for the current CodeManagerTable (Size) value. 412 * @param dwValue New value for the current CodeManagerTable (Size) value.
413 **/ 413 **/
414 void ComHeaderDirectory::setCodeManagerTableSize(dword dwValue) 414 void ComHeaderDirectory::setCodeManagerTableSize(dword dwValue)
415 { 415 {
416 m_ichComHeader.CodeManagerTable.Size = dwValue; 416 m_ichComHeader.CodeManagerTable.Size = dwValue;
417 } 417 }
418 418
419 /** 419 /**
420 * @param dwValue New value for the current VTableFixups (VirtualAddress) value. 420 * @param dwValue New value for the current VTableFixups (VirtualAddress) value.
421 **/ 421 **/
422 void ComHeaderDirectory::setVTableFixupsVa(dword dwValue) 422 void ComHeaderDirectory::setVTableFixupsVa(dword dwValue)
423 { 423 {
424 m_ichComHeader.VTableFixups.VirtualAddress = dwValue; 424 m_ichComHeader.VTableFixups.VirtualAddress = dwValue;
425 } 425 }
426 426
427 /** 427 /**
428 * @param dwValue New value for the current VTableFixups (Size) value. 428 * @param dwValue New value for the current VTableFixups (Size) value.
429 **/ 429 **/
430 void ComHeaderDirectory::setVTableFixupsSize(dword dwValue) 430 void ComHeaderDirectory::setVTableFixupsSize(dword dwValue)
431 { 431 {
432 m_ichComHeader.VTableFixups.Size = dwValue; 432 m_ichComHeader.VTableFixups.Size = dwValue;
433 } 433 }
434 434
435 /** 435 /**
436 * @param dwValue New value for the current ExportAddressTableJumps (VirtualAddress) value. 436 * @param dwValue New value for the current ExportAddressTableJumps (VirtualAddress) value.
437 **/ 437 **/
438 void ComHeaderDirectory::setExportAddressTableJumpsVa(dword dwValue) 438 void ComHeaderDirectory::setExportAddressTableJumpsVa(dword dwValue)
439 { 439 {
440 m_ichComHeader.ExportAddressTableJumps.VirtualAddress = dwValue; 440 m_ichComHeader.ExportAddressTableJumps.VirtualAddress = dwValue;
441 } 441 }
442 442
443 /** 443 /**
444 * @param dwValue New value for the current ExportAddressTableJumps (Size) value. 444 * @param dwValue New value for the current ExportAddressTableJumps (Size) value.
445 **/ 445 **/
446 void ComHeaderDirectory::setExportAddressTableJumpsSize(dword dwValue) 446 void ComHeaderDirectory::setExportAddressTableJumpsSize(dword dwValue)
447 { 447 {
448 m_ichComHeader.ExportAddressTableJumps.Size = dwValue; 448 m_ichComHeader.ExportAddressTableJumps.Size = dwValue;
449 } 449 }
450 450
451 /** 451 /**
452 * @param dwValue New value for the current ManagedNativeHeader (VirtualAddress) value. 452 * @param dwValue New value for the current ManagedNativeHeader (VirtualAddress) value.
453 **/ 453 **/
454 void ComHeaderDirectory::setManagedNativeHeaderVa(dword dwValue) 454 void ComHeaderDirectory::setManagedNativeHeaderVa(dword dwValue)
455 { 455 {
456 m_ichComHeader.ManagedNativeHeader.VirtualAddress = dwValue; 456 m_ichComHeader.ManagedNativeHeader.VirtualAddress = dwValue;
457 } 457 }
458 458
459 /** 459 /**
460 * @param dwValue New value for the current ManagedNativeHeader (Size) value. 460 * @param dwValue New value for the current ManagedNativeHeader (Size) value.
461 **/ 461 **/
462 void ComHeaderDirectory::setManagedNativeHeaderSize(dword dwValue) 462 void ComHeaderDirectory::setManagedNativeHeaderSize(dword dwValue)
463 { 463 {
464 m_ichComHeader.ManagedNativeHeader.Size = dwValue; 464 m_ichComHeader.ManagedNativeHeader.Size = dwValue;
465 } 465 }
466 466
467} 467}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.h
index 915813c1cc..cdc993df1f 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.h
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.h
@@ -1,120 +1,120 @@
1/* 1/*
2* ComHeaderDirectory.h - Part of the PeLib library. 2* ComHeaderDirectory.h - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#ifndef COMHEADERDIRECTORY_H 13#ifndef COMHEADERDIRECTORY_H
14#define COMHEADERDIRECTORY_H 14#define COMHEADERDIRECTORY_H
15 15
16namespace PeLib 16namespace PeLib
17{ 17{
18 /// Class that handles the COM+ descriptor directory. 18 /// Class that handles the COM+ descriptor directory.
19 /** 19 /**
20 * This class handles the COM+ Descriptor directory which was added to PE files 20 * This class handles the COM+ Descriptor directory which was added to PE files
21 * which work with the .NET runtime modules. 21 * which work with the .NET runtime modules.
22 **/ 22 **/
23 class ComHeaderDirectory 23 class ComHeaderDirectory
24 { 24 {
25 private: 25 private:
26 PELIB_IMAGE_COR20_HEADER m_ichComHeader; ///< The COM+ descriptor. 26 PELIB_IMAGE_COR20_HEADER m_ichComHeader; ///< The COM+ descriptor.
27 27
28 void read(InputBuffer& inputbuffer); 28 void read(InputBuffer& inputbuffer);
29 29
30 public: 30 public:
31 /// Read a file's COM+ runtime descriptor directory. 31 /// Read a file's COM+ runtime descriptor directory.
32 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize); // EXPORT 32 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize); // EXPORT
33 int read(unsigned char* buffer, unsigned int buffersize); // EXPORT 33 int read(unsigned char* buffer, unsigned int buffersize); // EXPORT
34 /// Rebuild the COM+ descriptor. 34 /// Rebuild the COM+ descriptor.
35 void rebuild(std::vector<byte>& vBuffer) const; // EXPORT 35 void rebuild(std::vector<byte>& vBuffer) const; // EXPORT
36 /// Returns the size of the current COM+ descriptor. 36 /// Returns the size of the current COM+ descriptor.
37 unsigned int size() const; // EXPORT 37 unsigned int size() const; // EXPORT
38 /// Writes the current COM+ descriptor directory to a file. 38 /// Writes the current COM+ descriptor directory to a file.
39 int write(const std::string& strFilename, unsigned int dwOffset) const; // EXPORT 39 int write(const std::string& strFilename, unsigned int dwOffset) const; // EXPORT
40 40
41 /// Get the COM+ descriptor's SizeOfHeader (cb) value. 41 /// Get the COM+ descriptor's SizeOfHeader (cb) value.
42 dword getSizeOfHeader() const; // EXPORT 42 dword getSizeOfHeader() const; // EXPORT
43 /// Get the COM+ descriptor's MajorRuntimeVersion value. 43 /// Get the COM+ descriptor's MajorRuntimeVersion value.
44 word getMajorRuntimeVersion() const; // EXPORT 44 word getMajorRuntimeVersion() const; // EXPORT
45 /// Get the COM+ descriptor's MinorRuntimeVersion value. 45 /// Get the COM+ descriptor's MinorRuntimeVersion value.
46 word getMinorRuntimeVersion() const; // EXPORT 46 word getMinorRuntimeVersion() const; // EXPORT
47 /// Get the COM+ descriptor's MetaData (Virtual Address) value. 47 /// Get the COM+ descriptor's MetaData (Virtual Address) value.
48 dword getMetaDataVa() const; // EXPORT 48 dword getMetaDataVa() const; // EXPORT
49 /// Get the COM+ descriptor's MetaData (Size) value. 49 /// Get the COM+ descriptor's MetaData (Size) value.
50 dword getMetaDataSize() const; // EXPORT 50 dword getMetaDataSize() const; // EXPORT
51 /// Get the COM+ descriptor's Flags value. 51 /// Get the COM+ descriptor's Flags value.
52 dword getFlags() const; // EXPORT 52 dword getFlags() const; // EXPORT
53 /// Get the COM+ descriptor's EntryPointToken value. 53 /// Get the COM+ descriptor's EntryPointToken value.
54 dword getEntryPointToken() const; // EXPORT 54 dword getEntryPointToken() const; // EXPORT
55 /// Get the COM+ descriptor's Resources (Virtual Address) value. 55 /// Get the COM+ descriptor's Resources (Virtual Address) value.
56 dword getResourcesVa() const; // EXPORT 56 dword getResourcesVa() const; // EXPORT
57 /// Get the COM+ descriptor's Resources (Size) value. 57 /// Get the COM+ descriptor's Resources (Size) value.
58 dword getResourcesSize(); // EXPORT 58 dword getResourcesSize(); // EXPORT
59 /// Get the COM+ descriptor's StrongNameSignature (Virtual Address) value. 59 /// Get the COM+ descriptor's StrongNameSignature (Virtual Address) value.
60 dword getStrongNameSignatureVa() const; // EXPORT 60 dword getStrongNameSignatureVa() const; // EXPORT
61 /// Get the COM+ descriptor's StrongNameSignature (Size) value. 61 /// Get the COM+ descriptor's StrongNameSignature (Size) value.
62 dword getStrongNameSignagureSize() const; // EXPORT 62 dword getStrongNameSignagureSize() const; // EXPORT
63 /// Get the COM+ descriptor's CodeManagerTable (Virtual Address) value. 63 /// Get the COM+ descriptor's CodeManagerTable (Virtual Address) value.
64 dword getCodeManagerTableVa() const; // EXPORT 64 dword getCodeManagerTableVa() const; // EXPORT
65 /// Get the COM+ descriptor's CodeManagerTable (Size) value. 65 /// Get the COM+ descriptor's CodeManagerTable (Size) value.
66 dword getCodeManagerTableSize() const; // EXPORT 66 dword getCodeManagerTableSize() const; // EXPORT
67 /// Get the COM+ descriptor's VTableFixup (Virtual Address) value. 67 /// Get the COM+ descriptor's VTableFixup (Virtual Address) value.
68 dword getVTableFixupsVa() const; // EXPORT 68 dword getVTableFixupsVa() const; // EXPORT
69 /// Get the COM+ descriptor's VTableFixup (Size) value. 69 /// Get the COM+ descriptor's VTableFixup (Size) value.
70 dword getVTableFixupsSize() const; // EXPORT 70 dword getVTableFixupsSize() const; // EXPORT
71 /// Get the COM+ descriptor's ExportAddressTable (Virtual Address) value. 71 /// Get the COM+ descriptor's ExportAddressTable (Virtual Address) value.
72 dword getExportAddressTableJumpsVa() const; // EXPORT 72 dword getExportAddressTableJumpsVa() const; // EXPORT
73 /// Get the COM+ descriptor's ExportAddressTable (Size) value. 73 /// Get the COM+ descriptor's ExportAddressTable (Size) value.
74 dword getExportAddressTableJumpsSize() const; // EXPORT 74 dword getExportAddressTableJumpsSize() const; // EXPORT
75 /// Get the COM+ descriptor's ManagedNativeHeader (Virtual Address) value. 75 /// Get the COM+ descriptor's ManagedNativeHeader (Virtual Address) value.
76 dword getManagedNativeHeaderVa() const; // EXPORT 76 dword getManagedNativeHeaderVa() const; // EXPORT
77 /// Get the COM+ descriptor's ManagedNativeHeader (Size) value. 77 /// Get the COM+ descriptor's ManagedNativeHeader (Size) value.
78 dword getManagedNativeHeaderSize() const; // EXPORT 78 dword getManagedNativeHeaderSize() const; // EXPORT
79 79
80 /// Change the COM+ descriptor's SizeOfHeader (cb) value. 80 /// Change the COM+ descriptor's SizeOfHeader (cb) value.
81 void setSizeOfHeader(dword dwValue); // EXPORT 81 void setSizeOfHeader(dword dwValue); // EXPORT
82 /// Change the COM+ descriptor's MajorRuntimeVersion value. 82 /// Change the COM+ descriptor's MajorRuntimeVersion value.
83 void setMajorRuntimeVersion(word wValue); // EXPORT 83 void setMajorRuntimeVersion(word wValue); // EXPORT
84 /// Change the COM+ descriptor's MinorRuntimeVersion value. 84 /// Change the COM+ descriptor's MinorRuntimeVersion value.
85 void setMinorRuntimeVersion(word wValue); // EXPORT 85 void setMinorRuntimeVersion(word wValue); // EXPORT
86 /// Change the COM+ descriptor's MetaData (VirtualAddress) value. 86 /// Change the COM+ descriptor's MetaData (VirtualAddress) value.
87 void setMetaDataVa(dword dwValue); // EXPORT 87 void setMetaDataVa(dword dwValue); // EXPORT
88 /// Change the COM+ descriptor's MetaData (Size) value. 88 /// Change the COM+ descriptor's MetaData (Size) value.
89 void setMetaDataSize(dword dwValue); // EXPORT 89 void setMetaDataSize(dword dwValue); // EXPORT
90 /// Change the COM+ descriptor's Flags value. 90 /// Change the COM+ descriptor's Flags value.
91 void setFlags(dword dwValue); // EXPORT 91 void setFlags(dword dwValue); // EXPORT
92 /// Change the COM+ descriptor's EntryPointToken value. 92 /// Change the COM+ descriptor's EntryPointToken value.
93 void setEntryPointToken(dword dwValue); // EXPORT 93 void setEntryPointToken(dword dwValue); // EXPORT
94 /// Change the COM+ descriptor's Resources (VirtualAddress) value. 94 /// Change the COM+ descriptor's Resources (VirtualAddress) value.
95 void setResourcesVa(dword dwValue); // EXPORT 95 void setResourcesVa(dword dwValue); // EXPORT
96 /// Change the COM+ descriptor's Resources (Size) value. 96 /// Change the COM+ descriptor's Resources (Size) value.
97 void setResourcesSize(dword dwValue); // EXPORT 97 void setResourcesSize(dword dwValue); // EXPORT
98 /// Change the COM+ descriptor's StrongNameSignatureVa (VirtualAddress) value. 98 /// Change the COM+ descriptor's StrongNameSignatureVa (VirtualAddress) value.
99 void setStrongNameSignatureVa(dword dwValue); // EXPORT 99 void setStrongNameSignatureVa(dword dwValue); // EXPORT
100 /// Change the COM+ descriptor's StrongNameSignatureVa (Size) value. 100 /// Change the COM+ descriptor's StrongNameSignatureVa (Size) value.
101 void setStrongNameSignagureSize(dword dwValue); // EXPORT 101 void setStrongNameSignagureSize(dword dwValue); // EXPORT
102 /// Change the COM+ descriptor's CodeManagerTable (VirtualAddress) value. 102 /// Change the COM+ descriptor's CodeManagerTable (VirtualAddress) value.
103 void setCodeManagerTableVa(dword dwValue); // EXPORT 103 void setCodeManagerTableVa(dword dwValue); // EXPORT
104 /// Change the COM+ descriptor's CodeManagerTable (Size) value. 104 /// Change the COM+ descriptor's CodeManagerTable (Size) value.
105 void setCodeManagerTableSize(dword dwValue); // EXPORT 105 void setCodeManagerTableSize(dword dwValue); // EXPORT
106 /// Change the COM+ descriptor's VTableFixups (VirtualAddress) value. 106 /// Change the COM+ descriptor's VTableFixups (VirtualAddress) value.
107 void setVTableFixupsVa(dword dwValue); // EXPORT 107 void setVTableFixupsVa(dword dwValue); // EXPORT
108 /// Change the COM+ descriptor's VTableFixups (Size) value. 108 /// Change the COM+ descriptor's VTableFixups (Size) value.
109 void setVTableFixupsSize(dword dwValue); // EXPORT 109 void setVTableFixupsSize(dword dwValue); // EXPORT
110 /// Change the COM+ descriptor's ExportAddressTableJumps (VirtualAddress) value. 110 /// Change the COM+ descriptor's ExportAddressTableJumps (VirtualAddress) value.
111 void setExportAddressTableJumpsVa(dword dwValue); // EXPORT 111 void setExportAddressTableJumpsVa(dword dwValue); // EXPORT
112 /// Change the COM+ descriptor's ExportAddressTableJumps (Size) value. 112 /// Change the COM+ descriptor's ExportAddressTableJumps (Size) value.
113 void setExportAddressTableJumpsSize(dword dwValue); // EXPORT 113 void setExportAddressTableJumpsSize(dword dwValue); // EXPORT
114 /// Change the COM+ descriptor's ManagedNativeHeader (VirtualAddress) value. 114 /// Change the COM+ descriptor's ManagedNativeHeader (VirtualAddress) value.
115 void setManagedNativeHeaderVa(dword dwValue); // EXPORT 115 void setManagedNativeHeaderVa(dword dwValue); // EXPORT
116 /// Change the COM+ descriptor's ManagedNativeHeader (Size) value. 116 /// Change the COM+ descriptor's ManagedNativeHeader (Size) value.
117 void setManagedNativeHeaderSize(dword dwValue); // EXPORT 117 void setManagedNativeHeaderSize(dword dwValue); // EXPORT
118 }; 118 };
119} 119}
120#endif 120#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.cpp
index eb3d5c5600..9a91c7b18c 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.cpp
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.cpp
@@ -1,383 +1,383 @@
1/* 1/*
2* DebugDirectory.cpp - Part of the PeLib library. 2* DebugDirectory.cpp - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#include "PeLibInc.h" 13#include "PeLibInc.h"
14#include "DebugDirectory.h" 14#include "DebugDirectory.h"
15 15
16namespace PeLib 16namespace PeLib
17{ 17{
18 void DebugDirectory::clear() 18 void DebugDirectory::clear()
19 { 19 {
20 m_vDebugInfo.clear(); 20 m_vDebugInfo.clear();
21 } 21 }
22 22
23 std::vector<PELIB_IMG_DEBUG_DIRECTORY> DebugDirectory::read(InputBuffer& ibBuffer, unsigned int uiSize) 23 std::vector<PELIB_IMG_DEBUG_DIRECTORY> DebugDirectory::read(InputBuffer& ibBuffer, unsigned int uiSize)
24 { 24 {
25 std::vector<PELIB_IMG_DEBUG_DIRECTORY> currDebugInfo; 25 std::vector<PELIB_IMG_DEBUG_DIRECTORY> currDebugInfo;
26 26
27 PELIB_IMG_DEBUG_DIRECTORY iddCurr; 27 PELIB_IMG_DEBUG_DIRECTORY iddCurr;
28 28
29 for (unsigned int i=0;i<uiSize/PELIB_IMAGE_DEBUG_DIRECTORY::size();i++) 29 for (unsigned int i=0;i<uiSize/PELIB_IMAGE_DEBUG_DIRECTORY::size();i++)
30 { 30 {
31 31
32 ibBuffer >> iddCurr.idd.Characteristics; 32 ibBuffer >> iddCurr.idd.Characteristics;
33 ibBuffer >> iddCurr.idd.TimeDateStamp; 33 ibBuffer >> iddCurr.idd.TimeDateStamp;
34 ibBuffer >> iddCurr.idd.MajorVersion; 34 ibBuffer >> iddCurr.idd.MajorVersion;
35 ibBuffer >> iddCurr.idd.MinorVersion; 35 ibBuffer >> iddCurr.idd.MinorVersion;
36 ibBuffer >> iddCurr.idd.Type; 36 ibBuffer >> iddCurr.idd.Type;
37 ibBuffer >> iddCurr.idd.SizeOfData; 37 ibBuffer >> iddCurr.idd.SizeOfData;
38 ibBuffer >> iddCurr.idd.AddressOfRawData; 38 ibBuffer >> iddCurr.idd.AddressOfRawData;
39 ibBuffer >> iddCurr.idd.PointerToRawData; 39 ibBuffer >> iddCurr.idd.PointerToRawData;
40 40
41 currDebugInfo.push_back(iddCurr); 41 currDebugInfo.push_back(iddCurr);
42 } 42 }
43 43
44 return currDebugInfo; 44 return currDebugInfo;
45 } 45 }
46 46
47 int DebugDirectory::read(unsigned char* buffer, unsigned int buffersize) 47 int DebugDirectory::read(unsigned char* buffer, unsigned int buffersize)
48 { 48 {
49 // XXX: Note, debug data is not read at all. This might or might not change 49 // XXX: Note, debug data is not read at all. This might or might not change
50 // in the future. 50 // in the future.
51 51
52 std::vector<byte> vDebugDirectory(buffer, buffer + buffersize); 52 std::vector<byte> vDebugDirectory(buffer, buffer + buffersize);
53 53
54 InputBuffer ibBuffer(vDebugDirectory); 54 InputBuffer ibBuffer(vDebugDirectory);
55 55
56 std::vector<PELIB_IMG_DEBUG_DIRECTORY> currDebugInfo = read(ibBuffer, buffersize); 56 std::vector<PELIB_IMG_DEBUG_DIRECTORY> currDebugInfo = read(ibBuffer, buffersize);
57 57
58 std::swap(currDebugInfo, m_vDebugInfo); 58 std::swap(currDebugInfo, m_vDebugInfo);
59 59
60 return NO_ERROR; 60 return NO_ERROR;
61 } 61 }
62 62
63 /** 63 /**
64 * @param strFilename Name of the file which will be read. 64 * @param strFilename Name of the file which will be read.
65 * @param uiOffset File offset of the Debug directory. 65 * @param uiOffset File offset of the Debug directory.
66 * @param uiSize Size of the Debug directory. 66 * @param uiSize Size of the Debug directory.
67 **/ 67 **/
68 int DebugDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize) 68 int DebugDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize)
69 { 69 {
70 std::ifstream ifFile(strFilename.c_str(), std::ios::binary); 70 std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
71 unsigned int ulFileSize = fileSize(ifFile); 71 unsigned int ulFileSize = fileSize(ifFile);
72 72
73 if (!ifFile) 73 if (!ifFile)
74 { 74 {
75 return ERROR_OPENING_FILE; 75 return ERROR_OPENING_FILE;
76 } 76 }
77 77
78 if (ulFileSize < uiOffset + uiSize) 78 if (ulFileSize < uiOffset + uiSize)
79 { 79 {
80 return ERROR_INVALID_FILE; 80 return ERROR_INVALID_FILE;
81 } 81 }
82 82
83 ifFile.seekg(uiOffset, std::ios::beg); 83 ifFile.seekg(uiOffset, std::ios::beg);
84 84
85 std::vector<byte> vDebugDirectory(uiSize); 85 std::vector<byte> vDebugDirectory(uiSize);
86 ifFile.read(reinterpret_cast<char*>(&vDebugDirectory[0]), uiSize); 86 ifFile.read(reinterpret_cast<char*>(&vDebugDirectory[0]), uiSize);
87 87
88 InputBuffer ibBuffer(vDebugDirectory); 88 InputBuffer ibBuffer(vDebugDirectory);
89 89
90 std::vector<PELIB_IMG_DEBUG_DIRECTORY> currDebugInfo = read(ibBuffer, uiSize); 90 std::vector<PELIB_IMG_DEBUG_DIRECTORY> currDebugInfo = read(ibBuffer, uiSize);
91 91
92 for (unsigned int i=0;i<currDebugInfo.size();i++) 92 for (unsigned int i=0;i<currDebugInfo.size();i++)
93 { 93 {
94 ifFile.seekg(currDebugInfo[i].idd.PointerToRawData, std::ios::beg); 94 ifFile.seekg(currDebugInfo[i].idd.PointerToRawData, std::ios::beg);
95 currDebugInfo[i].data.resize(currDebugInfo[i].idd.SizeOfData); 95 currDebugInfo[i].data.resize(currDebugInfo[i].idd.SizeOfData);
96 ifFile.read(reinterpret_cast<char*>(&currDebugInfo[i].data[0]), currDebugInfo[i].idd.SizeOfData); 96 ifFile.read(reinterpret_cast<char*>(&currDebugInfo[i].data[0]), currDebugInfo[i].idd.SizeOfData);
97 if (!ifFile) return ERROR_INVALID_FILE; 97 if (!ifFile) return ERROR_INVALID_FILE;
98 } 98 }
99 99
100 std::swap(currDebugInfo, m_vDebugInfo); 100 std::swap(currDebugInfo, m_vDebugInfo);
101 101
102 return NO_ERROR; 102 return NO_ERROR;
103 } 103 }
104 104
105 /** 105 /**
106 * Rebuilds the current debug directory. 106 * Rebuilds the current debug directory.
107 * @param vBuffer Buffer where the rebuilt directory is stored. 107 * @param vBuffer Buffer where the rebuilt directory is stored.
108 **/ 108 **/
109 void DebugDirectory::rebuild(std::vector<byte>& vBuffer) const 109 void DebugDirectory::rebuild(std::vector<byte>& vBuffer) const
110 { 110 {
111 OutputBuffer obBuffer(vBuffer); 111 OutputBuffer obBuffer(vBuffer);
112 112
113 for (unsigned int i=0;i<m_vDebugInfo.size();i++) 113 for (unsigned int i=0;i<m_vDebugInfo.size();i++)
114 { 114 {
115 obBuffer << m_vDebugInfo[i].idd.Characteristics; 115 obBuffer << m_vDebugInfo[i].idd.Characteristics;
116 obBuffer << m_vDebugInfo[i].idd.TimeDateStamp; 116 obBuffer << m_vDebugInfo[i].idd.TimeDateStamp;
117 obBuffer << m_vDebugInfo[i].idd.MajorVersion; 117 obBuffer << m_vDebugInfo[i].idd.MajorVersion;
118 obBuffer << m_vDebugInfo[i].idd.MinorVersion; 118 obBuffer << m_vDebugInfo[i].idd.MinorVersion;
119 obBuffer << m_vDebugInfo[i].idd.Type; 119 obBuffer << m_vDebugInfo[i].idd.Type;
120 obBuffer << m_vDebugInfo[i].idd.SizeOfData; 120 obBuffer << m_vDebugInfo[i].idd.SizeOfData;
121 obBuffer << m_vDebugInfo[i].idd.AddressOfRawData; 121 obBuffer << m_vDebugInfo[i].idd.AddressOfRawData;
122 obBuffer << m_vDebugInfo[i].idd.PointerToRawData; 122 obBuffer << m_vDebugInfo[i].idd.PointerToRawData;
123 } 123 }
124 } 124 }
125 125
126 /** 126 /**
127 * @return Size of the debug directory. 127 * @return Size of the debug directory.
128 **/ 128 **/
129 unsigned int DebugDirectory::size() const 129 unsigned int DebugDirectory::size() const
130 { 130 {
131 return static_cast<unsigned int>(m_vDebugInfo.size()) * PELIB_IMAGE_DEBUG_DIRECTORY::size(); 131 return static_cast<unsigned int>(m_vDebugInfo.size()) * PELIB_IMAGE_DEBUG_DIRECTORY::size();
132 } 132 }
133 133
134 /** 134 /**
135 * @param strFilename Name of the file which will be written. 135 * @param strFilename Name of the file which will be written.
136 * @param uiOffset File offset where the debug directory will be stored. 136 * @param uiOffset File offset where the debug directory will be stored.
137 **/ 137 **/
138 int DebugDirectory::write(const std::string& strFilename, unsigned int uiOffset) const 138 int DebugDirectory::write(const std::string& strFilename, unsigned int uiOffset) const
139 { 139 {
140 std::fstream ofFile(strFilename.c_str(), std::ios_base::in); 140 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
141 141
142 if (!ofFile) 142 if (!ofFile)
143 { 143 {
144 ofFile.clear(); 144 ofFile.clear();
145 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary); 145 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
146 } 146 }
147 else 147 else
148 { 148 {
149 ofFile.close(); 149 ofFile.close();
150 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary); 150 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
151 } 151 }
152 152
153 if (!ofFile) 153 if (!ofFile)
154 { 154 {
155 return ERROR_OPENING_FILE; 155 return ERROR_OPENING_FILE;
156 } 156 }
157 157
158 ofFile.seekp(uiOffset, std::ios::beg); 158 ofFile.seekp(uiOffset, std::ios::beg);
159 159
160 std::vector<unsigned char> vBuffer; 160 std::vector<unsigned char> vBuffer;
161 rebuild(vBuffer); 161 rebuild(vBuffer);
162 162
163 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size())); 163 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
164 164
165 ofFile.close(); 165 ofFile.close();
166 166
167 return NO_ERROR; 167 return NO_ERROR;
168 } 168 }
169 169
170 /** 170 /**
171 * @return Number of debug structures in the current Debug directory. 171 * @return Number of debug structures in the current Debug directory.
172 **/ 172 **/
173 unsigned int DebugDirectory::calcNumberOfEntries() const 173 unsigned int DebugDirectory::calcNumberOfEntries() const
174 { 174 {
175 return static_cast<unsigned int>(m_vDebugInfo.size()); 175 return static_cast<unsigned int>(m_vDebugInfo.size());
176 } 176 }
177 177
178 /** 178 /**
179 * Adds a new debug structure to the debug directory. The initial values of all members of the structure 179 * Adds a new debug structure to the debug directory. The initial values of all members of the structure
180 * are undefined. 180 * are undefined.
181 **/ 181 **/
182 void DebugDirectory::addEntry() 182 void DebugDirectory::addEntry()
183 { 183 {
184 PELIB_IMG_DEBUG_DIRECTORY p; 184 PELIB_IMG_DEBUG_DIRECTORY p;
185 m_vDebugInfo.push_back(p); 185 m_vDebugInfo.push_back(p);
186 } 186 }
187 187
188 /** 188 /**
189 * Removes a debug structure from the current debug directory. If an invalid structure is specified 189 * Removes a debug structure from the current debug directory. If an invalid structure is specified
190 * by the parameter uiIndex the result will be undefined behaviour. 190 * by the parameter uiIndex the result will be undefined behaviour.
191 * @param uiIndex Identifies the debug structure. 191 * @param uiIndex Identifies the debug structure.
192 **/ 192 **/
193 void DebugDirectory::removeEntry(unsigned int uiIndex) 193 void DebugDirectory::removeEntry(unsigned int uiIndex)
194 { 194 {
195 m_vDebugInfo.erase(m_vDebugInfo.begin() + uiIndex); 195 m_vDebugInfo.erase(m_vDebugInfo.begin() + uiIndex);
196 } 196 }
197 197
198 /** 198 /**
199 * Returns the Characteristics value of a debug structure. If an invalid structure is specified 199 * Returns the Characteristics value of a debug structure. If an invalid structure is specified
200 * by the parameter uiIndex the result will be undefined behaviour. 200 * by the parameter uiIndex the result will be undefined behaviour.
201 * @param uiIndex Identifies the debug structure. 201 * @param uiIndex Identifies the debug structure.
202 * @return Characteristics value of the debug structure. 202 * @return Characteristics value of the debug structure.
203 **/ 203 **/
204 dword DebugDirectory::getCharacteristics(unsigned int uiIndex) const 204 dword DebugDirectory::getCharacteristics(unsigned int uiIndex) const
205 { 205 {
206 return m_vDebugInfo[uiIndex].idd.Characteristics; 206 return m_vDebugInfo[uiIndex].idd.Characteristics;
207 } 207 }
208 208
209 /** 209 /**
210 * Returns the TimeDateStamp value of a debug structure. If an invalid structure is specified 210 * Returns the TimeDateStamp value of a debug structure. If an invalid structure is specified
211 * by the parameter uiIndex the result will be undefined behaviour. 211 * by the parameter uiIndex the result will be undefined behaviour.
212 * @param uiIndex Identifies the debug structure. 212 * @param uiIndex Identifies the debug structure.
213 * @return TimeDateStamp value of the debug structure. 213 * @return TimeDateStamp value of the debug structure.
214 **/ 214 **/
215 dword DebugDirectory::getTimeDateStamp(unsigned int uiIndex) const 215 dword DebugDirectory::getTimeDateStamp(unsigned int uiIndex) const
216 { 216 {
217 return m_vDebugInfo[uiIndex].idd.TimeDateStamp; 217 return m_vDebugInfo[uiIndex].idd.TimeDateStamp;
218 } 218 }
219 219
220 /** 220 /**
221 * Returns the MajorVersion value of a debug structure. If an invalid structure is specified 221 * Returns the MajorVersion value of a debug structure. If an invalid structure is specified
222 * by the parameter uiIndex the result will be undefined behaviour. 222 * by the parameter uiIndex the result will be undefined behaviour.
223 * @param uiIndex Identifies the debug structure. 223 * @param uiIndex Identifies the debug structure.
224 * @return MajorVersion value of the debug structure. 224 * @return MajorVersion value of the debug structure.
225 **/ 225 **/
226 word DebugDirectory::getMajorVersion(unsigned int uiIndex) const 226 word DebugDirectory::getMajorVersion(unsigned int uiIndex) const
227 { 227 {
228 return m_vDebugInfo[uiIndex].idd.MajorVersion; 228 return m_vDebugInfo[uiIndex].idd.MajorVersion;
229 } 229 }
230 230
231 /** 231 /**
232 * Returns the MinorVersion value of a debug structure. If an invalid structure is specified 232 * Returns the MinorVersion value of a debug structure. If an invalid structure is specified
233 * by the parameter uiIndex the result will be undefined behaviour. 233 * by the parameter uiIndex the result will be undefined behaviour.
234 * @param uiIndex Identifies the debug structure. 234 * @param uiIndex Identifies the debug structure.
235 * @return MinorVersion value of the debug structure. 235 * @return MinorVersion value of the debug structure.
236 **/ 236 **/
237 word DebugDirectory::getMinorVersion(unsigned int uiIndex) const 237 word DebugDirectory::getMinorVersion(unsigned int uiIndex) const
238 { 238 {
239 return m_vDebugInfo[uiIndex].idd.MinorVersion; 239 return m_vDebugInfo[uiIndex].idd.MinorVersion;
240 } 240 }
241 241
242 /** 242 /**
243 * Returns the Type value of a debug structure. If an invalid structure is specified 243 * Returns the Type value of a debug structure. If an invalid structure is specified
244 * by the parameter uiIndex the result will be undefined behaviour. 244 * by the parameter uiIndex the result will be undefined behaviour.
245 * @param uiIndex Identifies the debug structure. 245 * @param uiIndex Identifies the debug structure.
246 * @return Type value of the debug structure. 246 * @return Type value of the debug structure.
247 **/ 247 **/
248 dword DebugDirectory::getType(unsigned int uiIndex) const 248 dword DebugDirectory::getType(unsigned int uiIndex) const
249 { 249 {
250 return m_vDebugInfo[uiIndex].idd.Type; 250 return m_vDebugInfo[uiIndex].idd.Type;
251 } 251 }
252 252
253 /** 253 /**
254 * Returns the SizeOfData value of a debug structure. If an invalid structure is specified 254 * Returns the SizeOfData value of a debug structure. If an invalid structure is specified
255 * by the parameter uiIndex the result will be undefined behaviour. 255 * by the parameter uiIndex the result will be undefined behaviour.
256 * @param uiIndex Identifies the debug structure. 256 * @param uiIndex Identifies the debug structure.
257 * @return SizeOfData value of the debug structure. 257 * @return SizeOfData value of the debug structure.
258 **/ 258 **/
259 dword DebugDirectory::getSizeOfData(unsigned int uiIndex) const 259 dword DebugDirectory::getSizeOfData(unsigned int uiIndex) const
260 { 260 {
261 return m_vDebugInfo[uiIndex].idd.SizeOfData; 261 return m_vDebugInfo[uiIndex].idd.SizeOfData;
262 } 262 }
263 263
264 /** 264 /**
265 * Returns the AddressOfRawData value of a debug structure. If an invalid structure is specified 265 * Returns the AddressOfRawData value of a debug structure. If an invalid structure is specified
266 * by the parameter uiIndex the result will be undefined behaviour. 266 * by the parameter uiIndex the result will be undefined behaviour.
267 * @param uiIndex Identifies the debug structure. 267 * @param uiIndex Identifies the debug structure.
268 * @return AddressOfRawData value of the debug structure. 268 * @return AddressOfRawData value of the debug structure.
269 **/ 269 **/
270 dword DebugDirectory::getAddressOfRawData(unsigned int uiIndex) const 270 dword DebugDirectory::getAddressOfRawData(unsigned int uiIndex) const
271 { 271 {
272 return m_vDebugInfo[uiIndex].idd.AddressOfRawData; 272 return m_vDebugInfo[uiIndex].idd.AddressOfRawData;
273 } 273 }
274 274
275 /** 275 /**
276 * Returns the PointerToRawData value of a debug structure. If an invalid structure is specified 276 * Returns the PointerToRawData value of a debug structure. If an invalid structure is specified
277 * by the parameter uiIndex the result will be undefined behaviour. 277 * by the parameter uiIndex the result will be undefined behaviour.
278 * @param uiIndex Identifies the debug structure. 278 * @param uiIndex Identifies the debug structure.
279 * @return PointerToRawData value of the debug structure. 279 * @return PointerToRawData value of the debug structure.
280 **/ 280 **/
281 dword DebugDirectory::getPointerToRawData(unsigned int uiIndex) const 281 dword DebugDirectory::getPointerToRawData(unsigned int uiIndex) const
282 { 282 {
283 return m_vDebugInfo[uiIndex].idd.PointerToRawData; 283 return m_vDebugInfo[uiIndex].idd.PointerToRawData;
284 } 284 }
285 285
286 std::vector<byte> DebugDirectory::getData(unsigned int index) const 286 std::vector<byte> DebugDirectory::getData(unsigned int index) const
287 { 287 {
288 return m_vDebugInfo[index].data; 288 return m_vDebugInfo[index].data;
289 } 289 }
290 290
291 /** 291 /**
292 * Changes the Characteristics value of a debug structure. If an invalid structure is specified 292 * Changes the Characteristics value of a debug structure. If an invalid structure is specified
293 * by the parameter uiIndex the result will be undefined behaviour. 293 * by the parameter uiIndex the result will be undefined behaviour.
294 * @param uiIndex Identifies the debug structure. 294 * @param uiIndex Identifies the debug structure.
295 * @param dwValue New value of the Characteristics value of the debug structure. 295 * @param dwValue New value of the Characteristics value of the debug structure.
296 **/ 296 **/
297 void DebugDirectory::setCharacteristics(unsigned int uiIndex, dword dwValue) 297 void DebugDirectory::setCharacteristics(unsigned int uiIndex, dword dwValue)
298 { 298 {
299 m_vDebugInfo[uiIndex].idd.Characteristics = dwValue; 299 m_vDebugInfo[uiIndex].idd.Characteristics = dwValue;
300 } 300 }
301 301
302 /** 302 /**
303 * Changes the TimeDateStamp value of a debug structure. If an invalid structure is specified 303 * Changes the TimeDateStamp value of a debug structure. If an invalid structure is specified
304 * by the parameter uiIndex the result will be undefined behaviour. 304 * by the parameter uiIndex the result will be undefined behaviour.
305 * @param uiIndex Identifies the debug structure. 305 * @param uiIndex Identifies the debug structure.
306 * @param dwValue New value of the TimeDateStamp value of the debug structure. 306 * @param dwValue New value of the TimeDateStamp value of the debug structure.
307 **/ 307 **/
308 void DebugDirectory::setTimeDateStamp(unsigned int uiIndex, dword dwValue) 308 void DebugDirectory::setTimeDateStamp(unsigned int uiIndex, dword dwValue)
309 { 309 {
310 m_vDebugInfo[uiIndex].idd.TimeDateStamp = dwValue; 310 m_vDebugInfo[uiIndex].idd.TimeDateStamp = dwValue;
311 } 311 }
312 312
313 /** 313 /**
314 * Changes the MajorVersion value of a debug structure. If an invalid structure is specified 314 * Changes the MajorVersion value of a debug structure. If an invalid structure is specified
315 * by the parameter uiIndex the result will be undefined behaviour. 315 * by the parameter uiIndex the result will be undefined behaviour.
316 * @param uiIndex Identifies the debug structure. 316 * @param uiIndex Identifies the debug structure.
317 * @param wValue New value of the MajorVersion value of the debug structure. 317 * @param wValue New value of the MajorVersion value of the debug structure.
318 **/ 318 **/
319 void DebugDirectory::setMajorVersion(unsigned int uiIndex, word wValue) 319 void DebugDirectory::setMajorVersion(unsigned int uiIndex, word wValue)
320 { 320 {
321 m_vDebugInfo[uiIndex].idd.MajorVersion = wValue; 321 m_vDebugInfo[uiIndex].idd.MajorVersion = wValue;
322 } 322 }
323 323
324 /** 324 /**
325 * Changes the MinorVersion value of a debug structure. If an invalid structure is specified 325 * Changes the MinorVersion value of a debug structure. If an invalid structure is specified
326 * by the parameter uiIndex the result will be undefined behaviour. 326 * by the parameter uiIndex the result will be undefined behaviour.
327 * @param uiIndex Identifies the debug structure. 327 * @param uiIndex Identifies the debug structure.
328 * @param wValue New value of the MinorVersion value of the debug structure. 328 * @param wValue New value of the MinorVersion value of the debug structure.
329 **/ 329 **/
330 void DebugDirectory::setMinorVersion(unsigned int uiIndex, word wValue) 330 void DebugDirectory::setMinorVersion(unsigned int uiIndex, word wValue)
331 { 331 {
332 m_vDebugInfo[uiIndex].idd.MinorVersion = wValue; 332 m_vDebugInfo[uiIndex].idd.MinorVersion = wValue;
333 } 333 }
334 334
335 /** 335 /**
336 * Changes the Type value of a debug structure. If an invalid structure is specified 336 * Changes the Type value of a debug structure. If an invalid structure is specified
337 * by the parameter uiIndex the result will be undefined behaviour. 337 * by the parameter uiIndex the result will be undefined behaviour.
338 * @param uiIndex Identifies the debug structure. 338 * @param uiIndex Identifies the debug structure.
339 * @param dwValue New value of the Type value of the debug structure. 339 * @param dwValue New value of the Type value of the debug structure.
340 **/ 340 **/
341 void DebugDirectory::setType(unsigned int uiIndex, dword dwValue) 341 void DebugDirectory::setType(unsigned int uiIndex, dword dwValue)
342 { 342 {
343 m_vDebugInfo[uiIndex].idd.Type = dwValue; 343 m_vDebugInfo[uiIndex].idd.Type = dwValue;
344 } 344 }
345 345
346 /** 346 /**
347 * Changes the SizeOfData value of a debug structure. If an invalid structure is specified 347 * Changes the SizeOfData value of a debug structure. If an invalid structure is specified
348 * by the parameter uiIndex the result will be undefined behaviour. 348 * by the parameter uiIndex the result will be undefined behaviour.
349 * @param uiIndex Identifies the debug structure. 349 * @param uiIndex Identifies the debug structure.
350 * @param dwValue New value of the SizeOfData value of the debug structure. 350 * @param dwValue New value of the SizeOfData value of the debug structure.
351 **/ 351 **/
352 void DebugDirectory::setSizeOfData(unsigned int uiIndex, dword dwValue) 352 void DebugDirectory::setSizeOfData(unsigned int uiIndex, dword dwValue)
353 { 353 {
354 m_vDebugInfo[uiIndex].idd.SizeOfData = dwValue; 354 m_vDebugInfo[uiIndex].idd.SizeOfData = dwValue;
355 } 355 }
356 356
357 /** 357 /**
358 * Changes the AddressOfRawData value of a debug structure. If an invalid structure is specified 358 * Changes the AddressOfRawData value of a debug structure. If an invalid structure is specified
359 * by the parameter uiIndex the result will be undefined behaviour. 359 * by the parameter uiIndex the result will be undefined behaviour.
360 * @param uiIndex Identifies the debug structure. 360 * @param uiIndex Identifies the debug structure.
361 * @param dwValue New value of the AddressOfRawData value of the debug structure. 361 * @param dwValue New value of the AddressOfRawData value of the debug structure.
362 **/ 362 **/
363 void DebugDirectory::setAddressOfRawData(unsigned int uiIndex, dword dwValue) 363 void DebugDirectory::setAddressOfRawData(unsigned int uiIndex, dword dwValue)
364 { 364 {
365 m_vDebugInfo[uiIndex].idd.AddressOfRawData = dwValue; 365 m_vDebugInfo[uiIndex].idd.AddressOfRawData = dwValue;
366 } 366 }
367 367
368 /** 368 /**
369 * Changes the PointerToRawData value of a debug structure. If an invalid structure is specified 369 * Changes the PointerToRawData value of a debug structure. If an invalid structure is specified
370 * by the parameter uiIndex the result will be undefined behaviour. 370 * by the parameter uiIndex the result will be undefined behaviour.
371 * @param uiIndex Identifies the debug structure. 371 * @param uiIndex Identifies the debug structure.
372 * @param dwValue New value of the PointerToRawData value of the debug structure. 372 * @param dwValue New value of the PointerToRawData value of the debug structure.
373 **/ 373 **/
374 void DebugDirectory::setPointerToRawData(unsigned int uiIndex, dword dwValue) 374 void DebugDirectory::setPointerToRawData(unsigned int uiIndex, dword dwValue)
375 { 375 {
376 m_vDebugInfo[uiIndex].idd.PointerToRawData = dwValue; 376 m_vDebugInfo[uiIndex].idd.PointerToRawData = dwValue;
377 } 377 }
378 378
379 void DebugDirectory::setData(unsigned int index, const std::vector<byte>& data) 379 void DebugDirectory::setData(unsigned int index, const std::vector<byte>& data)
380 { 380 {
381 m_vDebugInfo[index].data = data; 381 m_vDebugInfo[index].data = data;
382 } 382 }
383} 383}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.h
index 0ffda38815..adfef6b52e 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.h
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.h
@@ -1,84 +1,84 @@
1/* 1/*
2* DebugDirectory.h - Part of the PeLib library. 2* DebugDirectory.h - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#ifndef DEBUGDIRECTORY_H 13#ifndef DEBUGDIRECTORY_H
14#define DEBUGDIRECTORY_H 14#define DEBUGDIRECTORY_H
15 15
16namespace PeLib 16namespace PeLib
17{ 17{
18 /// Class that handles the Debug directory. 18 /// Class that handles the Debug directory.
19 class DebugDirectory 19 class DebugDirectory
20 { 20 {
21 private: 21 private:
22 /// Stores the various DebugDirectory structures. 22 /// Stores the various DebugDirectory structures.
23 std::vector<PELIB_IMG_DEBUG_DIRECTORY> m_vDebugInfo; 23 std::vector<PELIB_IMG_DEBUG_DIRECTORY> m_vDebugInfo;
24 24
25 std::vector<PELIB_IMG_DEBUG_DIRECTORY> read(InputBuffer& ibBuffer, unsigned int uiSize); 25 std::vector<PELIB_IMG_DEBUG_DIRECTORY> read(InputBuffer& ibBuffer, unsigned int uiSize);
26 26
27 public: 27 public:
28 void clear(); // EXPORT 28 void clear(); // EXPORT
29 /// Reads the Debug directory from a file. 29 /// Reads the Debug directory from a file.
30 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize); // EXPORT 30 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize); // EXPORT
31 int read(unsigned char* buffer, unsigned int buffersize); 31 int read(unsigned char* buffer, unsigned int buffersize);
32 /// Rebuilds the current Debug directory. 32 /// Rebuilds the current Debug directory.
33 void rebuild(std::vector<byte>& obBuffer) const; // EXPORT 33 void rebuild(std::vector<byte>& obBuffer) const; // EXPORT
34 /// Returns the size the current Debug directory needs after rebuilding. 34 /// Returns the size the current Debug directory needs after rebuilding.
35 unsigned int size() const; 35 unsigned int size() const;
36 /// Writes the current Debug directory back to a file. 36 /// Writes the current Debug directory back to a file.
37 int write(const std::string& strFilename, unsigned int uiOffset) const; // EXPORT 37 int write(const std::string& strFilename, unsigned int uiOffset) const; // EXPORT
38 38
39 /// Returns the number of DebugDirectory image structures in the current DebugDirectory. 39 /// Returns the number of DebugDirectory image structures in the current DebugDirectory.
40 unsigned int calcNumberOfEntries() const; // EXPORT 40 unsigned int calcNumberOfEntries() const; // EXPORT
41 41
42 /// Adds a new debug structure. 42 /// Adds a new debug structure.
43 void addEntry(); // EXPORT 43 void addEntry(); // EXPORT
44 /// Removes a debug structure. 44 /// Removes a debug structure.
45 void removeEntry(unsigned int uiIndex); // EXPORT 45 void removeEntry(unsigned int uiIndex); // EXPORT
46 46
47 /// Returns the Characteristics value of a debug structure. 47 /// Returns the Characteristics value of a debug structure.
48 dword getCharacteristics(unsigned int uiIndex) const; // EXPORT 48 dword getCharacteristics(unsigned int uiIndex) const; // EXPORT
49 /// Returns the TimeDateStamp value of a debug structure. 49 /// Returns the TimeDateStamp value of a debug structure.
50 dword getTimeDateStamp(unsigned int uiIndex) const; // EXPORT 50 dword getTimeDateStamp(unsigned int uiIndex) const; // EXPORT
51 /// Returns the MajorVersion value of a debug structure. 51 /// Returns the MajorVersion value of a debug structure.
52 word getMajorVersion(unsigned int uiIndex) const; // EXPORT 52 word getMajorVersion(unsigned int uiIndex) const; // EXPORT
53 /// Returns the MinorVersion value of a debug structure. 53 /// Returns the MinorVersion value of a debug structure.
54 word getMinorVersion(unsigned int uiIndex) const; // EXPORT 54 word getMinorVersion(unsigned int uiIndex) const; // EXPORT
55 /// Returns the Type value of a debug structure. 55 /// Returns the Type value of a debug structure.
56 dword getType(unsigned int uiIndex) const; // EXPORT 56 dword getType(unsigned int uiIndex) const; // EXPORT
57 /// Returns the SizeOfData value of a debug structure. 57 /// Returns the SizeOfData value of a debug structure.
58 dword getSizeOfData(unsigned int uiIndex) const; // EXPORT 58 dword getSizeOfData(unsigned int uiIndex) const; // EXPORT
59 /// Returns the AddressOfRawData value of a debug structure. 59 /// Returns the AddressOfRawData value of a debug structure.
60 dword getAddressOfRawData(unsigned int uiIndex) const; // EXPORT 60 dword getAddressOfRawData(unsigned int uiIndex) const; // EXPORT
61 /// Returns the PointerToRawData value of a debug structure. 61 /// Returns the PointerToRawData value of a debug structure.
62 dword getPointerToRawData(unsigned int uiIndex) const; // EXPORT 62 dword getPointerToRawData(unsigned int uiIndex) const; // EXPORT
63 std::vector<byte> getData(unsigned int index) const; // EXPORT 63 std::vector<byte> getData(unsigned int index) const; // EXPORT
64 64
65 /// Sets the Characteristics value of a debug structure. 65 /// Sets the Characteristics value of a debug structure.
66 void setCharacteristics(unsigned int uiIndex, dword dwValue); // EXPORT 66 void setCharacteristics(unsigned int uiIndex, dword dwValue); // EXPORT
67 /// Sets the TimeDateStamp value of a debug structure. 67 /// Sets the TimeDateStamp value of a debug structure.
68 void setTimeDateStamp(unsigned int uiIndex, dword dwValue); // EXPORT 68 void setTimeDateStamp(unsigned int uiIndex, dword dwValue); // EXPORT
69 /// Sets the MajorVersion value of a debug structure. 69 /// Sets the MajorVersion value of a debug structure.
70 void setMajorVersion(unsigned int uiIndex, word wValue); // EXPORT 70 void setMajorVersion(unsigned int uiIndex, word wValue); // EXPORT
71 /// Sets the MinorVersion value of a debug structure. 71 /// Sets the MinorVersion value of a debug structure.
72 void setMinorVersion(unsigned int uiIndex, word wValue); // EXPORT 72 void setMinorVersion(unsigned int uiIndex, word wValue); // EXPORT
73 /// Sets the Type value of a debug structure. 73 /// Sets the Type value of a debug structure.
74 void setType(unsigned int uiIndex, dword dwValue); // EXPORT 74 void setType(unsigned int uiIndex, dword dwValue); // EXPORT
75 /// Sets the SizeOfData value of a debug structure. 75 /// Sets the SizeOfData value of a debug structure.
76 void setSizeOfData(unsigned int uiIndex, dword dwValue); // EXPORT 76 void setSizeOfData(unsigned int uiIndex, dword dwValue); // EXPORT
77 /// Sets the AddressOfRawData value of a debug structure. 77 /// Sets the AddressOfRawData value of a debug structure.
78 void setAddressOfRawData(unsigned int uiIndex, dword dwValue); // EXPORT 78 void setAddressOfRawData(unsigned int uiIndex, dword dwValue); // EXPORT
79 /// Sets the PointerToRawData value of a debug structure. 79 /// Sets the PointerToRawData value of a debug structure.
80 void setPointerToRawData(unsigned int uiIndex, dword dwValue); // EXPORT 80 void setPointerToRawData(unsigned int uiIndex, dword dwValue); // EXPORT
81 void setData(unsigned int index, const std::vector<byte>& data); // EXPORT 81 void setData(unsigned int index, const std::vector<byte>& data); // EXPORT
82 }; 82 };
83} 83}
84#endif 84#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.cpp
index aa9c28a50f..83c4b4e69d 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.cpp
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.cpp
@@ -1,692 +1,692 @@
1/* 1/*
2* ExportDirectory.cpp - Part of the PeLib library. 2* ExportDirectory.cpp - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13//#ifdef false 13//#ifdef false
14 14
15#include "PeLibInc.h" 15#include "PeLibInc.h"
16#include "ExportDirectory.h" 16#include "ExportDirectory.h"
17 17
18namespace PeLib 18namespace PeLib
19{ 19{
20 /** 20 /**
21 * @param strFuncname Name of the function. 21 * @param strFuncname Name of the function.
22 * @param dwFuncAddr RVA of the function. 22 * @param dwFuncAddr RVA of the function.
23 **/ 23 **/
24 void ExportDirectory::addFunction(const std::string& strFuncname, dword dwFuncAddr) 24 void ExportDirectory::addFunction(const std::string& strFuncname, dword dwFuncAddr)
25 { 25 {
26 PELIB_EXP_FUNC_INFORMATION efiCurr; 26 PELIB_EXP_FUNC_INFORMATION efiCurr;
27 efiCurr.funcname = strFuncname; 27 efiCurr.funcname = strFuncname;
28 efiCurr.addroffunc = dwFuncAddr; 28 efiCurr.addroffunc = dwFuncAddr;
29 m_ied.functions.push_back(efiCurr); 29 m_ied.functions.push_back(efiCurr);
30 } 30 }
31 31
32 void ExportDirectory::removeFunction(unsigned int index) 32 void ExportDirectory::removeFunction(unsigned int index)
33 { 33 {
34 m_ied.functions.erase(m_ied.functions.begin() + index); 34 m_ied.functions.erase(m_ied.functions.begin() + index);
35 } 35 }
36 36
37 void ExportDirectory::clear() 37 void ExportDirectory::clear()
38 { 38 {
39 m_ied.functions.clear(); 39 m_ied.functions.clear();
40 } 40 }
41 41
42 unsigned int ExportDirectory::calcNumberOfFunctions() const 42 unsigned int ExportDirectory::calcNumberOfFunctions() const
43 { 43 {
44 return static_cast<unsigned int>(m_ied.functions.size()); 44 return static_cast<unsigned int>(m_ied.functions.size());
45 } 45 }
46 46
47 /** 47 /**
48 * Identifies an exported function through it's name. 48 * Identifies an exported function through it's name.
49 * @param strFunctionName Name of the function 49 * @param strFunctionName Name of the function
50 * @return Number which identifies the functions. 50 * @return Number which identifies the functions.
51 **/ 51 **/
52 int ExportDirectory::getFunctionIndex(const std::string& strFunctionName) const 52 int ExportDirectory::getFunctionIndex(const std::string& strFunctionName) const
53 { 53 {
54 std::vector<PELIB_EXP_FUNC_INFORMATION>::const_iterator Iter = std::find_if(m_ied.functions.begin(), m_ied.functions.end(), std::bind2nd(std::mem_fun_ref(&PELIB_EXP_FUNC_INFORMATION::equal), strFunctionName)); 54 std::vector<PELIB_EXP_FUNC_INFORMATION>::const_iterator Iter = std::find_if(m_ied.functions.begin(), m_ied.functions.end(), std::bind2nd(std::mem_fun_ref(&PELIB_EXP_FUNC_INFORMATION::equal), strFunctionName));
55 55
56 if (Iter == m_ied.functions.end()) 56 if (Iter == m_ied.functions.end())
57 { 57 {
58// throw Exceptions::InvalidName(ExportDirectoryId, __LINE__); 58// throw Exceptions::InvalidName(ExportDirectoryId, __LINE__);
59 return -1; 59 return -1;
60 } 60 }
61 61
62 return static_cast<int>(std::distance(m_ied.functions.begin(), Iter)); 62 return static_cast<int>(std::distance(m_ied.functions.begin(), Iter));
63 } 63 }
64 64
65 /** 65 /**
66 * @param strFilename Name of the file. 66 * @param strFilename Name of the file.
67 * @param uiOffset File offset of the export directory. 67 * @param uiOffset File offset of the export directory.
68 * @param uiSize Size of the export directory. 68 * @param uiSize Size of the export directory.
69 * @param pehHeader A valid PE header which is necessary because some RVA calculations need to be done. 69 * @param pehHeader A valid PE header which is necessary because some RVA calculations need to be done.
70 * \todo: Proper use of InputBuffer 70 * \todo: Proper use of InputBuffer
71 **/ 71 **/
72 int ExportDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, const PeHeader& pehHeader) 72 int ExportDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, const PeHeader& pehHeader)
73 { 73 {
74 std::ifstream ifFile(strFilename.c_str(), std::ios::binary); 74 std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
75 75
76 if (!ifFile) 76 if (!ifFile)
77 { 77 {
78 return ERROR_OPENING_FILE; 78 return ERROR_OPENING_FILE;
79 } 79 }
80 80
81 unsigned int filesize = fileSize(ifFile); 81 unsigned int filesize = fileSize(ifFile);
82 82
83 if (filesize < uiOffset + uiSize) 83 if (filesize < uiOffset + uiSize)
84 { 84 {
85 return ERROR_INVALID_FILE; 85 return ERROR_INVALID_FILE;
86 } 86 }
87 87
88 ifFile.seekg(uiOffset, std::ios::beg); 88 ifFile.seekg(uiOffset, std::ios::beg);
89 89
90 PELIB_IMAGE_EXP_DIRECTORY iedCurr; 90 PELIB_IMAGE_EXP_DIRECTORY iedCurr;
91 91
92 std::vector<unsigned char> vExportdirectory(uiSize); 92 std::vector<unsigned char> vExportdirectory(uiSize);
93 ifFile.read(reinterpret_cast<char*>(&vExportdirectory[0]), uiSize); 93 ifFile.read(reinterpret_cast<char*>(&vExportdirectory[0]), uiSize);
94 94
95 InputBuffer inpBuffer(vExportdirectory); 95 InputBuffer inpBuffer(vExportdirectory);
96 96
97 inpBuffer >> iedCurr.ied.Characteristics; 97 inpBuffer >> iedCurr.ied.Characteristics;
98 inpBuffer >> iedCurr.ied.TimeDateStamp; 98 inpBuffer >> iedCurr.ied.TimeDateStamp;
99 inpBuffer >> iedCurr.ied.MajorVersion; 99 inpBuffer >> iedCurr.ied.MajorVersion;
100 inpBuffer >> iedCurr.ied.MinorVersion; 100 inpBuffer >> iedCurr.ied.MinorVersion;
101 inpBuffer >> iedCurr.ied.Name; 101 inpBuffer >> iedCurr.ied.Name;
102 inpBuffer >> iedCurr.ied.Base; 102 inpBuffer >> iedCurr.ied.Base;
103 inpBuffer >> iedCurr.ied.NumberOfFunctions; 103 inpBuffer >> iedCurr.ied.NumberOfFunctions;
104 inpBuffer >> iedCurr.ied.NumberOfNames; 104 inpBuffer >> iedCurr.ied.NumberOfNames;
105 inpBuffer >> iedCurr.ied.AddressOfFunctions; 105 inpBuffer >> iedCurr.ied.AddressOfFunctions;
106 inpBuffer >> iedCurr.ied.AddressOfNames; 106 inpBuffer >> iedCurr.ied.AddressOfNames;
107 inpBuffer >> iedCurr.ied.AddressOfNameOrdinals; 107 inpBuffer >> iedCurr.ied.AddressOfNameOrdinals;
108 108
109 if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader)) 109 if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
110 { 110 {
111 unsigned int offset = p32->rvaToOffset(iedCurr.ied.Name); 111 unsigned int offset = p32->rvaToOffset(iedCurr.ied.Name);
112 112
113 if (offset >= filesize) 113 if (offset >= filesize)
114 return ERROR_INVALID_FILE; 114 return ERROR_INVALID_FILE;
115 115
116 ifFile.seekg(offset, std::ios::beg); 116 ifFile.seekg(offset, std::ios::beg);
117 } 117 }
118 else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader)) 118 else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
119 { 119 {
120 // XXX: Files might be > 4 GB 120 // XXX: Files might be > 4 GB
121 unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.Name)); 121 unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.Name));
122 122
123 if (offset >= filesize) 123 if (offset >= filesize)
124 return ERROR_INVALID_FILE; 124 return ERROR_INVALID_FILE;
125 125
126 ifFile.seekg(offset, std::ios::beg); 126 ifFile.seekg(offset, std::ios::beg);
127 } 127 }
128 128
129 char c = 0; 129 char c = 0;
130 std::string strFname = ""; 130 std::string strFname = "";
131 do 131 do
132 { 132 {
133 ifFile.read(reinterpret_cast<char*>(&c), sizeof(c)); 133 ifFile.read(reinterpret_cast<char*>(&c), sizeof(c));
134 if (!ifFile) return ERROR_INVALID_FILE; 134 if (!ifFile) return ERROR_INVALID_FILE;
135 if (c) strFname += c; 135 if (c) strFname += c;
136 } 136 }
137 while (c != 0); 137 while (c != 0);
138 iedCurr.name = strFname; 138 iedCurr.name = strFname;
139 139
140 if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader)) 140 if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
141 { 141 {
142 unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfFunctions); 142 unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfFunctions);
143 143
144 if (offset >= filesize) 144 if (offset >= filesize)
145 return ERROR_INVALID_FILE; 145 return ERROR_INVALID_FILE;
146 146
147 ifFile.seekg(offset, std::ios::beg); 147 ifFile.seekg(offset, std::ios::beg);
148 } 148 }
149 else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader)) 149 else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
150 { 150 {
151 // XXX: File might be > 4 GB 151 // XXX: File might be > 4 GB
152 unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfFunctions)); 152 unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfFunctions));
153 153
154 if (offset >= filesize) 154 if (offset >= filesize)
155 return ERROR_INVALID_FILE; 155 return ERROR_INVALID_FILE;
156 156
157 ifFile.seekg(offset, std::ios::beg); 157 ifFile.seekg(offset, std::ios::beg);
158 } 158 }
159 159
160 PELIB_EXP_FUNC_INFORMATION efiCurr; 160 PELIB_EXP_FUNC_INFORMATION efiCurr;
161 efiCurr.ordinal = 0; efiCurr.addroffunc = 0; efiCurr.addrofname = 0; 161 efiCurr.ordinal = 0; efiCurr.addroffunc = 0; efiCurr.addrofname = 0;
162 162
163 for (unsigned int i=0;i<iedCurr.ied.NumberOfFunctions;i++) 163 for (unsigned int i=0;i<iedCurr.ied.NumberOfFunctions;i++)
164 { 164 {
165 if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader)) 165 if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
166 { 166 {
167 unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfFunctions) + i*sizeof(efiCurr.addroffunc); 167 unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfFunctions) + i*sizeof(efiCurr.addroffunc);
168 168
169 if (offset >= filesize) 169 if (offset >= filesize)
170 return ERROR_INVALID_FILE; 170 return ERROR_INVALID_FILE;
171 171
172 ifFile.seekg(offset, std::ios::beg); 172 ifFile.seekg(offset, std::ios::beg);
173 } 173 }
174 else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader)) 174 else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
175 { 175 {
176 // XXX: File might be > 4GB 176 // XXX: File might be > 4GB
177 unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfFunctions)) + i*sizeof(efiCurr.addroffunc); 177 unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfFunctions)) + i*sizeof(efiCurr.addroffunc);
178 178
179 if (offset >= filesize) 179 if (offset >= filesize)
180 return ERROR_INVALID_FILE; 180 return ERROR_INVALID_FILE;
181 181
182 ifFile.seekg(offset, std::ios::beg); 182 ifFile.seekg(offset, std::ios::beg);
183 } 183 }
184 184
185 ifFile.read(reinterpret_cast<char*>(&efiCurr.addroffunc), sizeof(efiCurr.addroffunc)); 185 ifFile.read(reinterpret_cast<char*>(&efiCurr.addroffunc), sizeof(efiCurr.addroffunc));
186 186
187 if (!ifFile) 187 if (!ifFile)
188 return ERROR_INVALID_FILE; 188 return ERROR_INVALID_FILE;
189 189
190 efiCurr.ordinal = i; 190 efiCurr.ordinal = i;
191 iedCurr.functions.push_back(efiCurr); 191 iedCurr.functions.push_back(efiCurr);
192 } 192 }
193 193
194 for (unsigned int i=0;i<iedCurr.ied.NumberOfNames;i++) 194 for (unsigned int i=0;i<iedCurr.ied.NumberOfNames;i++)
195 { 195 {
196 if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader)) 196 if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
197 { 197 {
198 unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfNameOrdinals) + i*sizeof(efiCurr.ordinal); 198 unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfNameOrdinals) + i*sizeof(efiCurr.ordinal);
199 199
200 if (offset >= filesize) 200 if (offset >= filesize)
201 return ERROR_INVALID_FILE; 201 return ERROR_INVALID_FILE;
202 202
203 ifFile.seekg(offset, std::ios::beg); 203 ifFile.seekg(offset, std::ios::beg);
204 } 204 }
205 else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader)) 205 else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
206 { 206 {
207 // XXX: File might be > 4 GB 207 // XXX: File might be > 4 GB
208 unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfNameOrdinals)) + i*sizeof(efiCurr.ordinal); 208 unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfNameOrdinals)) + i*sizeof(efiCurr.ordinal);
209 209
210 if (offset >= filesize) 210 if (offset >= filesize)
211 return ERROR_INVALID_FILE; 211 return ERROR_INVALID_FILE;
212 212
213 ifFile.seekg(offset, std::ios::beg); 213 ifFile.seekg(offset, std::ios::beg);
214 } 214 }
215 215
216 word ordinal; 216 word ordinal;
217 ifFile.read(reinterpret_cast<char*>(&ordinal), sizeof(ordinal)); 217 ifFile.read(reinterpret_cast<char*>(&ordinal), sizeof(ordinal));
218 218
219 if (!ifFile) 219 if (!ifFile)
220 return ERROR_INVALID_FILE; 220 return ERROR_INVALID_FILE;
221 221
222 iedCurr.functions[ordinal].ordinal = ordinal; 222 iedCurr.functions[ordinal].ordinal = ordinal;
223 223
224 if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader)) 224 if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
225 { 225 {
226 unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfNames) + i*sizeof(efiCurr.addrofname); 226 unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfNames) + i*sizeof(efiCurr.addrofname);
227 227
228 if (offset >= filesize) 228 if (offset >= filesize)
229 return ERROR_INVALID_FILE; 229 return ERROR_INVALID_FILE;
230 230
231 ifFile.seekg(offset, std::ios::beg); 231 ifFile.seekg(offset, std::ios::beg);
232 } 232 }
233 else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader)) 233 else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
234 { 234 {
235 // XXX: File might be > 4 GB. 235 // XXX: File might be > 4 GB.
236 unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfNames)) + i*sizeof(efiCurr.addrofname); 236 unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfNames)) + i*sizeof(efiCurr.addrofname);
237 237
238 if (offset >= filesize) 238 if (offset >= filesize)
239 return ERROR_INVALID_FILE; 239 return ERROR_INVALID_FILE;
240 240
241 ifFile.seekg(offset, std::ios::beg); 241 ifFile.seekg(offset, std::ios::beg);
242 } 242 }
243 243
244 ifFile.read(reinterpret_cast<char*>(&iedCurr.functions[ordinal].addrofname), sizeof(iedCurr.functions[ordinal].addrofname)); 244 ifFile.read(reinterpret_cast<char*>(&iedCurr.functions[ordinal].addrofname), sizeof(iedCurr.functions[ordinal].addrofname));
245 245
246 if (!ifFile) 246 if (!ifFile)
247 return ERROR_INVALID_FILE; 247 return ERROR_INVALID_FILE;
248 248
249 if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader)) 249 if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
250 { 250 {
251 unsigned int offset = p32->rvaToOffset(iedCurr.functions[ordinal].addrofname); 251 unsigned int offset = p32->rvaToOffset(iedCurr.functions[ordinal].addrofname);
252 252
253 if (offset >= filesize) 253 if (offset >= filesize)
254 return ERROR_INVALID_FILE; 254 return ERROR_INVALID_FILE;
255 255
256 ifFile.seekg(offset, std::ios::beg); 256 ifFile.seekg(offset, std::ios::beg);
257 } 257 }
258 else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader)) 258 else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
259 { 259 {
260 // XXX: File might be > 4 GB. 260 // XXX: File might be > 4 GB.
261 unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.functions[ordinal].addrofname)); 261 unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.functions[ordinal].addrofname));
262 262
263 if (offset >= filesize) 263 if (offset >= filesize)
264 return ERROR_INVALID_FILE; 264 return ERROR_INVALID_FILE;
265 265
266 ifFile.seekg(static_cast<unsigned int>(p64->rvaToOffset(iedCurr.functions[ordinal].addrofname)), std::ios::beg); 266 ifFile.seekg(static_cast<unsigned int>(p64->rvaToOffset(iedCurr.functions[ordinal].addrofname)), std::ios::beg);
267 } 267 }
268 268
269 char c = 0; 269 char c = 0;
270 std::string strFname = ""; 270 std::string strFname = "";
271 do 271 do
272 { 272 {
273 ifFile.read(reinterpret_cast<char*>(&c), sizeof(c)); 273 ifFile.read(reinterpret_cast<char*>(&c), sizeof(c));
274 274
275 if (!ifFile) 275 if (!ifFile)
276 return ERROR_INVALID_FILE; 276 return ERROR_INVALID_FILE;
277 277
278 if (c) strFname += c; 278 if (c) strFname += c;
279 } 279 }
280 while (c != 0); 280 while (c != 0);
281 281
282 iedCurr.functions[ordinal].funcname = strFname; 282 iedCurr.functions[ordinal].funcname = strFname;
283 } 283 }
284 284
285 std::swap(m_ied, iedCurr); 285 std::swap(m_ied, iedCurr);
286 286
287 return NO_ERROR; 287 return NO_ERROR;
288 } 288 }
289 289
290 /** 290 /**
291 * @param vBuffer Buffer where the rebuilt export directory is written to. 291 * @param vBuffer Buffer where the rebuilt export directory is written to.
292 * @param dwRva RVA of the export directory. 292 * @param dwRva RVA of the export directory.
293 * \todo fValid flag 293 * \todo fValid flag
294 **/ 294 **/
295 void ExportDirectory::rebuild(std::vector<byte>& vBuffer, dword dwRva) const 295 void ExportDirectory::rebuild(std::vector<byte>& vBuffer, dword dwRva) const
296 { 296 {
297 unsigned int uiSizeDirectory = sizeof(PELIB_IMAGE_EXPORT_DIRECTORY); 297 unsigned int uiSizeDirectory = sizeof(PELIB_IMAGE_EXPORT_DIRECTORY);
298 298
299 unsigned int uiSizeNames = 0; 299 unsigned int uiSizeNames = 0;
300 unsigned int uiSizeAddrFuncs = 0; 300 unsigned int uiSizeAddrFuncs = 0;
301 unsigned int uiSizeAddrNames = 0; 301 unsigned int uiSizeAddrNames = 0;
302 unsigned int uiSizeOrdinals = 0; 302 unsigned int uiSizeOrdinals = 0;
303 303
304 for (unsigned int i=0;i<m_ied.functions.size();i++) 304 for (unsigned int i=0;i<m_ied.functions.size();i++)
305 { 305 {
306 uiSizeNames += (m_ied.functions[i].funcname.empty()) ? 0 : static_cast<unsigned int>(m_ied.functions[i].funcname.size()) + 1; 306 uiSizeNames += (m_ied.functions[i].funcname.empty()) ? 0 : static_cast<unsigned int>(m_ied.functions[i].funcname.size()) + 1;
307 uiSizeAddrFuncs += sizeof(m_ied.functions[i].addroffunc); 307 uiSizeAddrFuncs += sizeof(m_ied.functions[i].addroffunc);
308 uiSizeAddrNames += (m_ied.functions[i].funcname.empty()) ? 0 : sizeof(m_ied.functions[i].addrofname); 308 uiSizeAddrNames += (m_ied.functions[i].funcname.empty()) ? 0 : sizeof(m_ied.functions[i].addrofname);
309 uiSizeOrdinals += (m_ied.functions[i].funcname.empty()) ? 0 : sizeof(m_ied.functions[i].ordinal); 309 uiSizeOrdinals += (m_ied.functions[i].funcname.empty()) ? 0 : sizeof(m_ied.functions[i].ordinal);
310 } 310 }
311 311
312 unsigned int uiFilenameSize = static_cast<unsigned int>(m_ied.name.size()) + 1; 312 unsigned int uiFilenameSize = static_cast<unsigned int>(m_ied.name.size()) + 1;
313 313
314 OutputBuffer obBuffer(vBuffer); 314 OutputBuffer obBuffer(vBuffer);
315 315
316 obBuffer << m_ied.ied.Characteristics; 316 obBuffer << m_ied.ied.Characteristics;
317 obBuffer << m_ied.ied.TimeDateStamp; 317 obBuffer << m_ied.ied.TimeDateStamp;
318 obBuffer << m_ied.ied.MajorVersion; 318 obBuffer << m_ied.ied.MajorVersion;
319 obBuffer << m_ied.ied.MinorVersion; 319 obBuffer << m_ied.ied.MinorVersion;
320 obBuffer << dwRva + uiSizeDirectory; 320 obBuffer << dwRva + uiSizeDirectory;
321 obBuffer << m_ied.ied.Base; 321 obBuffer << m_ied.ied.Base;
322 obBuffer << static_cast<unsigned int>(m_ied.functions.size()); 322 obBuffer << static_cast<unsigned int>(m_ied.functions.size());
323 323
324 // TODO: Not correct but sufficient for now. (Update: I forgot what this comment refers to, but I'll leave it in) 324 // TODO: Not correct but sufficient for now. (Update: I forgot what this comment refers to, but I'll leave it in)
325 obBuffer << static_cast<unsigned int>(m_ied.functions.size()); 325 obBuffer << static_cast<unsigned int>(m_ied.functions.size());
326 obBuffer << dwRva + uiSizeDirectory + uiFilenameSize; 326 obBuffer << dwRva + uiSizeDirectory + uiFilenameSize;
327 obBuffer << dwRva + uiSizeDirectory + uiFilenameSize + uiSizeAddrFuncs; 327 obBuffer << dwRva + uiSizeDirectory + uiFilenameSize + uiSizeAddrFuncs;
328 obBuffer << dwRva + uiSizeDirectory + uiFilenameSize + uiSizeAddrFuncs + uiSizeAddrNames; 328 obBuffer << dwRva + uiSizeDirectory + uiFilenameSize + uiSizeAddrFuncs + uiSizeAddrNames;
329 329
330 obBuffer.add(m_ied.name.c_str(), static_cast<unsigned int>(m_ied.name.size())+1); 330 obBuffer.add(m_ied.name.c_str(), static_cast<unsigned int>(m_ied.name.size())+1);
331 331
332 for (unsigned int i=0;i<m_ied.functions.size();i++) 332 for (unsigned int i=0;i<m_ied.functions.size();i++)
333 { 333 {
334 obBuffer << m_ied.functions[i].addroffunc; 334 obBuffer << m_ied.functions[i].addroffunc;
335 } 335 }
336 336
337 unsigned int ulFuncCounter = dwRva + uiSizeDirectory + uiFilenameSize + uiSizeAddrFuncs + uiSizeAddrNames + uiSizeOrdinals; 337 unsigned int ulFuncCounter = dwRva + uiSizeDirectory + uiFilenameSize + uiSizeAddrFuncs + uiSizeAddrNames + uiSizeOrdinals;
338 338
339 for (unsigned int i=0;i<m_ied.functions.size();i++) 339 for (unsigned int i=0;i<m_ied.functions.size();i++)
340 { 340 {
341 if (!m_ied.functions[i].funcname.empty()) 341 if (!m_ied.functions[i].funcname.empty())
342 { 342 {
343 obBuffer << ulFuncCounter; 343 obBuffer << ulFuncCounter;
344 ulFuncCounter += static_cast<unsigned int>(m_ied.functions[i].funcname.size()) + 1; 344 ulFuncCounter += static_cast<unsigned int>(m_ied.functions[i].funcname.size()) + 1;
345 } 345 }
346 } 346 }
347 347
348 for (unsigned int i=0;i<m_ied.functions.size();i++) 348 for (unsigned int i=0;i<m_ied.functions.size();i++)
349 { 349 {
350 if (!m_ied.functions[i].funcname.empty()) 350 if (!m_ied.functions[i].funcname.empty())
351 { 351 {
352 obBuffer << m_ied.functions[i].ordinal; 352 obBuffer << m_ied.functions[i].ordinal;
353 } 353 }
354 } 354 }
355 355
356 for (unsigned int i=0;i<m_ied.functions.size();i++) 356 for (unsigned int i=0;i<m_ied.functions.size();i++)
357 { 357 {
358 if (m_ied.functions[i].funcname.empty() && m_ied.functions[i].addroffunc) 358 if (m_ied.functions[i].funcname.empty() && m_ied.functions[i].addroffunc)
359 { 359 {
360 obBuffer << m_ied.functions[i].ordinal; 360 obBuffer << m_ied.functions[i].ordinal;
361 } 361 }
362 } 362 }
363 363
364 for (unsigned int i=0;i<m_ied.functions.size();i++) 364 for (unsigned int i=0;i<m_ied.functions.size();i++)
365 { 365 {
366 if (!m_ied.functions[i].funcname.empty()) 366 if (!m_ied.functions[i].funcname.empty())
367 { 367 {
368 obBuffer.add(m_ied.functions[i].funcname.c_str(), static_cast<unsigned int>(m_ied.functions[i].funcname.size()) + 1); 368 obBuffer.add(m_ied.functions[i].funcname.c_str(), static_cast<unsigned int>(m_ied.functions[i].funcname.size()) + 1);
369 } 369 }
370 } 370 }
371 } 371 }
372 372
373 /** 373 /**
374 * @return Size of the current export directory. 374 * @return Size of the current export directory.
375 **/ 375 **/
376 unsigned int ExportDirectory::size() const 376 unsigned int ExportDirectory::size() const
377 { 377 {
378 return m_ied.size(); 378 return m_ied.size();
379 } 379 }
380 380
381 /** 381 /**
382 * @param strFilename Name of the file. 382 * @param strFilename Name of the file.
383 * @param uiOffset File offset the export directory will be written to. 383 * @param uiOffset File offset the export directory will be written to.
384 * @param uiRva RVA of the export directory. 384 * @param uiRva RVA of the export directory.
385 * \todo Check if ofFile.write succeeded. 385 * \todo Check if ofFile.write succeeded.
386 **/ 386 **/
387 int ExportDirectory::write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva) const 387 int ExportDirectory::write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva) const
388 { 388 {
389 std::fstream ofFile(strFilename.c_str(), std::ios_base::in); 389 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
390 390
391 if (!ofFile) 391 if (!ofFile)
392 { 392 {
393 ofFile.clear(); 393 ofFile.clear();
394 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary); 394 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
395 } 395 }
396 else 396 else
397 { 397 {
398 ofFile.close(); 398 ofFile.close();
399 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary); 399 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
400 } 400 }
401 401
402 if (!ofFile) 402 if (!ofFile)
403 { 403 {
404 return ERROR_OPENING_FILE; 404 return ERROR_OPENING_FILE;
405 } 405 }
406 406
407 ofFile.seekp(uiOffset, std::ios::beg); 407 ofFile.seekp(uiOffset, std::ios::beg);
408 408
409 std::vector<unsigned char> vBuffer; 409 std::vector<unsigned char> vBuffer;
410 rebuild(vBuffer, uiRva); 410 rebuild(vBuffer, uiRva);
411 411
412 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size())); 412 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
413 413
414 ofFile.close(); 414 ofFile.close();
415 415
416 return NO_ERROR; 416 return NO_ERROR;
417 } 417 }
418 418
419 /** 419 /**
420 * Changes the filename according to the export directory. 420 * Changes the filename according to the export directory.
421 * @param strFilename New filename. 421 * @param strFilename New filename.
422 **/ 422 **/
423 void ExportDirectory::setNameString(const std::string& strFilename) 423 void ExportDirectory::setNameString(const std::string& strFilename)
424 { 424 {
425 m_ied.name = strFilename; 425 m_ied.name = strFilename;
426 } 426 }
427 427
428 std::string ExportDirectory::getNameString() const 428 std::string ExportDirectory::getNameString() const
429 { 429 {
430 return m_ied.name; 430 return m_ied.name;
431 } 431 }
432 432
433 /** 433 /**
434 * @param dwIndex Number which identifies an exported function. 434 * @param dwIndex Number which identifies an exported function.
435 * @return The name of that function. 435 * @return The name of that function.
436 **/ 436 **/
437 std::string ExportDirectory::getFunctionName(dword dwIndex) const 437 std::string ExportDirectory::getFunctionName(dword dwIndex) const
438 { 438 {
439 return m_ied.functions[dwIndex].funcname; 439 return m_ied.functions[dwIndex].funcname;
440 } 440 }
441 441
442 /** 442 /**
443 * @param dwIndex Number which identifies an exported function. 443 * @param dwIndex Number which identifies an exported function.
444 * @return The ordinal of that function. 444 * @return The ordinal of that function.
445 **/ 445 **/
446 word ExportDirectory::getFunctionOrdinal(dword dwIndex) const 446 word ExportDirectory::getFunctionOrdinal(dword dwIndex) const
447 { 447 {
448 return m_ied.functions[dwIndex].ordinal; 448 return m_ied.functions[dwIndex].ordinal;
449 } 449 }
450 450
451 /** 451 /**
452 * @param dwIndex Number which identifies an exported function. 452 * @param dwIndex Number which identifies an exported function.
453 * @return The RVA of the name string of that function. 453 * @return The RVA of the name string of that function.
454 **/ 454 **/
455 dword ExportDirectory::getAddressOfName(dword dwIndex) const 455 dword ExportDirectory::getAddressOfName(dword dwIndex) const
456 { 456 {
457 return m_ied.functions[dwIndex].addrofname; 457 return m_ied.functions[dwIndex].addrofname;
458 } 458 }
459 459
460 /** 460 /**
461 * @param dwIndex Number which identifies an exported function. 461 * @param dwIndex Number which identifies an exported function.
462 * @return The RVA of that function. 462 * @return The RVA of that function.
463 **/ 463 **/
464 dword ExportDirectory::getAddressOfFunction(dword dwIndex) const 464 dword ExportDirectory::getAddressOfFunction(dword dwIndex) const
465 { 465 {
466 return m_ied.functions[dwIndex].addroffunc; 466 return m_ied.functions[dwIndex].addroffunc;
467 } 467 }
468 468
469 /** 469 /**
470 * @param dwIndex Number which identifies an exported function. 470 * @param dwIndex Number which identifies an exported function.
471 * @param strName The name of that function. 471 * @param strName The name of that function.
472 **/ 472 **/
473 void ExportDirectory::setFunctionName(dword dwIndex, const std::string& strName) 473 void ExportDirectory::setFunctionName(dword dwIndex, const std::string& strName)
474 { 474 {
475 m_ied.functions[dwIndex].funcname = strName; 475 m_ied.functions[dwIndex].funcname = strName;
476 } 476 }
477 477
478 /** 478 /**
479 * @param dwIndex Number which identifies an exported function. 479 * @param dwIndex Number which identifies an exported function.
480 * @param wValue The ordinal of that function. 480 * @param wValue The ordinal of that function.
481 **/ 481 **/
482 void ExportDirectory::setFunctionOrdinal(dword dwIndex, word wValue) 482 void ExportDirectory::setFunctionOrdinal(dword dwIndex, word wValue)
483 { 483 {
484 m_ied.functions[dwIndex].ordinal = wValue; 484 m_ied.functions[dwIndex].ordinal = wValue;
485 } 485 }
486 486
487 /** 487 /**
488 * @param dwIndex Number which identifies an exported function. 488 * @param dwIndex Number which identifies an exported function.
489 * @param dwValue The RVA of the name string of that function. 489 * @param dwValue The RVA of the name string of that function.
490 **/ 490 **/
491 void ExportDirectory::setAddressOfName(dword dwIndex, dword dwValue) 491 void ExportDirectory::setAddressOfName(dword dwIndex, dword dwValue)
492 { 492 {
493 m_ied.functions[dwIndex].addrofname = dwValue; 493 m_ied.functions[dwIndex].addrofname = dwValue;
494 } 494 }
495 495
496 /** 496 /**
497 * @param dwIndex Number which identifies an exported function. 497 * @param dwIndex Number which identifies an exported function.
498 * @param dwValue The RVA of that function. 498 * @param dwValue The RVA of that function.
499 **/ 499 **/
500 void ExportDirectory::setAddressOfFunction(dword dwIndex, dword dwValue) 500 void ExportDirectory::setAddressOfFunction(dword dwIndex, dword dwValue)
501 { 501 {
502 m_ied.functions[dwIndex].addroffunc = dwValue; 502 m_ied.functions[dwIndex].addroffunc = dwValue;
503 } 503 }
504 504
505 /** 505 /**
506 * @return The ordinal base of the export directory. 506 * @return The ordinal base of the export directory.
507 **/ 507 **/
508 dword ExportDirectory::getBase() const 508 dword ExportDirectory::getBase() const
509 { 509 {
510 return m_ied.ied.Base; 510 return m_ied.ied.Base;
511 } 511 }
512 512
513 /** 513 /**
514 * @return The characteristics of the export directory. 514 * @return The characteristics of the export directory.
515 **/ 515 **/
516 dword ExportDirectory::getCharacteristics() const 516 dword ExportDirectory::getCharacteristics() const
517 { 517 {
518 return m_ied.ied.Characteristics; 518 return m_ied.ied.Characteristics;
519 } 519 }
520 520
521 /** 521 /**
522 * @return The time/date stamp of the export directory. 522 * @return The time/date stamp of the export directory.
523 **/ 523 **/
524 dword ExportDirectory::getTimeDateStamp() const 524 dword ExportDirectory::getTimeDateStamp() const
525 { 525 {
526 return m_ied.ied.TimeDateStamp; 526 return m_ied.ied.TimeDateStamp;
527 } 527 }
528 528
529 /** 529 /**
530 * @return The MajorVersion of the export directory. 530 * @return The MajorVersion of the export directory.
531 **/ 531 **/
532 word ExportDirectory::getMajorVersion() const 532 word ExportDirectory::getMajorVersion() const
533 { 533 {
534 return m_ied.ied.MajorVersion; 534 return m_ied.ied.MajorVersion;
535 } 535 }
536 536
537 /** 537 /**
538 * @return The MinorVersion of the export directory. 538 * @return The MinorVersion of the export directory.
539 **/ 539 **/
540 word ExportDirectory::getMinorVersion() const 540 word ExportDirectory::getMinorVersion() const
541 { 541 {
542 return m_ied.ied.MinorVersion; 542 return m_ied.ied.MinorVersion;
543 } 543 }
544 544
545 /** 545 /**
546 * @return The RVA of the name of the file. 546 * @return The RVA of the name of the file.
547 **/ 547 **/
548 dword ExportDirectory::getName() const 548 dword ExportDirectory::getName() const
549 { 549 {
550 return m_ied.ied.Name; 550 return m_ied.ied.Name;
551 } 551 }
552 552
553 /** 553 /**
554 * @return The NumberOfFunctions of the export directory. 554 * @return The NumberOfFunctions of the export directory.
555 **/ 555 **/
556 dword ExportDirectory::getNumberOfFunctions() const 556 dword ExportDirectory::getNumberOfFunctions() const
557 { 557 {
558 return m_ied.ied.NumberOfFunctions; 558 return m_ied.ied.NumberOfFunctions;
559 } 559 }
560 560
561 /** 561 /**
562 * @return The NumberOfNames of the export directory. 562 * @return The NumberOfNames of the export directory.
563 **/ 563 **/
564 dword ExportDirectory::getNumberOfNames() const 564 dword ExportDirectory::getNumberOfNames() const
565 { 565 {
566 return m_ied.ied.NumberOfNames; 566 return m_ied.ied.NumberOfNames;
567 } 567 }
568 568
569 /** 569 /**
570 * @return The AddressOfFunctions of the export directory. 570 * @return The AddressOfFunctions of the export directory.
571 **/ 571 **/
572 dword ExportDirectory::getAddressOfFunctions() const 572 dword ExportDirectory::getAddressOfFunctions() const
573 { 573 {
574 return m_ied.ied.AddressOfFunctions; 574 return m_ied.ied.AddressOfFunctions;
575 } 575 }
576 576
577 /** 577 /**
578 * @return The AddressOfNames of the export directory. 578 * @return The AddressOfNames of the export directory.
579 **/ 579 **/
580 dword ExportDirectory::getAddressOfNames() const 580 dword ExportDirectory::getAddressOfNames() const
581 { 581 {
582 return m_ied.ied.AddressOfNames; 582 return m_ied.ied.AddressOfNames;
583 } 583 }
584 584
585/* dword ExportDirectory::getNumberOfNameOrdinals() const 585/* dword ExportDirectory::getNumberOfNameOrdinals() const
586 { 586 {
587 return static_cast<dword>(m_ied.functions.size()); 587 return static_cast<dword>(m_ied.functions.size());
588 } 588 }
589 589
590 dword ExportDirectory::getNumberOfAddressOfFunctionNames() const 590 dword ExportDirectory::getNumberOfAddressOfFunctionNames() const
591 { 591 {
592 return static_cast<dword>(m_ied.functions.size()); 592 return static_cast<dword>(m_ied.functions.size());
593 } 593 }
594 594
595 dword ExportDirectory::getNumberOfAddressOfFunctions() const 595 dword ExportDirectory::getNumberOfAddressOfFunctions() const
596 { 596 {
597 return static_cast<dword>(m_ied.functions.size()); 597 return static_cast<dword>(m_ied.functions.size());
598 } 598 }
599*/ 599*/
600 /** 600 /**
601 * @return The AddressOfNameOrdinals of the export directory. 601 * @return The AddressOfNameOrdinals of the export directory.
602 **/ 602 **/
603 dword ExportDirectory::getAddressOfNameOrdinals() const 603 dword ExportDirectory::getAddressOfNameOrdinals() const
604 { 604 {
605 return m_ied.ied.AddressOfNameOrdinals; 605 return m_ied.ied.AddressOfNameOrdinals;
606 } 606 }
607 607
608 /** 608 /**
609 * @param dwValue The ordinal base of the export directory. 609 * @param dwValue The ordinal base of the export directory.
610 **/ 610 **/
611 void ExportDirectory::setBase(dword dwValue) 611 void ExportDirectory::setBase(dword dwValue)
612 { 612 {
613 m_ied.ied.Base = dwValue; 613 m_ied.ied.Base = dwValue;
614 } 614 }
615 615
616 /** 616 /**
617 * @param dwValue The Characteristics of the export directory. 617 * @param dwValue The Characteristics of the export directory.
618 **/ 618 **/
619 void ExportDirectory::setCharacteristics(dword dwValue) 619 void ExportDirectory::setCharacteristics(dword dwValue)
620 { 620 {
621 m_ied.ied.Characteristics = dwValue; 621 m_ied.ied.Characteristics = dwValue;
622 } 622 }
623 623
624 /** 624 /**
625 * @param dwValue The TimeDateStamp of the export directory. 625 * @param dwValue The TimeDateStamp of the export directory.
626 **/ 626 **/
627 void ExportDirectory::setTimeDateStamp(dword dwValue) 627 void ExportDirectory::setTimeDateStamp(dword dwValue)
628 { 628 {
629 m_ied.ied.TimeDateStamp = dwValue; 629 m_ied.ied.TimeDateStamp = dwValue;
630 } 630 }
631 631
632 /** 632 /**
633 * @param wValue The MajorVersion of the export directory. 633 * @param wValue The MajorVersion of the export directory.
634 **/ 634 **/
635 void ExportDirectory::setMajorVersion(word wValue) 635 void ExportDirectory::setMajorVersion(word wValue)
636 { 636 {
637 m_ied.ied.MajorVersion = wValue; 637 m_ied.ied.MajorVersion = wValue;
638 } 638 }
639 639
640 /** 640 /**
641 * @param wValue The MinorVersion of the export directory. 641 * @param wValue The MinorVersion of the export directory.
642 **/ 642 **/
643 void ExportDirectory::setMinorVersion(word wValue) 643 void ExportDirectory::setMinorVersion(word wValue)
644 { 644 {
645 m_ied.ied.MinorVersion = wValue; 645 m_ied.ied.MinorVersion = wValue;
646 } 646 }
647 647
648 /** 648 /**
649 * @param dwValue The Name of the export directory. 649 * @param dwValue The Name of the export directory.
650 **/ 650 **/
651 void ExportDirectory::setName(dword dwValue) 651 void ExportDirectory::setName(dword dwValue)
652 { 652 {
653 m_ied.ied.Name = dwValue; 653 m_ied.ied.Name = dwValue;
654 } 654 }
655 655
656 /** 656 /**
657 * @param dwValue The NumberOfFunctions of the export directory. 657 * @param dwValue The NumberOfFunctions of the export directory.
658 **/ 658 **/
659 void ExportDirectory::setNumberOfFunctions(dword dwValue) 659 void ExportDirectory::setNumberOfFunctions(dword dwValue)
660 { 660 {
661 m_ied.ied.NumberOfFunctions = dwValue; 661 m_ied.ied.NumberOfFunctions = dwValue;
662 } 662 }
663 663
664 /** 664 /**
665 * @param dwValue The NumberOfNames of the export directory. 665 * @param dwValue The NumberOfNames of the export directory.
666 **/ 666 **/
667 void ExportDirectory::setNumberOfNames(dword dwValue) 667 void ExportDirectory::setNumberOfNames(dword dwValue)
668 { 668 {
669 m_ied.ied.NumberOfNames = dwValue; 669 m_ied.ied.NumberOfNames = dwValue;
670 } 670 }
671 671
672 /** 672 /**
673 * @param dwValue The AddressOfFunctions of the export directory. 673 * @param dwValue The AddressOfFunctions of the export directory.
674 **/ 674 **/
675 void ExportDirectory::setAddressOfFunctions(dword dwValue) 675 void ExportDirectory::setAddressOfFunctions(dword dwValue)
676 { 676 {
677 m_ied.ied.AddressOfFunctions = dwValue; 677 m_ied.ied.AddressOfFunctions = dwValue;
678 } 678 }
679 679
680 /** 680 /**
681 * @param dwValue The AddressOfNames of the export directory. 681 * @param dwValue The AddressOfNames of the export directory.
682 **/ 682 **/
683 void ExportDirectory::setAddressOfNames(dword dwValue) 683 void ExportDirectory::setAddressOfNames(dword dwValue)
684 { 684 {
685 m_ied.ied.AddressOfNames = dwValue; 685 m_ied.ied.AddressOfNames = dwValue;
686 } 686 }
687 687
688 void ExportDirectory::setAddressOfNameOrdinals(dword value) 688 void ExportDirectory::setAddressOfNameOrdinals(dword value)
689 { 689 {
690 m_ied.ied.AddressOfNameOrdinals = value; 690 m_ied.ied.AddressOfNameOrdinals = value;
691 } 691 }
692} 692}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.h
index 17a7e57020..19609b65a7 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.h
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.h
@@ -1,133 +1,133 @@
1/* 1/*
2* ExportDirectory.h - Part of the PeLib library. 2* ExportDirectory.h - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#ifndef EXPORTDIRECTORY_H 13#ifndef EXPORTDIRECTORY_H
14#define EXPORTDIRECTORY_H 14#define EXPORTDIRECTORY_H
15#include "PeHeader.h" 15#include "PeHeader.h"
16 16
17namespace PeLib 17namespace PeLib
18{ 18{
19 /// Class that handles the export directory. 19 /// Class that handles the export directory.
20 /** 20 /**
21 * This class handles the export directory. 21 * This class handles the export directory.
22 * \todo getNameString 22 * \todo getNameString
23 **/ 23 **/
24// template<int bits> 24// template<int bits>
25 class ExportDirectory 25 class ExportDirectory
26 { 26 {
27 private: 27 private:
28 /// Used to store all necessary information about a file's exported functions. 28 /// Used to store all necessary information about a file's exported functions.
29 PELIB_IMAGE_EXP_DIRECTORY m_ied; 29 PELIB_IMAGE_EXP_DIRECTORY m_ied;
30 30
31 public: 31 public:
32 /// Add another function to be exported. 32 /// Add another function to be exported.
33 void addFunction(const std::string& strFuncname, dword dwFuncAddr); // EXPORT 33 void addFunction(const std::string& strFuncname, dword dwFuncAddr); // EXPORT
34 unsigned int calcNumberOfFunctions() const; // EXPORT 34 unsigned int calcNumberOfFunctions() const; // EXPORT
35 void clear(); // EXPORT 35 void clear(); // EXPORT
36 /// Identifies a function through it's name. 36 /// Identifies a function through it's name.
37 int getFunctionIndex(const std::string& strFunctionName) const; // EXPORT 37 int getFunctionIndex(const std::string& strFunctionName) const; // EXPORT
38 /// Read a file's export directory. 38 /// Read a file's export directory.
39 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, const PeHeader& pehHeader); // EXPORT 39 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, const PeHeader& pehHeader); // EXPORT
40 /// Rebuild the current export directory. 40 /// Rebuild the current export directory.
41 void rebuild(std::vector<byte>& vBuffer, dword dwRva) const; // EXPORT 41 void rebuild(std::vector<byte>& vBuffer, dword dwRva) const; // EXPORT
42 void removeFunction(unsigned int index); // EXPORT 42 void removeFunction(unsigned int index); // EXPORT
43 /// Returns the size of the current export directory. 43 /// Returns the size of the current export directory.
44 unsigned int size() const; // EXPORT 44 unsigned int size() const; // EXPORT
45 /// Writes the current export directory to a file. 45 /// Writes the current export directory to a file.
46 int write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva) const; // EXPORT 46 int write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva) const; // EXPORT
47 47
48 /// Changes the name of the file (according to the export directory). 48 /// Changes the name of the file (according to the export directory).
49 void setNameString(const std::string& strFilename); // EXPORT 49 void setNameString(const std::string& strFilename); // EXPORT
50 std::string getNameString() const; // EXPORT 50 std::string getNameString() const; // EXPORT
51 51
52 /// Get the name of an exported function. 52 /// Get the name of an exported function.
53 std::string getFunctionName(unsigned int index) const; // EXPORT 53 std::string getFunctionName(unsigned int index) const; // EXPORT
54 /// Get the ordinal of an exported function. 54 /// Get the ordinal of an exported function.
55 word getFunctionOrdinal(unsigned int index) const; // EXPORT 55 word getFunctionOrdinal(unsigned int index) const; // EXPORT
56 /// Get the address of the name of an exported function. 56 /// Get the address of the name of an exported function.
57 dword getAddressOfName(unsigned int index) const; // EXPORT 57 dword getAddressOfName(unsigned int index) const; // EXPORT
58 /// Get the address of an exported function. 58 /// Get the address of an exported function.
59 dword getAddressOfFunction(unsigned int index) const; // EXPORT 59 dword getAddressOfFunction(unsigned int index) const; // EXPORT
60 60
61 /// Change the name of an exported function. 61 /// Change the name of an exported function.
62 void setFunctionName(unsigned int index, const std::string& strName); // EXPORT 62 void setFunctionName(unsigned int index, const std::string& strName); // EXPORT
63 /// Change the ordinal of an exported function. 63 /// Change the ordinal of an exported function.
64 void setFunctionOrdinal(unsigned int index, word wValue); // EXPORT 64 void setFunctionOrdinal(unsigned int index, word wValue); // EXPORT
65 /// Change the address of the name of an exported function. 65 /// Change the address of the name of an exported function.
66 void setAddressOfName(unsigned int index, dword dwValue); // EXPORT 66 void setAddressOfName(unsigned int index, dword dwValue); // EXPORT
67 /// Change the address of an exported function. 67 /// Change the address of an exported function.
68 void setAddressOfFunction(unsigned int index, dword dwValue); // EXPORT 68 void setAddressOfFunction(unsigned int index, dword dwValue); // EXPORT
69 69
70 /* 70 /*
71 word getFunctionOrdinal(std::string strFuncname) const; 71 word getFunctionOrdinal(std::string strFuncname) const;
72 dword getAddressOfName(std::string strFuncname) const; 72 dword getAddressOfName(std::string strFuncname) const;
73 dword getAddressOfFunction(std::string strFuncname) const; 73 dword getAddressOfFunction(std::string strFuncname) const;
74 74
75 void setFunctionOrdinal(std::string strFuncname, word wValue); 75 void setFunctionOrdinal(std::string strFuncname, word wValue);
76 void setAddressOfName(std::string strFuncname, dword dwValue); 76 void setAddressOfName(std::string strFuncname, dword dwValue);
77 void setAddressOfFunction(std::string strFuncname, dword dwValue); 77 void setAddressOfFunction(std::string strFuncname, dword dwValue);
78 */ 78 */
79 79
80 /// Return the Base value of the export directory. 80 /// Return the Base value of the export directory.
81 dword getBase() const; // EXPORT 81 dword getBase() const; // EXPORT
82 /// Return the Characteristics value of the export directory. 82 /// Return the Characteristics value of the export directory.
83 dword getCharacteristics() const; // EXPORT 83 dword getCharacteristics() const; // EXPORT
84 /// Return the TimeDateStamp value of the export directory. 84 /// Return the TimeDateStamp value of the export directory.
85 dword getTimeDateStamp() const; // EXPORT 85 dword getTimeDateStamp() const; // EXPORT
86 /// Return the MajorVersion value of the export directory. 86 /// Return the MajorVersion value of the export directory.
87 word getMajorVersion() const; // EXPORT 87 word getMajorVersion() const; // EXPORT
88 /// Return the MinorVersion value of the export directory. 88 /// Return the MinorVersion value of the export directory.
89 word getMinorVersion() const; // EXPORT 89 word getMinorVersion() const; // EXPORT
90 /// Return the Name value of the export directory. 90 /// Return the Name value of the export directory.
91 dword getName() const; // EXPORT 91 dword getName() const; // EXPORT
92 /// Return the NumberOfFunctions value of the export directory. 92 /// Return the NumberOfFunctions value of the export directory.
93 dword getNumberOfFunctions() const; // EXPORT 93 dword getNumberOfFunctions() const; // EXPORT
94 /// Return the NumberOfNames value of the export directory. 94 /// Return the NumberOfNames value of the export directory.
95 dword getNumberOfNames() const; // EXPORT 95 dword getNumberOfNames() const; // EXPORT
96 /// Return the AddressOfFunctions value of the export directory. 96 /// Return the AddressOfFunctions value of the export directory.
97 dword getAddressOfFunctions() const; // EXPORT 97 dword getAddressOfFunctions() const; // EXPORT
98 /// Return the AddressOfNames value of the export directory. 98 /// Return the AddressOfNames value of the export directory.
99 dword getAddressOfNames() const; // EXPORT 99 dword getAddressOfNames() const; // EXPORT
100 /// Returns the AddressOfNameOrdinals value. 100 /// Returns the AddressOfNameOrdinals value.
101 dword getAddressOfNameOrdinals() const; // EXPORT 101 dword getAddressOfNameOrdinals() const; // EXPORT
102 102
103/* /// Returns the number of NameOrdinals. 103/* /// Returns the number of NameOrdinals.
104 dword getNumberOfNameOrdinals() const; // EXPORT 104 dword getNumberOfNameOrdinals() const; // EXPORT
105 /// Returns the number of AddressOfFunctionNames values. 105 /// Returns the number of AddressOfFunctionNames values.
106 dword getNumberOfAddressOfFunctionNames() const; // EXPORT 106 dword getNumberOfAddressOfFunctionNames() const; // EXPORT
107 /// Returns the number of AddressOfFunction values. 107 /// Returns the number of AddressOfFunction values.
108 dword getNumberOfAddressOfFunctions() const; // EXPORT 108 dword getNumberOfAddressOfFunctions() const; // EXPORT
109*/ 109*/
110 /// Set the Base value of the export directory. 110 /// Set the Base value of the export directory.
111 void setBase(dword dwValue); // EXPORT 111 void setBase(dword dwValue); // EXPORT
112 /// Set the Characteristics value of the export directory. 112 /// Set the Characteristics value of the export directory.
113 void setCharacteristics(dword dwValue); // EXPORT 113 void setCharacteristics(dword dwValue); // EXPORT
114 /// Set the TimeDateStamp value of the export directory. 114 /// Set the TimeDateStamp value of the export directory.
115 void setTimeDateStamp(dword dwValue); // EXPORT 115 void setTimeDateStamp(dword dwValue); // EXPORT
116 /// Set the MajorVersion value of the export directory. 116 /// Set the MajorVersion value of the export directory.
117 void setMajorVersion(word wValue); // EXPORT 117 void setMajorVersion(word wValue); // EXPORT
118 /// Set the MinorVersion value of the export directory. 118 /// Set the MinorVersion value of the export directory.
119 void setMinorVersion(word wValue); // EXPORT 119 void setMinorVersion(word wValue); // EXPORT
120 /// Set the Name value of the export directory. 120 /// Set the Name value of the export directory.
121 void setName(dword dwValue); // EXPORT 121 void setName(dword dwValue); // EXPORT
122 /// Set the NumberOfFunctions value of the export directory. 122 /// Set the NumberOfFunctions value of the export directory.
123 void setNumberOfFunctions(dword dwValue); // EXPORT 123 void setNumberOfFunctions(dword dwValue); // EXPORT
124 /// Set the NumberOfNames value of the export directory. 124 /// Set the NumberOfNames value of the export directory.
125 void setNumberOfNames(dword dwValue); // EXPORT 125 void setNumberOfNames(dword dwValue); // EXPORT
126 /// Set the AddressOfFunctions value of the export directory. 126 /// Set the AddressOfFunctions value of the export directory.
127 void setAddressOfFunctions(dword dwValue); // EXPORT 127 void setAddressOfFunctions(dword dwValue); // EXPORT
128 /// Set the AddressOfNames value of the export directory. 128 /// Set the AddressOfNames value of the export directory.
129 void setAddressOfNames(dword dwValue); // EXPORT 129 void setAddressOfNames(dword dwValue); // EXPORT
130 void setAddressOfNameOrdinals(dword value); // EXPORT 130 void setAddressOfNameOrdinals(dword value); // EXPORT
131 }; 131 };
132} 132}
133#endif 133#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.cpp
index 36482fcbeb..b32cfb2a8e 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.cpp
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.cpp
@@ -1,179 +1,179 @@
1/* 1/*
2* IatDirectory.h - Part of the PeLib library. 2* IatDirectory.h - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#include "IatDirectory.h" 13#include "IatDirectory.h"
14 14
15namespace PeLib 15namespace PeLib
16{ 16{
17 int IatDirectory::read(InputBuffer& inputBuffer, unsigned int size) 17 int IatDirectory::read(InputBuffer& inputBuffer, unsigned int size)
18 { 18 {
19 dword dwAddr; 19 dword dwAddr;
20 20
21 std::vector<dword> vIat; 21 std::vector<dword> vIat;
22 22
23 for (unsigned int i=0;i<size/sizeof(dword);i++) 23 for (unsigned int i=0;i<size/sizeof(dword);i++)
24 { 24 {
25 inputBuffer >> dwAddr; 25 inputBuffer >> dwAddr;
26 vIat.push_back(dwAddr); 26 vIat.push_back(dwAddr);
27 } 27 }
28 28
29 std::swap(vIat, m_vIat); 29 std::swap(vIat, m_vIat);
30 30
31 return NO_ERROR; 31 return NO_ERROR;
32 } 32 }
33 33
34 /** 34 /**
35 * Reads the Import Address table from a file. 35 * Reads the Import Address table from a file.
36 * @param strFilename Name of the file. 36 * @param strFilename Name of the file.
37 * @param dwOffset File offset of the IAT (see #PeFile::PeHeader::getIDIatRVA). 37 * @param dwOffset File offset of the IAT (see #PeFile::PeHeader::getIDIatRVA).
38 * @param dwSize Size of the IAT (see #PeFile::PeHeader::getIDIatSize). 38 * @param dwSize Size of the IAT (see #PeFile::PeHeader::getIDIatSize).
39 **/ 39 **/
40 int IatDirectory::read(const std::string& strFilename, unsigned int dwOffset, unsigned int dwSize) 40 int IatDirectory::read(const std::string& strFilename, unsigned int dwOffset, unsigned int dwSize)
41 { 41 {
42 std::ifstream ifFile(strFilename.c_str(), std::ios::binary); 42 std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
43 43
44 if (!ifFile) 44 if (!ifFile)
45 { 45 {
46 return ERROR_OPENING_FILE; 46 return ERROR_OPENING_FILE;
47 } 47 }
48 48
49 if (fileSize(ifFile) < dwOffset + dwSize) 49 if (fileSize(ifFile) < dwOffset + dwSize)
50 { 50 {
51 return ERROR_INVALID_FILE; 51 return ERROR_INVALID_FILE;
52 } 52 }
53 53
54 ifFile.seekg(dwOffset, std::ios::beg); 54 ifFile.seekg(dwOffset, std::ios::beg);
55 55
56 std::vector<byte> vBuffer(dwSize); 56 std::vector<byte> vBuffer(dwSize);
57 ifFile.read(reinterpret_cast<char*>(&vBuffer[0]), dwSize); 57 ifFile.read(reinterpret_cast<char*>(&vBuffer[0]), dwSize);
58 58
59 InputBuffer inpBuffer(vBuffer); 59 InputBuffer inpBuffer(vBuffer);
60 return read(inpBuffer, dwSize); 60 return read(inpBuffer, dwSize);
61 } 61 }
62 62
63 int IatDirectory::read(unsigned char* buffer, unsigned int buffersize) 63 int IatDirectory::read(unsigned char* buffer, unsigned int buffersize)
64 { 64 {
65 std::vector<byte> vBuffer(buffer, buffer + buffersize); 65 std::vector<byte> vBuffer(buffer, buffer + buffersize);
66 InputBuffer inpBuffer(vBuffer); 66 InputBuffer inpBuffer(vBuffer);
67 return read(inpBuffer, buffersize); 67 return read(inpBuffer, buffersize);
68 } 68 }
69 69
70 /** 70 /**
71 * Returns the number of fields in the IAT. This is equivalent to the number of 71 * Returns the number of fields in the IAT. This is equivalent to the number of
72 * imported functions. 72 * imported functions.
73 * @return Number of fields in the IAT. 73 * @return Number of fields in the IAT.
74 **/ 74 **/
75 unsigned int IatDirectory::calcNumberOfAddresses() const 75 unsigned int IatDirectory::calcNumberOfAddresses() const
76 { 76 {
77 return static_cast<unsigned int>(m_vIat.size()); 77 return static_cast<unsigned int>(m_vIat.size());
78 } 78 }
79 79
80 /** 80 /**
81 * Returns the dwValue of a field in the IAT. 81 * Returns the dwValue of a field in the IAT.
82 * @param dwAddrnr Number identifying the field. 82 * @param dwAddrnr Number identifying the field.
83 * @return dwValue of the field. 83 * @return dwValue of the field.
84 **/ 84 **/
85 dword IatDirectory::getAddress(unsigned int index) const 85 dword IatDirectory::getAddress(unsigned int index) const
86 { 86 {
87 return m_vIat[index]; 87 return m_vIat[index];
88 } 88 }
89 89
90 /** 90 /**
91 * Updates the dwValue of a field in the IAT. 91 * Updates the dwValue of a field in the IAT.
92 * @param dwAddrnr Number identifying the field. 92 * @param dwAddrnr Number identifying the field.
93 * @param dwValue New dwValue of the field. 93 * @param dwValue New dwValue of the field.
94 **/ 94 **/
95 void IatDirectory::setAddress(dword dwAddrnr, dword dwValue) 95 void IatDirectory::setAddress(dword dwAddrnr, dword dwValue)
96 { 96 {
97 m_vIat[dwAddrnr] = dwValue; 97 m_vIat[dwAddrnr] = dwValue;
98 } 98 }
99 99
100 /** 100 /**
101 * Adds another field to the IAT. 101 * Adds another field to the IAT.
102 * @param dwValue dwValue of the new field. 102 * @param dwValue dwValue of the new field.
103 **/ 103 **/
104 void IatDirectory::addAddress(dword dwValue) 104 void IatDirectory::addAddress(dword dwValue)
105 { 105 {
106 m_vIat.push_back(dwValue); 106 m_vIat.push_back(dwValue);
107 } 107 }
108 108
109 /** 109 /**
110 * Removes an address from the IAT. 110 * Removes an address from the IAT.
111 * @param dwAddrnr Number identifying the field. 111 * @param dwAddrnr Number identifying the field.
112 **/ 112 **/
113 void IatDirectory::removeAddress(unsigned int index) 113 void IatDirectory::removeAddress(unsigned int index)
114 { 114 {
115 std::vector<dword>::iterator pos = m_vIat.begin() + index; 115 std::vector<dword>::iterator pos = m_vIat.begin() + index;
116 m_vIat.erase(pos); 116 m_vIat.erase(pos);
117 } 117 }
118 118
119 /** 119 /**
120 * Delete all entries from the IAT. 120 * Delete all entries from the IAT.
121 **/ 121 **/
122 void IatDirectory::clear() 122 void IatDirectory::clear()
123 { 123 {
124 m_vIat.clear(); 124 m_vIat.clear();
125 } 125 }
126 126
127 /** 127 /**
128 * Rebuilds the complete Import Address Table. 128 * Rebuilds the complete Import Address Table.
129 * @param vBuffer Buffer where the rebuilt IAT will be stored. 129 * @param vBuffer Buffer where the rebuilt IAT will be stored.
130 **/ 130 **/
131 void IatDirectory::rebuild(std::vector<byte>& vBuffer) const 131 void IatDirectory::rebuild(std::vector<byte>& vBuffer) const
132 { 132 {
133 vBuffer.reserve(size()); 133 vBuffer.reserve(size());
134 OutputBuffer obBuffer(vBuffer); 134 OutputBuffer obBuffer(vBuffer);
135 135
136 for (unsigned int i=0;i<m_vIat.size();i++) 136 for (unsigned int i=0;i<m_vIat.size();i++)
137 { 137 {
138 obBuffer << m_vIat[i]; 138 obBuffer << m_vIat[i];
139 } 139 }
140 } 140 }
141 141
142 unsigned int IatDirectory::size() const 142 unsigned int IatDirectory::size() const
143 { 143 {
144 return static_cast<unsigned int>(m_vIat.size())* sizeof(dword); 144 return static_cast<unsigned int>(m_vIat.size())* sizeof(dword);
145 } 145 }
146 146
147 /// Writes the current IAT to a file. 147 /// Writes the current IAT to a file.
148 int IatDirectory::write(const std::string& strFilename, unsigned int uiOffset) const 148 int IatDirectory::write(const std::string& strFilename, unsigned int uiOffset) const
149 { 149 {
150 std::fstream ofFile(strFilename.c_str(), std::ios_base::in); 150 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
151 151
152 if (!ofFile) 152 if (!ofFile)
153 { 153 {
154 ofFile.clear(); 154 ofFile.clear();
155 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary); 155 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
156 } 156 }
157 else 157 else
158 { 158 {
159 ofFile.close(); 159 ofFile.close();
160 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary); 160 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
161 } 161 }
162 162
163 if (!ofFile) 163 if (!ofFile)
164 { 164 {
165 return ERROR_OPENING_FILE; 165 return ERROR_OPENING_FILE;
166 } 166 }
167 167
168 ofFile.seekp(uiOffset, std::ios::beg); 168 ofFile.seekp(uiOffset, std::ios::beg);
169 169
170 std::vector<unsigned char> vBuffer; 170 std::vector<unsigned char> vBuffer;
171 rebuild(vBuffer); 171 rebuild(vBuffer);
172 172
173 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size())); 173 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
174 174
175 ofFile.close(); 175 ofFile.close();
176 176
177 return NO_ERROR; 177 return NO_ERROR;
178 } 178 }
179} 179}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.h
index 81ef77ed6a..26c5d4009c 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.h
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.h
@@ -1,58 +1,58 @@
1/* 1/*
2* IatDirectory.h - Part of the PeLib library. 2* IatDirectory.h - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#ifndef IATDIRECTORY_H 13#ifndef IATDIRECTORY_H
14#define IATDIRECTORY_H 14#define IATDIRECTORY_H
15 15
16#include "PeLibInc.h" 16#include "PeLibInc.h"
17 17
18namespace PeLib 18namespace PeLib
19{ 19{
20 /// Class that handles the Import Address Table (IAT) 20 /// Class that handles the Import Address Table (IAT)
21 /** 21 /**
22 * This class can read and modify the Import Address Table of a PE file. 22 * This class can read and modify the Import Address Table of a PE file.
23 **/ 23 **/
24 class IatDirectory 24 class IatDirectory
25 { 25 {
26 private: 26 private:
27 std::vector<dword> m_vIat; ///< Stores the individual IAT fields. 27 std::vector<dword> m_vIat; ///< Stores the individual IAT fields.
28 28
29 int read(InputBuffer& inputBuffer, unsigned int size); 29 int read(InputBuffer& inputBuffer, unsigned int size);
30 30
31 public: 31 public:
32 /// Reads the Import Address Table from a PE file. 32 /// Reads the Import Address Table from a PE file.
33 int read(const std::string& strFilename, unsigned int dwOffset, unsigned int dwSize); // EXPORT 33 int read(const std::string& strFilename, unsigned int dwOffset, unsigned int dwSize); // EXPORT
34 int read(unsigned char* buffer, unsigned int buffersize); // EXPORT 34 int read(unsigned char* buffer, unsigned int buffersize); // EXPORT
35 /// Returns the number of fields in the IAT. 35 /// Returns the number of fields in the IAT.
36 unsigned int calcNumberOfAddresses() const; // EXPORT 36 unsigned int calcNumberOfAddresses() const; // EXPORT
37 /// Adds another address to the IAT. 37 /// Adds another address to the IAT.
38 void addAddress(dword dwValue); // EXPORT 38 void addAddress(dword dwValue); // EXPORT
39 /// Removes an address from the IAT. 39 /// Removes an address from the IAT.
40 void removeAddress(unsigned int index); // EXPORT 40 void removeAddress(unsigned int index); // EXPORT
41 /// Empties the IAT. 41 /// Empties the IAT.
42 void clear(); // EXPORT 42 void clear(); // EXPORT
43 // Rebuilds the IAT. 43 // Rebuilds the IAT.
44 void rebuild(std::vector<byte>& vBuffer) const; // EXPORT 44 void rebuild(std::vector<byte>& vBuffer) const; // EXPORT
45 /// Returns the size of the current IAT. 45 /// Returns the size of the current IAT.
46 unsigned int size() const; // EXPORT 46 unsigned int size() const; // EXPORT
47 /// Writes the current IAT to a file. 47 /// Writes the current IAT to a file.
48 int write(const std::string& strFilename, unsigned int uiOffset) const; // EXPORT 48 int write(const std::string& strFilename, unsigned int uiOffset) const; // EXPORT
49 49
50 /// Retrieve the value of a field in the IAT. 50 /// Retrieve the value of a field in the IAT.
51 dword getAddress(unsigned int index) const; // EXPORT 51 dword getAddress(unsigned int index) const; // EXPORT
52 /// Change the value of a field in the IAT. 52 /// Change the value of a field in the IAT.
53 void setAddress(dword dwAddrnr, dword dwValue); // EXPORT 53 void setAddress(dword dwAddrnr, dword dwValue); // EXPORT
54 }; 54 };
55} 55}
56 56
57#endif 57#endif
58 58
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/ImportDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/ImportDirectory.h
index 6578f0712a..42526f0c3c 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/ImportDirectory.h
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/ImportDirectory.h
@@ -1,1139 +1,1139 @@
1/* 1/*
2* ImportDirectory.h - Part of the PeLib library. 2* ImportDirectory.h - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#ifndef IMPORTDIRECTORY_H 13#ifndef IMPORTDIRECTORY_H
14#define IMPORTDIRECTORY_H 14#define IMPORTDIRECTORY_H
15 15
16#include "PeLibAux.h" 16#include "PeLibAux.h"
17#include "PeHeader.h" 17#include "PeHeader.h"
18 18
19namespace PeLib 19namespace PeLib
20{ 20{
21 /// Parameter for functions that can operate on the OLDDIR or new import directory. 21 /// Parameter for functions that can operate on the OLDDIR or new import directory.
22 enum currdir {OLDDIR = 1, NEWDIR}; 22 enum currdir {OLDDIR = 1, NEWDIR};
23 23
24 class PeLibException; 24 class PeLibException;
25 25
26 /// Class that handles import directories. 26 /// Class that handles import directories.
27 /** 27 /**
28 * This class can read import directories from existing PE files or start completely from scratch. 28 * This class can read import directories from existing PE files or start completely from scratch.
29 * Modifying import directories and writing them to files is also possible. 29 * Modifying import directories and writing them to files is also possible.
30 * It's worthy to note that many functions require an extra parameter of type currdir 30 * It's worthy to note that many functions require an extra parameter of type currdir
31 * because the structure of import directories make it necessary that the OLDDIR import directory 31 * because the structure of import directories make it necessary that the OLDDIR import directory
32 * must be preserved. That's why some functions (like adding and removing) imported functions 32 * must be preserved. That's why some functions (like adding and removing) imported functions
33 * only exist for the new import directory, not for the one which is already written to the file. 33 * only exist for the new import directory, not for the one which is already written to the file.
34 * \todo Adding functions by ordinal doesn't work yet (rebuild needs to be changed). 34 * \todo Adding functions by ordinal doesn't work yet (rebuild needs to be changed).
35 * \todo Somehow store the rvas of the chunks in the file. 35 * \todo Somehow store the rvas of the chunks in the file.
36 **/ 36 **/
37 template<int bits> 37 template<int bits>
38 class ImportDirectory 38 class ImportDirectory
39 { 39 {
40 typedef typename std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> >::iterator ImpDirFileIterator; 40 typedef typename std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> >::iterator ImpDirFileIterator;
41 typedef typename std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> >::const_iterator ConstImpDirFileIterator; 41 typedef typename std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> >::const_iterator ConstImpDirFileIterator;
42 42
43 private: 43 private:
44 /// Stores information about already imported DLLs. 44 /// Stores information about already imported DLLs.
45 std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> > m_vOldiid; 45 std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> > m_vOldiid;
46 /// Stores information about imported DLLs which will be added. 46 /// Stores information about imported DLLs which will be added.
47 std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> > m_vNewiid; 47 std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> > m_vNewiid;
48 48
49 // I can't convince Borland C++ to compile the function outside of the class declaration. 49 // I can't convince Borland C++ to compile the function outside of the class declaration.
50 // That's why the function definition is here. 50 // That's why the function definition is here.
51 /// Tests if a certain function is imported. 51 /// Tests if a certain function is imported.
52 template<typename T> bool hasFunction(std::string strFilename, T value, bool(PELIB_THUNK_DATA<bits>::* comp)(T) const) const 52 template<typename T> bool hasFunction(std::string strFilename, T value, bool(PELIB_THUNK_DATA<bits>::* comp)(T) const) const
53 { 53 {
54 ConstImpDirFileIterator FileIter = m_vOldiid.begin(); 54 ConstImpDirFileIterator FileIter = m_vOldiid.begin();
55 ConstImpDirFileIterator EndIter = m_vOldiid.end(); 55 ConstImpDirFileIterator EndIter = m_vOldiid.end();
56 56
57 for (int i=0;i<=1;i++) // Loop once for m_vOldiid and once for m_vNewiid 57 for (int i=0;i<=1;i++) // Loop once for m_vOldiid and once for m_vNewiid
58 { 58 {
59 do 59 do
60 { 60 {
61 FileIter = std::find_if(FileIter, EndIter, std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_IMPORT_DIRECTORY<bits>::operator==), strFilename)); 61 FileIter = std::find_if(FileIter, EndIter, std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_IMPORT_DIRECTORY<bits>::operator==), strFilename));
62 62
63 if (FileIter != EndIter) 63 if (FileIter != EndIter)
64 { 64 {
65 typename std::vector<PELIB_THUNK_DATA<bits> >::const_iterator Iter = std::find_if(FileIter->originalfirstthunk.begin(), FileIter->originalfirstthunk.end(), std::bind2nd(std::mem_fun_ref(comp), value)); 65 typename std::vector<PELIB_THUNK_DATA<bits> >::const_iterator Iter = std::find_if(FileIter->originalfirstthunk.begin(), FileIter->originalfirstthunk.end(), std::bind2nd(std::mem_fun_ref(comp), value));
66 if (Iter != FileIter->originalfirstthunk.end()) 66 if (Iter != FileIter->originalfirstthunk.end())
67 { 67 {
68 return true; 68 return true;
69 } 69 }
70 ++FileIter; 70 ++FileIter;
71 } 71 }
72 } 72 }
73 while (FileIter != EndIter); 73 while (FileIter != EndIter);
74 74
75 FileIter = m_vNewiid.begin(); 75 FileIter = m_vNewiid.begin();
76 EndIter = m_vNewiid.end(); 76 EndIter = m_vNewiid.end();
77 } 77 }
78 78
79 return false; 79 return false;
80 } 80 }
81 81
82 82
83 public: 83 public:
84 84
85 /// Add a function to the import directory. 85 /// Add a function to the import directory.
86 int addFunction(const std::string& strFilename, word wHint); // EXPORT _byHint 86 int addFunction(const std::string& strFilename, word wHint); // EXPORT _byHint
87 /// Add a function to the import directory. 87 /// Add a function to the import directory.
88 int addFunction(const std::string& strFilename, const std::string& strFuncname); // EXPORT _byName 88 int addFunction(const std::string& strFilename, const std::string& strFuncname); // EXPORT _byName
89 89
90 /// Get the ID of a file through it's name. 90 /// Get the ID of a file through it's name.
91 unsigned int getFileIndex(const std::string& strFilename, currdir cdDir) const; // EXPORT 91 unsigned int getFileIndex(const std::string& strFilename, currdir cdDir) const; // EXPORT
92 /// Get the ID of a function through it's name. 92 /// Get the ID of a function through it's name.
93 unsigned int getFunctionIndex(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const; // EXPORT 93 unsigned int getFunctionIndex(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const; // EXPORT
94 94
95 /// Get the name of an imported file. 95 /// Get the name of an imported file.
96 std::string getFileName(dword dwFilenr, currdir cdDir) const; // EXPORT 96 std::string getFileName(dword dwFilenr, currdir cdDir) const; // EXPORT
97 97
98 void setFileName(dword filenr, currdir dir, const std::string& name); // EXPORT 98 void setFileName(dword filenr, currdir dir, const std::string& name); // EXPORT
99 99
100 /// Get the hint of an imported function. 100 /// Get the hint of an imported function.
101 word getFunctionHint(dword dwFilenr, dword dwFuncnr, currdir cdDir) const; // EXPORT 101 word getFunctionHint(dword dwFilenr, dword dwFuncnr, currdir cdDir) const; // EXPORT
102 void setFunctionHint(dword dwFilenr, dword dwFuncnr, currdir cdDir, word value); // EXPORT 102 void setFunctionHint(dword dwFilenr, dword dwFuncnr, currdir cdDir, word value); // EXPORT
103 /// Get the name of an imported function. 103 /// Get the name of an imported function.
104 std::string getFunctionName(dword dwFilenr, dword dwFuncnr, currdir cdDir) const; // EXPORT 104 std::string getFunctionName(dword dwFilenr, dword dwFuncnr, currdir cdDir) const; // EXPORT
105 void setFunctionName(dword dwFilenr, dword dwFuncnr, currdir cdDir, const std::string& functionName); // EXPORT 105 void setFunctionName(dword dwFilenr, dword dwFuncnr, currdir cdDir, const std::string& functionName); // EXPORT
106 /// Get the number of files which are imported. 106 /// Get the number of files which are imported.
107 dword getNumberOfFiles(currdir cdDir) const; // EXPORT 107 dword getNumberOfFiles(currdir cdDir) const; // EXPORT
108 /// Get the number of fucntions which are imported by a specific file. 108 /// Get the number of fucntions which are imported by a specific file.
109 dword getNumberOfFunctions(dword dwFilenr, currdir cdDir) const; // EXPORT 109 dword getNumberOfFunctions(dword dwFilenr, currdir cdDir) const; // EXPORT
110 /// Read a file's import directory. 110 /// Read a file's import directory.
111 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, const PeHeaderT<bits>& pehHeader); // EXPORT 111 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, const PeHeaderT<bits>& pehHeader); // EXPORT
112 /// Rebuild the import directory. 112 /// Rebuild the import directory.
113 void rebuild(std::vector<byte>& vBuffer, dword dwRva, bool fixEntries = true) const; // EXPORT 113 void rebuild(std::vector<byte>& vBuffer, dword dwRva, bool fixEntries = true) const; // EXPORT
114 /// Remove a file from the import directory. 114 /// Remove a file from the import directory.
115 int removeFile(const std::string& strFilename); // EXPORT 115 int removeFile(const std::string& strFilename); // EXPORT
116 /// Remove a function from the import directory. 116 /// Remove a function from the import directory.
117 int removeFunction(const std::string& strFilename, const std::string& strFuncname); // EXPORT _byName 117 int removeFunction(const std::string& strFilename, const std::string& strFuncname); // EXPORT _byName
118 /// Remove a function from the import directory. 118 /// Remove a function from the import directory.
119 int removeFunction(const std::string& strFilename, word wHint); // EXPORT _byHint 119 int removeFunction(const std::string& strFilename, word wHint); // EXPORT _byHint
120 /// Returns the size of the current import directory. 120 /// Returns the size of the current import directory.
121 unsigned int size() const; // EXPORT 121 unsigned int size() const; // EXPORT
122 /// Writes the import directory to a file. 122 /// Writes the import directory to a file.
123 int write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva); // EXPORT 123 int write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva); // EXPORT
124 124
125 /// Returns the FirstThunk value of a function. 125 /// Returns the FirstThunk value of a function.
126 dword getFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir) const; // EXPORT _byNumber 126 dword getFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir) const; // EXPORT _byNumber
127 void setFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir, dword value); // EXPORT _byNumber 127 void setFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir, dword value); // EXPORT _byNumber
128 /// Returns the OriginalFirstThunk value of a function. 128 /// Returns the OriginalFirstThunk value of a function.
129 dword getOriginalFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir) const; // EXPORT _byNumber 129 dword getOriginalFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir) const; // EXPORT _byNumber
130 void setOriginalFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir, dword value); // EXPORT 130 void setOriginalFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir, dword value); // EXPORT
131 131
132// dword getFirstThunk(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const throw (PeLibException); 132// dword getFirstThunk(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const throw (PeLibException);
133// dword getOriginalFirstThunk(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const throw (PeLibException); 133// dword getOriginalFirstThunk(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const throw (PeLibException);
134 134
135 /// Returns the FirstThunk value of a file. 135 /// Returns the FirstThunk value of a file.
136 dword getFirstThunk(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName 136 dword getFirstThunk(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName
137 /// Returns the OriginalFirstThunk value of a file. 137 /// Returns the OriginalFirstThunk value of a file.
138 dword getOriginalFirstThunk(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName 138 dword getOriginalFirstThunk(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName
139 /// Returns the ForwarderChain value of a file. 139 /// Returns the ForwarderChain value of a file.
140 dword getForwarderChain(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName 140 dword getForwarderChain(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName
141 dword getRvaOfName(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName 141 dword getRvaOfName(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName
142 /// Returns the TimeDateStamp value of a file. 142 /// Returns the TimeDateStamp value of a file.
143 dword getTimeDateStamp(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName 143 dword getTimeDateStamp(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName
144 144
145 /// Returns the FirstThunk value of a file. 145 /// Returns the FirstThunk value of a file.
146 dword getFirstThunk(dword dwFilenr, currdir cdDir) const; // EXPORT 146 dword getFirstThunk(dword dwFilenr, currdir cdDir) const; // EXPORT
147 void setFirstThunk(dword dwFilenr, currdir cdDir, dword value); // EXPORT _byNumber_function 147 void setFirstThunk(dword dwFilenr, currdir cdDir, dword value); // EXPORT _byNumber_function
148 /// Returns the OriginalFirstThunk value of a file. 148 /// Returns the OriginalFirstThunk value of a file.
149 dword getOriginalFirstThunk(dword dwFilenr, currdir cdDir) const; // EXPORT 149 dword getOriginalFirstThunk(dword dwFilenr, currdir cdDir) const; // EXPORT
150 void setOriginalFirstThunk(dword dwFilenr, currdir cdDir, dword value); // EXPORT _byNumber_function 150 void setOriginalFirstThunk(dword dwFilenr, currdir cdDir, dword value); // EXPORT _byNumber_function
151 /// Returns the ForwarderChain value of a file. 151 /// Returns the ForwarderChain value of a file.
152 dword getForwarderChain(dword dwFilenr, currdir cdDir) const; // EXPORT _byNumber 152 dword getForwarderChain(dword dwFilenr, currdir cdDir) const; // EXPORT _byNumber
153 void setForwarderChain(dword dwFilenr, currdir cdDir, dword value); // EXPORT _byNumber_function 153 void setForwarderChain(dword dwFilenr, currdir cdDir, dword value); // EXPORT _byNumber_function
154 dword getRvaOfName(dword dwFilenr, currdir cdDir) const; // EXPORT _byNumber 154 dword getRvaOfName(dword dwFilenr, currdir cdDir) const; // EXPORT _byNumber
155 void setRvaOfName(dword dwFilenr, currdir cdDir, dword value); // EXPORT 155 void setRvaOfName(dword dwFilenr, currdir cdDir, dword value); // EXPORT
156 /// Returns the TimeDateStamp value of a file. 156 /// Returns the TimeDateStamp value of a file.
157 dword getTimeDateStamp(dword dwFilenr, currdir cdDir) const; // EXPORT 157 dword getTimeDateStamp(dword dwFilenr, currdir cdDir) const; // EXPORT
158 void setTimeDateStamp(dword dwFilenr, currdir cdDir, dword value); // EXPORT _byNumber 158 void setTimeDateStamp(dword dwFilenr, currdir cdDir, dword value); // EXPORT _byNumber
159 159
160// word getFunctionHint(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const throw (PeLibException); 160// word getFunctionHint(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const throw (PeLibException);
161 }; 161 };
162 162
163 /** 163 /**
164 * Add another import (by Ordinal) to the current file. Note that the import table is not automatically updated. 164 * Add another import (by Ordinal) to the current file. Note that the import table is not automatically updated.
165 * The new imported functions will be added when you recalculate the import table as it's necessary 165 * The new imported functions will be added when you recalculate the import table as it's necessary
166 * to specify the address the import table will have in the file. 166 * to specify the address the import table will have in the file.
167 * @param strFilename The name of a DLL. 167 * @param strFilename The name of a DLL.
168 * @param wHint The ordinal of the function in the DLL. 168 * @param wHint The ordinal of the function in the DLL.
169 **/ 169 **/
170 template<int bits> 170 template<int bits>
171 int ImportDirectory<bits>::addFunction(const std::string& strFilename, word wHint) 171 int ImportDirectory<bits>::addFunction(const std::string& strFilename, word wHint)
172 { 172 {
173 if (hasFunction(strFilename, wHint, &PELIB_THUNK_DATA<bits>::equalHint)) 173 if (hasFunction(strFilename, wHint, &PELIB_THUNK_DATA<bits>::equalHint))
174 { 174 {
175 return ERROR_DUPLICATE_ENTRY; 175 return ERROR_DUPLICATE_ENTRY;
176 } 176 }
177 177
178 // Find the imported file. 178 // Find the imported file.
179 ImpDirFileIterator FileIter = std::find_if(m_vNewiid.begin(), m_vNewiid.end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_IMPORT_DIRECTORY<bits>::operator==), strFilename)); 179 ImpDirFileIterator FileIter = std::find_if(m_vNewiid.begin(), m_vNewiid.end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_IMPORT_DIRECTORY<bits>::operator==), strFilename));
180 180
181 PELIB_IMAGE_IMPORT_DIRECTORY<bits> iid; 181 PELIB_IMAGE_IMPORT_DIRECTORY<bits> iid;
182 PELIB_THUNK_DATA<bits> td; 182 PELIB_THUNK_DATA<bits> td;
183 td.hint = wHint; 183 td.hint = wHint;
184 td.itd.Ordinal = wHint | PELIB_IMAGE_ORDINAL_FLAGS<bits>::IMAGE_ORDINAL_FLAG; 184 td.itd.Ordinal = wHint | PELIB_IMAGE_ORDINAL_FLAGS<bits>::IMAGE_ORDINAL_FLAG;
185 iid.name = strFilename; 185 iid.name = strFilename;
186 if (FileIter == m_vNewiid.end()) 186 if (FileIter == m_vNewiid.end())
187 { 187 {
188 iid.originalfirstthunk.push_back(td); 188 iid.originalfirstthunk.push_back(td);
189 iid.firstthunk.push_back(td); 189 iid.firstthunk.push_back(td);
190 m_vNewiid.push_back(iid); 190 m_vNewiid.push_back(iid);
191 } 191 }
192 else 192 else
193 { 193 {
194 FileIter->originalfirstthunk.push_back(td); 194 FileIter->originalfirstthunk.push_back(td);
195 FileIter->firstthunk.push_back(td); 195 FileIter->firstthunk.push_back(td);
196 } 196 }
197 197
198 return NO_ERROR; 198 return NO_ERROR;
199 } 199 }
200 200
201 /** 201 /**
202 * Add a function to the Import Directory. 202 * Add a function to the Import Directory.
203 * @param strFilename Name of the file which will be imported 203 * @param strFilename Name of the file which will be imported
204 * @param strFuncname Name of the function which will be imported. 204 * @param strFuncname Name of the function which will be imported.
205 **/ 205 **/
206 template<int bits> 206 template<int bits>
207 int ImportDirectory<bits>::addFunction(const std::string& strFilename, const std::string& strFuncname) 207 int ImportDirectory<bits>::addFunction(const std::string& strFilename, const std::string& strFuncname)
208 { 208 {
209 if (hasFunction(strFilename, strFuncname, &PELIB_THUNK_DATA<bits>::equalFunctionName)) 209 if (hasFunction(strFilename, strFuncname, &PELIB_THUNK_DATA<bits>::equalFunctionName))
210 { 210 {
211 return ERROR_DUPLICATE_ENTRY; 211 return ERROR_DUPLICATE_ENTRY;
212 } 212 }
213 213
214 // Find the imported file. 214 // Find the imported file.
215 ImpDirFileIterator FileIter = std::find_if(m_vNewiid.begin(), m_vNewiid.end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_IMPORT_DIRECTORY<bits>::operator==), strFilename)); 215 ImpDirFileIterator FileIter = std::find_if(m_vNewiid.begin(), m_vNewiid.end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_IMPORT_DIRECTORY<bits>::operator==), strFilename));
216 216
217 PELIB_IMAGE_IMPORT_DIRECTORY<bits> iid; 217 PELIB_IMAGE_IMPORT_DIRECTORY<bits> iid;
218 PELIB_THUNK_DATA<bits> td; 218 PELIB_THUNK_DATA<bits> td;
219 td.fname = strFuncname; 219 td.fname = strFuncname;
220 iid.name = strFilename; 220 iid.name = strFilename;
221 if (FileIter == m_vNewiid.end()) 221 if (FileIter == m_vNewiid.end())
222 { 222 {
223 iid.originalfirstthunk.push_back(td); 223 iid.originalfirstthunk.push_back(td);
224 iid.firstthunk.push_back(td); 224 iid.firstthunk.push_back(td);
225 m_vNewiid.push_back(iid); 225 m_vNewiid.push_back(iid);
226 } 226 }
227 else 227 else
228 { 228 {
229 FileIter->originalfirstthunk.push_back(td); 229 FileIter->originalfirstthunk.push_back(td);
230 FileIter->firstthunk.push_back(td); 230 FileIter->firstthunk.push_back(td);
231 } 231 }
232 232
233 return NO_ERROR; 233 return NO_ERROR;
234 } 234 }
235 235
236 /** 236 /**
237 * Searches through the import directory and returns the number of the import 237 * Searches through the import directory and returns the number of the import
238 * directory entry which belongs to the given filename. 238 * directory entry which belongs to the given filename.
239 * @param strFilename Name of the imported file. 239 * @param strFilename Name of the imported file.
240 * @param cdDir Flag to decide if the OLDDIR or new import directory is used. 240 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
241 * @return The ID of an imported file. 241 * @return The ID of an imported file.
242 **/ 242 **/
243 template<int bits> 243 template<int bits>
244 unsigned int ImportDirectory<bits>::getFileIndex(const std::string& strFilename, currdir cdDir) const 244 unsigned int ImportDirectory<bits>::getFileIndex(const std::string& strFilename, currdir cdDir) const
245 { 245 {
246 const std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> >* currDir; 246 const std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> >* currDir;
247 247
248 if (cdDir == OLDDIR) 248 if (cdDir == OLDDIR)
249 { 249 {
250 currDir = &m_vOldiid; 250 currDir = &m_vOldiid;
251 } 251 }
252 else 252 else
253 { 253 {
254 currDir = &m_vNewiid; 254 currDir = &m_vNewiid;
255 } 255 }
256 256
257 ConstImpDirFileIterator FileIter = std::find_if(currDir->begin(), currDir->end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_IMPORT_DIRECTORY<bits>::operator==), strFilename)); 257 ConstImpDirFileIterator FileIter = std::find_if(currDir->begin(), currDir->end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_IMPORT_DIRECTORY<bits>::operator==), strFilename));
258 258
259 if (FileIter != currDir->end()) 259 if (FileIter != currDir->end())
260 { 260 {
261 return static_cast<unsigned int>(std::distance(currDir->begin(), FileIter)); 261 return static_cast<unsigned int>(std::distance(currDir->begin(), FileIter));
262 } 262 }
263 else 263 else
264 { 264 {
265 return -1; 265 return -1;
266 // throw Exceptions::InvalidName(ImportDirectoryId, __LINE__); 266 // throw Exceptions::InvalidName(ImportDirectoryId, __LINE__);
267 } 267 }
268 268
269 return NO_ERROR; 269 return NO_ERROR;
270 } 270 }
271 271
272 /** 272 /**
273 * Searches through an imported file for a specific function. 273 * Searches through an imported file for a specific function.
274 * @param strFilename Name of the imported file. 274 * @param strFilename Name of the imported file.
275 * @param strFuncname Name of the imported function. 275 * @param strFuncname Name of the imported function.
276 * @param cdDir Flag to decide if the OLDDIR or new import directory is used. 276 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
277 * @return ID of the imported function. 277 * @return ID of the imported function.
278 **/ 278 **/
279 template<int bits> 279 template<int bits>
280 unsigned int ImportDirectory<bits>::getFunctionIndex(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const 280 unsigned int ImportDirectory<bits>::getFunctionIndex(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const
281 { 281 {
282 unsigned int uiFile = getFileIndex(strFilename, cdDir); 282 unsigned int uiFile = getFileIndex(strFilename, cdDir);
283 283
284 for (unsigned int i=0;i<getNumberOfFunctions(uiFile, cdDir);i++) 284 for (unsigned int i=0;i<getNumberOfFunctions(uiFile, cdDir);i++)
285 { 285 {
286 if (getFunctionName(uiFile, i, cdDir) == strFuncname) return i; 286 if (getFunctionName(uiFile, i, cdDir) == strFuncname) return i;
287 } 287 }
288 288
289 return -1; 289 return -1;
290 } 290 }
291 291
292 /** 292 /**
293 * Get the name of an imported file. 293 * Get the name of an imported file.
294 * @param dwFilenr Identifies which file should be checked. 294 * @param dwFilenr Identifies which file should be checked.
295 * @param cdDir Flag to decide if the OLDDIR or new import directory is used. 295 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
296 * @return Name of an imported file. 296 * @return Name of an imported file.
297 **/ 297 **/
298 template<int bits> 298 template<int bits>
299 std::string ImportDirectory<bits>::getFileName(dword dwFilenr, currdir cdDir) const 299 std::string ImportDirectory<bits>::getFileName(dword dwFilenr, currdir cdDir) const
300 { 300 {
301 if (cdDir == OLDDIR) return m_vOldiid[dwFilenr].name; 301 if (cdDir == OLDDIR) return m_vOldiid[dwFilenr].name;
302 else return m_vNewiid[dwFilenr].name; 302 else return m_vNewiid[dwFilenr].name;
303 } 303 }
304 304
305 template<int bits> 305 template<int bits>
306 void ImportDirectory<bits>::setFileName(dword filenr, currdir dir, const std::string& name) 306 void ImportDirectory<bits>::setFileName(dword filenr, currdir dir, const std::string& name)
307 { 307 {
308 if (dir == OLDDIR) m_vOldiid[filenr].name = name; 308 if (dir == OLDDIR) m_vOldiid[filenr].name = name;
309 else m_vNewiid[filenr].name = name; 309 else m_vNewiid[filenr].name = name;
310 } 310 }
311 311
312 /** 312 /**
313 * Get the name of an imported function. 313 * Get the name of an imported function.
314 * @param dwFilenr Identifies which file should be checked. 314 * @param dwFilenr Identifies which file should be checked.
315 * @param dwFuncnr Identifies which function should be checked. 315 * @param dwFuncnr Identifies which function should be checked.
316 * @param cdDir Flag to decide if the OLDDIR or new import directory is used. 316 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
317 * @return Name of an imported function. 317 * @return Name of an imported function.
318 * \todo Marked line is unsafe (function should be rewritten). 318 * \todo Marked line is unsafe (function should be rewritten).
319 **/ 319 **/
320 template<int bits> 320 template<int bits>
321 std::string ImportDirectory<bits>::getFunctionName(dword dwFilenr, dword dwFuncnr, currdir cdDir) const 321 std::string ImportDirectory<bits>::getFunctionName(dword dwFilenr, dword dwFuncnr, currdir cdDir) const
322 { 322 {
323 if (cdDir == OLDDIR) 323 if (cdDir == OLDDIR)
324 { 324 {
325 // Unsafe 325 // Unsafe
326 if (m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk) 326 if (m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk)
327 { 327 {
328 return m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].fname; 328 return m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].fname;
329 } 329 }
330 else 330 else
331 { 331 {
332 return m_vOldiid[dwFilenr].firstthunk[dwFuncnr].fname; 332 return m_vOldiid[dwFilenr].firstthunk[dwFuncnr].fname;
333 } 333 }
334 } 334 }
335 else 335 else
336 { 336 {
337 if (m_vNewiid[dwFilenr].impdesc.OriginalFirstThunk) 337 if (m_vNewiid[dwFilenr].impdesc.OriginalFirstThunk)
338 { 338 {
339 return m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].fname; 339 return m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].fname;
340 } 340 }
341 else 341 else
342 { 342 {
343 return m_vNewiid[dwFilenr].firstthunk[dwFuncnr].fname; 343 return m_vNewiid[dwFilenr].firstthunk[dwFuncnr].fname;
344 } 344 }
345 } 345 }
346 } 346 }
347 347
348 template<int bits> 348 template<int bits>
349 void ImportDirectory<bits>::setFunctionName(dword dwFilenr, dword dwFuncnr, currdir cdDir, const std::string& functionName) 349 void ImportDirectory<bits>::setFunctionName(dword dwFilenr, dword dwFuncnr, currdir cdDir, const std::string& functionName)
350 { 350 {
351 if (cdDir == OLDDIR) 351 if (cdDir == OLDDIR)
352 { 352 {
353 // Unsafe 353 // Unsafe
354 if (m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk) 354 if (m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk)
355 { 355 {
356 m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].fname = functionName; 356 m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].fname = functionName;
357 } 357 }
358 else 358 else
359 { 359 {
360 m_vOldiid[dwFilenr].firstthunk[dwFuncnr].fname = functionName; 360 m_vOldiid[dwFilenr].firstthunk[dwFuncnr].fname = functionName;
361 } 361 }
362 } 362 }
363 else 363 else
364 { 364 {
365 if (m_vNewiid[dwFilenr].impdesc.OriginalFirstThunk) 365 if (m_vNewiid[dwFilenr].impdesc.OriginalFirstThunk)
366 { 366 {
367 m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].fname = functionName; 367 m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].fname = functionName;
368 } 368 }
369 else 369 else
370 { 370 {
371 m_vNewiid[dwFilenr].firstthunk[dwFuncnr].fname = functionName; 371 m_vNewiid[dwFilenr].firstthunk[dwFuncnr].fname = functionName;
372 } 372 }
373 } 373 }
374 } 374 }
375 375
376 /** 376 /**
377 * Get the hint of an imported function. 377 * Get the hint of an imported function.
378 * @param dwFilenr Identifies which file should be checked. 378 * @param dwFilenr Identifies which file should be checked.
379 * @param dwFuncnr Identifies which function should be checked. 379 * @param dwFuncnr Identifies which function should be checked.
380 * @param cdDir Flag to decide if the OLDDIR or new import directory is used. 380 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
381 * @return Hint of an imported function. 381 * @return Hint of an imported function.
382 **/ 382 **/
383 template<int bits> 383 template<int bits>
384 word ImportDirectory<bits>::getFunctionHint(dword dwFilenr, dword dwFuncnr, currdir cdDir) const 384 word ImportDirectory<bits>::getFunctionHint(dword dwFilenr, dword dwFuncnr, currdir cdDir) const
385 { 385 {
386 if (cdDir == OLDDIR) 386 if (cdDir == OLDDIR)
387 { 387 {
388 if (m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk) 388 if (m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk)
389 { 389 {
390 return m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].hint; 390 return m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].hint;
391 } 391 }
392 else 392 else
393 { 393 {
394 return m_vOldiid[dwFilenr].firstthunk[dwFuncnr].hint; 394 return m_vOldiid[dwFilenr].firstthunk[dwFuncnr].hint;
395 } 395 }
396 } 396 }
397 else return m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].hint; 397 else return m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].hint;
398 } 398 }
399 399
400 template<int bits> 400 template<int bits>
401 void ImportDirectory<bits>::setFunctionHint(dword dwFilenr, dword dwFuncnr, currdir cdDir, word value) 401 void ImportDirectory<bits>::setFunctionHint(dword dwFilenr, dword dwFuncnr, currdir cdDir, word value)
402 { 402 {
403 if (cdDir == OLDDIR) 403 if (cdDir == OLDDIR)
404 { 404 {
405 if (m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk) 405 if (m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk)
406 { 406 {
407 m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].hint = value; 407 m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].hint = value;
408 } 408 }
409 else 409 else
410 { 410 {
411 m_vOldiid[dwFilenr].firstthunk[dwFuncnr].hint = value; 411 m_vOldiid[dwFilenr].firstthunk[dwFuncnr].hint = value;
412 } 412 }
413 } 413 }
414 else m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].hint = value; 414 else m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].hint = value;
415 } 415 }
416 416
417 /** 417 /**
418 * Get the number of files which are currently being imported. 418 * Get the number of files which are currently being imported.
419 * @param cdDir Flag to decide if the OLDDIR or new import directory is used. 419 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
420 * @return Number of files which are currently being imported. 420 * @return Number of files which are currently being imported.
421 **/ 421 **/
422 template<int bits> 422 template<int bits>
423 dword ImportDirectory<bits>::getNumberOfFiles(currdir cdDir) const 423 dword ImportDirectory<bits>::getNumberOfFiles(currdir cdDir) const
424 { 424 {
425 if (cdDir == OLDDIR) return static_cast<dword>(m_vOldiid.size()); 425 if (cdDir == OLDDIR) return static_cast<dword>(m_vOldiid.size());
426 else return static_cast<dword>(m_vNewiid.size()); 426 else return static_cast<dword>(m_vNewiid.size());
427 } 427 }
428 428
429 /** 429 /**
430 * Get the number of functions which are currently being imported from a specific file. 430 * Get the number of functions which are currently being imported from a specific file.
431 * @param dwFilenr Identifies which file should be checked. 431 * @param dwFilenr Identifies which file should be checked.
432 * @param cdDir Flag to decide if the OLDDIR or new import directory is used. 432 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
433 * @return Number of functions which are currently being imported from a specific file. 433 * @return Number of functions which are currently being imported from a specific file.
434 **/ 434 **/
435 template<int bits> 435 template<int bits>
436 dword ImportDirectory<bits>::getNumberOfFunctions(dword dwFilenr, currdir cdDir) const 436 dword ImportDirectory<bits>::getNumberOfFunctions(dword dwFilenr, currdir cdDir) const
437 { 437 {
438 if (cdDir == OLDDIR) return static_cast<unsigned int>(m_vOldiid[dwFilenr].firstthunk.size()); 438 if (cdDir == OLDDIR) return static_cast<unsigned int>(m_vOldiid[dwFilenr].firstthunk.size());
439 else return static_cast<unsigned int>(m_vNewiid[dwFilenr].firstthunk.size()); 439 else return static_cast<unsigned int>(m_vNewiid[dwFilenr].firstthunk.size());
440 } 440 }
441 441
442 /** 442 /**
443 * Read an import directory from a file. 443 * Read an import directory from a file.
444 * \todo Check if streams failed. 444 * \todo Check if streams failed.
445 * @param strFilename Name of the file which will be read. 445 * @param strFilename Name of the file which will be read.
446 * @param uiOffset Offset of the import directory (see #PeLib::PeHeader::getIDImportRVA). 446 * @param uiOffset Offset of the import directory (see #PeLib::PeHeader::getIDImportRVA).
447 * @param uiSize Size of the import directory (see #PeLib::PeHeader::getIDImportSize). 447 * @param uiSize Size of the import directory (see #PeLib::PeHeader::getIDImportSize).
448 * @param pehHeader A valid PE header. 448 * @param pehHeader A valid PE header.
449 **/ 449 **/
450 template<int bits> 450 template<int bits>
451 int ImportDirectory<bits>::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, const PeHeaderT<bits>& pehHeader) 451 int ImportDirectory<bits>::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, const PeHeaderT<bits>& pehHeader)
452 { 452 {
453 std::ifstream ifFile(strFilename.c_str(), std::ios_base::binary); 453 std::ifstream ifFile(strFilename.c_str(), std::ios_base::binary);
454 454
455 if (!ifFile) 455 if (!ifFile)
456 { 456 {
457 return ERROR_OPENING_FILE; 457 return ERROR_OPENING_FILE;
458 } 458 }
459 459
460 unsigned int uiFileSize = fileSize(ifFile); 460 unsigned int uiFileSize = fileSize(ifFile);
461 461
462 if (uiFileSize < uiOffset + uiSize) 462 if (uiFileSize < uiOffset + uiSize)
463 { 463 {
464 return ERROR_INVALID_FILE; 464 return ERROR_INVALID_FILE;
465 } 465 }
466 466
467 ifFile.seekg(uiOffset, std::ios_base::beg); 467 ifFile.seekg(uiOffset, std::ios_base::beg);
468 468
469 std::vector<unsigned char> vImportdirectory(uiSize); 469 std::vector<unsigned char> vImportdirectory(uiSize);
470 ifFile.read(reinterpret_cast<char*>(&vImportdirectory[0]), uiSize); 470 ifFile.read(reinterpret_cast<char*>(&vImportdirectory[0]), uiSize);
471 471
472 PELIB_IMAGE_IMPORT_DIRECTORY<bits> iidCurr; 472 PELIB_IMAGE_IMPORT_DIRECTORY<bits> iidCurr;
473 unsigned int uiDesccounter = 0; 473 unsigned int uiDesccounter = 0;
474 474
475 InputBuffer inpBuffer(vImportdirectory); 475 InputBuffer inpBuffer(vImportdirectory);
476 476
477 std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> > vOldIidCurr; 477 std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> > vOldIidCurr;
478 478
479 do // Read and store all descriptors 479 do // Read and store all descriptors
480 { 480 {
481 inpBuffer >> iidCurr.impdesc.OriginalFirstThunk; 481 inpBuffer >> iidCurr.impdesc.OriginalFirstThunk;
482 inpBuffer >> iidCurr.impdesc.TimeDateStamp; 482 inpBuffer >> iidCurr.impdesc.TimeDateStamp;
483 inpBuffer >> iidCurr.impdesc.ForwarderChain; 483 inpBuffer >> iidCurr.impdesc.ForwarderChain;
484 inpBuffer >> iidCurr.impdesc.Name; 484 inpBuffer >> iidCurr.impdesc.Name;
485 inpBuffer >> iidCurr.impdesc.FirstThunk; 485 inpBuffer >> iidCurr.impdesc.FirstThunk;
486 486
487 if (iidCurr.impdesc.OriginalFirstThunk != 0 || iidCurr.impdesc.TimeDateStamp != 0 || iidCurr.impdesc.ForwarderChain != 0 || 487 if (iidCurr.impdesc.OriginalFirstThunk != 0 || iidCurr.impdesc.TimeDateStamp != 0 || iidCurr.impdesc.ForwarderChain != 0 ||
488 iidCurr.impdesc.Name != 0 || iidCurr.impdesc.FirstThunk != 0) 488 iidCurr.impdesc.Name != 0 || iidCurr.impdesc.FirstThunk != 0)
489 { 489 {
490 vOldIidCurr.push_back(iidCurr); 490 vOldIidCurr.push_back(iidCurr);
491 } 491 }
492 492
493 uiDesccounter++; 493 uiDesccounter++;
494 494
495 if (uiSize < (uiDesccounter + 1) * PELIB_IMAGE_IMPORT_DESCRIPTOR::size()) break; 495 if (uiSize < (uiDesccounter + 1) * PELIB_IMAGE_IMPORT_DESCRIPTOR::size()) break;
496 } while (iidCurr.impdesc.OriginalFirstThunk != 0 || iidCurr.impdesc.TimeDateStamp != 0 || iidCurr.impdesc.ForwarderChain != 0 || 496 } while (iidCurr.impdesc.OriginalFirstThunk != 0 || iidCurr.impdesc.TimeDateStamp != 0 || iidCurr.impdesc.ForwarderChain != 0 ||
497 iidCurr.impdesc.Name != 0 || iidCurr.impdesc.FirstThunk != 0); 497 iidCurr.impdesc.Name != 0 || iidCurr.impdesc.FirstThunk != 0);
498 498
499 char namebuffer[2] = {0}; 499 char namebuffer[2] = {0};
500 500
501 // Name 501 // Name
502 for (unsigned int i=0;i<vOldIidCurr.size();i++) 502 for (unsigned int i=0;i<vOldIidCurr.size();i++)
503 { 503 {
504 ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(vOldIidCurr[i].impdesc.Name)), std::ios_base::beg); 504 ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(vOldIidCurr[i].impdesc.Name)), std::ios_base::beg);
505 505
506 std::string dllname = ""; 506 std::string dllname = "";
507 507
508 do 508 do
509 { 509 {
510 ifFile.read(namebuffer, 1); 510 ifFile.read(namebuffer, 1);
511 if (!ifFile || !namebuffer[0]) break; // reached end of file or 0-byte 511 if (!ifFile || !namebuffer[0]) break; // reached end of file or 0-byte
512 dllname += namebuffer; 512 dllname += namebuffer;
513 } while (true); 513 } while (true);
514 514
515 vOldIidCurr[i].name = dllname; 515 vOldIidCurr[i].name = dllname;
516 516
517 } 517 }
518 518
519 // OriginalFirstThunk 519 // OriginalFirstThunk
520 for (unsigned int i=0;i<vOldIidCurr.size();i++) 520 for (unsigned int i=0;i<vOldIidCurr.size();i++)
521 { 521 {
522 PELIB_THUNK_DATA<bits> tdCurr; 522 PELIB_THUNK_DATA<bits> tdCurr;
523 dword uiVaoft = vOldIidCurr[i].impdesc.OriginalFirstThunk; 523 dword uiVaoft = vOldIidCurr[i].impdesc.OriginalFirstThunk;
524 524
525 if (!uiVaoft) 525 if (!uiVaoft)
526 { 526 {
527 continue; 527 continue;
528 } 528 }
529 529
530 ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(uiVaoft)), std::ios_base::beg); 530 ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(uiVaoft)), std::ios_base::beg);
531 531
532 do 532 do
533 { 533 {
534 if (uiFileSize < pehHeader.rvaToOffset(uiVaoft) + sizeof(tdCurr.itd.Ordinal)) 534 if (uiFileSize < pehHeader.rvaToOffset(uiVaoft) + sizeof(tdCurr.itd.Ordinal))
535 { 535 {
536 return ERROR_INVALID_FILE; 536 return ERROR_INVALID_FILE;
537 } 537 }
538 uiVaoft += sizeof(tdCurr.itd.Ordinal); 538 uiVaoft += sizeof(tdCurr.itd.Ordinal);
539 539
540 ifFile.read(reinterpret_cast<char*>(&tdCurr.itd.Ordinal), sizeof(tdCurr.itd.Ordinal)); 540 ifFile.read(reinterpret_cast<char*>(&tdCurr.itd.Ordinal), sizeof(tdCurr.itd.Ordinal));
541 if (tdCurr.itd.Ordinal) vOldIidCurr[i].originalfirstthunk.push_back(tdCurr); 541 if (tdCurr.itd.Ordinal) vOldIidCurr[i].originalfirstthunk.push_back(tdCurr);
542 } while (tdCurr.itd.Ordinal); 542 } while (tdCurr.itd.Ordinal);
543 } 543 }
544 544
545 // FirstThunk 545 // FirstThunk
546 for (unsigned int i=0;i<vOldIidCurr.size();i++) 546 for (unsigned int i=0;i<vOldIidCurr.size();i++)
547 { 547 {
548 dword uiVaoft = vOldIidCurr[i].impdesc.FirstThunk; 548 dword uiVaoft = vOldIidCurr[i].impdesc.FirstThunk;
549 PELIB_THUNK_DATA<bits> tdCurr; 549 PELIB_THUNK_DATA<bits> tdCurr;
550 550
551 ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(uiVaoft)), std::ios_base::beg); 551 ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(uiVaoft)), std::ios_base::beg);
552 552
553 do 553 do
554 { 554 {
555 if (uiFileSize < pehHeader.rvaToOffset(uiVaoft) + sizeof(tdCurr.itd.Ordinal)) 555 if (uiFileSize < pehHeader.rvaToOffset(uiVaoft) + sizeof(tdCurr.itd.Ordinal))
556 { 556 {
557 return ERROR_INVALID_FILE; 557 return ERROR_INVALID_FILE;
558 } 558 }
559 559
560 uiVaoft += sizeof(tdCurr.itd.Ordinal); 560 uiVaoft += sizeof(tdCurr.itd.Ordinal);
561 561
562 ifFile.read(reinterpret_cast<char*>(&tdCurr.itd.Ordinal), sizeof(tdCurr.itd.Ordinal)); 562 ifFile.read(reinterpret_cast<char*>(&tdCurr.itd.Ordinal), sizeof(tdCurr.itd.Ordinal));
563 if (tdCurr.itd.Ordinal) vOldIidCurr[i].firstthunk.push_back(tdCurr); 563 if (tdCurr.itd.Ordinal) vOldIidCurr[i].firstthunk.push_back(tdCurr);
564 } while (tdCurr.itd.Ordinal); 564 } while (tdCurr.itd.Ordinal);
565 } 565 }
566 566
567 // Names 567 // Names
568 for (unsigned int i=0;i<vOldIidCurr.size();i++) 568 for (unsigned int i=0;i<vOldIidCurr.size();i++)
569 { 569 {
570 if (vOldIidCurr[i].impdesc.OriginalFirstThunk) 570 if (vOldIidCurr[i].impdesc.OriginalFirstThunk)
571 { 571 {
572 for (unsigned int j=0;j<vOldIidCurr[i].originalfirstthunk.size();j++) 572 for (unsigned int j=0;j<vOldIidCurr[i].originalfirstthunk.size();j++)
573 { 573 {
574 if (vOldIidCurr[i].originalfirstthunk[j].itd.Ordinal & PELIB_IMAGE_ORDINAL_FLAGS<bits>::IMAGE_ORDINAL_FLAG) 574 if (vOldIidCurr[i].originalfirstthunk[j].itd.Ordinal & PELIB_IMAGE_ORDINAL_FLAGS<bits>::IMAGE_ORDINAL_FLAG)
575 { 575 {
576 vOldIidCurr[i].originalfirstthunk[j].hint = 0; 576 vOldIidCurr[i].originalfirstthunk[j].hint = 0;
577 continue; 577 continue;
578 } 578 }
579 579
580 ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(vOldIidCurr[i].originalfirstthunk[j].itd.Ordinal)), std::ios_base::beg); 580 ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(vOldIidCurr[i].originalfirstthunk[j].itd.Ordinal)), std::ios_base::beg);
581 581
582 ifFile.read(reinterpret_cast<char*>(&vOldIidCurr[i].originalfirstthunk[j].hint), sizeof(vOldIidCurr[i].originalfirstthunk[j].hint)); 582 ifFile.read(reinterpret_cast<char*>(&vOldIidCurr[i].originalfirstthunk[j].hint), sizeof(vOldIidCurr[i].originalfirstthunk[j].hint));
583 583
584 if (!ifFile) 584 if (!ifFile)
585 return ERROR_INVALID_FILE; 585 return ERROR_INVALID_FILE;
586 586
587 std::string funcname = ""; 587 std::string funcname = "";
588 do 588 do
589 { 589 {
590 ifFile.read(namebuffer, 1); 590 ifFile.read(namebuffer, 1);
591 if (!ifFile || !namebuffer[0]) break; // reached end of file or 0-byte 591 if (!ifFile || !namebuffer[0]) break; // reached end of file or 0-byte
592 funcname += namebuffer; 592 funcname += namebuffer;
593 } while (true); 593 } while (true);
594 594
595 vOldIidCurr[i].originalfirstthunk[j].fname = funcname; 595 vOldIidCurr[i].originalfirstthunk[j].fname = funcname;
596 } 596 }
597 } 597 }
598 else 598 else
599 { 599 {
600 for (unsigned int j=0;j<vOldIidCurr[i].firstthunk.size();j++) 600 for (unsigned int j=0;j<vOldIidCurr[i].firstthunk.size();j++)
601 { 601 {
602 if (vOldIidCurr[i].firstthunk[j].itd.Ordinal & PELIB_IMAGE_ORDINAL_FLAGS<bits>::IMAGE_ORDINAL_FLAG) 602 if (vOldIidCurr[i].firstthunk[j].itd.Ordinal & PELIB_IMAGE_ORDINAL_FLAGS<bits>::IMAGE_ORDINAL_FLAG)
603 { 603 {
604 continue; 604 continue;
605 } 605 }
606 606
607 ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(vOldIidCurr[i].firstthunk[j].itd.Ordinal)), std::ios_base::beg); 607 ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(vOldIidCurr[i].firstthunk[j].itd.Ordinal)), std::ios_base::beg);
608 608
609 ifFile.read(reinterpret_cast<char*>(&vOldIidCurr[i].firstthunk[j].hint), sizeof(vOldIidCurr[i].firstthunk[j].hint)); 609 ifFile.read(reinterpret_cast<char*>(&vOldIidCurr[i].firstthunk[j].hint), sizeof(vOldIidCurr[i].firstthunk[j].hint));
610 610
611 if (!ifFile) 611 if (!ifFile)
612 return ERROR_INVALID_FILE; 612 return ERROR_INVALID_FILE;
613 613
614 std::string funcname = ""; 614 std::string funcname = "";
615 do 615 do
616 { 616 {
617 ifFile.read(namebuffer, 1); 617 ifFile.read(namebuffer, 1);
618 if (!ifFile || !namebuffer[0]) break; // reached end of file or 0-byte 618 if (!ifFile || !namebuffer[0]) break; // reached end of file or 0-byte
619 funcname += namebuffer; 619 funcname += namebuffer;
620 } while (true); 620 } while (true);
621 621
622 vOldIidCurr[i].firstthunk[j].fname = funcname; 622 vOldIidCurr[i].firstthunk[j].fname = funcname;
623 } 623 }
624 } 624 }
625 } 625 }
626 std::swap(vOldIidCurr, m_vOldiid); 626 std::swap(vOldIidCurr, m_vOldiid);
627 return NO_ERROR; 627 return NO_ERROR;
628 } 628 }
629 629
630 /** 630 /**
631 * Rebuilds the import directory. 631 * Rebuilds the import directory.
632 * @param vBuffer Buffer the rebuilt import directory will be written to. 632 * @param vBuffer Buffer the rebuilt import directory will be written to.
633 * @param dwRva The RVA of the ImportDirectory in the file. 633 * @param dwRva The RVA of the ImportDirectory in the file.
634 * \todo uiSizeoffuncnames is not used. 634 * \todo uiSizeoffuncnames is not used.
635 **/ 635 **/
636 template<int bits> 636 template<int bits>
637 void ImportDirectory<bits>::rebuild(std::vector<byte>& vBuffer, dword dwRva, bool fixEntries) const 637 void ImportDirectory<bits>::rebuild(std::vector<byte>& vBuffer, dword dwRva, bool fixEntries) const
638 { 638 {
639 unsigned int uiImprva = dwRva; 639 unsigned int uiImprva = dwRva;
640 unsigned int uiSizeofdescriptors = (static_cast<unsigned int>(m_vNewiid.size() + m_vOldiid.size()) + 1) * PELIB_IMAGE_IMPORT_DESCRIPTOR::size(); 640 unsigned int uiSizeofdescriptors = (static_cast<unsigned int>(m_vNewiid.size() + m_vOldiid.size()) + 1) * PELIB_IMAGE_IMPORT_DESCRIPTOR::size();
641 641
642 unsigned int uiSizeofdllnames = 0, uiSizeoffuncnames = 0; 642 unsigned int uiSizeofdllnames = 0, uiSizeoffuncnames = 0;
643 unsigned int uiSizeofoft = 0; 643 unsigned int uiSizeofoft = 0;
644 644
645 for (unsigned int i=0;i<m_vNewiid.size();i++) 645 for (unsigned int i=0;i<m_vNewiid.size();i++)
646 { 646 {
647 uiSizeofdllnames += static_cast<unsigned int>(m_vNewiid[i].name.size()) + 1; 647 uiSizeofdllnames += static_cast<unsigned int>(m_vNewiid[i].name.size()) + 1;
648 uiSizeofoft += (static_cast<unsigned int>(m_vNewiid[i].originalfirstthunk.size())+1) * PELIB_IMAGE_THUNK_DATA<bits>::size(); 648 uiSizeofoft += (static_cast<unsigned int>(m_vNewiid[i].originalfirstthunk.size())+1) * PELIB_IMAGE_THUNK_DATA<bits>::size();
649 649
650 for(unsigned int j=0;j<m_vNewiid[i].originalfirstthunk.size();j++) 650 for(unsigned int j=0;j<m_vNewiid[i].originalfirstthunk.size();j++)
651 { 651 {
652 // +3 for hint (word) and 00-byte 652 // +3 for hint (word) and 00-byte
653 uiSizeoffuncnames += (static_cast<unsigned int>(m_vNewiid[i].originalfirstthunk[j].fname.size()) + 3); 653 uiSizeoffuncnames += (static_cast<unsigned int>(m_vNewiid[i].originalfirstthunk[j].fname.size()) + 3);
654 } 654 }
655 } 655 }
656 656
657// for (unsigned int i=0;i<m_vNewiid.size();i++) 657// for (unsigned int i=0;i<m_vNewiid.size();i++)
658// { 658// {
659// uiSizeofoft += (static_cast<unsigned int>(m_vNewiid[i].originalfirstthunk.size())+1) * PELIB_IMAGE_THUNK_DATA<bits>::size(); 659// uiSizeofoft += (static_cast<unsigned int>(m_vNewiid[i].originalfirstthunk.size())+1) * PELIB_IMAGE_THUNK_DATA<bits>::size();
660// } 660// }
661 661
662 OutputBuffer obBuffer(vBuffer); 662 OutputBuffer obBuffer(vBuffer);
663 663
664 // Rebuild IMAGE_IMPORT_DESCRIPTORS 664 // Rebuild IMAGE_IMPORT_DESCRIPTORS
665 for (unsigned int i=0;i<m_vOldiid.size();i++) 665 for (unsigned int i=0;i<m_vOldiid.size();i++)
666 { 666 {
667 obBuffer << m_vOldiid[i].impdesc.OriginalFirstThunk; 667 obBuffer << m_vOldiid[i].impdesc.OriginalFirstThunk;
668 obBuffer << m_vOldiid[i].impdesc.TimeDateStamp; 668 obBuffer << m_vOldiid[i].impdesc.TimeDateStamp;
669 obBuffer << m_vOldiid[i].impdesc.ForwarderChain; 669 obBuffer << m_vOldiid[i].impdesc.ForwarderChain;
670 obBuffer << m_vOldiid[i].impdesc.Name; 670 obBuffer << m_vOldiid[i].impdesc.Name;
671 obBuffer << m_vOldiid[i].impdesc.FirstThunk; 671 obBuffer << m_vOldiid[i].impdesc.FirstThunk;
672 } 672 }
673 673
674 unsigned int dllsize = 0; 674 unsigned int dllsize = 0;
675 675
676 for (unsigned int i=0;i<m_vNewiid.size();i++) 676 for (unsigned int i=0;i<m_vNewiid.size();i++)
677 { 677 {
678 dword dwPoft = uiSizeofdescriptors + uiImprva; 678 dword dwPoft = uiSizeofdescriptors + uiImprva;
679 679
680 for (unsigned int j=1;j<=i;j++) 680 for (unsigned int j=1;j<=i;j++)
681 { 681 {
682 dwPoft += (static_cast<unsigned int>(m_vNewiid[j-1].originalfirstthunk.size()) + 1) * PELIB_IMAGE_THUNK_DATA<bits>::size(); 682 dwPoft += (static_cast<unsigned int>(m_vNewiid[j-1].originalfirstthunk.size()) + 1) * PELIB_IMAGE_THUNK_DATA<bits>::size();
683 } 683 }
684 684
685 obBuffer << (fixEntries ? dwPoft : m_vNewiid[i].impdesc.OriginalFirstThunk); 685 obBuffer << (fixEntries ? dwPoft : m_vNewiid[i].impdesc.OriginalFirstThunk);
686 obBuffer << m_vNewiid[i].impdesc.TimeDateStamp; 686 obBuffer << m_vNewiid[i].impdesc.TimeDateStamp;
687 obBuffer << m_vNewiid[i].impdesc.ForwarderChain; 687 obBuffer << m_vNewiid[i].impdesc.ForwarderChain;
688 dword dwPdll = uiSizeofdescriptors + uiSizeofoft + uiImprva + dllsize; 688 dword dwPdll = uiSizeofdescriptors + uiSizeofoft + uiImprva + dllsize;
689 obBuffer << (fixEntries ? dwPdll : m_vNewiid[i].impdesc.Name); 689 obBuffer << (fixEntries ? dwPdll : m_vNewiid[i].impdesc.Name);
690 obBuffer << (fixEntries ? dwPoft : m_vNewiid[i].impdesc.FirstThunk); 690 obBuffer << (fixEntries ? dwPoft : m_vNewiid[i].impdesc.FirstThunk);
691 691
692 dllsize += static_cast<unsigned int>(m_vNewiid[i].name.size()) + 1; 692 dllsize += static_cast<unsigned int>(m_vNewiid[i].name.size()) + 1;
693 } 693 }
694 694
695 obBuffer << (dword)0; 695 obBuffer << (dword)0;
696 obBuffer << (dword)0; 696 obBuffer << (dword)0;
697 obBuffer << (dword)0; 697 obBuffer << (dword)0;
698 obBuffer << (dword)0; 698 obBuffer << (dword)0;
699 obBuffer << (dword)0; 699 obBuffer << (dword)0;
700 700
701 unsigned int uiPfunc = uiSizeofdescriptors + uiSizeofoft + uiSizeofdllnames + uiImprva; 701 unsigned int uiPfunc = uiSizeofdescriptors + uiSizeofoft + uiSizeofdllnames + uiImprva;
702 702
703 // Rebuild original first thunk 703 // Rebuild original first thunk
704 for (unsigned int i=0;i<m_vNewiid.size();i++) 704 for (unsigned int i=0;i<m_vNewiid.size();i++)
705 { 705 {
706 for (unsigned int j=0;j<m_vNewiid[i].originalfirstthunk.size();j++) 706 for (unsigned int j=0;j<m_vNewiid[i].originalfirstthunk.size();j++)
707 { 707 {
708 if (m_vNewiid[i].originalfirstthunk[j].itd.Ordinal & PELIB_IMAGE_ORDINAL_FLAGS<bits>::IMAGE_ORDINAL_FLAG 708 if (m_vNewiid[i].originalfirstthunk[j].itd.Ordinal & PELIB_IMAGE_ORDINAL_FLAGS<bits>::IMAGE_ORDINAL_FLAG
709 || fixEntries == false) 709 || fixEntries == false)
710 { 710 {
711 obBuffer << m_vNewiid[i].originalfirstthunk[j].itd.Ordinal; 711 obBuffer << m_vNewiid[i].originalfirstthunk[j].itd.Ordinal;
712 } 712 }
713 else 713 else
714 { 714 {
715 obBuffer << uiPfunc; 715 obBuffer << uiPfunc;
716 } 716 }
717 uiPfunc += static_cast<unsigned int>(m_vNewiid[i].originalfirstthunk[j].fname.size()) + 3; 717 uiPfunc += static_cast<unsigned int>(m_vNewiid[i].originalfirstthunk[j].fname.size()) + 3;
718 } 718 }
719 obBuffer << (dword)0; 719 obBuffer << (dword)0;
720 } 720 }
721 721
722 // Write dllnames into import directory 722 // Write dllnames into import directory
723 for (unsigned int i=0;i<m_vNewiid.size();i++) 723 for (unsigned int i=0;i<m_vNewiid.size();i++)
724 { 724 {
725 obBuffer.add(m_vNewiid[i].name.c_str(), static_cast<unsigned int>(m_vNewiid[i].name.size())+1); 725 obBuffer.add(m_vNewiid[i].name.c_str(), static_cast<unsigned int>(m_vNewiid[i].name.size())+1);
726 } 726 }
727 727
728 // Write function names into directory 728 // Write function names into directory
729 for (unsigned int i=0;i<m_vNewiid.size();i++) 729 for (unsigned int i=0;i<m_vNewiid.size();i++)
730 { 730 {
731 for (unsigned int j=0;j<m_vNewiid[i].originalfirstthunk.size();j++) 731 for (unsigned int j=0;j<m_vNewiid[i].originalfirstthunk.size();j++)
732 { 732 {
733 obBuffer << m_vNewiid[i].originalfirstthunk[j].hint; 733 obBuffer << m_vNewiid[i].originalfirstthunk[j].hint;
734 obBuffer.add(m_vNewiid[i].originalfirstthunk[j].fname.c_str(), static_cast<unsigned int>(m_vNewiid[i].originalfirstthunk[j].fname.size()) + 1); 734 obBuffer.add(m_vNewiid[i].originalfirstthunk[j].fname.c_str(), static_cast<unsigned int>(m_vNewiid[i].originalfirstthunk[j].fname.size()) + 1);
735 } 735 }
736 } 736 }
737 } 737 }
738 738
739 /** 739 /**
740 * Removes a specific file and all functions of it from the import directory. 740 * Removes a specific file and all functions of it from the import directory.
741 * @param strFilename Name of the file which will be removed. 741 * @param strFilename Name of the file which will be removed.
742 **/ 742 **/
743 template<int bits> 743 template<int bits>
744 int ImportDirectory<bits>::removeFile(const std::string& strFilename) 744 int ImportDirectory<bits>::removeFile(const std::string& strFilename)
745 { 745 {
746 unsigned int oldSize = static_cast<unsigned int>(m_vNewiid.size()); 746 unsigned int oldSize = static_cast<unsigned int>(m_vNewiid.size());
747 747
748 m_vNewiid.erase(std::remove_if(m_vNewiid.begin(), m_vNewiid.end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_IMPORT_DIRECTORY<bits>::operator==), strFilename)), m_vNewiid.end()); 748 m_vNewiid.erase(std::remove_if(m_vNewiid.begin(), m_vNewiid.end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_IMPORT_DIRECTORY<bits>::operator==), strFilename)), m_vNewiid.end());
749 749
750 return oldSize == m_vNewiid.size() ? 1 : 0; 750 return oldSize == m_vNewiid.size() ? 1 : 0;
751 } 751 }
752 752
753 /** 753 /**
754 * Removes a specific function from the import directory. 754 * Removes a specific function from the import directory.
755 * @param strFilename Name of the file which exports the function. 755 * @param strFilename Name of the file which exports the function.
756 * @param strFuncname Name of the imported function. 756 * @param strFuncname Name of the imported function.
757 **/ 757 **/
758 template<int bits> 758 template<int bits>
759 int ImportDirectory<bits>::removeFunction(const std::string& strFilename, const std::string& strFuncname) 759 int ImportDirectory<bits>::removeFunction(const std::string& strFilename, const std::string& strFuncname)
760 { 760 {
761 ImpDirFileIterator viPos = m_vNewiid.begin(); 761 ImpDirFileIterator viPos = m_vNewiid.begin();
762 762
763 int notFound = 1; 763 int notFound = 1;
764 764
765 while (viPos != m_vNewiid.end()) 765 while (viPos != m_vNewiid.end())
766 { 766 {
767 if (isEqualNc(viPos->name, strFilename)) 767 if (isEqualNc(viPos->name, strFilename))
768 { 768 {
769 unsigned int oldSize = static_cast<unsigned int>(viPos->originalfirstthunk.size()); 769 unsigned int oldSize = static_cast<unsigned int>(viPos->originalfirstthunk.size());
770 viPos->originalfirstthunk.erase(std::remove_if(viPos->originalfirstthunk.begin(), viPos->originalfirstthunk.end(), std::bind2nd(std::mem_fun_ref(&PELIB_THUNK_DATA<bits>::equalFunctionName), strFuncname)), viPos->originalfirstthunk.end()); 770 viPos->originalfirstthunk.erase(std::remove_if(viPos->originalfirstthunk.begin(), viPos->originalfirstthunk.end(), std::bind2nd(std::mem_fun_ref(&PELIB_THUNK_DATA<bits>::equalFunctionName), strFuncname)), viPos->originalfirstthunk.end());
771 //viPos->originalfirstthunk.erase(std::remove_if(viPos->originalfirstthunk.begin(), viPos->originalfirstthunk.end(), std::bind2nd(CompPolicy<PELIB_THUNK_DATA, std::string>(), strFuncname))); 771 //viPos->originalfirstthunk.erase(std::remove_if(viPos->originalfirstthunk.begin(), viPos->originalfirstthunk.end(), std::bind2nd(CompPolicy<PELIB_THUNK_DATA, std::string>(), strFuncname)));
772 if (viPos->originalfirstthunk.size() != oldSize) notFound = 0; 772 if (viPos->originalfirstthunk.size() != oldSize) notFound = 0;
773 } 773 }
774 ++viPos; 774 ++viPos;
775 } 775 }
776 776
777 return notFound; 777 return notFound;
778 } 778 }
779 779
780 /** 780 /**
781 * Removes a specific function from the import directory. 781 * Removes a specific function from the import directory.
782 * @param strFilename Name of the file which exports the function. 782 * @param strFilename Name of the file which exports the function.
783 * @param wHint The hint of the function. 783 * @param wHint The hint of the function.
784 **/ 784 **/
785 template<int bits> 785 template<int bits>
786 int ImportDirectory<bits>::removeFunction(const std::string& strFilename, word wHint) 786 int ImportDirectory<bits>::removeFunction(const std::string& strFilename, word wHint)
787 { 787 {
788 ImpDirFileIterator viPos = m_vNewiid.begin(); 788 ImpDirFileIterator viPos = m_vNewiid.begin();
789 int notFound = 1; 789 int notFound = 1;
790 790
791 while (viPos != m_vNewiid.end()) 791 while (viPos != m_vNewiid.end())
792 { 792 {
793 if (isEqualNc(viPos->name, strFilename)) 793 if (isEqualNc(viPos->name, strFilename))
794 { 794 {
795 unsigned int oldSize = static_cast<unsigned int>(viPos->originalfirstthunk.size()); 795 unsigned int oldSize = static_cast<unsigned int>(viPos->originalfirstthunk.size());
796 viPos->originalfirstthunk.erase(std::remove_if(viPos->originalfirstthunk.begin(), viPos->originalfirstthunk.end(), std::bind2nd(std::mem_fun_ref(&PELIB_THUNK_DATA<bits>::equalHint), wHint)), viPos->originalfirstthunk.end()); 796 viPos->originalfirstthunk.erase(std::remove_if(viPos->originalfirstthunk.begin(), viPos->originalfirstthunk.end(), std::bind2nd(std::mem_fun_ref(&PELIB_THUNK_DATA<bits>::equalHint), wHint)), viPos->originalfirstthunk.end());
797 unsigned int newPos = static_cast<unsigned int>(viPos->originalfirstthunk.size()); 797 unsigned int newPos = static_cast<unsigned int>(viPos->originalfirstthunk.size());
798 if (viPos->originalfirstthunk.size() != oldSize) notFound = 0; 798 if (viPos->originalfirstthunk.size() != oldSize) notFound = 0;
799 } 799 }
800 ++viPos; 800 ++viPos;
801 } 801 }
802 802
803 return notFound; 803 return notFound;
804 } 804 }
805 805
806 /** 806 /**
807 * Writes the current import directory to a file. 807 * Writes the current import directory to a file.
808 * @param strFilename Name of the file. 808 * @param strFilename Name of the file.
809 * @param uiOffset File Offset of the new import directory. 809 * @param uiOffset File Offset of the new import directory.
810 * @param uiRva RVA which belongs to that file offset. 810 * @param uiRva RVA which belongs to that file offset.
811 **/ 811 **/
812 template<int bits> 812 template<int bits>
813 int ImportDirectory<bits>::write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva) 813 int ImportDirectory<bits>::write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva)
814 { 814 {
815 std::fstream ofFile(strFilename.c_str(), std::ios_base::in); 815 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
816 816
817 if (!ofFile) 817 if (!ofFile)
818 { 818 {
819 ofFile.clear(); 819 ofFile.clear();
820 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary); 820 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
821 } 821 }
822 else 822 else
823 { 823 {
824 ofFile.close(); 824 ofFile.close();
825 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary); 825 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
826 } 826 }
827 827
828 if (!ofFile) 828 if (!ofFile)
829 { 829 {
830 return ERROR_OPENING_FILE; 830 return ERROR_OPENING_FILE;
831 } 831 }
832 832
833 ofFile.seekp(uiOffset, std::ios_base::beg); 833 ofFile.seekp(uiOffset, std::ios_base::beg);
834 834
835 std::vector<byte> vBuffer; 835 std::vector<byte> vBuffer;
836 836
837 rebuild(vBuffer, uiRva); 837 rebuild(vBuffer, uiRva);
838 838
839 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), vBuffer.size()); 839 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), vBuffer.size());
840 ofFile.close(); 840 ofFile.close();
841 841
842 std::copy(m_vNewiid.begin(), m_vNewiid.end(), std::back_inserter(m_vOldiid)); 842 std::copy(m_vNewiid.begin(), m_vNewiid.end(), std::back_inserter(m_vOldiid));
843 m_vNewiid.clear(); 843 m_vNewiid.clear();
844 844
845 return NO_ERROR; 845 return NO_ERROR;
846 } 846 }
847 847
848 /** 848 /**
849 * Returns the size of the import directory. 849 * Returns the size of the import directory.
850 * @return Size of the import directory. 850 * @return Size of the import directory.
851 **/ 851 **/
852 template<int bits> 852 template<int bits>
853 unsigned int ImportDirectory<bits>::size() const 853 unsigned int ImportDirectory<bits>::size() const
854 { 854 {
855 // Only the descriptors of m_vOldiid must be rebuilt, not the data they point to. 855 // Only the descriptors of m_vOldiid must be rebuilt, not the data they point to.
856 return std::accumulate(m_vNewiid.begin(), m_vNewiid.end(), 0, accumulate<PELIB_IMAGE_IMPORT_DIRECTORY<bits> >) 856 return std::accumulate(m_vNewiid.begin(), m_vNewiid.end(), 0, accumulate<PELIB_IMAGE_IMPORT_DIRECTORY<bits> >)
857 + (m_vOldiid.size() + 1) * PELIB_IMAGE_IMPORT_DESCRIPTOR::size(); 857 + (m_vOldiid.size() + 1) * PELIB_IMAGE_IMPORT_DESCRIPTOR::size();
858 } 858 }
859 859
860 /** 860 /**
861 * @param strFilename Name of the imported file. 861 * @param strFilename Name of the imported file.
862 * @param cdDir Flag to decide if the OLDDIR or new import directory is used. 862 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
863 * @return FirstThunk value of an imported file. 863 * @return FirstThunk value of an imported file.
864 **/ 864 **/
865 template<int bits> 865 template<int bits>
866 dword ImportDirectory<bits>::getFirstThunk(const std::string& strFilename, currdir cdDir) const 866 dword ImportDirectory<bits>::getFirstThunk(const std::string& strFilename, currdir cdDir) const
867 { 867 {
868 if (cdDir == OLDDIR) 868 if (cdDir == OLDDIR)
869 { 869 {
870 return m_vOldiid[getFileIndex(strFilename, cdDir)].impdesc.FirstThunk; 870 return m_vOldiid[getFileIndex(strFilename, cdDir)].impdesc.FirstThunk;
871 } 871 }
872 else 872 else
873 { 873 {
874 return m_vNewiid[getFileIndex(strFilename, cdDir)].impdesc.FirstThunk; 874 return m_vNewiid[getFileIndex(strFilename, cdDir)].impdesc.FirstThunk;
875 } 875 }
876 } 876 }
877 877
878 /** 878 /**
879 * @param strFilename Name of the imported file. 879 * @param strFilename Name of the imported file.
880 * @param cdDir Flag to decide if the OLDDIR or new import directory is used. 880 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
881 * @return OriginalFirstThunk value of an imported file. 881 * @return OriginalFirstThunk value of an imported file.
882 **/ 882 **/
883 template<int bits> 883 template<int bits>
884 dword ImportDirectory<bits>::getOriginalFirstThunk(const std::string& strFilename, currdir cdDir) const 884 dword ImportDirectory<bits>::getOriginalFirstThunk(const std::string& strFilename, currdir cdDir) const
885 { 885 {
886 if (cdDir == OLDDIR) 886 if (cdDir == OLDDIR)
887 { 887 {
888 return m_vOldiid[getFileIndex(strFilename, cdDir)].impdesc.OriginalFirstThunk; 888 return m_vOldiid[getFileIndex(strFilename, cdDir)].impdesc.OriginalFirstThunk;
889 } 889 }
890 else 890 else
891 { 891 {
892 return m_vNewiid[getFileIndex(strFilename, cdDir)].impdesc.OriginalFirstThunk; 892 return m_vNewiid[getFileIndex(strFilename, cdDir)].impdesc.OriginalFirstThunk;
893 } 893 }
894 } 894 }
895 895
896 /** 896 /**
897 * @param strFilename Name of the imported file. 897 * @param strFilename Name of the imported file.
898 * @param cdDir Flag to decide if the OLDDIR or new import directory is used. 898 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
899 * @return ForwarderChain value of an imported file. 899 * @return ForwarderChain value of an imported file.
900 **/ 900 **/
901 template<int bits> 901 template<int bits>
902 dword ImportDirectory<bits>::getForwarderChain(const std::string& strFilename, currdir cdDir) const 902 dword ImportDirectory<bits>::getForwarderChain(const std::string& strFilename, currdir cdDir) const
903 { 903 {
904 if (cdDir == OLDDIR) 904 if (cdDir == OLDDIR)
905 { 905 {
906 return m_vOldiid[getFileIndex(strFilename, cdDir)].impdesc.ForwarderChain; 906 return m_vOldiid[getFileIndex(strFilename, cdDir)].impdesc.ForwarderChain;
907 } 907 }
908 else 908 else
909 { 909 {
910 return m_vNewiid[getFileIndex(strFilename, cdDir)].impdesc.ForwarderChain; 910 return m_vNewiid[getFileIndex(strFilename, cdDir)].impdesc.ForwarderChain;
911 } 911 }
912 } 912 }
913 913
914 /** 914 /**
915 * @param strFilename Name of the imported file. 915 * @param strFilename Name of the imported file.
916 * @param cdDir Flag to decide if the OLDDIR or new import directory is used. 916 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
917 * @return TimeDateStamp value of an imported file. 917 * @return TimeDateStamp value of an imported file.
918 **/ 918 **/
919 template<int bits> 919 template<int bits>
920 dword ImportDirectory<bits>::getTimeDateStamp(const std::string& strFilename, currdir cdDir) const 920 dword ImportDirectory<bits>::getTimeDateStamp(const std::string& strFilename, currdir cdDir) const
921 { 921 {
922 if (cdDir == OLDDIR) 922 if (cdDir == OLDDIR)
923 { 923 {
924 return m_vOldiid[getFileIndex(strFilename, cdDir)].impdesc.TimeDateStamp; 924 return m_vOldiid[getFileIndex(strFilename, cdDir)].impdesc.TimeDateStamp;
925 } 925 }
926 else 926 else
927 { 927 {
928 return m_vNewiid[getFileIndex(strFilename, cdDir)].impdesc.TimeDateStamp; 928 return m_vNewiid[getFileIndex(strFilename, cdDir)].impdesc.TimeDateStamp;
929 } 929 }
930 } 930 }
931 931
932 template<int bits> 932 template<int bits>
933 dword ImportDirectory<bits>::getRvaOfName(const std::string& strFilename, currdir cdDir) const 933 dword ImportDirectory<bits>::getRvaOfName(const std::string& strFilename, currdir cdDir) const
934 { 934 {
935 if (cdDir == OLDDIR) 935 if (cdDir == OLDDIR)
936 { 936 {
937 return m_vOldiid[getFileIndex(strFilename, cdDir)].impdesc.Name; 937 return m_vOldiid[getFileIndex(strFilename, cdDir)].impdesc.Name;
938 } 938 }
939 else 939 else
940 { 940 {
941 return m_vNewiid[getFileIndex(strFilename, cdDir)].impdesc.Name; 941 return m_vNewiid[getFileIndex(strFilename, cdDir)].impdesc.Name;
942 } 942 }
943 } 943 }
944 944
945 /** 945 /**
946 * @param strFilename Name of the imported file. 946 * @param strFilename Name of the imported file.
947 * @param cdDir Flag to decide if the OLDDIR or new import directory is used. 947 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
948 * @return FirstThunk value of an imported file. 948 * @return FirstThunk value of an imported file.
949 **/ 949 **/
950 template<int bits> 950 template<int bits>
951 dword ImportDirectory<bits>::getFirstThunk(dword dwFilenr, currdir cdDir) const 951 dword ImportDirectory<bits>::getFirstThunk(dword dwFilenr, currdir cdDir) const
952 { 952 {
953 if (cdDir == OLDDIR) 953 if (cdDir == OLDDIR)
954 { 954 {
955 return m_vOldiid[dwFilenr].impdesc.FirstThunk; 955 return m_vOldiid[dwFilenr].impdesc.FirstThunk;
956 } 956 }
957 else 957 else
958 { 958 {
959 return m_vNewiid[dwFilenr].impdesc.FirstThunk; 959 return m_vNewiid[dwFilenr].impdesc.FirstThunk;
960 } 960 }
961 } 961 }
962 962
963 template<int bits> 963 template<int bits>
964 void ImportDirectory<bits>::setFirstThunk(dword dwFilenr, currdir cdDir, dword value) 964 void ImportDirectory<bits>::setFirstThunk(dword dwFilenr, currdir cdDir, dword value)
965 { 965 {
966 if (cdDir == OLDDIR) 966 if (cdDir == OLDDIR)
967 { 967 {
968 m_vOldiid[dwFilenr].impdesc.FirstThunk = value; 968 m_vOldiid[dwFilenr].impdesc.FirstThunk = value;
969 } 969 }
970 else 970 else
971 { 971 {
972 m_vNewiid[dwFilenr].impdesc.FirstThunk = value; 972 m_vNewiid[dwFilenr].impdesc.FirstThunk = value;
973 } 973 }
974 } 974 }
975 975
976 /** 976 /**
977 * @param strFilename Name of the imported file. 977 * @param strFilename Name of the imported file.
978 * @param cdDir Flag to decide if the OLDDIR or new import directory is used. 978 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
979 * @return OriginalFirstThunk value of an imported file. 979 * @return OriginalFirstThunk value of an imported file.
980 **/ 980 **/
981 template<int bits> 981 template<int bits>
982 dword ImportDirectory<bits>::getOriginalFirstThunk(dword dwFilenr, currdir cdDir) const 982 dword ImportDirectory<bits>::getOriginalFirstThunk(dword dwFilenr, currdir cdDir) const
983 { 983 {
984 if (cdDir == OLDDIR) 984 if (cdDir == OLDDIR)
985 { 985 {
986 return m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk; 986 return m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk;
987 } 987 }
988 else 988 else
989 { 989 {
990 return m_vNewiid[dwFilenr].impdesc.OriginalFirstThunk; 990 return m_vNewiid[dwFilenr].impdesc.OriginalFirstThunk;
991 } 991 }
992 } 992 }
993 993
994 template<int bits> 994 template<int bits>
995 void ImportDirectory<bits>::setOriginalFirstThunk(dword dwFilenr, currdir cdDir, dword value) 995 void ImportDirectory<bits>::setOriginalFirstThunk(dword dwFilenr, currdir cdDir, dword value)
996 { 996 {
997 if (cdDir == OLDDIR) 997 if (cdDir == OLDDIR)
998 { 998 {
999 m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk = value; 999 m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk = value;
1000 } 1000 }
1001 else 1001 else
1002 { 1002 {
1003 m_vNewiid[dwFilenr].impdesc.OriginalFirstThunk = value; 1003 m_vNewiid[dwFilenr].impdesc.OriginalFirstThunk = value;
1004 } 1004 }
1005 } 1005 }
1006 1006
1007 /** 1007 /**
1008 * @param strFilename Name of the imported file. 1008 * @param strFilename Name of the imported file.
1009 * @param cdDir Flag to decide if the OLDDIR or new import directory is used. 1009 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
1010 * @return ForwarderChain value of an imported file. 1010 * @return ForwarderChain value of an imported file.
1011 **/ 1011 **/
1012 template<int bits> 1012 template<int bits>
1013 dword ImportDirectory<bits>::getForwarderChain(dword dwFilenr, currdir cdDir) const 1013 dword ImportDirectory<bits>::getForwarderChain(dword dwFilenr, currdir cdDir) const
1014 { 1014 {
1015 if (cdDir == OLDDIR) 1015 if (cdDir == OLDDIR)
1016 { 1016 {
1017 return m_vOldiid[dwFilenr].impdesc.ForwarderChain; 1017 return m_vOldiid[dwFilenr].impdesc.ForwarderChain;
1018 } 1018 }
1019 else 1019 else
1020 { 1020 {
1021 return m_vNewiid[dwFilenr].impdesc.ForwarderChain; 1021 return m_vNewiid[dwFilenr].impdesc.ForwarderChain;
1022 } 1022 }
1023 } 1023 }
1024 1024
1025 template<int bits> 1025 template<int bits>
1026 void ImportDirectory<bits>::setForwarderChain(dword dwFilenr, currdir cdDir, dword value) 1026 void ImportDirectory<bits>::setForwarderChain(dword dwFilenr, currdir cdDir, dword value)
1027 { 1027 {
1028 if (cdDir == OLDDIR) 1028 if (cdDir == OLDDIR)
1029 { 1029 {
1030 m_vOldiid[dwFilenr].impdesc.ForwarderChain = value; 1030 m_vOldiid[dwFilenr].impdesc.ForwarderChain = value;
1031 } 1031 }
1032 else 1032 else
1033 { 1033 {
1034 m_vNewiid[dwFilenr].impdesc.ForwarderChain = value; 1034 m_vNewiid[dwFilenr].impdesc.ForwarderChain = value;
1035 } 1035 }
1036 } 1036 }
1037 1037
1038 /** 1038 /**
1039 * @param strFilename Name of the imported file. 1039 * @param strFilename Name of the imported file.
1040 * @param cdDir Flag to decide if the OLDDIR or new import directory is used. 1040 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
1041 * @return TimeDateStamp value of an imported file. 1041 * @return TimeDateStamp value of an imported file.
1042 **/ 1042 **/
1043 template<int bits> 1043 template<int bits>
1044 dword ImportDirectory<bits>::getTimeDateStamp(dword dwFilenr, currdir cdDir) const 1044 dword ImportDirectory<bits>::getTimeDateStamp(dword dwFilenr, currdir cdDir) const
1045 { 1045 {
1046 if (cdDir == OLDDIR) 1046 if (cdDir == OLDDIR)
1047 { 1047 {
1048 return m_vOldiid[dwFilenr].impdesc.TimeDateStamp; 1048 return m_vOldiid[dwFilenr].impdesc.TimeDateStamp;
1049 } 1049 }
1050 else 1050 else
1051 { 1051 {
1052 return m_vNewiid[dwFilenr].impdesc.TimeDateStamp; 1052 return m_vNewiid[dwFilenr].impdesc.TimeDateStamp;
1053 } 1053 }
1054 } 1054 }
1055 1055
1056 template<int bits> 1056 template<int bits>
1057 void ImportDirectory<bits>::setTimeDateStamp(dword dwFilenr, currdir cdDir, dword value) 1057 void ImportDirectory<bits>::setTimeDateStamp(dword dwFilenr, currdir cdDir, dword value)
1058 { 1058 {
1059 if (cdDir == OLDDIR) 1059 if (cdDir == OLDDIR)
1060 { 1060 {
1061 m_vOldiid[dwFilenr].impdesc.TimeDateStamp = value; 1061 m_vOldiid[dwFilenr].impdesc.TimeDateStamp = value;
1062 } 1062 }
1063 else 1063 else
1064 { 1064 {
1065 m_vNewiid[dwFilenr].impdesc.TimeDateStamp = value; 1065 m_vNewiid[dwFilenr].impdesc.TimeDateStamp = value;
1066 } 1066 }
1067 } 1067 }
1068 1068
1069 template<int bits> 1069 template<int bits>
1070 dword ImportDirectory<bits>::getRvaOfName(dword dwFilenr, currdir cdDir) const 1070 dword ImportDirectory<bits>::getRvaOfName(dword dwFilenr, currdir cdDir) const
1071 { 1071 {
1072 if (cdDir == OLDDIR) 1072 if (cdDir == OLDDIR)
1073 { 1073 {
1074 return m_vOldiid[dwFilenr].impdesc.Name; 1074 return m_vOldiid[dwFilenr].impdesc.Name;
1075 } 1075 }
1076 else 1076 else
1077 { 1077 {
1078 return m_vNewiid[dwFilenr].impdesc.Name; 1078 return m_vNewiid[dwFilenr].impdesc.Name;
1079 } 1079 }
1080 } 1080 }
1081 1081
1082 template<int bits> 1082 template<int bits>
1083 void ImportDirectory<bits>::setRvaOfName(dword dwFilenr, currdir cdDir, dword value) 1083 void ImportDirectory<bits>::setRvaOfName(dword dwFilenr, currdir cdDir, dword value)
1084 { 1084 {
1085 if (cdDir == OLDDIR) 1085 if (cdDir == OLDDIR)
1086 { 1086 {
1087 m_vOldiid[dwFilenr].impdesc.Name = value; 1087 m_vOldiid[dwFilenr].impdesc.Name = value;
1088 } 1088 }
1089 else 1089 else
1090 { 1090 {
1091 m_vNewiid[dwFilenr].impdesc.Name = value; 1091 m_vNewiid[dwFilenr].impdesc.Name = value;
1092 } 1092 }
1093 } 1093 }
1094 1094
1095 /** 1095 /**
1096 * @param dwFilenr ID of the imported file. 1096 * @param dwFilenr ID of the imported file.
1097 * @param dwFuncnr ID of the imported function. 1097 * @param dwFuncnr ID of the imported function.
1098 * @param cdDir Flag to decide if the OLDDIR or new import directory is used. 1098 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
1099 * @return FirstThunk value of an imported function. 1099 * @return FirstThunk value of an imported function.
1100 **/ 1100 **/
1101 template<int bits> 1101 template<int bits>
1102 dword ImportDirectory<bits>::getFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir) const 1102 dword ImportDirectory<bits>::getFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir) const
1103 { 1103 {
1104 if (cdDir == OLDDIR) return m_vOldiid[dwFilenr].firstthunk[dwFuncnr].itd.Ordinal; 1104 if (cdDir == OLDDIR) return m_vOldiid[dwFilenr].firstthunk[dwFuncnr].itd.Ordinal;
1105 else return m_vNewiid[dwFilenr].firstthunk[dwFuncnr].itd.Ordinal; 1105 else return m_vNewiid[dwFilenr].firstthunk[dwFuncnr].itd.Ordinal;
1106 } 1106 }
1107 1107
1108 template<int bits> 1108 template<int bits>
1109 void ImportDirectory<bits>::setFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir, dword value) 1109 void ImportDirectory<bits>::setFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir, dword value)
1110 { 1110 {
1111 if (cdDir == OLDDIR) m_vOldiid[dwFilenr].firstthunk[dwFuncnr].itd.Ordinal = value; 1111 if (cdDir == OLDDIR) m_vOldiid[dwFilenr].firstthunk[dwFuncnr].itd.Ordinal = value;
1112 else m_vNewiid[dwFilenr].firstthunk[dwFuncnr].itd.Ordinal = value; 1112 else m_vNewiid[dwFilenr].firstthunk[dwFuncnr].itd.Ordinal = value;
1113 } 1113 }
1114 1114
1115 /** 1115 /**
1116 * @param dwFilenr ID of the imported file. 1116 * @param dwFilenr ID of the imported file.
1117 * @param dwFuncnr ID of the imported function. 1117 * @param dwFuncnr ID of the imported function.
1118 * @param cdDir Flag to decide if the OLDDIR or new import directory is used. 1118 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
1119 * @return OriginalFirstThunk value of an imported function. 1119 * @return OriginalFirstThunk value of an imported function.
1120 **/ 1120 **/
1121 template<int bits> 1121 template<int bits>
1122 dword ImportDirectory<bits>::getOriginalFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir) const 1122 dword ImportDirectory<bits>::getOriginalFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir) const
1123 { 1123 {
1124 if (cdDir == OLDDIR) return m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].itd.Ordinal; 1124 if (cdDir == OLDDIR) return m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].itd.Ordinal;
1125 else return m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].itd.Ordinal; 1125 else return m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].itd.Ordinal;
1126 } 1126 }
1127 1127
1128 template<int bits> 1128 template<int bits>
1129 void ImportDirectory<bits>::setOriginalFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir, dword value) 1129 void ImportDirectory<bits>::setOriginalFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir, dword value)
1130 { 1130 {
1131 if (cdDir == OLDDIR) m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].itd.Ordinal = value; 1131 if (cdDir == OLDDIR) m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].itd.Ordinal = value;
1132 else m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].itd.Ordinal = value; 1132 else m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].itd.Ordinal = value;
1133 } 1133 }
1134 1134
1135 typedef ImportDirectory<32> ImportDirectory32; 1135 typedef ImportDirectory<32> ImportDirectory32;
1136 typedef ImportDirectory<64> ImportDirectory64; 1136 typedef ImportDirectory<64> ImportDirectory64;
1137} 1137}
1138 1138
1139#endif 1139#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/MzHeader.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/MzHeader.cpp
index 39fe54d80d..3a2119b7ac 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/MzHeader.cpp
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/MzHeader.cpp
@@ -1,584 +1,584 @@
1/* 1/*
2* MzHeader.cpp - Part of the PeLib library. 2* MzHeader.cpp - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#include "MzHeader.h" 13#include "MzHeader.h"
14#include <iostream> 14#include <iostream>
15 15
16namespace PeLib 16namespace PeLib
17{ 17{
18 /** 18 /**
19 * Reads data from an InputBuffer into the struct that represents the MZ header. 19 * Reads data from an InputBuffer into the struct that represents the MZ header.
20 * It's required that the size of the input buffer is at least as big as the 20 * It's required that the size of the input buffer is at least as big as the
21 * size of a MZ header. Otherwise we get undefined behaviour. 21 * size of a MZ header. Otherwise we get undefined behaviour.
22 * @param ibBuffer InputBuffer that holds the data. 22 * @param ibBuffer InputBuffer that holds the data.
23 * @return A non-zero value is returned if a problem occured. 23 * @return A non-zero value is returned if a problem occured.
24 **/ 24 **/
25 void MzHeader::read(InputBuffer& ibBuffer) 25 void MzHeader::read(InputBuffer& ibBuffer)
26 { 26 {
27 ibBuffer >> m_idhHeader.e_magic; 27 ibBuffer >> m_idhHeader.e_magic;
28 ibBuffer >> m_idhHeader.e_cblp; 28 ibBuffer >> m_idhHeader.e_cblp;
29 ibBuffer >> m_idhHeader.e_cp; 29 ibBuffer >> m_idhHeader.e_cp;
30 ibBuffer >> m_idhHeader.e_crlc; 30 ibBuffer >> m_idhHeader.e_crlc;
31 ibBuffer >> m_idhHeader.e_cparhdr; 31 ibBuffer >> m_idhHeader.e_cparhdr;
32 ibBuffer >> m_idhHeader.e_minalloc; 32 ibBuffer >> m_idhHeader.e_minalloc;
33 ibBuffer >> m_idhHeader.e_maxalloc; 33 ibBuffer >> m_idhHeader.e_maxalloc;
34 ibBuffer >> m_idhHeader.e_ss; 34 ibBuffer >> m_idhHeader.e_ss;
35 ibBuffer >> m_idhHeader.e_sp; 35 ibBuffer >> m_idhHeader.e_sp;
36 ibBuffer >> m_idhHeader.e_csum; 36 ibBuffer >> m_idhHeader.e_csum;
37 ibBuffer >> m_idhHeader.e_ip; 37 ibBuffer >> m_idhHeader.e_ip;
38 ibBuffer >> m_idhHeader.e_cs; 38 ibBuffer >> m_idhHeader.e_cs;
39 ibBuffer >> m_idhHeader.e_lfarlc; 39 ibBuffer >> m_idhHeader.e_lfarlc;
40 ibBuffer >> m_idhHeader.e_ovno; 40 ibBuffer >> m_idhHeader.e_ovno;
41 41
42 for (unsigned int i=0;i<sizeof(m_idhHeader.e_res)/sizeof(m_idhHeader.e_res[0]);i++) 42 for (unsigned int i=0;i<sizeof(m_idhHeader.e_res)/sizeof(m_idhHeader.e_res[0]);i++)
43 { 43 {
44 ibBuffer >> m_idhHeader.e_res[i]; 44 ibBuffer >> m_idhHeader.e_res[i];
45 } 45 }
46 46
47 ibBuffer >> m_idhHeader.e_oemid; 47 ibBuffer >> m_idhHeader.e_oemid;
48 ibBuffer >> m_idhHeader.e_oeminfo; 48 ibBuffer >> m_idhHeader.e_oeminfo;
49 49
50 for (unsigned int i=0;i<sizeof(m_idhHeader.e_res2)/sizeof(m_idhHeader.e_res2[0]);i++) 50 for (unsigned int i=0;i<sizeof(m_idhHeader.e_res2)/sizeof(m_idhHeader.e_res2[0]);i++)
51 { 51 {
52 ibBuffer >> m_idhHeader.e_res2[i]; 52 ibBuffer >> m_idhHeader.e_res2[i];
53 } 53 }
54 54
55 ibBuffer >> m_idhHeader.e_lfanew; 55 ibBuffer >> m_idhHeader.e_lfanew;
56 } 56 }
57 57
58 /** 58 /**
59 * Tests if the currently loaded MZ header is a valid MZ header. 59 * Tests if the currently loaded MZ header is a valid MZ header.
60 * Note that this function does not check if the address to the PE header is valid as this is not possible. 60 * Note that this function does not check if the address to the PE header is valid as this is not possible.
61 * Actually, the only thing this function checks is if the e_magic value is set to 0x5A4D (IMAGE_DOS_SIGNATURE). 61 * Actually, the only thing this function checks is if the e_magic value is set to 0x5A4D (IMAGE_DOS_SIGNATURE).
62 * Everything else is not relevant for Windows 2000 and that's the system PeLib is focusing on for now. 62 * Everything else is not relevant for Windows 2000 and that's the system PeLib is focusing on for now.
63 * @return A boolean value that indicates if the MZ header is correct or not. 63 * @return A boolean value that indicates if the MZ header is correct or not.
64 **/ 64 **/
65 bool MzHeader::isValid() const 65 bool MzHeader::isValid() const
66 { 66 {
67 // The only thing that matters on Windows 2K is the e_magic value. The entire rest is for DOS compatibility. 67 // The only thing that matters on Windows 2K is the e_magic value. The entire rest is for DOS compatibility.
68 return isValid(e_magic); 68 return isValid(e_magic);
69 } 69 }
70 70
71 bool MzHeader::isValid(Field f) const 71 bool MzHeader::isValid(Field f) const
72 { 72 {
73 if (f == e_magic) 73 if (f == e_magic)
74 { 74 {
75 return m_idhHeader.e_magic == PELIB_IMAGE_DOS_SIGNATURE; 75 return m_idhHeader.e_magic == PELIB_IMAGE_DOS_SIGNATURE;
76 } 76 }
77 else 77 else
78 { 78 {
79 return true; 79 return true;
80 } 80 }
81 } 81 }
82 82
83 /** 83 /**
84 * Corrects all erroneous values of the current MZ header. Note that this function does not correct the 84 * Corrects all erroneous values of the current MZ header. Note that this function does not correct the
85 * pointer to the PE header. 85 * pointer to the PE header.
86 * Actually, the only thing this function corrects is the e_magic value. 86 * Actually, the only thing this function corrects is the e_magic value.
87 * Everything else is not relevant for Windows 2000 and that's the system PeLib is focusing on for now. 87 * Everything else is not relevant for Windows 2000 and that's the system PeLib is focusing on for now.
88 **/ 88 **/
89 void MzHeader::makeValid() 89 void MzHeader::makeValid()
90 { 90 {
91 // The only thing that matters on Windows is the e_magic value. The entire rest is for DOS compatibility. 91 // The only thing that matters on Windows is the e_magic value. The entire rest is for DOS compatibility.
92 setMagicNumber(PELIB_IMAGE_DOS_SIGNATURE); 92 setMagicNumber(PELIB_IMAGE_DOS_SIGNATURE);
93 } 93 }
94 94
95 void MzHeader::makeValid(Field f) 95 void MzHeader::makeValid(Field f)
96 { 96 {
97 if (f == e_magic) 97 if (f == e_magic)
98 { 98 {
99 setMagicNumber(PELIB_IMAGE_DOS_SIGNATURE); 99 setMagicNumber(PELIB_IMAGE_DOS_SIGNATURE);
100 } 100 }
101 } 101 }
102 102
103 /** 103 /**
104 * Reads the MZ header from a file. Note that this function does not verify if a file is actually a MZ file. 104 * Reads the MZ header from a file. Note that this function does not verify if a file is actually a MZ file.
105 * For this purpose see #PeFile::MzHeader::isValid. The reason for this is simple: Otherwise it might not 105 * For this purpose see #PeFile::MzHeader::isValid. The reason for this is simple: Otherwise it might not
106 * be possible to load damaged PE files to repair them. 106 * be possible to load damaged PE files to repair them.
107 * @param strFilename Name of the file which will be read. 107 * @param strFilename Name of the file which will be read.
108 * @return A non-zero value is returned if a problem occured. 108 * @return A non-zero value is returned if a problem occured.
109 **/ 109 **/
110 int MzHeader::read(const std::string& strFilename) 110 int MzHeader::read(const std::string& strFilename)
111 { 111 {
112 std::ifstream ifFile(strFilename.c_str(), std::ios::binary); 112 std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
113 113
114 if (!ifFile) 114 if (!ifFile)
115 { 115 {
116 return ERROR_OPENING_FILE; 116 return ERROR_OPENING_FILE;
117 } 117 }
118 118
119 if (fileSize(ifFile) < PELIB_IMAGE_DOS_HEADER::size()) 119 if (fileSize(ifFile) < PELIB_IMAGE_DOS_HEADER::size())
120 { 120 {
121 return ERROR_INVALID_FILE; 121 return ERROR_INVALID_FILE;
122 } 122 }
123 123
124 ifFile.seekg(0, std::ios::beg); 124 ifFile.seekg(0, std::ios::beg);
125 125
126 originalOffset = 0; 126 originalOffset = 0;
127 127
128 std::vector<byte> vBuffer(PELIB_IMAGE_DOS_HEADER::size()); 128 std::vector<byte> vBuffer(PELIB_IMAGE_DOS_HEADER::size());
129 ifFile.read(reinterpret_cast<char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size())); 129 ifFile.read(reinterpret_cast<char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
130 ifFile.close(); 130 ifFile.close();
131 131
132 InputBuffer ibBuffer(vBuffer); 132 InputBuffer ibBuffer(vBuffer);
133 read(ibBuffer); 133 read(ibBuffer);
134 return NO_ERROR; 134 return NO_ERROR;
135 } 135 }
136 136
137 /** 137 /**
138 * Reads the MZ header from memory. A pointer to a location in memory is passed and the data 138 * Reads the MZ header from memory. A pointer to a location in memory is passed and the data
139 * at this location is treated like a MZ header structure. The MZ header does not need to be valid. 139 * at this location is treated like a MZ header structure. The MZ header does not need to be valid.
140 * @param pcBuffer Pointer to a MZ header. 140 * @param pcBuffer Pointer to a MZ header.
141 * @param uiSize Length of the buffer. 141 * @param uiSize Length of the buffer.
142 * @return A non-zero value is returned if a problem occured. 142 * @return A non-zero value is returned if a problem occured.
143 **/ 143 **/
144 int MzHeader::read(unsigned char* pcBuffer, unsigned int uiSize, unsigned int originalOffs) 144 int MzHeader::read(unsigned char* pcBuffer, unsigned int uiSize, unsigned int originalOffs)
145 { 145 {
146 if (uiSize < PELIB_IMAGE_DOS_HEADER::size()) 146 if (uiSize < PELIB_IMAGE_DOS_HEADER::size())
147 { 147 {
148 return ERROR_INVALID_FILE; 148 return ERROR_INVALID_FILE;
149 } 149 }
150 150
151 std::vector<byte> vBuffer(pcBuffer, pcBuffer + uiSize); 151 std::vector<byte> vBuffer(pcBuffer, pcBuffer + uiSize);
152 for (int i=0;i<0x40;i++) std::cout << std::hex << (int)vBuffer[i] << " "; 152 for (int i=0;i<0x40;i++) std::cout << std::hex << (int)vBuffer[i] << " ";
153 153
154 originalOffset = originalOffs; 154 originalOffset = originalOffs;
155 155
156 InputBuffer ibBuffer(vBuffer); 156 InputBuffer ibBuffer(vBuffer);
157 read(ibBuffer); 157 read(ibBuffer);
158 return NO_ERROR; 158 return NO_ERROR;
159 } 159 }
160 160
161 /** 161 /**
162 * Rebuilds the MZ header so that it can be written to a file. It's not guaranteed that the 162 * Rebuilds the MZ header so that it can be written to a file. It's not guaranteed that the
163 * MZ header will be valid. If you want to make sure that the MZ header will be valid you 163 * MZ header will be valid. If you want to make sure that the MZ header will be valid you
164 * must call #PeLib::MzHeader::makeValid first. 164 * must call #PeLib::MzHeader::makeValid first.
165 * @param vBuffer Buffer where the rebuilt MZ header will be stored. 165 * @param vBuffer Buffer where the rebuilt MZ header will be stored.
166 **/ 166 **/
167 void MzHeader::rebuild(std::vector<byte>& vBuffer) const 167 void MzHeader::rebuild(std::vector<byte>& vBuffer) const
168 { 168 {
169 OutputBuffer obBuffer(vBuffer); 169 OutputBuffer obBuffer(vBuffer);
170 170
171 obBuffer << m_idhHeader.e_magic; 171 obBuffer << m_idhHeader.e_magic;
172 obBuffer << m_idhHeader.e_cblp; 172 obBuffer << m_idhHeader.e_cblp;
173 obBuffer << m_idhHeader.e_cp; 173 obBuffer << m_idhHeader.e_cp;
174 obBuffer << m_idhHeader.e_crlc; 174 obBuffer << m_idhHeader.e_crlc;
175 obBuffer << m_idhHeader.e_cparhdr; 175 obBuffer << m_idhHeader.e_cparhdr;
176 obBuffer << m_idhHeader.e_minalloc; 176 obBuffer << m_idhHeader.e_minalloc;
177 obBuffer << m_idhHeader.e_maxalloc; 177 obBuffer << m_idhHeader.e_maxalloc;
178 obBuffer << m_idhHeader.e_ss; 178 obBuffer << m_idhHeader.e_ss;
179 obBuffer << m_idhHeader.e_sp; 179 obBuffer << m_idhHeader.e_sp;
180 obBuffer << m_idhHeader.e_csum; 180 obBuffer << m_idhHeader.e_csum;
181 obBuffer << m_idhHeader.e_ip; 181 obBuffer << m_idhHeader.e_ip;
182 obBuffer << m_idhHeader.e_cs; 182 obBuffer << m_idhHeader.e_cs;
183 obBuffer << m_idhHeader.e_lfarlc; 183 obBuffer << m_idhHeader.e_lfarlc;
184 obBuffer << m_idhHeader.e_ovno; 184 obBuffer << m_idhHeader.e_ovno;
185 185
186 for (unsigned int i=0;i<sizeof(m_idhHeader.e_res)/sizeof(m_idhHeader.e_res[0]);i++) 186 for (unsigned int i=0;i<sizeof(m_idhHeader.e_res)/sizeof(m_idhHeader.e_res[0]);i++)
187 { 187 {
188 obBuffer << m_idhHeader.e_res[i]; 188 obBuffer << m_idhHeader.e_res[i];
189 } 189 }
190 190
191 obBuffer << m_idhHeader.e_oemid; 191 obBuffer << m_idhHeader.e_oemid;
192 obBuffer << m_idhHeader.e_oeminfo; 192 obBuffer << m_idhHeader.e_oeminfo;
193 193
194 for (unsigned int i=0;i<sizeof(m_idhHeader.e_res2)/sizeof(m_idhHeader.e_res2[0]);i++) 194 for (unsigned int i=0;i<sizeof(m_idhHeader.e_res2)/sizeof(m_idhHeader.e_res2[0]);i++)
195 { 195 {
196 obBuffer << m_idhHeader.e_res2[i]; 196 obBuffer << m_idhHeader.e_res2[i];
197 } 197 }
198 198
199 obBuffer << m_idhHeader.e_lfanew; 199 obBuffer << m_idhHeader.e_lfanew;
200 } 200 }
201 201
202 /** 202 /**
203 * Returns the size of the MZ header. This size is actually always sizeof(IMAGE_DOS_HEADER) (== 0x40) 203 * Returns the size of the MZ header. This size is actually always sizeof(IMAGE_DOS_HEADER) (== 0x40)
204 * because the MZ header is a header of constant size if you disregard the dos stub. If you want to know the 204 * because the MZ header is a header of constant size if you disregard the dos stub. If you want to know the
205 * size of the MZ header + the size of the dos stub check #PeLib::MzHeader::getAddressOfPeHeader. 205 * size of the MZ header + the size of the dos stub check #PeLib::MzHeader::getAddressOfPeHeader.
206 * @return Size of the MZ header. 206 * @return Size of the MZ header.
207 **/ 207 **/
208 unsigned int MzHeader::size() const 208 unsigned int MzHeader::size() const
209 { 209 {
210 return sizeof(m_idhHeader); 210 return sizeof(m_idhHeader);
211 } 211 }
212 212
213 /** 213 /**
214 * Writes the current MZ header to a file. The file does not have to exist. If it doesn't exist 214 * Writes the current MZ header to a file. The file does not have to exist. If it doesn't exist
215 * it will be created. 215 * it will be created.
216 * @param strFilename Name of the file the header will be written to. 216 * @param strFilename Name of the file the header will be written to.
217 * @param dwOffset Offset the header will be written to (defaults to 0). 217 * @param dwOffset Offset the header will be written to (defaults to 0).
218 * @return A non-zero value is returned if a problem occured. 218 * @return A non-zero value is returned if a problem occured.
219 **/ 219 **/
220 int MzHeader::write(const std::string& strFilename, dword dwOffset = 0) const 220 int MzHeader::write(const std::string& strFilename, dword dwOffset = 0) const
221 { 221 {
222 std::fstream ofFile(strFilename.c_str(), std::ios_base::in); 222 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
223 223
224 if (!ofFile) 224 if (!ofFile)
225 { 225 {
226 ofFile.clear(); 226 ofFile.clear();
227 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary); 227 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
228 } 228 }
229 else 229 else
230 { 230 {
231 ofFile.close(); 231 ofFile.close();
232 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary); 232 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
233 } 233 }
234 234
235 if (!ofFile) 235 if (!ofFile)
236 { 236 {
237 return ERROR_OPENING_FILE; 237 return ERROR_OPENING_FILE;
238 } 238 }
239 239
240 ofFile.seekp(dwOffset, std::ios::beg); 240 ofFile.seekp(dwOffset, std::ios::beg);
241 241
242 std::vector<unsigned char> vBuffer; 242 std::vector<unsigned char> vBuffer;
243 243
244 rebuild(vBuffer); 244 rebuild(vBuffer);
245 245
246 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size())); 246 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
247 247
248 ofFile.close(); 248 ofFile.close();
249 249
250 return NO_ERROR; 250 return NO_ERROR;
251 } 251 }
252 252
253 /** 253 /**
254 * Returns the MZ header's e_magic value. 254 * Returns the MZ header's e_magic value.
255 **/ 255 **/
256 word MzHeader::getMagicNumber() const 256 word MzHeader::getMagicNumber() const
257 { 257 {
258 return m_idhHeader.e_magic; 258 return m_idhHeader.e_magic;
259 } 259 }
260 260
261 /** 261 /**
262 * Returns the MZ header's e_cblp value. 262 * Returns the MZ header's e_cblp value.
263 **/ 263 **/
264 word MzHeader::getBytesOnLastPage() const 264 word MzHeader::getBytesOnLastPage() const
265 { 265 {
266 return m_idhHeader.e_cblp; 266 return m_idhHeader.e_cblp;
267 } 267 }
268 268
269 /** 269 /**
270 * Returns the MZ header's e_cp value. 270 * Returns the MZ header's e_cp value.
271 **/ 271 **/
272 word MzHeader::getPagesInFile() const 272 word MzHeader::getPagesInFile() const
273 { 273 {
274 return m_idhHeader.e_cp; 274 return m_idhHeader.e_cp;
275 } 275 }
276 276
277 /** 277 /**
278 * Returns the MZ header's e_crlc value. 278 * Returns the MZ header's e_crlc value.
279 **/ 279 **/
280 word MzHeader::getRelocations() const 280 word MzHeader::getRelocations() const
281 { 281 {
282 return m_idhHeader.e_crlc; 282 return m_idhHeader.e_crlc;
283 } 283 }
284 284
285 /** 285 /**
286 * Returns the MZ header's e_cparhdr value. 286 * Returns the MZ header's e_cparhdr value.
287 **/ 287 **/
288 word MzHeader::getSizeOfHeader() const 288 word MzHeader::getSizeOfHeader() const
289 { 289 {
290 return m_idhHeader.e_cparhdr; 290 return m_idhHeader.e_cparhdr;
291 } 291 }
292 292
293 /** 293 /**
294 * Returns the MZ header's e_minalloc value. 294 * Returns the MZ header's e_minalloc value.
295 **/ 295 **/
296 word MzHeader::getMinExtraParagraphs() const 296 word MzHeader::getMinExtraParagraphs() const
297 { 297 {
298 return m_idhHeader.e_minalloc; 298 return m_idhHeader.e_minalloc;
299 } 299 }
300 300
301 /** 301 /**
302 * Returns the MZ header's e_maxalloc value. 302 * Returns the MZ header's e_maxalloc value.
303 **/ 303 **/
304 word MzHeader::getMaxExtraParagraphs() const 304 word MzHeader::getMaxExtraParagraphs() const
305 { 305 {
306 return m_idhHeader.e_maxalloc; 306 return m_idhHeader.e_maxalloc;
307 } 307 }
308 308
309 /** 309 /**
310 * Returns the MZ header's e_ss value. 310 * Returns the MZ header's e_ss value.
311 **/ 311 **/
312 word MzHeader::getSsValue() const 312 word MzHeader::getSsValue() const
313 { 313 {
314 return m_idhHeader.e_ss; 314 return m_idhHeader.e_ss;
315 } 315 }
316 316
317 /** 317 /**
318 * Returns the MZ header's e_sp value. 318 * Returns the MZ header's e_sp value.
319 **/ 319 **/
320 word MzHeader::getSpValue() const 320 word MzHeader::getSpValue() const
321 { 321 {
322 return m_idhHeader.e_sp; 322 return m_idhHeader.e_sp;
323 } 323 }
324 324
325 /** 325 /**
326 * Returns the MZ header's e_csum value. 326 * Returns the MZ header's e_csum value.
327 **/ 327 **/
328 word MzHeader::getChecksum() const 328 word MzHeader::getChecksum() const
329 { 329 {
330 return m_idhHeader.e_csum; 330 return m_idhHeader.e_csum;
331 } 331 }
332 332
333 /** 333 /**
334 * Returns the MZ header's e_ip value. 334 * Returns the MZ header's e_ip value.
335 **/ 335 **/
336 word MzHeader::getIpValue() const 336 word MzHeader::getIpValue() const
337 { 337 {
338 return m_idhHeader.e_ip; 338 return m_idhHeader.e_ip;
339 } 339 }
340 340
341 /** 341 /**
342 * Returns the MZ header's e_cs value. 342 * Returns the MZ header's e_cs value.
343 **/ 343 **/
344 word MzHeader::getCsValue() const 344 word MzHeader::getCsValue() const
345 { 345 {
346 return m_idhHeader.e_cs; 346 return m_idhHeader.e_cs;
347 } 347 }
348 348
349 /** 349 /**
350 * Returns the MZ header's e_lfarlc value. 350 * Returns the MZ header's e_lfarlc value.
351 **/ 351 **/
352 word MzHeader::getAddrOfRelocationTable() const 352 word MzHeader::getAddrOfRelocationTable() const
353 { 353 {
354 return m_idhHeader.e_lfarlc; 354 return m_idhHeader.e_lfarlc;
355 } 355 }
356 356
357 /** 357 /**
358 * Returns the MZ header's e_ovno value. 358 * Returns the MZ header's e_ovno value.
359 **/ 359 **/
360 word MzHeader::getOverlayNumber() const 360 word MzHeader::getOverlayNumber() const
361 { 361 {
362 return m_idhHeader.e_ovno; 362 return m_idhHeader.e_ovno;
363 } 363 }
364 364
365 /** 365 /**
366 * Returns the MZ header's e_oemid value. 366 * Returns the MZ header's e_oemid value.
367 **/ 367 **/
368 word MzHeader::getOemIdentifier() const 368 word MzHeader::getOemIdentifier() const
369 { 369 {
370 return m_idhHeader.e_oemid; 370 return m_idhHeader.e_oemid;
371 } 371 }
372 372
373 /** 373 /**
374 * Returns the MZ header's e_oeminfo value. 374 * Returns the MZ header's e_oeminfo value.
375 **/ 375 **/
376 word MzHeader::getOemInformation() const 376 word MzHeader::getOemInformation() const
377 { 377 {
378 return m_idhHeader.e_oeminfo; 378 return m_idhHeader.e_oeminfo;
379 } 379 }
380 380
381 /** 381 /**
382 * Returns the MZ header's e_lfanew value. 382 * Returns the MZ header's e_lfanew value.
383 **/ 383 **/
384 dword MzHeader::getAddressOfPeHeader() const 384 dword MzHeader::getAddressOfPeHeader() const
385 { 385 {
386 return m_idhHeader.e_lfanew; 386 return m_idhHeader.e_lfanew;
387 } 387 }
388 388
389 /** 389 /**
390 * Returns the MZ header's e_res[uiNr] value. If the parameter uiNr is out of range 390 * Returns the MZ header's e_res[uiNr] value. If the parameter uiNr is out of range
391 * you will get undefined behaviour. 391 * you will get undefined behaviour.
392 * @param uiNr The index of the word in the e_res array (valid range: 0-3) 392 * @param uiNr The index of the word in the e_res array (valid range: 0-3)
393 **/ 393 **/
394 word MzHeader::getReservedWords1(unsigned int uiNr) const 394 word MzHeader::getReservedWords1(unsigned int uiNr) const
395 { 395 {
396 return m_idhHeader.e_res[uiNr]; 396 return m_idhHeader.e_res[uiNr];
397 } 397 }
398 398
399 /** 399 /**
400 * Returns the MZ header's e_res2[uiNr] value. If the parameter uiNr is out of range 400 * Returns the MZ header's e_res2[uiNr] value. If the parameter uiNr is out of range
401 * you will get undefined behaviour. 401 * you will get undefined behaviour.
402 * @param uiNr The index of the word in the e_res array (valid range: 0-9) 402 * @param uiNr The index of the word in the e_res array (valid range: 0-9)
403 **/ 403 **/
404 word MzHeader::getReservedWords2(unsigned int uiNr) const 404 word MzHeader::getReservedWords2(unsigned int uiNr) const
405 { 405 {
406 return m_idhHeader.e_res2[uiNr]; 406 return m_idhHeader.e_res2[uiNr];
407 } 407 }
408 408
409 /** 409 /**
410 * Sets the MZ header's e_magic value. 410 * Sets the MZ header's e_magic value.
411 * @param wValue The new value of e_magic. 411 * @param wValue The new value of e_magic.
412 **/ 412 **/
413 void MzHeader::setMagicNumber(word wValue) 413 void MzHeader::setMagicNumber(word wValue)
414 { 414 {
415 m_idhHeader.e_magic = wValue; 415 m_idhHeader.e_magic = wValue;
416 } 416 }
417 417
418 /** 418 /**
419 * Sets the MZ header's e_cblp value. 419 * Sets the MZ header's e_cblp value.
420 * @param wValue The new value of e_cblp. 420 * @param wValue The new value of e_cblp.
421 **/ 421 **/
422 void MzHeader::setBytesOnLastPage(word wValue) 422 void MzHeader::setBytesOnLastPage(word wValue)
423 { 423 {
424 m_idhHeader.e_cblp = wValue; 424 m_idhHeader.e_cblp = wValue;
425 } 425 }
426 426
427 /** 427 /**
428 * Sets the MZ header's e_cp value. 428 * Sets the MZ header's e_cp value.
429 * @param wValue The new value of e_cp. 429 * @param wValue The new value of e_cp.
430 **/ 430 **/
431 void MzHeader::setPagesInFile(word wValue) 431 void MzHeader::setPagesInFile(word wValue)
432 { 432 {
433 m_idhHeader.e_cp = wValue; 433 m_idhHeader.e_cp = wValue;
434 } 434 }
435 435
436 /** 436 /**
437 * Sets the MZ header's e_crlc value. 437 * Sets the MZ header's e_crlc value.
438 * @param wValue The new value of e_crlc. 438 * @param wValue The new value of e_crlc.
439 **/ 439 **/
440 void MzHeader::setRelocations(word wValue) 440 void MzHeader::setRelocations(word wValue)
441 { 441 {
442 m_idhHeader.e_crlc = wValue; 442 m_idhHeader.e_crlc = wValue;
443 } 443 }
444 444
445 /** 445 /**
446 * Sets the MZ header's e_cparhdr value. 446 * Sets the MZ header's e_cparhdr value.
447 * @param wValue The new value of e_cparhdr. 447 * @param wValue The new value of e_cparhdr.
448 **/ 448 **/
449 void MzHeader::setSizeOfHeader(word wValue) 449 void MzHeader::setSizeOfHeader(word wValue)
450 { 450 {
451 m_idhHeader.e_cparhdr = wValue; 451 m_idhHeader.e_cparhdr = wValue;
452 } 452 }
453 453
454 /** 454 /**
455 * Sets the MZ header's e_minalloc value. 455 * Sets the MZ header's e_minalloc value.
456 * @param wValue The new value of e_minalloc. 456 * @param wValue The new value of e_minalloc.
457 **/ 457 **/
458 void MzHeader::setMinExtraParagraphs(word wValue) 458 void MzHeader::setMinExtraParagraphs(word wValue)
459 { 459 {
460 m_idhHeader.e_minalloc = wValue; 460 m_idhHeader.e_minalloc = wValue;
461 } 461 }
462 462
463 /** 463 /**
464 * Sets the MZ header's e_maxalloc value. 464 * Sets the MZ header's e_maxalloc value.
465 * @param wValue The new value of e_maxalloc. 465 * @param wValue The new value of e_maxalloc.
466 **/ 466 **/
467 void MzHeader::setMaxExtraParagraphs(word wValue) 467 void MzHeader::setMaxExtraParagraphs(word wValue)
468 { 468 {
469 m_idhHeader.e_maxalloc = wValue; 469 m_idhHeader.e_maxalloc = wValue;
470 } 470 }
471 471
472 /** 472 /**
473 * Sets the MZ header's e_ss value. 473 * Sets the MZ header's e_ss value.
474 * @param wValue The new value of e_ss. 474 * @param wValue The new value of e_ss.
475 **/ 475 **/
476 void MzHeader::setSsValue(word wValue) 476 void MzHeader::setSsValue(word wValue)
477 { 477 {
478 m_idhHeader.e_ss = wValue; 478 m_idhHeader.e_ss = wValue;
479 } 479 }
480 480
481 /** 481 /**
482 * Sets the MZ header's e_sp value. 482 * Sets the MZ header's e_sp value.
483 * @param wValue The new value of e_sp. 483 * @param wValue The new value of e_sp.
484 **/ 484 **/
485 void MzHeader::setSpValue(word wValue) 485 void MzHeader::setSpValue(word wValue)
486 { 486 {
487 m_idhHeader.e_sp = wValue; 487 m_idhHeader.e_sp = wValue;
488 } 488 }
489 489
490 /** 490 /**
491 * Sets the MZ header's e_csum value. 491 * Sets the MZ header's e_csum value.
492 * @param wValue The new value of e_csum. 492 * @param wValue The new value of e_csum.
493 **/ 493 **/
494 void MzHeader::setChecksum(word wValue) 494 void MzHeader::setChecksum(word wValue)
495 { 495 {
496 m_idhHeader.e_csum = wValue; 496 m_idhHeader.e_csum = wValue;
497 } 497 }
498 498
499 /** 499 /**
500 * Sets the MZ header's e_ip value. 500 * Sets the MZ header's e_ip value.
501 * @param wValue The new value of e_ip. 501 * @param wValue The new value of e_ip.
502 **/ 502 **/
503 void MzHeader::setIpValue(word wValue) 503 void MzHeader::setIpValue(word wValue)
504 { 504 {
505 m_idhHeader.e_ip = wValue; 505 m_idhHeader.e_ip = wValue;
506 } 506 }
507 507
508 /** 508 /**
509 * Sets the MZ header's e_cs value. 509 * Sets the MZ header's e_cs value.
510 * @param wValue The new value of e_cs. 510 * @param wValue The new value of e_cs.
511 **/ 511 **/
512 void MzHeader::setCsValue(word wValue) 512 void MzHeader::setCsValue(word wValue)
513 { 513 {
514 m_idhHeader.e_cs = wValue; 514 m_idhHeader.e_cs = wValue;
515 } 515 }
516 516
517 /** 517 /**
518 * Sets the MZ header's e_lfarlc value. 518 * Sets the MZ header's e_lfarlc value.
519 * @param wValue The new value of e_lfarlc. 519 * @param wValue The new value of e_lfarlc.
520 **/ 520 **/
521 void MzHeader::setAddrOfRelocationTable(word wValue) 521 void MzHeader::setAddrOfRelocationTable(word wValue)
522 { 522 {
523 m_idhHeader.e_lfarlc = wValue; 523 m_idhHeader.e_lfarlc = wValue;
524 } 524 }
525 525
526 /** 526 /**
527 * Sets the MZ header's e_ovno value. 527 * Sets the MZ header's e_ovno value.
528 * @param wValue The new value of e_ovno. 528 * @param wValue The new value of e_ovno.
529 **/ 529 **/
530 void MzHeader::setOverlayNumber(word wValue) 530 void MzHeader::setOverlayNumber(word wValue)
531 { 531 {
532 m_idhHeader.e_ovno = wValue; 532 m_idhHeader.e_ovno = wValue;
533 } 533 }
534 534
535 /** 535 /**
536 * Sets the MZ header's e_oemid value. 536 * Sets the MZ header's e_oemid value.
537 * @param wValue The new value of e_oemid. 537 * @param wValue The new value of e_oemid.
538 **/ 538 **/
539 void MzHeader::setOemIdentifier(word wValue) 539 void MzHeader::setOemIdentifier(word wValue)
540 { 540 {
541 m_idhHeader.e_oemid = wValue; 541 m_idhHeader.e_oemid = wValue;
542 } 542 }
543 543
544 /** 544 /**
545 * Sets the MZ header's e_oeminfo value. 545 * Sets the MZ header's e_oeminfo value.
546 * @param wValue The new value of e_oeminfo. 546 * @param wValue The new value of e_oeminfo.
547 **/ 547 **/
548 void MzHeader::setOemInformation(word wValue) 548 void MzHeader::setOemInformation(word wValue)
549 { 549 {
550 m_idhHeader.e_oeminfo = wValue; 550 m_idhHeader.e_oeminfo = wValue;
551 } 551 }
552 552
553 /** 553 /**
554 * Sets the MZ header's e_lfanew value. 554 * Sets the MZ header's e_lfanew value.
555 * @param lValue The new value of e_lfanew. 555 * @param lValue The new value of e_lfanew.
556 **/ 556 **/
557 void MzHeader::setAddressOfPeHeader(dword lValue) 557 void MzHeader::setAddressOfPeHeader(dword lValue)
558 { 558 {
559 m_idhHeader.e_lfanew = lValue; 559 m_idhHeader.e_lfanew = lValue;
560 } 560 }
561 561
562 /** 562 /**
563 * Sets the MZ header's e_res[uiNr] value. If the parameter uiNr is out of range 563 * Sets the MZ header's e_res[uiNr] value. If the parameter uiNr is out of range
564 * you will get undefined behaviour. 564 * you will get undefined behaviour.
565 * @param uiNr The index of the word in the e_res array (valid range: 0-3) 565 * @param uiNr The index of the word in the e_res array (valid range: 0-3)
566 * @param wValue The new value of e_res[nr]. 566 * @param wValue The new value of e_res[nr].
567 **/ 567 **/
568 void MzHeader::setReservedWords1(unsigned int uiNr, word wValue) 568 void MzHeader::setReservedWords1(unsigned int uiNr, word wValue)
569 { 569 {
570 m_idhHeader.e_res[uiNr] = wValue; 570 m_idhHeader.e_res[uiNr] = wValue;
571 } 571 }
572 572
573 /** 573 /**
574 * Sets the MZ header's e_res2[uiNr] value. If the parameter uiNr is out of range 574 * Sets the MZ header's e_res2[uiNr] value. If the parameter uiNr is out of range
575 * you will get undefined behaviour. 575 * you will get undefined behaviour.
576 * @param uiNr The index of the word in the e_res2 array (valid range: 0-9) 576 * @param uiNr The index of the word in the e_res2 array (valid range: 0-9)
577 * @param wValue The new value of e_res[nr]. 577 * @param wValue The new value of e_res[nr].
578 **/ 578 **/
579 void MzHeader::setReservedWords2(unsigned int uiNr, word wValue) 579 void MzHeader::setReservedWords2(unsigned int uiNr, word wValue)
580 { 580 {
581 m_idhHeader.e_res2[uiNr] = wValue; 581 m_idhHeader.e_res2[uiNr] = wValue;
582 } 582 }
583 583
584} 584}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/MzHeader.h b/utils/zenutils/libraries/pelib-0.9/pelib/MzHeader.h
index 5aca6bfe59..4acb819727 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/MzHeader.h
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/MzHeader.h
@@ -1,148 +1,148 @@
1/* 1/*
2* MzHeader.h - Part of the PeLib library. 2* MzHeader.h - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#ifndef MZHEADER_H 13#ifndef MZHEADER_H
14#define MZHEADER_H 14#define MZHEADER_H
15 15
16#include "PeLibInc.h" 16#include "PeLibInc.h"
17 17
18namespace PeLib 18namespace PeLib
19{ 19{
20 /// Class that handles the MZ header of files. 20 /// Class that handles the MZ header of files.
21 /** 21 /**
22 * This class can read and modify MZ headers. It provides set- and get functions to access 22 * This class can read and modify MZ headers. It provides set- and get functions to access
23 * all individual members of a MZ header. Furthermore it's possible to validate and rebuild 23 * all individual members of a MZ header. Furthermore it's possible to validate and rebuild
24 * MZ headers. 24 * MZ headers.
25 **/ 25 **/
26 class MzHeader 26 class MzHeader
27 { 27 {
28 private: 28 private:
29 PELIB_IMAGE_DOS_HEADER m_idhHeader; ///< Stores all MZ header information. 29 PELIB_IMAGE_DOS_HEADER m_idhHeader; ///< Stores all MZ header information.
30 30
31 /// Reads data from an InputBuffer into a MZ header struct. 31 /// Reads data from an InputBuffer into a MZ header struct.
32 void read(InputBuffer& ibBuffer); 32 void read(InputBuffer& ibBuffer);
33 33
34 /// Offset of the MZ header in the original file. 34 /// Offset of the MZ header in the original file.
35 unsigned int originalOffset; 35 unsigned int originalOffset;
36 36
37 public: 37 public:
38 38
39 enum Field {e_magic, e_cblp, e_cp, e_crlc, e_cparhdr, e_minalloc, e_maxalloc, 39 enum Field {e_magic, e_cblp, e_cp, e_crlc, e_cparhdr, e_minalloc, e_maxalloc,
40 e_ss, e_sp, e_csum, e_ip, e_cs, e_lfarlc, e_ovno, e_res, e_oemid, 40 e_ss, e_sp, e_csum, e_ip, e_cs, e_lfarlc, e_ovno, e_res, e_oemid,
41 e_oeminfo, e_res2, e_lfanew}; 41 e_oeminfo, e_res2, e_lfanew};
42 42
43 /// Checks if the current MZ header is valid. 43 /// Checks if the current MZ header is valid.
44 bool isValid() const; // EXPORT 44 bool isValid() const; // EXPORT
45 45
46 bool isValid(Field field) const; // EXPORT _field 46 bool isValid(Field field) const; // EXPORT _field
47 47
48 /// Corrects the current MZ header. 48 /// Corrects the current MZ header.
49 void makeValid(); // EXPORT 49 void makeValid(); // EXPORT
50 50
51 void makeValid(Field field); // EXPORT _field 51 void makeValid(Field field); // EXPORT _field
52 52
53 /// Reads the MZ header of a file. 53 /// Reads the MZ header of a file.
54 int read(const std::string& strFilename); // EXPORT 54 int read(const std::string& strFilename); // EXPORT
55 55
56 /// Reads the MZ header from a memory location. 56 /// Reads the MZ header from a memory location.
57 int read(unsigned char* pcBuffer, unsigned int uiSize, unsigned int originalOffs = 0); // EXPORT _fromMemory 57 int read(unsigned char* pcBuffer, unsigned int uiSize, unsigned int originalOffs = 0); // EXPORT _fromMemory
58 58
59 /// Rebuild the MZ header. 59 /// Rebuild the MZ header.
60 void rebuild(std::vector<byte>& vBuffer) const; // EXPORT 60 void rebuild(std::vector<byte>& vBuffer) const; // EXPORT
61 61
62 /// Returns the size of the current MZ header. 62 /// Returns the size of the current MZ header.
63 unsigned int size() const; // EXPORT 63 unsigned int size() const; // EXPORT
64 64
65 /// Writes the current MZ header to offset 0 of a file. 65 /// Writes the current MZ header to offset 0 of a file.
66 int write(const std::string& strFilename, dword dwOffset) const; // EXPORT 66 int write(const std::string& strFilename, dword dwOffset) const; // EXPORT
67 67
68 /// Gets the e_magic value of the MZ header. 68 /// Gets the e_magic value of the MZ header.
69 word getMagicNumber() const; // EXPORT 69 word getMagicNumber() const; // EXPORT
70 /// Gets the e_cblp value of the MZ header. 70 /// Gets the e_cblp value of the MZ header.
71 word getBytesOnLastPage() const; // EXPORT 71 word getBytesOnLastPage() const; // EXPORT
72 /// Gets the e_cp value of the MZ header. 72 /// Gets the e_cp value of the MZ header.
73 word getPagesInFile() const; // EXPORT 73 word getPagesInFile() const; // EXPORT
74 /// Gets the e_crlc value of the MZ header. 74 /// Gets the e_crlc value of the MZ header.
75 word getRelocations() const; // EXPORT 75 word getRelocations() const; // EXPORT
76 /// Gets the e_cparhdr value of the MZ header. 76 /// Gets the e_cparhdr value of the MZ header.
77 word getSizeOfHeader() const; // EXPORT 77 word getSizeOfHeader() const; // EXPORT
78 /// Gets the e_minalloc value of the MZ header. 78 /// Gets the e_minalloc value of the MZ header.
79 word getMinExtraParagraphs() const; // EXPORT 79 word getMinExtraParagraphs() const; // EXPORT
80 /// Gets the e_maxalloc value of the MZ header. 80 /// Gets the e_maxalloc value of the MZ header.
81 word getMaxExtraParagraphs() const; // EXPORT 81 word getMaxExtraParagraphs() const; // EXPORT
82 /// Gets the e_ss value of the MZ header. 82 /// Gets the e_ss value of the MZ header.
83 word getSsValue() const; // EXPORT 83 word getSsValue() const; // EXPORT
84 /// Gets the e_sp value of the MZ header. 84 /// Gets the e_sp value of the MZ header.
85 word getSpValue() const; // EXPORT 85 word getSpValue() const; // EXPORT
86 /// Gets the e_csum value of the MZ header. 86 /// Gets the e_csum value of the MZ header.
87 word getChecksum() const; // EXPORT 87 word getChecksum() const; // EXPORT
88 /// Gets the e_ip value of the MZ header. 88 /// Gets the e_ip value of the MZ header.
89 word getIpValue() const; // EXPORT 89 word getIpValue() const; // EXPORT
90 /// Gets the e_cs value of the MZ header. 90 /// Gets the e_cs value of the MZ header.
91 word getCsValue() const; // EXPORT 91 word getCsValue() const; // EXPORT
92 /// Gets the e_lfarlc value of the MZ header. 92 /// Gets the e_lfarlc value of the MZ header.
93 word getAddrOfRelocationTable() const; // EXPORT 93 word getAddrOfRelocationTable() const; // EXPORT
94 /// Gets the e_ovnovalue of the MZ header. 94 /// Gets the e_ovnovalue of the MZ header.
95 word getOverlayNumber() const; // EXPORT 95 word getOverlayNumber() const; // EXPORT
96 /// Gets the e_oemid value of the MZ header. 96 /// Gets the e_oemid value of the MZ header.
97 word getOemIdentifier() const; // EXPORT 97 word getOemIdentifier() const; // EXPORT
98 /// Gets the e_oeminfo value of the MZ header. 98 /// Gets the e_oeminfo value of the MZ header.
99 word getOemInformation() const; // EXPORT 99 word getOemInformation() const; // EXPORT
100 /// Gets the e_lfanew value of the MZ header. 100 /// Gets the e_lfanew value of the MZ header.
101 dword getAddressOfPeHeader() const; // EXPORT 101 dword getAddressOfPeHeader() const; // EXPORT
102 /// Gets the e_res of the MZ header. 102 /// Gets the e_res of the MZ header.
103 word getReservedWords1(unsigned int uiNr) const; // EXPORT 103 word getReservedWords1(unsigned int uiNr) const; // EXPORT
104 /// Gets the e_res2 of the MZ header. 104 /// Gets the e_res2 of the MZ header.
105 word getReservedWords2(unsigned int uiNr) const; // EXPORT 105 word getReservedWords2(unsigned int uiNr) const; // EXPORT
106 106
107 /// Sets the e_magic value of the MZ header. 107 /// Sets the e_magic value of the MZ header.
108 void setMagicNumber(word wValue); // EXPORT 108 void setMagicNumber(word wValue); // EXPORT
109 /// Sets the e_cblp value of the MZ header. 109 /// Sets the e_cblp value of the MZ header.
110 void setBytesOnLastPage(word wValue); // EXPORT 110 void setBytesOnLastPage(word wValue); // EXPORT
111 /// Sets the e_cp value of the MZ header. 111 /// Sets the e_cp value of the MZ header.
112 void setPagesInFile(word wValue); // EXPORT 112 void setPagesInFile(word wValue); // EXPORT
113 /// Sets the e_crlc value of the MZ header. 113 /// Sets the e_crlc value of the MZ header.
114 void setRelocations(word wValue); // EXPORT 114 void setRelocations(word wValue); // EXPORT
115 /// Sets the e_cparhdr value of the MZ header. 115 /// Sets the e_cparhdr value of the MZ header.
116 void setSizeOfHeader(word wValue); // EXPORT 116 void setSizeOfHeader(word wValue); // EXPORT
117 /// Sets the e_minalloc value of the MZ header. 117 /// Sets the e_minalloc value of the MZ header.
118 void setMinExtraParagraphs(word wValue); // EXPORT 118 void setMinExtraParagraphs(word wValue); // EXPORT
119 /// Sets the e_maxalloc value of the MZ header. 119 /// Sets the e_maxalloc value of the MZ header.
120 void setMaxExtraParagraphs(word wValue); // EXPORT 120 void setMaxExtraParagraphs(word wValue); // EXPORT
121 /// Sets the e_ss value of the MZ header. 121 /// Sets the e_ss value of the MZ header.
122 void setSsValue(word wValue); // EXPORT 122 void setSsValue(word wValue); // EXPORT
123 /// Sets the e_sp value of the MZ header. 123 /// Sets the e_sp value of the MZ header.
124 void setSpValue(word wValue); // EXPORT 124 void setSpValue(word wValue); // EXPORT
125 /// Sets the e_csum value of the MZ header. 125 /// Sets the e_csum value of the MZ header.
126 void setChecksum(word wValue); // EXPORT 126 void setChecksum(word wValue); // EXPORT
127 /// Sets the e_ip value of the MZ header. 127 /// Sets the e_ip value of the MZ header.
128 void setIpValue(word wValue); // EXPORT 128 void setIpValue(word wValue); // EXPORT
129 /// Sets the e_cs value of the MZ header. 129 /// Sets the e_cs value of the MZ header.
130 void setCsValue(word wValue); // EXPORT 130 void setCsValue(word wValue); // EXPORT
131 /// Sets the e_lfarlc value of the MZ header. 131 /// Sets the e_lfarlc value of the MZ header.
132 void setAddrOfRelocationTable(word wValue); // EXPORT 132 void setAddrOfRelocationTable(word wValue); // EXPORT
133 /// Sets the e_ovno value of the MZ header. 133 /// Sets the e_ovno value of the MZ header.
134 void setOverlayNumber(word wValue); // EXPORT 134 void setOverlayNumber(word wValue); // EXPORT
135 /// Sets the e_oemid value of the MZ header. 135 /// Sets the e_oemid value of the MZ header.
136 void setOemIdentifier(word wValue); // EXPORT 136 void setOemIdentifier(word wValue); // EXPORT
137 /// Sets the e_oeminfo value of the MZ header. 137 /// Sets the e_oeminfo value of the MZ header.
138 void setOemInformation(word wValue); // EXPORT 138 void setOemInformation(word wValue); // EXPORT
139 /// Sets the e_lfanew value of the MZ header. 139 /// Sets the e_lfanew value of the MZ header.
140 void setAddressOfPeHeader(dword dwValue); // EXPORT 140 void setAddressOfPeHeader(dword dwValue); // EXPORT
141 /// Sets the e_res value of the MZ header. 141 /// Sets the e_res value of the MZ header.
142 void setReservedWords1(unsigned int uiNr, word wValue); // EXPORT 142 void setReservedWords1(unsigned int uiNr, word wValue); // EXPORT
143 /// Sets the e_res2 value of the MZ header. 143 /// Sets the e_res2 value of the MZ header.
144 void setReservedWords2(unsigned int uiNr, word wValue); // EXPORT 144 void setReservedWords2(unsigned int uiNr, word wValue); // EXPORT
145 }; 145 };
146} 146}
147 147
148#endif 148#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/PeFile.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/PeFile.cpp
index 39f2488b81..9e9f2d8691 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/PeFile.cpp
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/PeFile.cpp
@@ -1,169 +1,169 @@
1/* 1/*
2* PeLib.cpp - Part of the PeLib library. 2* PeLib.cpp - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#include "PeFile.h" 13#include "PeFile.h"
14 14
15namespace PeLib 15namespace PeLib
16{ 16{
17 PeFile::~PeFile() 17 PeFile::~PeFile()
18 { 18 {
19 } 19 }
20 20
21 PeFile32::PeFile32() : PeFileT<32>() 21 PeFile32::PeFile32() : PeFileT<32>()
22 { 22 {
23 } 23 }
24 24
25 PeFile32::PeFile32(const std::string& strFlename) : PeFileT<32>(strFlename) 25 PeFile32::PeFile32(const std::string& strFlename) : PeFileT<32>(strFlename)
26 { 26 {
27 } 27 }
28 28
29 PeFile64::PeFile64() : PeFileT<64>() 29 PeFile64::PeFile64() : PeFileT<64>()
30 { 30 {
31 } 31 }
32 32
33 PeFile64::PeFile64(const std::string& strFlename) : PeFileT<64>(strFlename) 33 PeFile64::PeFile64(const std::string& strFlename) : PeFileT<64>(strFlename)
34 { 34 {
35 } 35 }
36 36
37 /** 37 /**
38 * @return A reference to the file's MZ header. 38 * @return A reference to the file's MZ header.
39 **/ 39 **/
40 40
41 const MzHeader& PeFile::mzHeader() const 41 const MzHeader& PeFile::mzHeader() const
42 { 42 {
43 return m_mzh; 43 return m_mzh;
44 } 44 }
45 45
46 /** 46 /**
47 * @return A reference to the file's MZ header. 47 * @return A reference to the file's MZ header.
48 **/ 48 **/
49 49
50 MzHeader& PeFile::mzHeader() 50 MzHeader& PeFile::mzHeader()
51 { 51 {
52 return m_mzh; 52 return m_mzh;
53 } 53 }
54 54
55 /** 55 /**
56 * @return A reference to the file's export directory. 56 * @return A reference to the file's export directory.
57 **/ 57 **/
58 58
59 const ExportDirectory& PeFile::expDir() const 59 const ExportDirectory& PeFile::expDir() const
60 { 60 {
61 return m_expdir; 61 return m_expdir;
62 } 62 }
63 63
64 /** 64 /**
65 * @return A reference to the file's export directory. 65 * @return A reference to the file's export directory.
66 **/ 66 **/
67 67
68 ExportDirectory& PeFile::expDir() 68 ExportDirectory& PeFile::expDir()
69 { 69 {
70 return m_expdir; 70 return m_expdir;
71 } 71 }
72 72
73 /** 73 /**
74 * @return A reference to the file's bound import directory. 74 * @return A reference to the file's bound import directory.
75 **/ 75 **/
76 76
77 const BoundImportDirectory& PeFile::boundImpDir() const 77 const BoundImportDirectory& PeFile::boundImpDir() const
78 { 78 {
79 return m_boundimpdir; 79 return m_boundimpdir;
80 } 80 }
81 81
82 /** 82 /**
83 * @return A reference to the file's bound import directory. 83 * @return A reference to the file's bound import directory.
84 **/ 84 **/
85 85
86 BoundImportDirectory& PeFile::boundImpDir() 86 BoundImportDirectory& PeFile::boundImpDir()
87 { 87 {
88 return m_boundimpdir; 88 return m_boundimpdir;
89 } 89 }
90 90
91 /** 91 /**
92 * @return A reference to the file's resource directory. 92 * @return A reference to the file's resource directory.
93 **/ 93 **/
94 94
95 const ResourceDirectory& PeFile::resDir() const 95 const ResourceDirectory& PeFile::resDir() const
96 { 96 {
97 return m_resdir; 97 return m_resdir;
98 } 98 }
99 99
100 /** 100 /**
101 * @return A reference to the file's resource directory. 101 * @return A reference to the file's resource directory.
102 **/ 102 **/
103 103
104 ResourceDirectory& PeFile::resDir() 104 ResourceDirectory& PeFile::resDir()
105 { 105 {
106 return m_resdir; 106 return m_resdir;
107 } 107 }
108 108
109 /** 109 /**
110 * @return A reference to the file's relocations directory. 110 * @return A reference to the file's relocations directory.
111 **/ 111 **/
112 112
113 const RelocationsDirectory& PeFile::relocDir() const 113 const RelocationsDirectory& PeFile::relocDir() const
114 { 114 {
115 return m_relocs; 115 return m_relocs;
116 } 116 }
117 117
118 /** 118 /**
119 * @return A reference to the file's relocations directory. 119 * @return A reference to the file's relocations directory.
120 **/ 120 **/
121 121
122 RelocationsDirectory& PeFile::relocDir() 122 RelocationsDirectory& PeFile::relocDir()
123 { 123 {
124 return m_relocs; 124 return m_relocs;
125 } 125 }
126 126
127 /** 127 /**
128 * @return A reference to the file's COM+ descriptor directory. 128 * @return A reference to the file's COM+ descriptor directory.
129 **/ 129 **/
130 130
131 const ComHeaderDirectory& PeFile::comDir() const 131 const ComHeaderDirectory& PeFile::comDir() const
132 { 132 {
133 return m_comdesc; 133 return m_comdesc;
134 } 134 }
135 135
136 /** 136 /**
137 * @return A reference to the file's COM+ descriptor directory. 137 * @return A reference to the file's COM+ descriptor directory.
138 **/ 138 **/
139 139
140 ComHeaderDirectory & PeFile::comDir() 140 ComHeaderDirectory & PeFile::comDir()
141 { 141 {
142 return m_comdesc; 142 return m_comdesc;
143 } 143 }
144 144
145 145
146 const IatDirectory& PeFile::iatDir() const 146 const IatDirectory& PeFile::iatDir() const
147 { 147 {
148 return m_iat; 148 return m_iat;
149 } 149 }
150 150
151 151
152 IatDirectory& PeFile::iatDir() 152 IatDirectory& PeFile::iatDir()
153 { 153 {
154 return m_iat; 154 return m_iat;
155 } 155 }
156 156
157 157
158 const DebugDirectory& PeFile::debugDir() const 158 const DebugDirectory& PeFile::debugDir() const
159 { 159 {
160 return m_debugdir; 160 return m_debugdir;
161 } 161 }
162 162
163 163
164 DebugDirectory& PeFile::debugDir() 164 DebugDirectory& PeFile::debugDir()
165 { 165 {
166 return m_debugdir; 166 return m_debugdir;
167 } 167 }
168 168
169} 169}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/PeFile.h b/utils/zenutils/libraries/pelib-0.9/pelib/PeFile.h
index a2b02cdfa8..e08d8da309 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/PeFile.h
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/PeFile.h
@@ -1,451 +1,451 @@
1/* 1/*
2* PeFile.h - Part of the PeLib library. 2* PeFile.h - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#ifndef PEFILE_H 13#ifndef PEFILE_H
14#define PEFILE_H 14#define PEFILE_H
15 15
16#include "PeLibInc.h" 16#include "PeLibInc.h"
17#include "MzHeader.h" 17#include "MzHeader.h"
18#include "PeHeader.h" 18#include "PeHeader.h"
19#include "ImportDirectory.h" 19#include "ImportDirectory.h"
20#include "ExportDirectory.h" 20#include "ExportDirectory.h"
21#include "BoundImportDirectory.h" 21#include "BoundImportDirectory.h"
22#include "ResourceDirectory.h" 22#include "ResourceDirectory.h"
23#include "RelocationsDirectory.h" 23#include "RelocationsDirectory.h"
24#include "ComHeaderDirectory.h" 24#include "ComHeaderDirectory.h"
25#include "IatDirectory.h" 25#include "IatDirectory.h"
26#include "DebugDirectory.h" 26#include "DebugDirectory.h"
27#include "TlsDirectory.h" 27#include "TlsDirectory.h"
28 28
29namespace PeLib 29namespace PeLib
30{ 30{
31 class PeFile32; 31 class PeFile32;
32 class PeFile64; 32 class PeFile64;
33 33
34 /** 34 /**
35 * Visitor base class for PeFiles. 35 * Visitor base class for PeFiles.
36 **/ 36 **/
37 class PeFileVisitor 37 class PeFileVisitor
38 { 38 {
39 public: 39 public:
40 virtual void callback(PeFile32 &file){} 40 virtual void callback(PeFile32 &file){}
41 virtual void callback(PeFile64 &file){} 41 virtual void callback(PeFile64 &file){}
42 virtual ~PeFileVisitor(){} 42 virtual ~PeFileVisitor(){}
43 }; 43 };
44 44
45 /** 45 /**
46 * Traits class that's used to decide of what type the PeHeader in a PeFile is. 46 * Traits class that's used to decide of what type the PeHeader in a PeFile is.
47 **/ 47 **/
48 template<int> 48 template<int>
49 struct PeFile_Traits; 49 struct PeFile_Traits;
50 50
51 template<> 51 template<>
52 struct PeFile_Traits<32> 52 struct PeFile_Traits<32>
53 { 53 {
54 typedef PeHeader32 PeHeader32_64; 54 typedef PeHeader32 PeHeader32_64;
55 }; 55 };
56 56
57 template<> 57 template<>
58 struct PeFile_Traits<64> 58 struct PeFile_Traits<64>
59 { 59 {
60 typedef PeHeader64 PeHeader32_64; 60 typedef PeHeader64 PeHeader32_64;
61 }; 61 };
62 62
63 /** 63 /**
64 * This class represents the common structures of PE and PE+ files. 64 * This class represents the common structures of PE and PE+ files.
65 **/ 65 **/
66 class PeFile 66 class PeFile
67 { 67 {
68 protected: 68 protected:
69 std::string m_filename; ///< Name of the current file. 69 std::string m_filename; ///< Name of the current file.
70 MzHeader m_mzh; ///< MZ header of the current file. 70 MzHeader m_mzh; ///< MZ header of the current file.
71 ExportDirectory m_expdir; ///< Export directory of the current file. 71 ExportDirectory m_expdir; ///< Export directory of the current file.
72 BoundImportDirectory m_boundimpdir; ///< BoundImportDirectory of the current file. 72 BoundImportDirectory m_boundimpdir; ///< BoundImportDirectory of the current file.
73 ResourceDirectory m_resdir; ///< ResourceDirectory of the current file. 73 ResourceDirectory m_resdir; ///< ResourceDirectory of the current file.
74 RelocationsDirectory m_relocs; ///< Relocations directory of the current file. 74 RelocationsDirectory m_relocs; ///< Relocations directory of the current file.
75 ComHeaderDirectory m_comdesc; ///< COM+ descriptor directory of the current file. 75 ComHeaderDirectory m_comdesc; ///< COM+ descriptor directory of the current file.
76 IatDirectory m_iat; ///< Import address table of the current file. 76 IatDirectory m_iat; ///< Import address table of the current file.
77 DebugDirectory m_debugdir; 77 DebugDirectory m_debugdir;
78 public: 78 public:
79 virtual ~PeFile(); 79 virtual ~PeFile();
80 80
81 /// Returns the name of the current file. 81 /// Returns the name of the current file.
82 virtual std::string getFileName() const = 0; // EXPORT 82 virtual std::string getFileName() const = 0; // EXPORT
83 /// Changes the name of the current file. 83 /// Changes the name of the current file.
84 virtual void setFileName(std::string strFilename) = 0; // EXPORT 84 virtual void setFileName(std::string strFilename) = 0; // EXPORT
85 85
86 virtual void visit(PeFileVisitor &v) = 0; 86 virtual void visit(PeFileVisitor &v) = 0;
87 87
88 /// Reads the MZ header of the current file from disc. 88 /// Reads the MZ header of the current file from disc.
89 virtual int readMzHeader() = 0; // EXPORT 89 virtual int readMzHeader() = 0; // EXPORT
90 /// Reads the export directory of the current file from disc. 90 /// Reads the export directory of the current file from disc.
91 virtual int readExportDirectory() = 0; // EXPORT 91 virtual int readExportDirectory() = 0; // EXPORT
92 /// Reads the PE header of the current file from disc. 92 /// Reads the PE header of the current file from disc.
93 virtual int readPeHeader() = 0; // EXPORT 93 virtual int readPeHeader() = 0; // EXPORT
94 /// Reads the import directory of the current file from disc. 94 /// Reads the import directory of the current file from disc.
95 virtual int readImportDirectory() = 0; // EXPORT 95 virtual int readImportDirectory() = 0; // EXPORT
96 /// Reads the bound import directory of the current file from disc. 96 /// Reads the bound import directory of the current file from disc.
97 virtual int readBoundImportDirectory() = 0; // EXPORT 97 virtual int readBoundImportDirectory() = 0; // EXPORT
98 /// Reads the resource directory of the current file from disc. 98 /// Reads the resource directory of the current file from disc.
99 virtual int readResourceDirectory() = 0; // EXPORT 99 virtual int readResourceDirectory() = 0; // EXPORT
100 /// Reads the relocations directory of the current file from disc. 100 /// Reads the relocations directory of the current file from disc.
101 virtual int readRelocationsDirectory() = 0; // EXPORT 101 virtual int readRelocationsDirectory() = 0; // EXPORT
102 /// Reads the COM+ descriptor directory of the current file from disc. 102 /// Reads the COM+ descriptor directory of the current file from disc.
103 virtual int readComHeaderDirectory() = 0; // EXPORT 103 virtual int readComHeaderDirectory() = 0; // EXPORT
104 /// Reads the IAT directory of the current file from disc. 104 /// Reads the IAT directory of the current file from disc.
105 virtual int readIatDirectory() = 0; // EXPORT 105 virtual int readIatDirectory() = 0; // EXPORT
106 /// Reads the Debug directory of the current file. 106 /// Reads the Debug directory of the current file.
107 virtual int readDebugDirectory() = 0; // EXPORT 107 virtual int readDebugDirectory() = 0; // EXPORT
108 virtual int readTlsDirectory() = 0; // EXPORT 108 virtual int readTlsDirectory() = 0; // EXPORT
109 109
110 virtual unsigned int getBits() const = 0; 110 virtual unsigned int getBits() const = 0;
111 111
112 /// Accessor function for the MZ header. 112 /// Accessor function for the MZ header.
113 const MzHeader& mzHeader() const; 113 const MzHeader& mzHeader() const;
114 /// Accessor function for the MZ header. 114 /// Accessor function for the MZ header.
115 MzHeader& mzHeader(); // EXPORT 115 MzHeader& mzHeader(); // EXPORT
116 116
117 /// Accessor function for the export directory. 117 /// Accessor function for the export directory.
118 const ExportDirectory& expDir() const; 118 const ExportDirectory& expDir() const;
119 /// Accessor function for the export directory. 119 /// Accessor function for the export directory.
120 ExportDirectory& expDir(); // EXPORT 120 ExportDirectory& expDir(); // EXPORT
121 121
122 /// Accessor function for the bound import directory. 122 /// Accessor function for the bound import directory.
123 const BoundImportDirectory& boundImpDir() const; 123 const BoundImportDirectory& boundImpDir() const;
124 /// Accessor function for the bound import directory. 124 /// Accessor function for the bound import directory.
125 BoundImportDirectory& boundImpDir(); // EXPORT 125 BoundImportDirectory& boundImpDir(); // EXPORT
126 126
127 /// Accessor function for the resource directory. 127 /// Accessor function for the resource directory.
128 const ResourceDirectory& resDir() const; 128 const ResourceDirectory& resDir() const;
129 /// Accessor function for the resource directory. 129 /// Accessor function for the resource directory.
130 ResourceDirectory& resDir(); // EXPORT 130 ResourceDirectory& resDir(); // EXPORT
131 131
132 /// Accessor function for the relocations directory. 132 /// Accessor function for the relocations directory.
133 const RelocationsDirectory& relocDir() const; 133 const RelocationsDirectory& relocDir() const;
134 /// Accessor function for the relocations directory. 134 /// Accessor function for the relocations directory.
135 RelocationsDirectory& relocDir(); // EXPORT 135 RelocationsDirectory& relocDir(); // EXPORT
136 136
137 /// Accessor function for the COM+ descriptor directory. 137 /// Accessor function for the COM+ descriptor directory.
138 const ComHeaderDirectory& comDir() const; 138 const ComHeaderDirectory& comDir() const;
139 /// Accessor function for the COM+ descriptor directory. 139 /// Accessor function for the COM+ descriptor directory.
140 ComHeaderDirectory& comDir(); // EXPORT 140 ComHeaderDirectory& comDir(); // EXPORT
141 141
142 /// Accessor function for the IAT directory. 142 /// Accessor function for the IAT directory.
143 const IatDirectory& iatDir() const; 143 const IatDirectory& iatDir() const;
144 /// Accessor function for the IAT directory. 144 /// Accessor function for the IAT directory.
145 IatDirectory& iatDir(); // EXPORT 145 IatDirectory& iatDir(); // EXPORT
146 146
147 /// Accessor function for the debug directory. 147 /// Accessor function for the debug directory.
148 const DebugDirectory& debugDir() const; 148 const DebugDirectory& debugDir() const;
149 /// Accessor function for the debug directory. 149 /// Accessor function for the debug directory.
150 DebugDirectory& debugDir(); // EXPORT 150 DebugDirectory& debugDir(); // EXPORT
151 151
152 }; 152 };
153 153
154 /** 154 /**
155 * This class implements the common structures of PE and PE+ files. 155 * This class implements the common structures of PE and PE+ files.
156 **/ 156 **/
157 template<int bits> 157 template<int bits>
158 class PeFileT : public PeFile 158 class PeFileT : public PeFile
159 { 159 {
160 typedef typename PeFile_Traits<bits>::PeHeader32_64 PeHeader32_64; 160 typedef typename PeFile_Traits<bits>::PeHeader32_64 PeHeader32_64;
161 161
162 private: 162 private:
163 PeHeader32_64 m_peh; ///< PE header of the current file. 163 PeHeader32_64 m_peh; ///< PE header of the current file.
164 ImportDirectory<bits> m_impdir; ///< Import directory of the current file. 164 ImportDirectory<bits> m_impdir; ///< Import directory of the current file.
165 TlsDirectory<bits> m_tlsdir; 165 TlsDirectory<bits> m_tlsdir;
166 166
167 public: 167 public:
168 /// Default constructor which exists only for the sake of allowing to construct files without filenames. 168 /// Default constructor which exists only for the sake of allowing to construct files without filenames.
169 PeFileT(); 169 PeFileT();
170 170
171 virtual ~PeFileT() {} 171 virtual ~PeFileT() {}
172 172
173 /// Initializes a PeFile with a filename 173 /// Initializes a PeFile with a filename
174 explicit PeFileT(const std::string& strFilename); 174 explicit PeFileT(const std::string& strFilename);
175 175
176 /// Returns the name of the current file. 176 /// Returns the name of the current file.
177 std::string getFileName() const; 177 std::string getFileName() const;
178 /// Changes the name of the current file. 178 /// Changes the name of the current file.
179 void setFileName(std::string strFilename); 179 void setFileName(std::string strFilename);
180 180
181 /// Reads the MZ header of the current file from disc. 181 /// Reads the MZ header of the current file from disc.
182 int readMzHeader() ; 182 int readMzHeader() ;
183 /// Reads the export directory of the current file from disc. 183 /// Reads the export directory of the current file from disc.
184 int readExportDirectory() ; 184 int readExportDirectory() ;
185 /// Reads the PE header of the current file from disc. 185 /// Reads the PE header of the current file from disc.
186 int readPeHeader() ; 186 int readPeHeader() ;
187 /// Reads the import directory of the current file from disc. 187 /// Reads the import directory of the current file from disc.
188 int readImportDirectory() ; 188 int readImportDirectory() ;
189 /// Reads the bound import directory of the current file from disc. 189 /// Reads the bound import directory of the current file from disc.
190 int readBoundImportDirectory() ; 190 int readBoundImportDirectory() ;
191 /// Reads the resource directory of the current file from disc. 191 /// Reads the resource directory of the current file from disc.
192 int readResourceDirectory() ; 192 int readResourceDirectory() ;
193 /// Reads the relocations directory of the current file from disc. 193 /// Reads the relocations directory of the current file from disc.
194 int readRelocationsDirectory() ; 194 int readRelocationsDirectory() ;
195 /// Reads the COM+ descriptor directory of the current file from disc. 195 /// Reads the COM+ descriptor directory of the current file from disc.
196 int readComHeaderDirectory() ; 196 int readComHeaderDirectory() ;
197 /// Reads the IAT directory of the current file from disc. 197 /// Reads the IAT directory of the current file from disc.
198 int readIatDirectory() ; 198 int readIatDirectory() ;
199 /// Reads the Debug directory of the current file. 199 /// Reads the Debug directory of the current file.
200 int readDebugDirectory() ; 200 int readDebugDirectory() ;
201 int readTlsDirectory() ; 201 int readTlsDirectory() ;
202 202
203 unsigned int getBits() const 203 unsigned int getBits() const
204 { 204 {
205 return bits; 205 return bits;
206 } 206 }
207 207
208 /// Accessor function for the PE header. 208 /// Accessor function for the PE header.
209 const PeHeader32_64& peHeader() const; 209 const PeHeader32_64& peHeader() const;
210 /// Accessor function for the PE header. 210 /// Accessor function for the PE header.
211 PeHeader32_64& peHeader(); 211 PeHeader32_64& peHeader();
212 212
213 /// Accessor function for the import directory. 213 /// Accessor function for the import directory.
214 const ImportDirectory<bits>& impDir() const; 214 const ImportDirectory<bits>& impDir() const;
215 /// Accessor function for the import directory. 215 /// Accessor function for the import directory.
216 ImportDirectory<bits>& impDir(); 216 ImportDirectory<bits>& impDir();
217 217
218 const TlsDirectory<bits>& tlsDir() const; 218 const TlsDirectory<bits>& tlsDir() const;
219 TlsDirectory<bits>& tlsDir(); 219 TlsDirectory<bits>& tlsDir();
220 }; 220 };
221 221
222 /** 222 /**
223 * This class is the main class for handling PE files. 223 * This class is the main class for handling PE files.
224 **/ 224 **/
225 class PeFile32 : public PeFileT<32> 225 class PeFile32 : public PeFileT<32>
226 { 226 {
227 public: 227 public:
228 /// Default constructor which exists only for the sake of allowing to construct files without filenames. 228 /// Default constructor which exists only for the sake of allowing to construct files without filenames.
229 PeFile32(); 229 PeFile32();
230 230
231 /// Initializes a PeFile with a filename 231 /// Initializes a PeFile with a filename
232 explicit PeFile32(const std::string& strFlename); 232 explicit PeFile32(const std::string& strFlename);
233 virtual void visit(PeFileVisitor &v) { v.callback( *this ); } 233 virtual void visit(PeFileVisitor &v) { v.callback( *this ); }
234 }; 234 };
235 235
236 /** 236 /**
237 * This class is the main class for handling PE+ files. 237 * This class is the main class for handling PE+ files.
238 **/ 238 **/
239 class PeFile64 : public PeFileT<64> 239 class PeFile64 : public PeFileT<64>
240 { 240 {
241 public: 241 public:
242 /// Default constructor which exists only for the sake of allowing to construct files without filenames. 242 /// Default constructor which exists only for the sake of allowing to construct files without filenames.
243 PeFile64(); 243 PeFile64();
244 244
245 /// Initializes a PeFile with a filename 245 /// Initializes a PeFile with a filename
246 explicit PeFile64(const std::string& strFlename); 246 explicit PeFile64(const std::string& strFlename);
247 virtual void visit(PeFileVisitor &v) { v.callback( *this ); } 247 virtual void visit(PeFileVisitor &v) { v.callback( *this ); }
248 }; 248 };
249 249
250 //typedef PeFileT<32> PeFile32; 250 //typedef PeFileT<32> PeFile32;
251 //typedef PeFileT<64> PeFile64; 251 //typedef PeFileT<64> PeFile64;
252 252
253 /** 253 /**
254 * @param strFilename Name of the current file. 254 * @param strFilename Name of the current file.
255 **/ 255 **/
256 template<int bits> 256 template<int bits>
257 PeFileT<bits>::PeFileT(const std::string& strFilename) 257 PeFileT<bits>::PeFileT(const std::string& strFilename)
258 { 258 {
259 m_filename = strFilename; 259 m_filename = strFilename;
260 } 260 }
261 261
262 template<int bits> 262 template<int bits>
263 PeFileT<bits>::PeFileT() 263 PeFileT<bits>::PeFileT()
264 { 264 {
265 } 265 }
266 266
267 template<int bits> 267 template<int bits>
268 int PeFileT<bits>::readPeHeader() 268 int PeFileT<bits>::readPeHeader()
269 { 269 {
270 return peHeader().read(getFileName(), mzHeader().getAddressOfPeHeader()); 270 return peHeader().read(getFileName(), mzHeader().getAddressOfPeHeader());
271 } 271 }
272 272
273 273
274 template<int bits> 274 template<int bits>
275 int PeFileT<bits>::readImportDirectory() 275 int PeFileT<bits>::readImportDirectory()
276 { 276 {
277 if (peHeader().calcNumberOfRvaAndSizes() >= 2 277 if (peHeader().calcNumberOfRvaAndSizes() >= 2
278 && peHeader().getIddImportRva() 278 && peHeader().getIddImportRva()
279 && peHeader().getIddImportSize()) 279 && peHeader().getIddImportSize())
280 { 280 {
281 return impDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddImportRva())), peHeader().getIddImportSize(), peHeader()); 281 return impDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddImportRva())), peHeader().getIddImportSize(), peHeader());
282 } 282 }
283 return ERROR_DIRECTORY_DOES_NOT_EXIST; 283 return ERROR_DIRECTORY_DOES_NOT_EXIST;
284 } 284 }
285 285
286 /** 286 /**
287 * @return A reference to the file's PE header. 287 * @return A reference to the file's PE header.
288 **/ 288 **/
289 template<int bits> 289 template<int bits>
290 const typename PeFile_Traits<bits>::PeHeader32_64& PeFileT<bits>::peHeader() const 290 const typename PeFile_Traits<bits>::PeHeader32_64& PeFileT<bits>::peHeader() const
291 { 291 {
292 return m_peh; 292 return m_peh;
293 } 293 }
294 294
295 /** 295 /**
296 * @return A reference to the file's PE header. 296 * @return A reference to the file's PE header.
297 **/ 297 **/
298 template<int bits> 298 template<int bits>
299 typename PeFile_Traits<bits>::PeHeader32_64& PeFileT<bits>::peHeader() 299 typename PeFile_Traits<bits>::PeHeader32_64& PeFileT<bits>::peHeader()
300 { 300 {
301 return m_peh; 301 return m_peh;
302 } 302 }
303 303
304 /** 304 /**
305 * @return A reference to the file's import directory. 305 * @return A reference to the file's import directory.
306 **/ 306 **/
307 template<int bits> 307 template<int bits>
308 const ImportDirectory<bits>& PeFileT<bits>::impDir() const 308 const ImportDirectory<bits>& PeFileT<bits>::impDir() const
309 { 309 {
310 return m_impdir; 310 return m_impdir;
311 } 311 }
312 312
313 /** 313 /**
314 * @return A reference to the file's import directory. 314 * @return A reference to the file's import directory.
315 **/ 315 **/
316 template<int bits> 316 template<int bits>
317 ImportDirectory<bits>& PeFileT<bits>::impDir() 317 ImportDirectory<bits>& PeFileT<bits>::impDir()
318 { 318 {
319 return m_impdir; 319 return m_impdir;
320 } 320 }
321 321
322 template<int bits> 322 template<int bits>
323 const TlsDirectory<bits>& PeFileT<bits>::tlsDir() const 323 const TlsDirectory<bits>& PeFileT<bits>::tlsDir() const
324 { 324 {
325 return m_tlsdir; 325 return m_tlsdir;
326 } 326 }
327 327
328 template<int bits> 328 template<int bits>
329 TlsDirectory<bits>& PeFileT<bits>::tlsDir() 329 TlsDirectory<bits>& PeFileT<bits>::tlsDir()
330 { 330 {
331 return m_tlsdir; 331 return m_tlsdir;
332 } 332 }
333 333
334 /** 334 /**
335 * @return Filename of the current file. 335 * @return Filename of the current file.
336 **/ 336 **/
337 template<int bits> 337 template<int bits>
338 std::string PeFileT<bits>::getFileName() const 338 std::string PeFileT<bits>::getFileName() const
339 { 339 {
340 return m_filename; 340 return m_filename;
341 } 341 }
342 342
343 /** 343 /**
344 * @param strFilename New filename. 344 * @param strFilename New filename.
345 **/ 345 **/
346 template<int bits> 346 template<int bits>
347 void PeFileT<bits>::setFileName(std::string strFilename) 347 void PeFileT<bits>::setFileName(std::string strFilename)
348 { 348 {
349 m_filename = strFilename; 349 m_filename = strFilename;
350 } 350 }
351 351
352 template<int bits> 352 template<int bits>
353 int PeFileT<bits>::readMzHeader() 353 int PeFileT<bits>::readMzHeader()
354 { 354 {
355 return mzHeader().read(getFileName()); 355 return mzHeader().read(getFileName());
356 } 356 }
357 357
358 template<int bits> 358 template<int bits>
359 int PeFileT<bits>::readExportDirectory() 359 int PeFileT<bits>::readExportDirectory()
360 { 360 {
361 if (peHeader().calcNumberOfRvaAndSizes() >= 1 361 if (peHeader().calcNumberOfRvaAndSizes() >= 1
362 && peHeader().getIddExportRva() && peHeader().getIddExportSize()) 362 && peHeader().getIddExportRva() && peHeader().getIddExportSize())
363 { 363 {
364 return expDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddExportRva())), peHeader().getIddExportSize(), peHeader()); 364 return expDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddExportRva())), peHeader().getIddExportSize(), peHeader());
365 } 365 }
366 return ERROR_DIRECTORY_DOES_NOT_EXIST; 366 return ERROR_DIRECTORY_DOES_NOT_EXIST;
367 } 367 }
368 368
369 369
370 template<int bits> 370 template<int bits>
371 int PeFileT<bits>::readBoundImportDirectory() 371 int PeFileT<bits>::readBoundImportDirectory()
372 { 372 {
373 if (peHeader().calcNumberOfRvaAndSizes() >= 12 373 if (peHeader().calcNumberOfRvaAndSizes() >= 12
374 && peHeader().getIddBoundImportRva() && peHeader().getIddBoundImportSize()) 374 && peHeader().getIddBoundImportRva() && peHeader().getIddBoundImportSize())
375 { 375 {
376 return boundImpDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddBoundImportRva())), peHeader().getIddBoundImportSize()); 376 return boundImpDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddBoundImportRva())), peHeader().getIddBoundImportSize());
377 } 377 }
378 return ERROR_DIRECTORY_DOES_NOT_EXIST; 378 return ERROR_DIRECTORY_DOES_NOT_EXIST;
379 } 379 }
380 380
381 template<int bits> 381 template<int bits>
382 int PeFileT<bits>::readResourceDirectory() 382 int PeFileT<bits>::readResourceDirectory()
383 { 383 {
384 if (peHeader().calcNumberOfRvaAndSizes() >= 3 384 if (peHeader().calcNumberOfRvaAndSizes() >= 3
385 && peHeader().getIddResourceRva() && peHeader().getIddResourceSize()) 385 && peHeader().getIddResourceRva() && peHeader().getIddResourceSize())
386 { 386 {
387 return resDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddResourceRva())), peHeader().getIddResourceSize(), peHeader().getIddResourceRva()); 387 return resDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddResourceRva())), peHeader().getIddResourceSize(), peHeader().getIddResourceRva());
388 } 388 }
389 return ERROR_DIRECTORY_DOES_NOT_EXIST; 389 return ERROR_DIRECTORY_DOES_NOT_EXIST;
390 } 390 }
391 391
392 template<int bits> 392 template<int bits>
393 int PeFileT<bits>::readRelocationsDirectory() 393 int PeFileT<bits>::readRelocationsDirectory()
394 { 394 {
395 if (peHeader().calcNumberOfRvaAndSizes() >= 6 395 if (peHeader().calcNumberOfRvaAndSizes() >= 6
396 && peHeader().getIddBaseRelocRva() && peHeader().getIddBaseRelocSize()) 396 && peHeader().getIddBaseRelocRva() && peHeader().getIddBaseRelocSize())
397 { 397 {
398 return relocDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddBaseRelocRva())), peHeader().getIddBaseRelocSize()); 398 return relocDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddBaseRelocRva())), peHeader().getIddBaseRelocSize());
399 } 399 }
400 return ERROR_DIRECTORY_DOES_NOT_EXIST; 400 return ERROR_DIRECTORY_DOES_NOT_EXIST;
401 } 401 }
402 402
403 template<int bits> 403 template<int bits>
404 int PeFileT<bits>::readComHeaderDirectory() 404 int PeFileT<bits>::readComHeaderDirectory()
405 { 405 {
406 if (peHeader().calcNumberOfRvaAndSizes() >= 15 406 if (peHeader().calcNumberOfRvaAndSizes() >= 15
407 && peHeader().getIddComHeaderRva() && peHeader().getIddComHeaderSize()) 407 && peHeader().getIddComHeaderRva() && peHeader().getIddComHeaderSize())
408 { 408 {
409 return comDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddComHeaderRva())), peHeader().getIddComHeaderSize()); 409 return comDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddComHeaderRva())), peHeader().getIddComHeaderSize());
410 } 410 }
411 std::cout << peHeader().getIddComHeaderRva() << std::endl; 411 std::cout << peHeader().getIddComHeaderRva() << std::endl;
412 std::exit(0); 412 std::exit(0);
413 return ERROR_DIRECTORY_DOES_NOT_EXIST; 413 return ERROR_DIRECTORY_DOES_NOT_EXIST;
414 } 414 }
415 415
416 template<int bits> 416 template<int bits>
417 int PeFileT<bits>::readIatDirectory() 417 int PeFileT<bits>::readIatDirectory()
418 { 418 {
419 if (peHeader().calcNumberOfRvaAndSizes() >= 13 419 if (peHeader().calcNumberOfRvaAndSizes() >= 13
420 && peHeader().getIddIatRva() && peHeader().getIddIatSize()) 420 && peHeader().getIddIatRva() && peHeader().getIddIatSize())
421 { 421 {
422 return iatDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddIatRva())), peHeader().getIddIatSize()); 422 return iatDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddIatRva())), peHeader().getIddIatSize());
423 } 423 }
424 return ERROR_DIRECTORY_DOES_NOT_EXIST; 424 return ERROR_DIRECTORY_DOES_NOT_EXIST;
425 } 425 }
426 426
427 template<int bits> 427 template<int bits>
428 int PeFileT<bits>::readDebugDirectory() 428 int PeFileT<bits>::readDebugDirectory()
429 { 429 {
430 if (peHeader().calcNumberOfRvaAndSizes() >= 7 430 if (peHeader().calcNumberOfRvaAndSizes() >= 7
431 && peHeader().getIddDebugRva() && peHeader().getIddDebugSize()) 431 && peHeader().getIddDebugRva() && peHeader().getIddDebugSize())
432 { 432 {
433 return debugDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddDebugRva())), peHeader().getIddDebugSize()); 433 return debugDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddDebugRva())), peHeader().getIddDebugSize());
434 } 434 }
435 return ERROR_DIRECTORY_DOES_NOT_EXIST; 435 return ERROR_DIRECTORY_DOES_NOT_EXIST;
436 } 436 }
437 437
438 template<int bits> 438 template<int bits>
439 int PeFileT<bits>::readTlsDirectory() 439 int PeFileT<bits>::readTlsDirectory()
440 { 440 {
441 if (peHeader().calcNumberOfRvaAndSizes() >= 10 441 if (peHeader().calcNumberOfRvaAndSizes() >= 10
442 && peHeader().getIddTlsRva() && peHeader().getIddTlsSize()) 442 && peHeader().getIddTlsRva() && peHeader().getIddTlsSize())
443 { 443 {
444 return tlsDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddTlsRva())), peHeader().getIddTlsSize()); 444 return tlsDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddTlsRva())), peHeader().getIddTlsSize());
445 } 445 }
446 return ERROR_DIRECTORY_DOES_NOT_EXIST; 446 return ERROR_DIRECTORY_DOES_NOT_EXIST;
447 } 447 }
448 448
449} 449}
450 450
451#endif 451#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/PeHeader.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/PeHeader.cpp
index fe7011072c..1199e6bdd1 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/PeHeader.cpp
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/PeHeader.cpp
@@ -1,90 +1,90 @@
1/* 1/*
2* PeHeader.cpp - Part of the PeLib library. 2* PeHeader.cpp - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#include "PeLibInc.h" 13#include "PeLibInc.h"
14#include "PeHeader.h" 14#include "PeHeader.h"
15 15
16namespace PeLib 16namespace PeLib
17{ 17{
18 template<> 18 template<>
19 void PeHeaderT<32>::readBaseOfData(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<32>& header) const 19 void PeHeaderT<32>::readBaseOfData(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<32>& header) const
20 { 20 {
21 ibBuffer >> header.OptionalHeader.BaseOfData; 21 ibBuffer >> header.OptionalHeader.BaseOfData;
22 } 22 }
23 23
24 template<> 24 template<>
25 void PeHeaderT<64>::readBaseOfData(InputBuffer&, PELIB_IMAGE_NT_HEADERS<64>&) const 25 void PeHeaderT<64>::readBaseOfData(InputBuffer&, PELIB_IMAGE_NT_HEADERS<64>&) const
26 { 26 {
27 } 27 }
28 28
29 template<> 29 template<>
30 void PeHeaderT<32>::rebuildBaseOfData(OutputBuffer& obBuffer) const 30 void PeHeaderT<32>::rebuildBaseOfData(OutputBuffer& obBuffer) const
31 { 31 {
32 obBuffer << m_inthHeader.OptionalHeader.BaseOfData; 32 obBuffer << m_inthHeader.OptionalHeader.BaseOfData;
33 } 33 }
34 34
35 template<> 35 template<>
36 void PeHeaderT<64>::rebuildBaseOfData(OutputBuffer&) const 36 void PeHeaderT<64>::rebuildBaseOfData(OutputBuffer&) const
37 { 37 {
38 } 38 }
39 39
40 template<> 40 template<>
41 bool PeHeaderT<32>::isValid() const 41 bool PeHeaderT<32>::isValid() const
42 { 42 {
43 return true; 43 return true;
44 } 44 }
45 45
46 template<> 46 template<>
47 bool PeHeaderT<64>::isValid() const 47 bool PeHeaderT<64>::isValid() const
48 { 48 {
49 return true; 49 return true;
50 } 50 }
51 51
52 template<> 52 template<>
53 bool PeHeaderT<32>::isValid(unsigned int pehf) const 53 bool PeHeaderT<32>::isValid(unsigned int pehf) const
54 { 54 {
55 /* 55 /*
56 if (pehf == NtSignature) 56 if (pehf == NtSignature)
57 { 57 {
58 return m_inthHeader.Signature == IMAGE_NT_SIGNATURE; 58 return m_inthHeader.Signature == IMAGE_NT_SIGNATURE;
59 } 59 }
60 else if (pehf == NumberOfSections) 60 else if (pehf == NumberOfSections)
61 { 61 {
62 return getNumberOfSections() == calcNumberOfSections(); 62 return getNumberOfSections() == calcNumberOfSections();
63 } */ 63 } */
64 return false; 64 return false;
65 } 65 }
66 66
67 template<> 67 template<>
68 bool PeHeaderT<64>::isValid(unsigned int pehf) const 68 bool PeHeaderT<64>::isValid(unsigned int pehf) const
69 { 69 {
70 return false; 70 return false;
71 } 71 }
72 72
73 /** 73 /**
74 * @return The BaseOfData value from the PE header. 74 * @return The BaseOfData value from the PE header.
75 **/ 75 **/
76 dword PeHeader32::getBaseOfData() const 76 dword PeHeader32::getBaseOfData() const
77 { 77 {
78 return m_inthHeader.OptionalHeader.BaseOfData; 78 return m_inthHeader.OptionalHeader.BaseOfData;
79 } 79 }
80 80
81 /** 81 /**
82 * Changes the file's BaseOfData. 82 * Changes the file's BaseOfData.
83 * @param dwValue New value. 83 * @param dwValue New value.
84 **/ 84 **/
85 void PeHeader32::setBaseOfData(dword dwValue) 85 void PeHeader32::setBaseOfData(dword dwValue)
86 { 86 {
87 m_inthHeader.OptionalHeader.BaseOfData = dwValue; 87 m_inthHeader.OptionalHeader.BaseOfData = dwValue;
88 } 88 }
89 89
90} 90}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/PeHeader.h b/utils/zenutils/libraries/pelib-0.9/pelib/PeHeader.h
index 08eaca4072..d5c1748233 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/PeHeader.h
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/PeHeader.h
@@ -1,2685 +1,2685 @@
1/* 1/*
2* PeHeader.h - Part of the PeLib library. 2* PeHeader.h - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#ifndef PEHEADER_H 13#ifndef PEHEADER_H
14#define PEHEADER_H 14#define PEHEADER_H
15 15
16#include "PeLibAux.h" 16#include "PeLibAux.h"
17 17
18namespace PeLib 18namespace PeLib
19{ 19{
20 class PeHeader 20 class PeHeader
21 { 21 {
22// protected: 22// protected:
23// virtual void readBaseOfData(InputBuffer& ibBuffer) = 0; 23// virtual void readBaseOfData(InputBuffer& ibBuffer) = 0;
24// virtual void rebuildBaseOfData(OutputBuffer& obBuffer) const = 0; 24// virtual void rebuildBaseOfData(OutputBuffer& obBuffer) const = 0;
25 25
26 public: 26 public:
27 virtual ~PeHeader(){}; 27 virtual ~PeHeader(){};
28 }; 28 };
29 29
30 /// Class that handles the PE header of files. 30 /// Class that handles the PE header of files.
31 /** 31 /**
32 * This class can read and modify PE headers. It provides set- and get functions to access 32 * This class can read and modify PE headers. It provides set- and get functions to access
33 * all individual members of a PE header. Furthermore it's possible to validate and rebuild 33 * all individual members of a PE header. Furthermore it's possible to validate and rebuild
34 * PE headers. A PE header includes the IMAGE_Nt_HEADERS and the section definitions of a PE file. 34 * PE headers. A PE header includes the IMAGE_Nt_HEADERS and the section definitions of a PE file.
35 * \todo getIdReservedRva 35 * \todo getIdReservedRva
36 **/ 36 **/
37 template<int x> 37 template<int x>
38 class PeHeaderT : public PeHeader 38 class PeHeaderT : public PeHeader
39 { 39 {
40 private: 40 private:
41 void readBaseOfData(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const; 41 void readBaseOfData(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const;
42 void rebuildBaseOfData(OutputBuffer& obBuffer) const; 42 void rebuildBaseOfData(OutputBuffer& obBuffer) const;
43 43
44 protected: 44 protected:
45 std::vector<PELIB_IMAGE_SECTION_HEADER> m_vIsh; ///< Stores section header information. 45 std::vector<PELIB_IMAGE_SECTION_HEADER> m_vIsh; ///< Stores section header information.
46 PELIB_IMAGE_NT_HEADERS<x> m_inthHeader; ///< Stores Nt header information. 46 PELIB_IMAGE_NT_HEADERS<x> m_inthHeader; ///< Stores Nt header information.
47 dword m_uiOffset; ///< Equivalent to the value returned by #PeLib::MzHeader::getAddressOfPeFile 47 dword m_uiOffset; ///< Equivalent to the value returned by #PeLib::MzHeader::getAddressOfPeFile
48 48
49 public: 49 public:
50 typedef typename FieldSizes<x>::VAR4_8 VAR4_8; 50 typedef typename FieldSizes<x>::VAR4_8 VAR4_8;
51 51
52 PeHeaderT() : m_uiOffset(0) 52 PeHeaderT() : m_uiOffset(0)
53 { 53 {
54 } 54 }
55 55
56 /// Add a section to the header. 56 /// Add a section to the header.
57 int addSection(const std::string& strName, dword dwSize); // EXPORT 57 int addSection(const std::string& strName, dword dwSize); // EXPORT
58 58
59 unsigned int calcSizeOfImage() const; // EXPORT 59 unsigned int calcSizeOfImage() const; // EXPORT
60 60
61 /// Returns the unused space after the header. 61 /// Returns the unused space after the header.
62 unsigned int calcSpaceAfterHeader() const; // EXPORT 62 unsigned int calcSpaceAfterHeader() const; // EXPORT
63 63
64 /// Returns the address of the physically first section (not the first defined section). 64 /// Returns the address of the physically first section (not the first defined section).
65 unsigned int calcStartOfCode() const; // EXPORT 65 unsigned int calcStartOfCode() const; // EXPORT
66 66
67 /// Calculates the offset for a new section of size uiSize. 67 /// Calculates the offset for a new section of size uiSize.
68 unsigned int calcOffset() const; // EXPORT 68 unsigned int calcOffset() const; // EXPORT
69 69
70 /// Calculates the Rva for a new section of size uiSize. 70 /// Calculates the Rva for a new section of size uiSize.
71 unsigned int calcRva() const; // EXPORT 71 unsigned int calcRva() const; // EXPORT
72 72
73 /// Returns the number of sections in the current file. 73 /// Returns the number of sections in the current file.
74 word calcNumberOfSections() const; // EXPORT 74 word calcNumberOfSections() const; // EXPORT
75 75
76 void enlargeLastSection(unsigned int uiSize); // EXPORT 76 void enlargeLastSection(unsigned int uiSize); // EXPORT
77 77
78 /// Returns the section Id of the section that contains the offset. 78 /// Returns the section Id of the section that contains the offset.
79 word getSectionWithOffset(VAR4_8 dwOffset) const; // EXPORT 79 word getSectionWithOffset(VAR4_8 dwOffset) const; // EXPORT
80 80
81 /// Returns the number of the section which the given relative address points to. 81 /// Returns the number of the section which the given relative address points to.
82 word getSectionWithRva(VAR4_8 rva) const; // EXPORT 82 word getSectionWithRva(VAR4_8 rva) const; // EXPORT
83 83
84 bool isValid() const; // EXPORT 84 bool isValid() const; // EXPORT
85 bool isValid(unsigned int foo) const; // EXPORT 85 bool isValid(unsigned int foo) const; // EXPORT
86 86
87 /// Corrects the current PE header. 87 /// Corrects the current PE header.
88 void makeValid(dword dwOffset); // EXPORT 88 void makeValid(dword dwOffset); // EXPORT
89 89
90 /// Converts a file offset to a relative virtual offset. 90 /// Converts a file offset to a relative virtual offset.
91 unsigned int offsetToRva(VAR4_8 dwOffset) const; // EXPORT 91 unsigned int offsetToRva(VAR4_8 dwOffset) const; // EXPORT
92 92
93 /// Converts a file offset to a virtual address. 93 /// Converts a file offset to a virtual address.
94 unsigned int offsetToVa(VAR4_8 dwOffset) const; // EXPORT 94 unsigned int offsetToVa(VAR4_8 dwOffset) const; // EXPORT
95 95
96 /// Reads the PE header of a file. 96 /// Reads the PE header of a file.
97 int read(std::string strFilename, unsigned int uiOffset); // EXPORT 97 int read(std::string strFilename, unsigned int uiOffset); // EXPORT
98 98
99 int read(const unsigned char* pcBuffer, unsigned int uiSize, unsigned int uiOffset); // EXPORT 99 int read(const unsigned char* pcBuffer, unsigned int uiSize, unsigned int uiOffset); // EXPORT
100 100
101 void readHeader(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const; 101 void readHeader(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const;
102 void readDataDirectories(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const; 102 void readDataDirectories(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const;
103 std::vector<PELIB_IMAGE_SECTION_HEADER> readSections(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const; 103 std::vector<PELIB_IMAGE_SECTION_HEADER> readSections(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const;
104 104
105 /// Rebuilds the current PE header. 105 /// Rebuilds the current PE header.
106 void rebuild(std::vector<byte>& vBuffer) const; // EXPORT 106 void rebuild(std::vector<byte>& vBuffer) const; // EXPORT
107 107
108 /// Converts a relative virtual address to a file offset. 108 /// Converts a relative virtual address to a file offset.
109 VAR4_8 rvaToOffset(VAR4_8 dwRva) const; // EXPORT 109 VAR4_8 rvaToOffset(VAR4_8 dwRva) const; // EXPORT
110 110
111 /// Converts a relative virtual address to a virtual address. 111 /// Converts a relative virtual address to a virtual address.
112 VAR4_8 rvaToVa(VAR4_8 dwRva) const; // EXPORT 112 VAR4_8 rvaToVa(VAR4_8 dwRva) const; // EXPORT
113 113
114 /// Calculates the size for the current PE header including all section definitions. 114 /// Calculates the size for the current PE header including all section definitions.
115 unsigned int size() const; 115 unsigned int size() const;
116 116
117 VAR4_8 vaToRva(VAR4_8 dwRva) const; // EXPORT 117 VAR4_8 vaToRva(VAR4_8 dwRva) const; // EXPORT
118 VAR4_8 vaToOffset(VAR4_8 dwRva) const; // EXPORT 118 VAR4_8 vaToOffset(VAR4_8 dwRva) const; // EXPORT
119 119
120 /// Save the PE header to a file. 120 /// Save the PE header to a file.
121 int write(std::string strFilename, unsigned int uiOffset) const; // EXPORT 121 int write(std::string strFilename, unsigned int uiOffset) const; // EXPORT
122 122
123 /// Writes sections to a file. 123 /// Writes sections to a file.
124 int writeSections(const std::string& strFilename) const; // EXPORT 124 int writeSections(const std::string& strFilename) const; // EXPORT
125 /// Overwrites a section with new data. 125 /// Overwrites a section with new data.
126 int writeSectionData(const std::string& strFilename, word wSecnr, const std::vector<byte>& vBuffer) const; // EXPORT 126 int writeSectionData(const std::string& strFilename, word wSecnr, const std::vector<byte>& vBuffer) const; // EXPORT
127 127
128// header getters 128// header getters
129 /// Returns the Signature value of the header. 129 /// Returns the Signature value of the header.
130 dword getNtSignature() const; // EXPORT 130 dword getNtSignature() const; // EXPORT
131 /// Returns the Machine value of the header. 131 /// Returns the Machine value of the header.
132 word getMachine() const; // EXPORT 132 word getMachine() const; // EXPORT
133 /// Returns the Sections value of the header. 133 /// Returns the Sections value of the header.
134 word getNumberOfSections() const; // EXPORT 134 word getNumberOfSections() const; // EXPORT
135 /// Returns the TimeDateStamp value of the header. 135 /// Returns the TimeDateStamp value of the header.
136 dword getTimeDateStamp() const; // EXPORT 136 dword getTimeDateStamp() const; // EXPORT
137 /// Returns the PointerToSymbolTable value of the header. 137 /// Returns the PointerToSymbolTable value of the header.
138 dword getPointerToSymbolTable() const; // EXPORT 138 dword getPointerToSymbolTable() const; // EXPORT
139 /// Returns the NumberOfSymbols value of the header. 139 /// Returns the NumberOfSymbols value of the header.
140 dword getNumberOfSymbols() const; // EXPORT 140 dword getNumberOfSymbols() const; // EXPORT
141 /// Returns the SizeOfOptionalHeader value of the header. 141 /// Returns the SizeOfOptionalHeader value of the header.
142 word getSizeOfOptionalHeader() const; // EXPORT 142 word getSizeOfOptionalHeader() const; // EXPORT
143 /// Returns the Characteristics value of the header. 143 /// Returns the Characteristics value of the header.
144 word getCharacteristics() const; // EXPORT 144 word getCharacteristics() const; // EXPORT
145 145
146 /// Returns the Magic value of the header. 146 /// Returns the Magic value of the header.
147 word getMagic() const; // EXPORT 147 word getMagic() const; // EXPORT
148 /// Returns the MajorLinkerVersion value of the header. 148 /// Returns the MajorLinkerVersion value of the header.
149 byte getMajorLinkerVersion() const; // EXPORT 149 byte getMajorLinkerVersion() const; // EXPORT
150 /// Returns the MinorLinkerVersion value of the header. 150 /// Returns the MinorLinkerVersion value of the header.
151 byte getMinorLinkerVersion() const; // EXPORT 151 byte getMinorLinkerVersion() const; // EXPORT
152 /// Returns the SizeOfCode value of the header. 152 /// Returns the SizeOfCode value of the header.
153 dword getSizeOfCode() const; // EXPORT 153 dword getSizeOfCode() const; // EXPORT
154 /// Returns the SizeOfInitializedData value of the header. 154 /// Returns the SizeOfInitializedData value of the header.
155 dword getSizeOfInitializedData() const; // EXPORT 155 dword getSizeOfInitializedData() const; // EXPORT
156 /// Returns the SizeOfUninitializedData value of the header. 156 /// Returns the SizeOfUninitializedData value of the header.
157 dword getSizeOfUninitializedData() const; // EXPORT 157 dword getSizeOfUninitializedData() const; // EXPORT
158 /// Returns the AddressOfEntryPoint value of the header. 158 /// Returns the AddressOfEntryPoint value of the header.
159 dword getAddressOfEntryPoint() const; // EXPORT 159 dword getAddressOfEntryPoint() const; // EXPORT
160 /// Returns the BaseOfCode value of the header. 160 /// Returns the BaseOfCode value of the header.
161 dword getBaseOfCode() const; // EXPORT 161 dword getBaseOfCode() const; // EXPORT
162 /// Returns the ImageBase value of the header. 162 /// Returns the ImageBase value of the header.
163 VAR4_8 getImageBase() const; // EXPORT 163 VAR4_8 getImageBase() const; // EXPORT
164 /// Returns the SectionAlignment value of the header. 164 /// Returns the SectionAlignment value of the header.
165 dword getSectionAlignment() const; // EXPORT 165 dword getSectionAlignment() const; // EXPORT
166 /// Returns the FileAlignment value of the header. 166 /// Returns the FileAlignment value of the header.
167 dword getFileAlignment() const; // EXPORT 167 dword getFileAlignment() const; // EXPORT
168 /// Returns the MajorOperatingSystemVersion value of the header. 168 /// Returns the MajorOperatingSystemVersion value of the header.
169 word getMajorOperatingSystemVersion() const; // EXPORT 169 word getMajorOperatingSystemVersion() const; // EXPORT
170 /// Returns the MinorOperatingSystemVersion value of the header. 170 /// Returns the MinorOperatingSystemVersion value of the header.
171 word getMinorOperatingSystemVersion() const; // EXPORT 171 word getMinorOperatingSystemVersion() const; // EXPORT
172 /// Returns the MajorImageVersion value of the header. 172 /// Returns the MajorImageVersion value of the header.
173 word getMajorImageVersion() const; // EXPORT 173 word getMajorImageVersion() const; // EXPORT
174 /// Returns the MinorImageVersion value of the header. 174 /// Returns the MinorImageVersion value of the header.
175 word getMinorImageVersion() const; // EXPORT 175 word getMinorImageVersion() const; // EXPORT
176 /// Returns the MajorSubsystemVersion value of the header. 176 /// Returns the MajorSubsystemVersion value of the header.
177 word getMajorSubsystemVersion() const; // EXPORT 177 word getMajorSubsystemVersion() const; // EXPORT
178 /// Returns the MinorSubsystemVersion value of the header. 178 /// Returns the MinorSubsystemVersion value of the header.
179 word getMinorSubsystemVersion() const; // EXPORT 179 word getMinorSubsystemVersion() const; // EXPORT
180 /// Returns the Reserved1 value of the header. 180 /// Returns the Reserved1 value of the header.
181 dword getWin32VersionValue() const; // EXPORT 181 dword getWin32VersionValue() const; // EXPORT
182 /// Returns the SizeOfImage value of the header. 182 /// Returns the SizeOfImage value of the header.
183 dword getSizeOfImage() const; // EXPORT 183 dword getSizeOfImage() const; // EXPORT
184 /// Returns the SizeOfHeaders value of the header. 184 /// Returns the SizeOfHeaders value of the header.
185 dword getSizeOfHeaders() const; // EXPORT 185 dword getSizeOfHeaders() const; // EXPORT
186 /// Returns the CheckSum value of the header. 186 /// Returns the CheckSum value of the header.
187 dword getCheckSum() const; // EXPORT 187 dword getCheckSum() const; // EXPORT
188 /// Returns the Subsystem value of the header. 188 /// Returns the Subsystem value of the header.
189 word getSubsystem() const; // EXPORT 189 word getSubsystem() const; // EXPORT
190 /// Returns the DllCharacteristics value of the header. 190 /// Returns the DllCharacteristics value of the header.
191 word getDllCharacteristics() const; // EXPORT 191 word getDllCharacteristics() const; // EXPORT
192 /// Returns the SizeOfStackReserve value of the header. 192 /// Returns the SizeOfStackReserve value of the header.
193 VAR4_8 getSizeOfStackReserve() const; // EXPORT 193 VAR4_8 getSizeOfStackReserve() const; // EXPORT
194 /// Returns the SizeOfStackCommit value of the header. 194 /// Returns the SizeOfStackCommit value of the header.
195 VAR4_8 getSizeOfStackCommit() const; // EXPORT 195 VAR4_8 getSizeOfStackCommit() const; // EXPORT
196 /// Returns the SizeOfHeapReserve value of the header. 196 /// Returns the SizeOfHeapReserve value of the header.
197 VAR4_8 getSizeOfHeapReserve() const; // EXPORT 197 VAR4_8 getSizeOfHeapReserve() const; // EXPORT
198 /// Returns the SizeOfHeapCommit value of the header. 198 /// Returns the SizeOfHeapCommit value of the header.
199 VAR4_8 getSizeOfHeapCommit() const; // EXPORT 199 VAR4_8 getSizeOfHeapCommit() const; // EXPORT
200 /// Returns the LoaderFlags value of the header. 200 /// Returns the LoaderFlags value of the header.
201 dword getLoaderFlags() const; // EXPORT 201 dword getLoaderFlags() const; // EXPORT
202 /// Returns the NumberOfRvaAndSizes value of the header. 202 /// Returns the NumberOfRvaAndSizes value of the header.
203 dword getNumberOfRvaAndSizes() const; // EXPORT 203 dword getNumberOfRvaAndSizes() const; // EXPORT
204 dword calcNumberOfRvaAndSizes() const; // EXPORT 204 dword calcNumberOfRvaAndSizes() const; // EXPORT
205 205
206 void addDataDirectory(); // EXPORT 206 void addDataDirectory(); // EXPORT
207 void removeDataDirectory(dword index); // EXPORT 207 void removeDataDirectory(dword index); // EXPORT
208 208
209// image directory getters 209// image directory getters
210 /// Returns the relative virtual address of the image directory Export. 210 /// Returns the relative virtual address of the image directory Export.
211 dword getIddExportRva() const; // EXPORT 211 dword getIddExportRva() const; // EXPORT
212 /// Returns the size of the image directory Export. 212 /// Returns the size of the image directory Export.
213 dword getIddExportSize() const; // EXPORT 213 dword getIddExportSize() const; // EXPORT
214 /// Returns the relative virtual address of the image directory Import. 214 /// Returns the relative virtual address of the image directory Import.
215 dword getIddImportRva() const; // EXPORT 215 dword getIddImportRva() const; // EXPORT
216 /// Returns the size of the image directory Import. 216 /// Returns the size of the image directory Import.
217 dword getIddImportSize() const; // EXPORT 217 dword getIddImportSize() const; // EXPORT
218 /// Returns the relative virtual address of the image directory Resource. 218 /// Returns the relative virtual address of the image directory Resource.
219 dword getIddResourceRva() const; // EXPORT 219 dword getIddResourceRva() const; // EXPORT
220 /// Returns the size of the image directory Resource. 220 /// Returns the size of the image directory Resource.
221 dword getIddResourceSize() const; // EXPORT 221 dword getIddResourceSize() const; // EXPORT
222 /// Returns the relative virtual address of the image directory Exception. 222 /// Returns the relative virtual address of the image directory Exception.
223 dword getIddExceptionRva() const; // EXPORT 223 dword getIddExceptionRva() const; // EXPORT
224 /// Returns the size of the image directory Exception. 224 /// Returns the size of the image directory Exception.
225 dword getIddExceptionSize() const; // EXPORT 225 dword getIddExceptionSize() const; // EXPORT
226 /// Returns the relative virtual address of the image directory Security. 226 /// Returns the relative virtual address of the image directory Security.
227 dword getIddSecurityRva() const; // EXPORT 227 dword getIddSecurityRva() const; // EXPORT
228 /// Returns the size of the image directory Security. 228 /// Returns the size of the image directory Security.
229 dword getIddSecuritySize() const; // EXPORT 229 dword getIddSecuritySize() const; // EXPORT
230 /// Returns the relative virtual address of the image directory Base Reloc. 230 /// Returns the relative virtual address of the image directory Base Reloc.
231 dword getIddBaseRelocRva() const; // EXPORT 231 dword getIddBaseRelocRva() const; // EXPORT
232 /// Returns the size of the image directory Base Reloc. 232 /// Returns the size of the image directory Base Reloc.
233 dword getIddBaseRelocSize() const; // EXPORT 233 dword getIddBaseRelocSize() const; // EXPORT
234 /// Returns the relative virtual address of the image directory Debug. 234 /// Returns the relative virtual address of the image directory Debug.
235 dword getIddDebugRva() const; // EXPORT 235 dword getIddDebugRva() const; // EXPORT
236 /// Returns the size of the image directory Debug. 236 /// Returns the size of the image directory Debug.
237 dword getIddDebugSize() const; // EXPORT 237 dword getIddDebugSize() const; // EXPORT
238 /// Returns the relative virtual address of the image directory Architecture. 238 /// Returns the relative virtual address of the image directory Architecture.
239 dword getIddArchitectureRva() const; // EXPORT 239 dword getIddArchitectureRva() const; // EXPORT
240 /// Returns the size of the image directory Architecture. 240 /// Returns the size of the image directory Architecture.
241 dword getIddArchitectureSize() const; // EXPORT 241 dword getIddArchitectureSize() const; // EXPORT
242 /// Returns the relative virtual address of the image directory GlobalPtr. 242 /// Returns the relative virtual address of the image directory GlobalPtr.
243 dword getIddGlobalPtrRva() const; // EXPORT 243 dword getIddGlobalPtrRva() const; // EXPORT
244 /// Returns the size of the image directory GlobalPtr. 244 /// Returns the size of the image directory GlobalPtr.
245 dword getIddGlobalPtrSize() const; // EXPORT 245 dword getIddGlobalPtrSize() const; // EXPORT
246 /// Returns the relative virtual address of the image directory Tls. 246 /// Returns the relative virtual address of the image directory Tls.
247 dword getIddTlsRva() const; // EXPORT 247 dword getIddTlsRva() const; // EXPORT
248 /// Returns the size of the image directory Tls. 248 /// Returns the size of the image directory Tls.
249 dword getIddTlsSize() const; // EXPORT 249 dword getIddTlsSize() const; // EXPORT
250 /// Returns the relative virtual address of the image directory LoadConfig. 250 /// Returns the relative virtual address of the image directory LoadConfig.
251 dword getIddLoadConfigRva() const; // EXPORT 251 dword getIddLoadConfigRva() const; // EXPORT
252 /// Returns the size of the image directory LoadConfig. 252 /// Returns the size of the image directory LoadConfig.
253 dword getIddLoadConfigSize() const; // EXPORT 253 dword getIddLoadConfigSize() const; // EXPORT
254 /// Returns the relative virtual address of the image directory BoundImport. 254 /// Returns the relative virtual address of the image directory BoundImport.
255 dword getIddBoundImportRva() const; // EXPORT 255 dword getIddBoundImportRva() const; // EXPORT
256 /// Returns the size of the image directory BoundImport. 256 /// Returns the size of the image directory BoundImport.
257 dword getIddBoundImportSize() const; // EXPORT 257 dword getIddBoundImportSize() const; // EXPORT
258 /// Returns the relative virtual address of the image directory Iat. 258 /// Returns the relative virtual address of the image directory Iat.
259 dword getIddIatRva() const; // EXPORT 259 dword getIddIatRva() const; // EXPORT
260 /// Returns the size of the image directory Iat. 260 /// Returns the size of the image directory Iat.
261 dword getIddIatSize() const; // EXPORT 261 dword getIddIatSize() const; // EXPORT
262 /// Returns the relative virtual address of the image directory DelayImport. 262 /// Returns the relative virtual address of the image directory DelayImport.
263 dword getIddDelayImportRva() const; // EXPORT 263 dword getIddDelayImportRva() const; // EXPORT
264 /// Returns the size of the image directory DelayImport. 264 /// Returns the size of the image directory DelayImport.
265 dword getIddDelayImportSize() const; // EXPORT 265 dword getIddDelayImportSize() const; // EXPORT
266 /// Returns the relative virtual address of the image directory COM Descriptor. 266 /// Returns the relative virtual address of the image directory COM Descriptor.
267 dword getIddComHeaderRva() const; // EXPORT 267 dword getIddComHeaderRva() const; // EXPORT
268 /// Returns the size of the image directory COM Descriptor. 268 /// Returns the size of the image directory COM Descriptor.
269 dword getIddComHeaderSize() const; // EXPORT 269 dword getIddComHeaderSize() const; // EXPORT
270 270
271 /// Returns the relative virtual address of an image directory. 271 /// Returns the relative virtual address of an image directory.
272 dword getImageDataDirectoryRva(dword dwDirectory) const; // EXPORT 272 dword getImageDataDirectoryRva(dword dwDirectory) const; // EXPORT
273 /// Returns the size of an image directory. 273 /// Returns the size of an image directory.
274 dword getImageDataDirectorySize(dword dwDirectory) const; // EXPORT 274 dword getImageDataDirectorySize(dword dwDirectory) const; // EXPORT
275 275
276 void setImageDataDirectoryRva(dword dwDirectory, dword value); // EXPORT 276 void setImageDataDirectoryRva(dword dwDirectory, dword value); // EXPORT
277 void setImageDataDirectorySize(dword dwDirectory, dword value); // EXPORT 277 void setImageDataDirectorySize(dword dwDirectory, dword value); // EXPORT
278 278
279// section getters 279// section getters
280 /// Returns the name of a section. 280 /// Returns the name of a section.
281 std::string getSectionName(word uiSectionnr) const; // EXPORT 281 std::string getSectionName(word uiSectionnr) const; // EXPORT
282 /// Returns the virtual size of a section. 282 /// Returns the virtual size of a section.
283 dword getVirtualSize(word uiSectionnr) const; // EXPORT 283 dword getVirtualSize(word uiSectionnr) const; // EXPORT
284 /// Returns the virtual address of a section. 284 /// Returns the virtual address of a section.
285 dword getVirtualAddress(word uiSectionnr) const; // EXPORT 285 dword getVirtualAddress(word uiSectionnr) const; // EXPORT
286 /// Returns the size of a section's raw data. 286 /// Returns the size of a section's raw data.
287 dword getSizeOfRawData(word uiSectionnr) const; // EXPORT 287 dword getSizeOfRawData(word uiSectionnr) const; // EXPORT
288 /// Returns file offset of the data of a section. 288 /// Returns file offset of the data of a section.
289 dword getPointerToRawData(word uiSectionnr) const; // EXPORT 289 dword getPointerToRawData(word uiSectionnr) const; // EXPORT
290 /// Returns the rva of the relocations of a section. 290 /// Returns the rva of the relocations of a section.
291 dword getPointerToRelocations(word uiSectionnr) const; // EXPORT 291 dword getPointerToRelocations(word uiSectionnr) const; // EXPORT
292 /// Returns the rva of the line numbers of a section. 292 /// Returns the rva of the line numbers of a section.
293 dword getPointerToLinenumbers(word uiSectionnr) const; // EXPORT 293 dword getPointerToLinenumbers(word uiSectionnr) const; // EXPORT
294 /// Returns the number of relocations of a section. 294 /// Returns the number of relocations of a section.
295 dword getNumberOfRelocations(word uiSectionnr) const; // EXPORT 295 dword getNumberOfRelocations(word uiSectionnr) const; // EXPORT
296 /// Returns the number of line numbers of a section. 296 /// Returns the number of line numbers of a section.
297 dword getNumberOfLinenumbers(word uiSectionnr) const; // EXPORT 297 dword getNumberOfLinenumbers(word uiSectionnr) const; // EXPORT
298 /// Returns the characteristics of a section. 298 /// Returns the characteristics of a section.
299 dword getCharacteristics(word uiSectionnr) const; // EXPORT _section 299 dword getCharacteristics(word uiSectionnr) const; // EXPORT _section
300 300
301// header setters 301// header setters
302 /// Sets the Signature value of the header. 302 /// Sets the Signature value of the header.
303 void setNtSignature(dword value); // EXPORT 303 void setNtSignature(dword value); // EXPORT
304 /// Sets the Machine value of the header. 304 /// Sets the Machine value of the header.
305 void setMachine(word value); // EXPORT 305 void setMachine(word value); // EXPORT
306 /// Sets the Sections value of the header. 306 /// Sets the Sections value of the header.
307 void setNumberOfSections(word value); // EXPORT 307 void setNumberOfSections(word value); // EXPORT
308 /// Sets the TimeDateStamp value of the header. 308 /// Sets the TimeDateStamp value of the header.
309 void setTimeDateStamp(dword value); // EXPORT 309 void setTimeDateStamp(dword value); // EXPORT
310 /// Sets the PointerToSymbolTable value of the header. 310 /// Sets the PointerToSymbolTable value of the header.
311 void setPointerToSymbolTable(dword value); // EXPORT 311 void setPointerToSymbolTable(dword value); // EXPORT
312 /// Sets the NumberOfSymbols value of the header. 312 /// Sets the NumberOfSymbols value of the header.
313 void setNumberOfSymbols(dword value); // EXPORT 313 void setNumberOfSymbols(dword value); // EXPORT
314 /// Sets the SizeOfOptionalHeader value of the header. 314 /// Sets the SizeOfOptionalHeader value of the header.
315 void setSizeOfOptionalHeader(word value); // EXPORT 315 void setSizeOfOptionalHeader(word value); // EXPORT
316 /// Sets the Characteristics value of the header. 316 /// Sets the Characteristics value of the header.
317 void setCharacteristics(word value); // EXPORT _section 317 void setCharacteristics(word value); // EXPORT _section
318 318
319 /// Sets the Magic value of the header. 319 /// Sets the Magic value of the header.
320 void setMagic(word value); // EXPORT 320 void setMagic(word value); // EXPORT
321 /// Sets the MajorLinkerVersion value of the header. 321 /// Sets the MajorLinkerVersion value of the header.
322 void setMajorLinkerVersion(byte value); // EXPORT 322 void setMajorLinkerVersion(byte value); // EXPORT
323 /// Sets the MinorLinkerVersion value of the header. 323 /// Sets the MinorLinkerVersion value of the header.
324 void setMinorLinkerVersion(byte value); // EXPORT 324 void setMinorLinkerVersion(byte value); // EXPORT
325 /// Sets the SizeOfCode value of the header. 325 /// Sets the SizeOfCode value of the header.
326 void setSizeOfCode(dword value); // EXPORT 326 void setSizeOfCode(dword value); // EXPORT
327 /// Sets the SizeOfInitializedData value of the header. 327 /// Sets the SizeOfInitializedData value of the header.
328 void setSizeOfInitializedData(dword value); // EXPORT 328 void setSizeOfInitializedData(dword value); // EXPORT
329 /// Sets the SizeOfUninitializedData value of the header. 329 /// Sets the SizeOfUninitializedData value of the header.
330 void setSizeOfUninitializedData(dword value); // EXPORT 330 void setSizeOfUninitializedData(dword value); // EXPORT
331 /// Sets the AddressOfEntryPoint value of the header. 331 /// Sets the AddressOfEntryPoint value of the header.
332 void setAddressOfEntryPoint(dword value); // EXPORT 332 void setAddressOfEntryPoint(dword value); // EXPORT
333 /// Sets the BaseOfCode value of the header. 333 /// Sets the BaseOfCode value of the header.
334 void setBaseOfCode(dword value); // EXPORT 334 void setBaseOfCode(dword value); // EXPORT
335 /// Sets the ImageBase value of the header. 335 /// Sets the ImageBase value of the header.
336 void setImageBase(VAR4_8 value); // EXPORT 336 void setImageBase(VAR4_8 value); // EXPORT
337 /// Sets the SectionAlignment value of the header. 337 /// Sets the SectionAlignment value of the header.
338 void setSectionAlignment(dword value); // EXPORT 338 void setSectionAlignment(dword value); // EXPORT
339 /// Sets the FileAlignment value of the header. 339 /// Sets the FileAlignment value of the header.
340 void setFileAlignment(dword value); // EXPORT 340 void setFileAlignment(dword value); // EXPORT
341 /// Sets the MajorOperatingSystemVersion value of the header. 341 /// Sets the MajorOperatingSystemVersion value of the header.
342 void setMajorOperatingSystemVersion(word value); // EXPORT 342 void setMajorOperatingSystemVersion(word value); // EXPORT
343 /// Sets the MinorOperatingSystemVersion value of the header. 343 /// Sets the MinorOperatingSystemVersion value of the header.
344 void setMinorOperatingSystemVersion(word value); // EXPORT 344 void setMinorOperatingSystemVersion(word value); // EXPORT
345 /// Sets the MajorImageVersion value of the header. 345 /// Sets the MajorImageVersion value of the header.
346 void setMajorImageVersion(word value); // EXPORT 346 void setMajorImageVersion(word value); // EXPORT
347 /// Sets the MinorImageVersion value of the header. 347 /// Sets the MinorImageVersion value of the header.
348 void setMinorImageVersion(word value); // EXPORT 348 void setMinorImageVersion(word value); // EXPORT
349 /// Sets the MajorSubsystemVersion value of the header. 349 /// Sets the MajorSubsystemVersion value of the header.
350 void setMajorSubsystemVersion(word value); // EXPORT 350 void setMajorSubsystemVersion(word value); // EXPORT
351 /// Sets the MinorSubsystemVersion value of the header. 351 /// Sets the MinorSubsystemVersion value of the header.
352 void setMinorSubsystemVersion(word value); // EXPORT 352 void setMinorSubsystemVersion(word value); // EXPORT
353 /// Sets the Reserved1 value of the header. 353 /// Sets the Reserved1 value of the header.
354 void setWin32VersionValue(dword value); // EXPORT 354 void setWin32VersionValue(dword value); // EXPORT
355 /// Sets the SizeOfImage value of the header. 355 /// Sets the SizeOfImage value of the header.
356 void setSizeOfImage(dword value); // EXPORT 356 void setSizeOfImage(dword value); // EXPORT
357 /// Sets the SizeOfHeaders value of the header. 357 /// Sets the SizeOfHeaders value of the header.
358 void setSizeOfHeaders(dword value); // EXPORT 358 void setSizeOfHeaders(dword value); // EXPORT
359 /// Sets the CheckSum value of the header. 359 /// Sets the CheckSum value of the header.
360 void setCheckSum(dword value); // EXPORT 360 void setCheckSum(dword value); // EXPORT
361 /// Sets the Subsystem value of the header. 361 /// Sets the Subsystem value of the header.
362 void setSubsystem(word value); // EXPORT 362 void setSubsystem(word value); // EXPORT
363 /// Sets the DllCharacteristics value of the header. 363 /// Sets the DllCharacteristics value of the header.
364 void setDllCharacteristics(word value); // EXPORT 364 void setDllCharacteristics(word value); // EXPORT
365 /// Sets the SizeOfStackReserve value of the header. 365 /// Sets the SizeOfStackReserve value of the header.
366 void setSizeOfStackReserve(VAR4_8 value); // EXPORT 366 void setSizeOfStackReserve(VAR4_8 value); // EXPORT
367 /// Sets the SizeOfStackCommit value of the header. 367 /// Sets the SizeOfStackCommit value of the header.
368 void setSizeOfStackCommit(VAR4_8 value); // EXPORT 368 void setSizeOfStackCommit(VAR4_8 value); // EXPORT
369 /// Sets the SizeOfHeapReserve value of the header. 369 /// Sets the SizeOfHeapReserve value of the header.
370 void setSizeOfHeapReserve(VAR4_8 value); // EXPORT 370 void setSizeOfHeapReserve(VAR4_8 value); // EXPORT
371 /// Sets the SizeOfHeapCommit value of the header. 371 /// Sets the SizeOfHeapCommit value of the header.
372 void setSizeOfHeapCommit(VAR4_8 value); // EXPORT 372 void setSizeOfHeapCommit(VAR4_8 value); // EXPORT
373 /// Sets the LoaderFlags value of the header. 373 /// Sets the LoaderFlags value of the header.
374 void setLoaderFlags(dword value); // EXPORT 374 void setLoaderFlags(dword value); // EXPORT
375 /// Sets the NumberOfRvaAndSizes value of the header. 375 /// Sets the NumberOfRvaAndSizes value of the header.
376 void setNumberOfRvaAndSizes(dword value); // EXPORT 376 void setNumberOfRvaAndSizes(dword value); // EXPORT
377 377
378// image directory getters 378// image directory getters
379 void setIddDebugRva(dword dwValue); // EXPORT 379 void setIddDebugRva(dword dwValue); // EXPORT
380 void setIddDebugSize(dword dwValue); // EXPORT 380 void setIddDebugSize(dword dwValue); // EXPORT
381 void setIddDelayImportRva(dword dwValue); // EXPORT 381 void setIddDelayImportRva(dword dwValue); // EXPORT
382 void setIddDelayImportSize(dword dwValue); // EXPORT 382 void setIddDelayImportSize(dword dwValue); // EXPORT
383 void setIddExceptionRva(dword dwValue); // EXPORT 383 void setIddExceptionRva(dword dwValue); // EXPORT
384 void setIddExceptionSize(dword dwValue); // EXPORT 384 void setIddExceptionSize(dword dwValue); // EXPORT
385 void setIddGlobalPtrRva(dword dwValue); // EXPORT 385 void setIddGlobalPtrRva(dword dwValue); // EXPORT
386 void setIddGlobalPtrSize(dword dwValue); // EXPORT 386 void setIddGlobalPtrSize(dword dwValue); // EXPORT
387 void setIddIatRva(dword dwValue); // EXPORT 387 void setIddIatRva(dword dwValue); // EXPORT
388 void setIddIatSize(dword dwValue); // EXPORT 388 void setIddIatSize(dword dwValue); // EXPORT
389 void setIddLoadConfigRva(dword dwValue); // EXPORT 389 void setIddLoadConfigRva(dword dwValue); // EXPORT
390 void setIddLoadConfigSize(dword dwValue); // EXPORT 390 void setIddLoadConfigSize(dword dwValue); // EXPORT
391 void setIddResourceRva(dword dwValue); // EXPORT 391 void setIddResourceRva(dword dwValue); // EXPORT
392 void setIddResourceSize(dword dwValue); // EXPORT 392 void setIddResourceSize(dword dwValue); // EXPORT
393 void setIddSecurityRva(dword dwValue); // EXPORT 393 void setIddSecurityRva(dword dwValue); // EXPORT
394 void setIddSecuritySize(dword dwValue); // EXPORT 394 void setIddSecuritySize(dword dwValue); // EXPORT
395 void setIddTlsRva(dword dwValue); // EXPORT 395 void setIddTlsRva(dword dwValue); // EXPORT
396 void setIddTlsSize(dword dwValue); // EXPORT 396 void setIddTlsSize(dword dwValue); // EXPORT
397 397
398 void setIddImportRva(dword dwValue); // EXPORT 398 void setIddImportRva(dword dwValue); // EXPORT
399 void setIddImportSize(dword dwValue); // EXPORT 399 void setIddImportSize(dword dwValue); // EXPORT
400 void setIddExportRva(dword dwValue); // EXPORT 400 void setIddExportRva(dword dwValue); // EXPORT
401 void setIddExportSize(dword dwValue); // EXPORT 401 void setIddExportSize(dword dwValue); // EXPORT
402 402
403 void setIddBaseRelocRva(dword value); // EXPORT 403 void setIddBaseRelocRva(dword value); // EXPORT
404 void setIddBaseRelocSize(dword value); // EXPORT 404 void setIddBaseRelocSize(dword value); // EXPORT
405 void setIddArchitectureRva(dword value); // EXPORT 405 void setIddArchitectureRva(dword value); // EXPORT
406 void setIddArchitectureSize(dword value); // EXPORT 406 void setIddArchitectureSize(dword value); // EXPORT
407 void setIddComHeaderRva(dword value); // EXPORT 407 void setIddComHeaderRva(dword value); // EXPORT
408 void setIddComHeaderSize(dword value); // EXPORT 408 void setIddComHeaderSize(dword value); // EXPORT
409 409
410 /// Set the name of a section. 410 /// Set the name of a section.
411 void setSectionName(word uiSectionnr, std::string strName); // EXPORT 411 void setSectionName(word uiSectionnr, std::string strName); // EXPORT
412 /// Set the virtual size of a section. 412 /// Set the virtual size of a section.
413 void setVirtualSize(word uiSectionnr, dword dwValue); // EXPORT 413 void setVirtualSize(word uiSectionnr, dword dwValue); // EXPORT
414 /// Set the virtual address of a section. 414 /// Set the virtual address of a section.
415 void setVirtualAddress(word uiSectionnr, dword dwValue); // EXPORT 415 void setVirtualAddress(word uiSectionnr, dword dwValue); // EXPORT
416 /// Set the size of raw data of a section. 416 /// Set the size of raw data of a section.
417 void setSizeOfRawData(word uiSectionnr, dword dwValue); // EXPORT 417 void setSizeOfRawData(word uiSectionnr, dword dwValue); // EXPORT
418 /// Set the file offset of a section. 418 /// Set the file offset of a section.
419 void setPointerToRawData(word uiSectionnr, dword dwValue); // EXPORT 419 void setPointerToRawData(word uiSectionnr, dword dwValue); // EXPORT
420 /// Set the pointer to relocations of a section. 420 /// Set the pointer to relocations of a section.
421 void setPointerToRelocations(word uiSectionnr, dword dwValue); // EXPORT 421 void setPointerToRelocations(word uiSectionnr, dword dwValue); // EXPORT
422 /// Set the pointer to linenumbers of a section. 422 /// Set the pointer to linenumbers of a section.
423 void setPointerToLinenumbers(word uiSectionnr, dword dwValue); // EXPORT 423 void setPointerToLinenumbers(word uiSectionnr, dword dwValue); // EXPORT
424 /// Set the number of relocations a section. 424 /// Set the number of relocations a section.
425 void setNumberOfRelocations(word uiSectionnr, dword dwValue); // EXPORT 425 void setNumberOfRelocations(word uiSectionnr, dword dwValue); // EXPORT
426 /// Set the number of linenumbers section. 426 /// Set the number of linenumbers section.
427 void setNumberOfLinenumbers(word uiSectionnr, dword dwValue); // EXPORT 427 void setNumberOfLinenumbers(word uiSectionnr, dword dwValue); // EXPORT
428 /// Set the characteristics of a section. 428 /// Set the characteristics of a section.
429 void setCharacteristics(word uiSectionnr, dword dwValue); // EXPORT 429 void setCharacteristics(word uiSectionnr, dword dwValue); // EXPORT
430 }; 430 };
431 431
432 class PeHeader32 : public PeHeaderT<32> 432 class PeHeader32 : public PeHeaderT<32>
433 { 433 {
434 public: 434 public:
435 /// Returns the BaseOfData value of the header. 435 /// Returns the BaseOfData value of the header.
436 dword getBaseOfData() const; // EXPORT 436 dword getBaseOfData() const; // EXPORT
437 /// Sets the BaseOfData value of the header. 437 /// Sets the BaseOfData value of the header.
438 void setBaseOfData(dword value); // EXPORT 438 void setBaseOfData(dword value); // EXPORT
439 }; 439 };
440 440
441 class PeHeader64 : public PeHeaderT<64> 441 class PeHeader64 : public PeHeaderT<64>
442 { 442 {
443 }; 443 };
444 444
445 template<int x> 445 template<int x>
446 void PeHeaderT<x>::addDataDirectory() 446 void PeHeaderT<x>::addDataDirectory()
447 { 447 {
448 m_inthHeader.dataDirectories.push_back(PELIB_IMAGE_DATA_DIRECTORY()); 448 m_inthHeader.dataDirectories.push_back(PELIB_IMAGE_DATA_DIRECTORY());
449 } 449 }
450 450
451 template<int x> 451 template<int x>
452 void PeHeaderT<x>::removeDataDirectory(dword index) 452 void PeHeaderT<x>::removeDataDirectory(dword index)
453 { 453 {
454 m_inthHeader.dataDirectories.erase(m_inthHeader.dataDirectories.begin() + index); 454 m_inthHeader.dataDirectories.erase(m_inthHeader.dataDirectories.begin() + index);
455 } 455 }
456 456
457 /** 457 /**
458 * Adds a new section to the header. The physical and virtual address as well as the virtual 458 * Adds a new section to the header. The physical and virtual address as well as the virtual
459 * size of the section will be determined automatically from the raw size. The section 459 * size of the section will be determined automatically from the raw size. The section
460 * characteristics will be set to IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ | 460 * characteristics will be set to IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ |
461 * IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_CNT_CODE. All other values will be set to 0. 461 * IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_CNT_CODE. All other values will be set to 0.
462 * Note: It's important that if the current header's FileAlignment and/or SectionAlignment values are 462 * Note: It's important that if the current header's FileAlignment and/or SectionAlignment values are
463 * 0 this function will fail. 463 * 0 this function will fail.
464 * @param strName Name of the new section. If this name is longer than 8 bytes only the first 8 bytes will be used. 464 * @param strName Name of the new section. If this name is longer than 8 bytes only the first 8 bytes will be used.
465 * @param dwSize Physical size of the new section in bytes. 465 * @param dwSize Physical size of the new section in bytes.
466 * \todo Better code that handles files with 0 sections. 466 * \todo Better code that handles files with 0 sections.
467 **/ 467 **/
468 template<int x> 468 template<int x>
469 int PeHeaderT<x>::addSection(const std::string& strName, dword dwSize) 469 int PeHeaderT<x>::addSection(const std::string& strName, dword dwSize)
470 { 470 {
471 unsigned int uiSecnr = calcNumberOfSections(); 471 unsigned int uiSecnr = calcNumberOfSections();
472 472
473 if (!getFileAlignment()) 473 if (!getFileAlignment())
474 { 474 {
475 return ERROR_NO_FILE_ALIGNMENT; 475 return ERROR_NO_FILE_ALIGNMENT;
476 } 476 }
477 else if (!getSectionAlignment()) 477 else if (!getSectionAlignment())
478 { 478 {
479 return ERROR_NO_SECTION_ALIGNMENT; 479 return ERROR_NO_SECTION_ALIGNMENT;
480 } 480 }
481 481
482 if (uiSecnr) // Always allow 1 section. 482 if (uiSecnr) // Always allow 1 section.
483 { 483 {
484 if (uiSecnr == 0xFFFF) 484 if (uiSecnr == 0xFFFF)
485 { 485 {
486 return ERROR_TOO_MANY_SECTIONS; 486 return ERROR_TOO_MANY_SECTIONS;
487 } 487 }
488 else if (calcSpaceAfterHeader() < PELIB_IMAGE_SECTION_HEADER::size()) 488 else if (calcSpaceAfterHeader() < PELIB_IMAGE_SECTION_HEADER::size())
489 { 489 {
490 return ERROR_NOT_ENOUGH_SPACE; 490 return ERROR_NOT_ENOUGH_SPACE;
491 } 491 }
492 } 492 }
493 493
494 dword dwOffset = calcOffset(/*dwSize*/); 494 dword dwOffset = calcOffset(/*dwSize*/);
495 dword dwRva = calcRva(/*dwSize*/); 495 dword dwRva = calcRva(/*dwSize*/);
496 496
497 PELIB_IMAGE_SECTION_HEADER ishdCurr; 497 PELIB_IMAGE_SECTION_HEADER ishdCurr;
498 m_vIsh.push_back(ishdCurr); 498 m_vIsh.push_back(ishdCurr);
499 499
500 setSectionName(uiSecnr, strName); 500 setSectionName(uiSecnr, strName);
501 setSizeOfRawData(uiSecnr, alignOffset(dwSize, getFileAlignment())); 501 setSizeOfRawData(uiSecnr, alignOffset(dwSize, getFileAlignment()));
502 setPointerToRawData(uiSecnr, dwOffset); 502 setPointerToRawData(uiSecnr, dwOffset);
503 setVirtualSize(uiSecnr, alignOffset(dwSize, getSectionAlignment())); 503 setVirtualSize(uiSecnr, alignOffset(dwSize, getSectionAlignment()));
504 setVirtualAddress(uiSecnr, dwRva); 504 setVirtualAddress(uiSecnr, dwRva);
505 setCharacteristics(uiSecnr, PELIB_IMAGE_SCN_MEM_WRITE | PELIB_IMAGE_SCN_MEM_READ | PELIB_IMAGE_SCN_CNT_INITIALIZED_DATA | PELIB_IMAGE_SCN_CNT_CODE); 505 setCharacteristics(uiSecnr, PELIB_IMAGE_SCN_MEM_WRITE | PELIB_IMAGE_SCN_MEM_READ | PELIB_IMAGE_SCN_CNT_INITIALIZED_DATA | PELIB_IMAGE_SCN_CNT_CODE);
506 506
507 return NO_ERROR; 507 return NO_ERROR;
508 } 508 }
509 509
510 /** 510 /**
511 * Calculates a valid SizeOfImage value given the information from the current PE header. 511 * Calculates a valid SizeOfImage value given the information from the current PE header.
512 * Note that this calculation works in Win2K but probably does not work in Win9X. I didn't test that though. 512 * Note that this calculation works in Win2K but probably does not work in Win9X. I didn't test that though.
513 * @return Valid SizeOfImage value. 513 * @return Valid SizeOfImage value.
514 **/ 514 **/
515 template<int x> 515 template<int x>
516 unsigned int PeHeaderT<x>::calcSizeOfImage() const 516 unsigned int PeHeaderT<x>::calcSizeOfImage() const
517 { 517 {
518 // Major note here: It's possible for sections to exist with a Virtual Size of 0. 518 // Major note here: It's possible for sections to exist with a Virtual Size of 0.
519 // That's why it's necessary to use std::max(Vsize, RawSize) here. 519 // That's why it's necessary to use std::max(Vsize, RawSize) here.
520 // An example for such a file is dbeng6.exe (made by Sybase). 520 // An example for such a file is dbeng6.exe (made by Sybase).
521 // In this file each and every section has a VSize of 0 but it still runs. 521 // In this file each and every section has a VSize of 0 but it still runs.
522 522
523 std::vector<PELIB_IMAGE_SECTION_HEADER>::const_iterator ishLastSection = std::max_element(m_vIsh.begin(), m_vIsh.end(), std::mem_fun_ref(&PELIB_IMAGE_SECTION_HEADER::biggerVirtualAddress)); 523 std::vector<PELIB_IMAGE_SECTION_HEADER>::const_iterator ishLastSection = std::max_element(m_vIsh.begin(), m_vIsh.end(), std::mem_fun_ref(&PELIB_IMAGE_SECTION_HEADER::biggerVirtualAddress));
524 if (ishLastSection->VirtualSize != 0) return ishLastSection->VirtualAddress + ishLastSection->VirtualSize; 524 if (ishLastSection->VirtualSize != 0) return ishLastSection->VirtualAddress + ishLastSection->VirtualSize;
525 return ishLastSection->VirtualAddress + std::max(ishLastSection->VirtualSize, ishLastSection->SizeOfRawData); 525 return ishLastSection->VirtualAddress + std::max(ishLastSection->VirtualSize, ishLastSection->SizeOfRawData);
526 } 526 }
527 527
528 /** 528 /**
529 * Calculates the space between the last byte of the header and the first byte that's used for something 529 * Calculates the space between the last byte of the header and the first byte that's used for something
530 * else (that's either the first section or an image directory). 530 * else (that's either the first section or an image directory).
531 * @return Unused space after the header. 531 * @return Unused space after the header.
532 * \todo There are PE files with sections beginning at offset 0. They 532 * \todo There are PE files with sections beginning at offset 0. They
533 * need to be considered. 533 * need to be considered.
534 **/ 534 **/
535 template<int x> 535 template<int x>
536 unsigned int PeHeaderT<x>::calcSpaceAfterHeader() const 536 unsigned int PeHeaderT<x>::calcSpaceAfterHeader() const
537 { 537 {
538 return (calcStartOfCode() > size() + m_uiOffset) ? calcStartOfCode() - (size() + m_uiOffset) : 0; 538 return (calcStartOfCode() > size() + m_uiOffset) ? calcStartOfCode() - (size() + m_uiOffset) : 0;
539 } 539 }
540 540
541 /** 541 /**
542 * Returns the first offset of the file that's actually used for something different than the header. 542 * Returns the first offset of the file that's actually used for something different than the header.
543 * That something is not necessarily code, it can be a data directory too. 543 * That something is not necessarily code, it can be a data directory too.
544 * This offset can be the beginning of a section or the beginning of a directory. 544 * This offset can be the beginning of a section or the beginning of a directory.
545 * \todo Some optimizization is surely possible here. 545 * \todo Some optimizization is surely possible here.
546 * \todo There are PE files with sections beginning at offset 0. They 546 * \todo There are PE files with sections beginning at offset 0. They
547 * need to be considered. Returning 0 for these files doesn't really make sense. 547 * need to be considered. Returning 0 for these files doesn't really make sense.
548 * So far these sections are disregarded. 548 * So far these sections are disregarded.
549 **/ 549 **/
550 template<int x> 550 template<int x>
551 unsigned int PeHeaderT<x>::calcStartOfCode() const 551 unsigned int PeHeaderT<x>::calcStartOfCode() const
552 { 552 {
553 unsigned int directories = calcNumberOfRvaAndSizes(); 553 unsigned int directories = calcNumberOfRvaAndSizes();
554 dword dwMinOffset = 0xFFFFFFFF; 554 dword dwMinOffset = 0xFFFFFFFF;
555 if (directories >= 1 && getIddExportRva() && rvaToOffset(getIddExportRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddExportRva()); 555 if (directories >= 1 && getIddExportRva() && rvaToOffset(getIddExportRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddExportRva());
556 if (directories >= 2 && getIddImportRva() && rvaToOffset(getIddImportRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddImportRva()); 556 if (directories >= 2 && getIddImportRva() && rvaToOffset(getIddImportRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddImportRva());
557 if (directories >= 3 && getIddResourceRva() && rvaToOffset(getIddResourceRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddResourceRva()); 557 if (directories >= 3 && getIddResourceRva() && rvaToOffset(getIddResourceRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddResourceRva());
558 if (directories >= 4 && getIddExceptionRva() && rvaToOffset(getIddExceptionRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddExceptionRva()); 558 if (directories >= 4 && getIddExceptionRva() && rvaToOffset(getIddExceptionRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddExceptionRva());
559 if (directories >= 5 && getIddSecurityRva() && rvaToOffset(getIddSecurityRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddSecurityRva()); 559 if (directories >= 5 && getIddSecurityRva() && rvaToOffset(getIddSecurityRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddSecurityRva());
560 if (directories >= 6 && getIddBaseRelocRva() && rvaToOffset(getIddBaseRelocRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddBaseRelocRva()); 560 if (directories >= 6 && getIddBaseRelocRva() && rvaToOffset(getIddBaseRelocRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddBaseRelocRva());
561 if (directories >= 7 && getIddDebugRva() && rvaToOffset(getIddDebugRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddDebugRva()); 561 if (directories >= 7 && getIddDebugRva() && rvaToOffset(getIddDebugRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddDebugRva());
562 if (directories >= 8 && getIddArchitectureRva() && rvaToOffset(getIddArchitectureRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddArchitectureRva()); 562 if (directories >= 8 && getIddArchitectureRva() && rvaToOffset(getIddArchitectureRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddArchitectureRva());
563 if (directories >= 9 && getIddGlobalPtrRva() && rvaToOffset(getIddGlobalPtrRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddGlobalPtrRva()); 563 if (directories >= 9 && getIddGlobalPtrRva() && rvaToOffset(getIddGlobalPtrRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddGlobalPtrRva());
564 if (directories >= 10 && getIddTlsRva() && rvaToOffset(getIddTlsRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddTlsRva()); 564 if (directories >= 10 && getIddTlsRva() && rvaToOffset(getIddTlsRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddTlsRva());
565 if (directories >= 11 && getIddLoadConfigRva() && rvaToOffset(getIddLoadConfigRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddLoadConfigRva()); 565 if (directories >= 11 && getIddLoadConfigRva() && rvaToOffset(getIddLoadConfigRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddLoadConfigRva());
566 if (directories >= 12 && getIddBoundImportRva() && rvaToOffset(getIddBoundImportRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddBoundImportRva()); 566 if (directories >= 12 && getIddBoundImportRva() && rvaToOffset(getIddBoundImportRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddBoundImportRva());
567 if (directories >= 13 && getIddIatRva() && rvaToOffset(getIddIatRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddIatRva()); 567 if (directories >= 13 && getIddIatRva() && rvaToOffset(getIddIatRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddIatRva());
568 if (directories >= 14 && getIddDelayImportRva() && rvaToOffset(getIddDelayImportRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddDelayImportRva()); 568 if (directories >= 14 && getIddDelayImportRva() && rvaToOffset(getIddDelayImportRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddDelayImportRva());
569 if (directories >= 15 && getIddComHeaderRva() && rvaToOffset(getIddComHeaderRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddComHeaderRva()); 569 if (directories >= 15 && getIddComHeaderRva() && rvaToOffset(getIddComHeaderRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddComHeaderRva());
570 570
571 for (word i=0;i<calcNumberOfSections();i++) 571 for (word i=0;i<calcNumberOfSections();i++)
572 { 572 {
573 if ((getPointerToRawData(i) < dwMinOffset || dwMinOffset == 0xFFFFFFFF) && getSizeOfRawData(i)) 573 if ((getPointerToRawData(i) < dwMinOffset || dwMinOffset == 0xFFFFFFFF) && getSizeOfRawData(i))
574 { 574 {
575 if (getPointerToRawData(i)) dwMinOffset = getPointerToRawData(i); 575 if (getPointerToRawData(i)) dwMinOffset = getPointerToRawData(i);
576 } 576 }
577 } 577 }
578 return dwMinOffset; 578 return dwMinOffset;
579 } 579 }
580 580
581 /** 581 /**
582 * Calculates the file offset for a new section. The file offset will already be aligned to the file's FileAlignment. 582 * Calculates the file offset for a new section. The file offset will already be aligned to the file's FileAlignment.
583 * @return Aligned file offset. 583 * @return Aligned file offset.
584 * \todo uiSize isn't used yet. Will be used later on to search for caves. 584 * \todo uiSize isn't used yet. Will be used later on to search for caves.
585 **/ 585 **/
586 template<int x> 586 template<int x>
587 unsigned int PeHeaderT<x>::calcOffset(/*unsigned int uiSize*/) const 587 unsigned int PeHeaderT<x>::calcOffset(/*unsigned int uiSize*/) const
588 { 588 {
589 unsigned int maxoffset = size(); 589 unsigned int maxoffset = size();
590 590
591 for (word i=0;i<calcNumberOfSections();i++) 591 for (word i=0;i<calcNumberOfSections();i++)
592 { 592 {
593 if (getPointerToRawData(i) + getSizeOfRawData(i) > maxoffset) maxoffset = getPointerToRawData(i) + getSizeOfRawData(i); 593 if (getPointerToRawData(i) + getSizeOfRawData(i) > maxoffset) maxoffset = getPointerToRawData(i) + getSizeOfRawData(i);
594 } 594 }
595 595
596 return alignOffset(maxoffset, getFileAlignment()); 596 return alignOffset(maxoffset, getFileAlignment());
597 } 597 }
598 598
599 /** 599 /**
600 * Calculates the Rva for a new section. The Rva will already be aligned to the file's SectionAlignment. 600 * Calculates the Rva for a new section. The Rva will already be aligned to the file's SectionAlignment.
601 * \todo uiSize isn't used yet. Will be used later on to search for caves. 601 * \todo uiSize isn't used yet. Will be used later on to search for caves.
602 * @return Aligned Rva. 602 * @return Aligned Rva.
603 **/ 603 **/
604 template<int x> 604 template<int x>
605 unsigned int PeHeaderT<x>::calcRva(/*unsigned int uiSize*/) const 605 unsigned int PeHeaderT<x>::calcRva(/*unsigned int uiSize*/) const
606 { 606 {
607 // Major note here: It's possible for sections to exist with a Virtual Size of 0. 607 // Major note here: It's possible for sections to exist with a Virtual Size of 0.
608 // That's why it's necessary to use std::max(Vsize, RawSize) here. 608 // That's why it's necessary to use std::max(Vsize, RawSize) here.
609 // An example for such a file is dbeng6.exe (made by Sybase). 609 // An example for such a file is dbeng6.exe (made by Sybase).
610 // In this file each and every section has a VSize of 0 but it still runs. 610 // In this file each and every section has a VSize of 0 but it still runs.
611 611
612 unsigned int maxoffset = size(); 612 unsigned int maxoffset = size();
613 for (word i=0;i<calcNumberOfSections();i++) 613 for (word i=0;i<calcNumberOfSections();i++)
614 { 614 {
615 if (getVirtualAddress(i) + std::max(getVirtualSize(i), getSizeOfRawData(i)) > maxoffset) maxoffset = getVirtualAddress(i) + std::max(getVirtualSize(i), getSizeOfRawData(i)); 615 if (getVirtualAddress(i) + std::max(getVirtualSize(i), getSizeOfRawData(i)) > maxoffset) maxoffset = getVirtualAddress(i) + std::max(getVirtualSize(i), getSizeOfRawData(i));
616 } 616 }
617 617
618 return alignOffset(maxoffset, getSectionAlignment()); 618 return alignOffset(maxoffset, getSectionAlignment());
619 } 619 }
620 620
621 /** 621 /**
622 * Returns the number of currently defined sections. Note that this value can be different from the number 622 * Returns the number of currently defined sections. Note that this value can be different from the number
623 * of sections according to the header (see #PeLib::PeHeaderT<x>::getNumberOfSections). 623 * of sections according to the header (see #PeLib::PeHeaderT<x>::getNumberOfSections).
624 * @return Number of currently defined sections. 624 * @return Number of currently defined sections.
625 **/ 625 **/
626 template<int x> 626 template<int x>
627 word PeHeaderT<x>::calcNumberOfSections() const 627 word PeHeaderT<x>::calcNumberOfSections() const
628 { 628 {
629 return static_cast<PeLib::word>(m_vIsh.size()); 629 return static_cast<PeLib::word>(m_vIsh.size());
630 } 630 }
631 631
632 /** 632 /**
633 * Enlarges the physically last section in the file. 633 * Enlarges the physically last section in the file.
634 * @param uiSize Additional size that's added to the section's size. 634 * @param uiSize Additional size that's added to the section's size.
635 **/ 635 **/
636 template<int x> 636 template<int x>
637 void PeHeaderT<x>::enlargeLastSection(unsigned int uiSize) 637 void PeHeaderT<x>::enlargeLastSection(unsigned int uiSize)
638 { 638 {
639 std::vector<PELIB_IMAGE_SECTION_HEADER>::iterator ishLastSection = std::max_element(m_vIsh.begin(), m_vIsh.end(), std::mem_fun_ref(&PELIB_IMAGE_SECTION_HEADER::biggerFileOffset)); 639 std::vector<PELIB_IMAGE_SECTION_HEADER>::iterator ishLastSection = std::max_element(m_vIsh.begin(), m_vIsh.end(), std::mem_fun_ref(&PELIB_IMAGE_SECTION_HEADER::biggerFileOffset));
640 unsigned int uiRawDataSize = alignOffset(ishLastSection->SizeOfRawData + uiSize, getFileAlignment()); 640 unsigned int uiRawDataSize = alignOffset(ishLastSection->SizeOfRawData + uiSize, getFileAlignment());
641 641
642 ishLastSection->SizeOfRawData = uiRawDataSize; 642 ishLastSection->SizeOfRawData = uiRawDataSize;
643 ishLastSection->VirtualSize = ishLastSection->SizeOfRawData; 643 ishLastSection->VirtualSize = ishLastSection->SizeOfRawData;
644 644
645 setSizeOfImage(calcSizeOfImage()); 645 setSizeOfImage(calcSizeOfImage());
646 } 646 }
647 647
648 /** 648 /**
649 * Determines the section which contains the file offset. 649 * Determines the section which contains the file offset.
650 * @param dwOffset File offset. 650 * @param dwOffset File offset.
651 * @return Section Id of the section which contains the offset. 651 * @return Section Id of the section which contains the offset.
652 **/ 652 **/
653 template<int x> 653 template<int x>
654 word PeHeaderT<x>::getSectionWithOffset(VAR4_8 dwOffset) const 654 word PeHeaderT<x>::getSectionWithOffset(VAR4_8 dwOffset) const
655 { 655 {
656 // Offset = 0 must be handled explicitly as there are files 656 // Offset = 0 must be handled explicitly as there are files
657 // with sections that begin at offset 0, that means the section 657 // with sections that begin at offset 0, that means the section
658 // only exists in memory. 658 // only exists in memory.
659 659
660 if (!dwOffset) return std::numeric_limits<word>::max(); 660 if (!dwOffset) return std::numeric_limits<word>::max();
661 661
662 for (word i=0;i<calcNumberOfSections();i++) 662 for (word i=0;i<calcNumberOfSections();i++)
663 { 663 {
664 // Explicity exclude sections with raw pointer = 0. 664 // Explicity exclude sections with raw pointer = 0.
665 dword rawptr = getPointerToRawData(i); 665 dword rawptr = getPointerToRawData(i);
666 if (rawptr && rawptr <= dwOffset && rawptr + getSizeOfRawData(i) > dwOffset) return i; 666 if (rawptr && rawptr <= dwOffset && rawptr + getSizeOfRawData(i) > dwOffset) return i;
667 } 667 }
668 668
669 return std::numeric_limits<word>::max(); 669 return std::numeric_limits<word>::max();
670 } 670 }
671 671
672 /** 672 /**
673 * Determines the section which contains the Rva. 673 * Determines the section which contains the Rva.
674 * @param dwRva A relative virtual address. 674 * @param dwRva A relative virtual address.
675 * @return Section Id of the section which contains the Rva. 675 * @return Section Id of the section which contains the Rva.
676 **/ 676 **/
677 template<int x> 677 template<int x>
678 word PeHeaderT<x>::getSectionWithRva(VAR4_8 dwRva) const 678 word PeHeaderT<x>::getSectionWithRva(VAR4_8 dwRva) const
679 { 679 {
680 // Major note here: It's possible for sections to exist with a Virtual Size of 0. 680 // Major note here: It's possible for sections to exist with a Virtual Size of 0.
681 // That's why it's necessary to use std::max(Vsize, RawSize) here. 681 // That's why it's necessary to use std::max(Vsize, RawSize) here.
682 // An example for such a file is dbeng6.exe (made by Sybase). 682 // An example for such a file is dbeng6.exe (made by Sybase).
683 // In this file each and every section has a VSize of 0 but it still runs. 683 // In this file each and every section has a VSize of 0 but it still runs.
684 684
685 for (word i=0;i<calcNumberOfSections();i++) 685 for (word i=0;i<calcNumberOfSections();i++)
686 { 686 {
687 // Weird VC++7 error doesn't allow me to use std::max here. 687 // Weird VC++7 error doesn't allow me to use std::max here.
688 dword max = getVirtualSize(i) >= getSizeOfRawData(i) ? getVirtualSize(i) : getSizeOfRawData(i); 688 dword max = getVirtualSize(i) >= getSizeOfRawData(i) ? getVirtualSize(i) : getSizeOfRawData(i);
689 if (getVirtualAddress(i) <= dwRva && getVirtualAddress(i) + max > dwRva) return i; 689 if (getVirtualAddress(i) <= dwRva && getVirtualAddress(i) + max > dwRva) return i;
690 } 690 }
691 691
692 return -1; 692 return -1;
693 } 693 }
694 694
695 /** 695 /**
696 * Corrects all faulty values of the current PE header. The following values will be corrected: NtSignature, 696 * Corrects all faulty values of the current PE header. The following values will be corrected: NtSignature,
697 * NumberOfSections, SizeOfOptionalHeader, FileAlignment (will be aligned to n*0x200), 697 * NumberOfSections, SizeOfOptionalHeader, FileAlignment (will be aligned to n*0x200),
698 * SectionAlignment (will be aligned to n*0x1000), NumberOfRvaAndSizes, SizeOfHeaders, SizeOfImage, 698 * SectionAlignment (will be aligned to n*0x1000), NumberOfRvaAndSizes, SizeOfHeaders, SizeOfImage,
699 * Magic, Characteristics. 699 * Magic, Characteristics.
700 * @param dwOffset Beginning of PeHeader (see #PeLib::MzHeader::getAddressOfPeHeader). 700 * @param dwOffset Beginning of PeHeader (see #PeLib::MzHeader::getAddressOfPeHeader).
701 * \todo 32bit and 64bit versions. 701 * \todo 32bit and 64bit versions.
702 **/ 702 **/
703 template<int x> 703 template<int x>
704 void PeHeaderT<x>::makeValid(dword dwOffset) 704 void PeHeaderT<x>::makeValid(dword dwOffset)
705 { 705 {
706 setNtSignature(PELIB_IMAGE_NT_SIGNATURE); // 'PE' 706 setNtSignature(PELIB_IMAGE_NT_SIGNATURE); // 'PE'
707 setMachine(PELIB_IMAGE_FILE_MACHINE_I386); 707 setMachine(PELIB_IMAGE_FILE_MACHINE_I386);
708 setNumberOfSections(calcNumberOfSections()); 708 setNumberOfSections(calcNumberOfSections());
709 709
710 // Check if 64 bits. 710 // Check if 64 bits.
711 setSizeOfOptionalHeader(PELIB_IMAGE_OPTIONAL_HEADER<x>::size() + calcNumberOfRvaAndSizes() * 8); 711 setSizeOfOptionalHeader(PELIB_IMAGE_OPTIONAL_HEADER<x>::size() + calcNumberOfRvaAndSizes() * 8);
712 712
713 // Check if 64 bits. 713 // Check if 64 bits.
714 dword dwCharacteristics = PELIB_IMAGE_FILE_EXECUTABLE_IMAGE | PELIB_IMAGE_FILE_32BIT_MACHINE; 714 dword dwCharacteristics = PELIB_IMAGE_FILE_EXECUTABLE_IMAGE | PELIB_IMAGE_FILE_32BIT_MACHINE;
715 setCharacteristics(dwCharacteristics); 715 setCharacteristics(dwCharacteristics);
716 716
717 // Check if 64 bits. 717 // Check if 64 bits.
718 setMagic(PELIB_IMAGE_NT_OPTIONAL_HDR32_MAGIC); 718 setMagic(PELIB_IMAGE_NT_OPTIONAL_HDR32_MAGIC);
719 719
720 // setImageBase(0x01000000); 720 // setImageBase(0x01000000);
721 721
722 // Align file and section alignment values 722 // Align file and section alignment values
723 unsigned int dwAlignedOffset = alignOffset(getSectionAlignment(), 0x1000); 723 unsigned int dwAlignedOffset = alignOffset(getSectionAlignment(), 0x1000);
724 setSectionAlignment(dwAlignedOffset ? dwAlignedOffset : 0x1000); 724 setSectionAlignment(dwAlignedOffset ? dwAlignedOffset : 0x1000);
725 725
726 dwAlignedOffset = alignOffset(getFileAlignment(), 0x200); 726 dwAlignedOffset = alignOffset(getFileAlignment(), 0x200);
727 setFileAlignment(dwAlignedOffset ? dwAlignedOffset : 0x200); 727 setFileAlignment(dwAlignedOffset ? dwAlignedOffset : 0x200);
728 728
729// setMajorSubsystemVersion(4); 729// setMajorSubsystemVersion(4);
730// setSubsystem(IMAGE_SUBSYSTEM_WINDOWS_GUI); 730// setSubsystem(IMAGE_SUBSYSTEM_WINDOWS_GUI);
731 setNumberOfRvaAndSizes(calcNumberOfRvaAndSizes()); 731 setNumberOfRvaAndSizes(calcNumberOfRvaAndSizes());
732 732
733 // Code below depends on code above. Don't change the order. 733 // Code below depends on code above. Don't change the order.
734 dword dwSizeOfHeaders = alignOffset(dwOffset + size(), getFileAlignment()); 734 dword dwSizeOfHeaders = alignOffset(dwOffset + size(), getFileAlignment());
735 setSizeOfHeaders(dwSizeOfHeaders); 735 setSizeOfHeaders(dwSizeOfHeaders);
736 736
737 dword dwSizeOfImage = alignOffset(dwSizeOfHeaders, getSectionAlignment()); 737 dword dwSizeOfImage = alignOffset(dwSizeOfHeaders, getSectionAlignment());
738 738
739 for (int i=0;i<calcNumberOfSections();i++) 739 for (int i=0;i<calcNumberOfSections();i++)
740 { 740 {
741 dwSizeOfImage += alignOffset(getVirtualSize(i), getSectionAlignment()); 741 dwSizeOfImage += alignOffset(getVirtualSize(i), getSectionAlignment());
742 } 742 }
743 743
744 dwSizeOfImage = alignOffset(dwSizeOfImage, getSectionAlignment()); 744 dwSizeOfImage = alignOffset(dwSizeOfImage, getSectionAlignment());
745 setSizeOfImage(dwSizeOfImage); 745 setSizeOfImage(dwSizeOfImage);
746 } 746 }
747 747
748 template<int x> 748 template<int x>
749 unsigned int PeHeaderT<x>::offsetToRva(VAR4_8 dwOffset) const 749 unsigned int PeHeaderT<x>::offsetToRva(VAR4_8 dwOffset) const
750 { 750 {
751 if (dwOffset < calcStartOfCode()) return dwOffset; 751 if (dwOffset < calcStartOfCode()) return dwOffset;
752 752
753 PeLib::word uiSecnr = getSectionWithOffset(dwOffset); 753 PeLib::word uiSecnr = getSectionWithOffset(dwOffset);
754 754
755 if (uiSecnr == 0xFFFF) return -1; 755 if (uiSecnr == 0xFFFF) return -1;
756 756
757 return getVirtualAddress(uiSecnr) + dwOffset - getPointerToRawData(uiSecnr); 757 return getVirtualAddress(uiSecnr) + dwOffset - getPointerToRawData(uiSecnr);
758 } 758 }
759 759
760 /** 760 /**
761 * Converts a file offset to a virtual address. 761 * Converts a file offset to a virtual address.
762 * @param dwOffset File offset. 762 * @param dwOffset File offset.
763 * @return Virtual Address. 763 * @return Virtual Address.
764 **/ 764 **/
765 template<int x> 765 template<int x>
766 unsigned int PeHeaderT<x>::offsetToVa(VAR4_8 dwOffset) const 766 unsigned int PeHeaderT<x>::offsetToVa(VAR4_8 dwOffset) const
767 { 767 {
768 if (dwOffset < calcStartOfCode()) return getImageBase() + dwOffset; 768 if (dwOffset < calcStartOfCode()) return getImageBase() + dwOffset;
769 769
770 PeLib::word uiSecnr = getSectionWithOffset(dwOffset); 770 PeLib::word uiSecnr = getSectionWithOffset(dwOffset);
771 771
772 if (uiSecnr == 0xFFFF) return -1; 772 if (uiSecnr == 0xFFFF) return -1;
773 773
774 return getImageBase() + getVirtualAddress(uiSecnr) + dwOffset - getPointerToRawData(uiSecnr); 774 return getImageBase() + getVirtualAddress(uiSecnr) + dwOffset - getPointerToRawData(uiSecnr);
775 } 775 }
776 776
777 template<int x> 777 template<int x>
778 void PeHeaderT<x>::readHeader(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const 778 void PeHeaderT<x>::readHeader(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const
779 { 779 {
780 ibBuffer >> header.Signature; 780 ibBuffer >> header.Signature;
781 781
782 ibBuffer >> header.FileHeader.Machine; 782 ibBuffer >> header.FileHeader.Machine;
783 ibBuffer >> header.FileHeader.NumberOfSections; 783 ibBuffer >> header.FileHeader.NumberOfSections;
784 ibBuffer >> header.FileHeader.TimeDateStamp; 784 ibBuffer >> header.FileHeader.TimeDateStamp;
785 ibBuffer >> header.FileHeader.PointerToSymbolTable; 785 ibBuffer >> header.FileHeader.PointerToSymbolTable;
786 ibBuffer >> header.FileHeader.NumberOfSymbols; 786 ibBuffer >> header.FileHeader.NumberOfSymbols;
787 ibBuffer >> header.FileHeader.SizeOfOptionalHeader; 787 ibBuffer >> header.FileHeader.SizeOfOptionalHeader;
788 ibBuffer >> header.FileHeader.Characteristics; 788 ibBuffer >> header.FileHeader.Characteristics;
789 ibBuffer >> header.OptionalHeader.Magic; 789 ibBuffer >> header.OptionalHeader.Magic;
790 790
791 ibBuffer >> header.OptionalHeader.MajorLinkerVersion; 791 ibBuffer >> header.OptionalHeader.MajorLinkerVersion;
792 ibBuffer >> header.OptionalHeader.MinorLinkerVersion; 792 ibBuffer >> header.OptionalHeader.MinorLinkerVersion;
793 ibBuffer >> header.OptionalHeader.SizeOfCode; 793 ibBuffer >> header.OptionalHeader.SizeOfCode;
794 ibBuffer >> header.OptionalHeader.SizeOfInitializedData; 794 ibBuffer >> header.OptionalHeader.SizeOfInitializedData;
795 ibBuffer >> header.OptionalHeader.SizeOfUninitializedData; 795 ibBuffer >> header.OptionalHeader.SizeOfUninitializedData;
796 ibBuffer >> header.OptionalHeader.AddressOfEntryPoint; 796 ibBuffer >> header.OptionalHeader.AddressOfEntryPoint;
797 ibBuffer >> header.OptionalHeader.BaseOfCode; 797 ibBuffer >> header.OptionalHeader.BaseOfCode;
798 readBaseOfData(ibBuffer, header); 798 readBaseOfData(ibBuffer, header);
799 ibBuffer >> header.OptionalHeader.ImageBase; 799 ibBuffer >> header.OptionalHeader.ImageBase;
800 ibBuffer >> header.OptionalHeader.SectionAlignment; 800 ibBuffer >> header.OptionalHeader.SectionAlignment;
801 ibBuffer >> header.OptionalHeader.FileAlignment; 801 ibBuffer >> header.OptionalHeader.FileAlignment;
802 ibBuffer >> header.OptionalHeader.MajorOperatingSystemVersion; 802 ibBuffer >> header.OptionalHeader.MajorOperatingSystemVersion;
803 ibBuffer >> header.OptionalHeader.MinorOperatingSystemVersion; 803 ibBuffer >> header.OptionalHeader.MinorOperatingSystemVersion;
804 ibBuffer >> header.OptionalHeader.MajorImageVersion; 804 ibBuffer >> header.OptionalHeader.MajorImageVersion;
805 ibBuffer >> header.OptionalHeader.MinorImageVersion; 805 ibBuffer >> header.OptionalHeader.MinorImageVersion;
806 ibBuffer >> header.OptionalHeader.MajorSubsystemVersion; 806 ibBuffer >> header.OptionalHeader.MajorSubsystemVersion;
807 ibBuffer >> header.OptionalHeader.MinorSubsystemVersion; 807 ibBuffer >> header.OptionalHeader.MinorSubsystemVersion;
808 ibBuffer >> header.OptionalHeader.Win32VersionValue; 808 ibBuffer >> header.OptionalHeader.Win32VersionValue;
809 ibBuffer >> header.OptionalHeader.SizeOfImage; 809 ibBuffer >> header.OptionalHeader.SizeOfImage;
810 ibBuffer >> header.OptionalHeader.SizeOfHeaders; 810 ibBuffer >> header.OptionalHeader.SizeOfHeaders;
811 ibBuffer >> header.OptionalHeader.CheckSum; 811 ibBuffer >> header.OptionalHeader.CheckSum;
812 ibBuffer >> header.OptionalHeader.Subsystem; 812 ibBuffer >> header.OptionalHeader.Subsystem;
813 ibBuffer >> header.OptionalHeader.DllCharacteristics; 813 ibBuffer >> header.OptionalHeader.DllCharacteristics;
814 ibBuffer >> header.OptionalHeader.SizeOfStackReserve; 814 ibBuffer >> header.OptionalHeader.SizeOfStackReserve;
815 ibBuffer >> header.OptionalHeader.SizeOfStackCommit; 815 ibBuffer >> header.OptionalHeader.SizeOfStackCommit;
816 ibBuffer >> header.OptionalHeader.SizeOfHeapReserve; 816 ibBuffer >> header.OptionalHeader.SizeOfHeapReserve;
817 ibBuffer >> header.OptionalHeader.SizeOfHeapCommit; 817 ibBuffer >> header.OptionalHeader.SizeOfHeapCommit;
818 ibBuffer >> header.OptionalHeader.LoaderFlags; 818 ibBuffer >> header.OptionalHeader.LoaderFlags;
819 ibBuffer >> header.OptionalHeader.NumberOfRvaAndSizes; 819 ibBuffer >> header.OptionalHeader.NumberOfRvaAndSizes;
820 } 820 }
821 821
822 template<int x> 822 template<int x>
823 void PeHeaderT<x>::readDataDirectories(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const 823 void PeHeaderT<x>::readDataDirectories(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const
824 { 824 {
825 PELIB_IMAGE_DATA_DIRECTORY idd; 825 PELIB_IMAGE_DATA_DIRECTORY idd;
826 826
827 for (unsigned int i=0;i<header.OptionalHeader.NumberOfRvaAndSizes;i++) 827 for (unsigned int i=0;i<header.OptionalHeader.NumberOfRvaAndSizes;i++)
828 { 828 {
829 ibBuffer >> idd.VirtualAddress; 829 ibBuffer >> idd.VirtualAddress;
830 ibBuffer >> idd.Size; 830 ibBuffer >> idd.Size;
831 header.dataDirectories.push_back(idd); 831 header.dataDirectories.push_back(idd);
832 } 832 }
833 } 833 }
834 834
835 template<int x> 835 template<int x>
836 std::vector<PELIB_IMAGE_SECTION_HEADER> PeHeaderT<x>::readSections(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const 836 std::vector<PELIB_IMAGE_SECTION_HEADER> PeHeaderT<x>::readSections(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const
837 { 837 {
838 const unsigned int nrSections = header.FileHeader.NumberOfSections; 838 const unsigned int nrSections = header.FileHeader.NumberOfSections;
839 PELIB_IMAGE_SECTION_HEADER ishCurr; 839 PELIB_IMAGE_SECTION_HEADER ishCurr;
840 840
841 std::vector<PELIB_IMAGE_SECTION_HEADER> vIshdCurr; 841 std::vector<PELIB_IMAGE_SECTION_HEADER> vIshdCurr;
842 842
843 for (unsigned int i=0;i<nrSections;i++) 843 for (unsigned int i=0;i<nrSections;i++)
844 { 844 {
845 ibBuffer.read(reinterpret_cast<char*>(ishCurr.Name), 8); 845 ibBuffer.read(reinterpret_cast<char*>(ishCurr.Name), 8);
846 ibBuffer >> ishCurr.VirtualSize; 846 ibBuffer >> ishCurr.VirtualSize;
847 ibBuffer >> ishCurr.VirtualAddress; 847 ibBuffer >> ishCurr.VirtualAddress;
848 ibBuffer >> ishCurr.SizeOfRawData; 848 ibBuffer >> ishCurr.SizeOfRawData;
849 ibBuffer >> ishCurr.PointerToRawData; 849 ibBuffer >> ishCurr.PointerToRawData;
850 ibBuffer >> ishCurr.PointerToRelocations; 850 ibBuffer >> ishCurr.PointerToRelocations;
851 ibBuffer >> ishCurr.PointerToLinenumbers; 851 ibBuffer >> ishCurr.PointerToLinenumbers;
852 ibBuffer >> ishCurr.NumberOfRelocations; 852 ibBuffer >> ishCurr.NumberOfRelocations;
853 ibBuffer >> ishCurr.NumberOfLinenumbers; 853 ibBuffer >> ishCurr.NumberOfLinenumbers;
854 ibBuffer >> ishCurr.Characteristics; 854 ibBuffer >> ishCurr.Characteristics;
855 vIshdCurr.push_back(ishCurr); 855 vIshdCurr.push_back(ishCurr);
856 } 856 }
857 857
858 return vIshdCurr; 858 return vIshdCurr;
859 } 859 }
860 860
861 template<int x> 861 template<int x>
862 int PeHeaderT<x>::read(const unsigned char* pcBuffer, unsigned int uiSize, unsigned int uiOffset) 862 int PeHeaderT<x>::read(const unsigned char* pcBuffer, unsigned int uiSize, unsigned int uiOffset)
863 { 863 {
864 if (uiSize < m_inthHeader.size()) 864 if (uiSize < m_inthHeader.size())
865 { 865 {
866 return ERROR_INVALID_FILE; 866 return ERROR_INVALID_FILE;
867 } 867 }
868 868
869 std::vector<unsigned char> vBuffer(pcBuffer, pcBuffer + m_inthHeader.size()); 869 std::vector<unsigned char> vBuffer(pcBuffer, pcBuffer + m_inthHeader.size());
870 870
871 InputBuffer ibBuffer(vBuffer); 871 InputBuffer ibBuffer(vBuffer);
872 PELIB_IMAGE_NT_HEADERS<x> header; 872 PELIB_IMAGE_NT_HEADERS<x> header;
873 873
874 readHeader(ibBuffer, header); 874 readHeader(ibBuffer, header);
875 875
876 if (uiSize < m_inthHeader.size() + header.OptionalHeader.NumberOfRvaAndSizes * 8 + header.FileHeader.NumberOfSections * 0x28) 876 if (uiSize < m_inthHeader.size() + header.OptionalHeader.NumberOfRvaAndSizes * 8 + header.FileHeader.NumberOfSections * 0x28)
877 { 877 {
878 return ERROR_INVALID_FILE; 878 return ERROR_INVALID_FILE;
879 } 879 }
880 880
881 vBuffer.resize(header.OptionalHeader.NumberOfRvaAndSizes * 8 + header.FileHeader.NumberOfSections * 0x28); 881 vBuffer.resize(header.OptionalHeader.NumberOfRvaAndSizes * 8 + header.FileHeader.NumberOfSections * 0x28);
882 vBuffer.assign(pcBuffer + m_inthHeader.size(), pcBuffer + m_inthHeader.size() + header.OptionalHeader.NumberOfRvaAndSizes * 8 + header.FileHeader.NumberOfSections * 0x28); 882 vBuffer.assign(pcBuffer + m_inthHeader.size(), pcBuffer + m_inthHeader.size() + header.OptionalHeader.NumberOfRvaAndSizes * 8 + header.FileHeader.NumberOfSections * 0x28);
883 883
884 ibBuffer.setBuffer(vBuffer); 884 ibBuffer.setBuffer(vBuffer);
885 885
886 readDataDirectories(ibBuffer, header); 886 readDataDirectories(ibBuffer, header);
887 887
888 m_vIsh = readSections(ibBuffer, header); 888 m_vIsh = readSections(ibBuffer, header);
889 889
890 std::swap(m_inthHeader, header); 890 std::swap(m_inthHeader, header);
891 891
892 m_uiOffset = uiOffset; 892 m_uiOffset = uiOffset;
893 893
894 return NO_ERROR; 894 return NO_ERROR;
895 } 895 }
896 896
897 /** 897 /**
898 * Reads the PE header from a file Note that this function does not verify if a file is actually a MZ file. 898 * Reads the PE header from a file Note that this function does not verify if a file is actually a MZ file.
899 * For this purpose see #PeLib::PeHeaderT<x>::isValid. The only check this function makes is a check to see if 899 * For this purpose see #PeLib::PeHeaderT<x>::isValid. The only check this function makes is a check to see if
900 * the file is large enough to be a PE header. If the data is valid doesn't matter. 900 * the file is large enough to be a PE header. If the data is valid doesn't matter.
901 * @param strFilename Name of the file which will be read. 901 * @param strFilename Name of the file which will be read.
902 * @param uiOffset File offset of PE header (see #PeLib::MzHeader::getAddressOfPeHeader). 902 * @param uiOffset File offset of PE header (see #PeLib::MzHeader::getAddressOfPeHeader).
903 **/ 903 **/
904 template<int x> 904 template<int x>
905 int PeHeaderT<x>::read(std::string strFilename, unsigned int uiOffset) 905 int PeHeaderT<x>::read(std::string strFilename, unsigned int uiOffset)
906 { 906 {
907 std::ifstream ifFile(strFilename.c_str(), std::ios::binary); 907 std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
908 908
909 if (!ifFile) 909 if (!ifFile)
910 { 910 {
911 return ERROR_OPENING_FILE; 911 return ERROR_OPENING_FILE;
912 } 912 }
913 913
914 // File too small 914 // File too small
915 if (fileSize(ifFile) < uiOffset + m_inthHeader.size()) 915 if (fileSize(ifFile) < uiOffset + m_inthHeader.size())
916 { 916 {
917 return ERROR_INVALID_FILE; 917 return ERROR_INVALID_FILE;
918 } 918 }
919 919
920 std::vector<unsigned char> vBuffer(m_inthHeader.size()); 920 std::vector<unsigned char> vBuffer(m_inthHeader.size());
921 921
922 ifFile.seekg(uiOffset, std::ios::beg); 922 ifFile.seekg(uiOffset, std::ios::beg);
923 ifFile.read(reinterpret_cast<char*>(&vBuffer[0]), static_cast<std::streamsize>(vBuffer.size())); 923 ifFile.read(reinterpret_cast<char*>(&vBuffer[0]), static_cast<std::streamsize>(vBuffer.size()));
924 924
925 InputBuffer ibBuffer(vBuffer); 925 InputBuffer ibBuffer(vBuffer);
926 PELIB_IMAGE_NT_HEADERS<x> header; 926 PELIB_IMAGE_NT_HEADERS<x> header;
927 927
928 readHeader(ibBuffer, header); 928 readHeader(ibBuffer, header);
929 929
930 vBuffer.resize(header.OptionalHeader.NumberOfRvaAndSizes * 8 + header.FileHeader.NumberOfSections * 0x28); 930 vBuffer.resize(header.OptionalHeader.NumberOfRvaAndSizes * 8 + header.FileHeader.NumberOfSections * 0x28);
931 931
932 ifFile.read(reinterpret_cast<char*>(&vBuffer[0]), static_cast<std::streamsize>(vBuffer.size())); 932 ifFile.read(reinterpret_cast<char*>(&vBuffer[0]), static_cast<std::streamsize>(vBuffer.size()));
933 if (!ifFile) 933 if (!ifFile)
934 { 934 {
935 return ERROR_INVALID_FILE; 935 return ERROR_INVALID_FILE;
936 } 936 }
937 937
938 ibBuffer.setBuffer(vBuffer); 938 ibBuffer.setBuffer(vBuffer);
939 939
940 readDataDirectories(ibBuffer, header); 940 readDataDirectories(ibBuffer, header);
941 941
942 // Sections 942 // Sections
943// const unsigned int nrSections = header.FileHeader.NumberOfSections; 943// const unsigned int nrSections = header.FileHeader.NumberOfSections;
944// if (fileSize(ifFile) < uiOffset + m_inthHeader.size() + nrSections * PELIB_IMAGE_SECTION_HEADER::size()) 944// if (fileSize(ifFile) < uiOffset + m_inthHeader.size() + nrSections * PELIB_IMAGE_SECTION_HEADER::size())
945// { 945// {
946// return ERROR_INVALID_FILE; 946// return ERROR_INVALID_FILE;
947// } 947// }
948 948
949 m_vIsh = readSections(ibBuffer, header); 949 m_vIsh = readSections(ibBuffer, header);
950 950
951 std::swap(m_inthHeader, header); 951 std::swap(m_inthHeader, header);
952 952
953 m_uiOffset = uiOffset; 953 m_uiOffset = uiOffset;
954 954
955 ifFile.close(); 955 ifFile.close();
956 956
957 return NO_ERROR; 957 return NO_ERROR;
958 } 958 }
959 959
960 /** 960 /**
961 * Rebuilds the PE header so that it can be written to a file. It's not guaranteed that the 961 * Rebuilds the PE header so that it can be written to a file. It's not guaranteed that the
962 * header will be valid. If you want to make sure that the header will be valid you 962 * header will be valid. If you want to make sure that the header will be valid you
963 * must call #PeLib::PeHeaderT<x>::makeValid first. 963 * must call #PeLib::PeHeaderT<x>::makeValid first.
964 * @param vBuffer Buffer where the rebuilt header will be stored. 964 * @param vBuffer Buffer where the rebuilt header will be stored.
965 **/ 965 **/
966 template<int x> 966 template<int x>
967 void PeHeaderT<x>::rebuild(std::vector<byte>& vBuffer) const 967 void PeHeaderT<x>::rebuild(std::vector<byte>& vBuffer) const
968 { 968 {
969 OutputBuffer obBuffer(vBuffer); 969 OutputBuffer obBuffer(vBuffer);
970 970
971 obBuffer << m_inthHeader.Signature; 971 obBuffer << m_inthHeader.Signature;
972 972
973 obBuffer << m_inthHeader.FileHeader.Machine; 973 obBuffer << m_inthHeader.FileHeader.Machine;
974 obBuffer << m_inthHeader.FileHeader.NumberOfSections; 974 obBuffer << m_inthHeader.FileHeader.NumberOfSections;
975 obBuffer << m_inthHeader.FileHeader.TimeDateStamp; 975 obBuffer << m_inthHeader.FileHeader.TimeDateStamp;
976 obBuffer << m_inthHeader.FileHeader.PointerToSymbolTable; 976 obBuffer << m_inthHeader.FileHeader.PointerToSymbolTable;
977 obBuffer << m_inthHeader.FileHeader.NumberOfSymbols; 977 obBuffer << m_inthHeader.FileHeader.NumberOfSymbols;
978 obBuffer << m_inthHeader.FileHeader.SizeOfOptionalHeader; 978 obBuffer << m_inthHeader.FileHeader.SizeOfOptionalHeader;
979 obBuffer << m_inthHeader.FileHeader.Characteristics; 979 obBuffer << m_inthHeader.FileHeader.Characteristics;
980 obBuffer << m_inthHeader.OptionalHeader.Magic; 980 obBuffer << m_inthHeader.OptionalHeader.Magic;
981 obBuffer << m_inthHeader.OptionalHeader.MajorLinkerVersion; 981 obBuffer << m_inthHeader.OptionalHeader.MajorLinkerVersion;
982 obBuffer << m_inthHeader.OptionalHeader.MinorLinkerVersion; 982 obBuffer << m_inthHeader.OptionalHeader.MinorLinkerVersion;
983 obBuffer << m_inthHeader.OptionalHeader.SizeOfCode; 983 obBuffer << m_inthHeader.OptionalHeader.SizeOfCode;
984 obBuffer << m_inthHeader.OptionalHeader.SizeOfInitializedData; 984 obBuffer << m_inthHeader.OptionalHeader.SizeOfInitializedData;
985 obBuffer << m_inthHeader.OptionalHeader.SizeOfUninitializedData; 985 obBuffer << m_inthHeader.OptionalHeader.SizeOfUninitializedData;
986 obBuffer << m_inthHeader.OptionalHeader.AddressOfEntryPoint; 986 obBuffer << m_inthHeader.OptionalHeader.AddressOfEntryPoint;
987 obBuffer << m_inthHeader.OptionalHeader.BaseOfCode; 987 obBuffer << m_inthHeader.OptionalHeader.BaseOfCode;
988 rebuildBaseOfData(obBuffer); 988 rebuildBaseOfData(obBuffer);
989// obBuffer << m_inthHeader.OptionalHeader.BaseOfData; 989// obBuffer << m_inthHeader.OptionalHeader.BaseOfData;
990 obBuffer << m_inthHeader.OptionalHeader.ImageBase; 990 obBuffer << m_inthHeader.OptionalHeader.ImageBase;
991 obBuffer << m_inthHeader.OptionalHeader.SectionAlignment; 991 obBuffer << m_inthHeader.OptionalHeader.SectionAlignment;
992 obBuffer << m_inthHeader.OptionalHeader.FileAlignment; 992 obBuffer << m_inthHeader.OptionalHeader.FileAlignment;
993 obBuffer << m_inthHeader.OptionalHeader.MajorOperatingSystemVersion; 993 obBuffer << m_inthHeader.OptionalHeader.MajorOperatingSystemVersion;
994 obBuffer << m_inthHeader.OptionalHeader.MinorOperatingSystemVersion; 994 obBuffer << m_inthHeader.OptionalHeader.MinorOperatingSystemVersion;
995 obBuffer << m_inthHeader.OptionalHeader.MajorImageVersion; 995 obBuffer << m_inthHeader.OptionalHeader.MajorImageVersion;
996 obBuffer << m_inthHeader.OptionalHeader.MinorImageVersion; 996 obBuffer << m_inthHeader.OptionalHeader.MinorImageVersion;
997 obBuffer << m_inthHeader.OptionalHeader.MajorSubsystemVersion; 997 obBuffer << m_inthHeader.OptionalHeader.MajorSubsystemVersion;
998 obBuffer << m_inthHeader.OptionalHeader.MinorSubsystemVersion; 998 obBuffer << m_inthHeader.OptionalHeader.MinorSubsystemVersion;
999 obBuffer << m_inthHeader.OptionalHeader.Win32VersionValue; 999 obBuffer << m_inthHeader.OptionalHeader.Win32VersionValue;
1000 obBuffer << m_inthHeader.OptionalHeader.SizeOfImage; 1000 obBuffer << m_inthHeader.OptionalHeader.SizeOfImage;
1001 obBuffer << m_inthHeader.OptionalHeader.SizeOfHeaders; 1001 obBuffer << m_inthHeader.OptionalHeader.SizeOfHeaders;
1002 obBuffer << m_inthHeader.OptionalHeader.CheckSum; 1002 obBuffer << m_inthHeader.OptionalHeader.CheckSum;
1003 obBuffer << m_inthHeader.OptionalHeader.Subsystem; 1003 obBuffer << m_inthHeader.OptionalHeader.Subsystem;
1004 obBuffer << m_inthHeader.OptionalHeader.DllCharacteristics; 1004 obBuffer << m_inthHeader.OptionalHeader.DllCharacteristics;
1005 obBuffer << m_inthHeader.OptionalHeader.SizeOfStackReserve; 1005 obBuffer << m_inthHeader.OptionalHeader.SizeOfStackReserve;
1006 obBuffer << m_inthHeader.OptionalHeader.SizeOfStackCommit; 1006 obBuffer << m_inthHeader.OptionalHeader.SizeOfStackCommit;
1007 obBuffer << m_inthHeader.OptionalHeader.SizeOfHeapReserve; 1007 obBuffer << m_inthHeader.OptionalHeader.SizeOfHeapReserve;
1008 obBuffer << m_inthHeader.OptionalHeader.SizeOfHeapCommit; 1008 obBuffer << m_inthHeader.OptionalHeader.SizeOfHeapCommit;
1009 obBuffer << m_inthHeader.OptionalHeader.LoaderFlags; 1009 obBuffer << m_inthHeader.OptionalHeader.LoaderFlags;
1010 obBuffer << m_inthHeader.OptionalHeader.NumberOfRvaAndSizes; 1010 obBuffer << m_inthHeader.OptionalHeader.NumberOfRvaAndSizes;
1011 1011
1012 // The 0x10 data directories 1012 // The 0x10 data directories
1013 for (unsigned int i=0;i<calcNumberOfRvaAndSizes();i++) 1013 for (unsigned int i=0;i<calcNumberOfRvaAndSizes();i++)
1014 { 1014 {
1015 obBuffer << m_inthHeader.dataDirectories[i].VirtualAddress; 1015 obBuffer << m_inthHeader.dataDirectories[i].VirtualAddress;
1016 obBuffer << m_inthHeader.dataDirectories[i].Size; 1016 obBuffer << m_inthHeader.dataDirectories[i].Size;
1017 } 1017 }
1018 1018
1019 // The section definitions 1019 // The section definitions
1020 const unsigned int nrSections = calcNumberOfSections(); 1020 const unsigned int nrSections = calcNumberOfSections();
1021 for (unsigned int i=0;i<nrSections;i++) 1021 for (unsigned int i=0;i<nrSections;i++)
1022 { 1022 {
1023 char temp[9] = {0}; 1023 char temp[9] = {0};
1024 strcpy(temp, getSectionName(i).c_str()); 1024 strcpy(temp, getSectionName(i).c_str());
1025 obBuffer.add(temp, 8); 1025 obBuffer.add(temp, 8);
1026 obBuffer << m_vIsh[i].VirtualSize; 1026 obBuffer << m_vIsh[i].VirtualSize;
1027 obBuffer << m_vIsh[i].VirtualAddress; 1027 obBuffer << m_vIsh[i].VirtualAddress;
1028 obBuffer << m_vIsh[i].SizeOfRawData; 1028 obBuffer << m_vIsh[i].SizeOfRawData;
1029 obBuffer << m_vIsh[i].PointerToRawData; 1029 obBuffer << m_vIsh[i].PointerToRawData;
1030 obBuffer << m_vIsh[i].PointerToRelocations; 1030 obBuffer << m_vIsh[i].PointerToRelocations;
1031 obBuffer << m_vIsh[i].PointerToLinenumbers; 1031 obBuffer << m_vIsh[i].PointerToLinenumbers;
1032 obBuffer << m_vIsh[i].NumberOfRelocations; 1032 obBuffer << m_vIsh[i].NumberOfRelocations;
1033 obBuffer << m_vIsh[i].NumberOfLinenumbers; 1033 obBuffer << m_vIsh[i].NumberOfLinenumbers;
1034 obBuffer << m_vIsh[i].Characteristics; 1034 obBuffer << m_vIsh[i].Characteristics;
1035 } 1035 }
1036 } 1036 }
1037 1037
1038 /** 1038 /**
1039 * Converts a relative virtual offset to a file offset. 1039 * Converts a relative virtual offset to a file offset.
1040 * @param dwRva A relative virtual offset. 1040 * @param dwRva A relative virtual offset.
1041 * @return A file offset. 1041 * @return A file offset.
1042 * \todo It's not always 0x1000. 1042 * \todo It's not always 0x1000.
1043 **/ 1043 **/
1044 template<int x> 1044 template<int x>
1045 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::rvaToOffset(VAR4_8 dwRva) const 1045 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::rvaToOffset(VAR4_8 dwRva) const
1046 { 1046 {
1047 // XXX: Not correct 1047 // XXX: Not correct
1048 if (dwRva < 0x1000) return dwRva; 1048 if (dwRva < 0x1000) return dwRva;
1049 1049
1050 PeLib::word uiSecnr = getSectionWithRva(dwRva); 1050 PeLib::word uiSecnr = getSectionWithRva(dwRva);
1051 if (uiSecnr == 0xFFFF || dwRva > getVirtualAddress(uiSecnr) + getSizeOfRawData(uiSecnr)) 1051 if (uiSecnr == 0xFFFF || dwRva > getVirtualAddress(uiSecnr) + getSizeOfRawData(uiSecnr))
1052 { 1052 {
1053 return std::numeric_limits<VAR4_8>::max(); 1053 return std::numeric_limits<VAR4_8>::max();
1054 } 1054 }
1055 1055
1056 return getPointerToRawData(uiSecnr) + dwRva - getVirtualAddress(uiSecnr); 1056 return getPointerToRawData(uiSecnr) + dwRva - getVirtualAddress(uiSecnr);
1057 } 1057 }
1058 1058
1059 /** 1059 /**
1060 * Converts a relative virtual offset to a virtual offset. 1060 * Converts a relative virtual offset to a virtual offset.
1061 * @param dwRva A relative virtual offset. 1061 * @param dwRva A relative virtual offset.
1062 * @return A virtual offset. 1062 * @return A virtual offset.
1063 **/ 1063 **/
1064 template<int x> 1064 template<int x>
1065 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::rvaToVa(VAR4_8 dwRva) const 1065 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::rvaToVa(VAR4_8 dwRva) const
1066 { 1066 {
1067 return getImageBase() + dwRva; 1067 return getImageBase() + dwRva;
1068 } 1068 }
1069 1069
1070 /** 1070 /**
1071 * Calculates the size of the current PE header. This includes the actual header and the section definitions. 1071 * Calculates the size of the current PE header. This includes the actual header and the section definitions.
1072 * @return Size of the current PE header. 1072 * @return Size of the current PE header.
1073 * \todo Better handling of files with less than 0x10 directories. 1073 * \todo Better handling of files with less than 0x10 directories.
1074 **/ 1074 **/
1075 template<int x> 1075 template<int x>
1076 unsigned int PeHeaderT<x>::size() const 1076 unsigned int PeHeaderT<x>::size() const
1077 { 1077 {
1078 return m_inthHeader.size() + getNumberOfSections() * PELIB_IMAGE_SECTION_HEADER::size(); 1078 return m_inthHeader.size() + getNumberOfSections() * PELIB_IMAGE_SECTION_HEADER::size();
1079 } 1079 }
1080 1080
1081 // \todo Not sure if this works. 1081 // \todo Not sure if this works.
1082 template<int x> 1082 template<int x>
1083 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::vaToRva(VAR4_8 dwRva) const 1083 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::vaToRva(VAR4_8 dwRva) const
1084 { 1084 {
1085 if (dwRva - getImageBase() < calcStartOfCode()) return dwRva - getImageBase(); 1085 if (dwRva - getImageBase() < calcStartOfCode()) return dwRva - getImageBase();
1086 1086
1087 if (getSectionWithRva(dwRva - getImageBase()) == 0xFFFF) return -1; 1087 if (getSectionWithRva(dwRva - getImageBase()) == 0xFFFF) return -1;
1088 1088
1089 return dwRva - getImageBase(); 1089 return dwRva - getImageBase();
1090 } 1090 }
1091 1091
1092 template<int x> 1092 template<int x>
1093 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::vaToOffset(VAR4_8 dwRva) const 1093 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::vaToOffset(VAR4_8 dwRva) const
1094 { 1094 {
1095 return rvaToOffset(dwRva - getImageBase()); 1095 return rvaToOffset(dwRva - getImageBase());
1096 } 1096 }
1097 1097
1098 /** 1098 /**
1099 * Saves the PE header to a file. Note that this only saves the header information, if you have added sections 1099 * Saves the PE header to a file. Note that this only saves the header information, if you have added sections
1100 * and want to save these to the file you have to call #PeLib::PeHeaderT<x>::saveSections too. This function also 1100 * and want to save these to the file you have to call #PeLib::PeHeaderT<x>::saveSections too. This function also
1101 * does not verify if the PE header is correct. If you want to make sure that the current PE header is valid, 1101 * does not verify if the PE header is correct. If you want to make sure that the current PE header is valid,
1102 * call #PeLib::PeHeaderT<x>::isValid and #PeLib::PeHeaderT<x>::makeValid first. 1102 * call #PeLib::PeHeaderT<x>::isValid and #PeLib::PeHeaderT<x>::makeValid first.
1103 * @param strFilename Filename of the file the header will be written to. 1103 * @param strFilename Filename of the file the header will be written to.
1104 * @param uiOffset File offset the header will be written to. 1104 * @param uiOffset File offset the header will be written to.
1105 **/ 1105 **/
1106 template<int x> 1106 template<int x>
1107 int PeHeaderT<x>::write(std::string strFilename, unsigned int uiOffset) const 1107 int PeHeaderT<x>::write(std::string strFilename, unsigned int uiOffset) const
1108 { 1108 {
1109 std::fstream ofFile(strFilename.c_str(), std::ios_base::in); 1109 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
1110 1110
1111 if (!ofFile) 1111 if (!ofFile)
1112 { 1112 {
1113 ofFile.clear(); 1113 ofFile.clear();
1114 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary); 1114 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
1115 } 1115 }
1116 else 1116 else
1117 { 1117 {
1118 ofFile.close(); 1118 ofFile.close();
1119 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary); 1119 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
1120 } 1120 }
1121 1121
1122 if (!ofFile) 1122 if (!ofFile)
1123 { 1123 {
1124 return ERROR_OPENING_FILE; 1124 return ERROR_OPENING_FILE;
1125 } 1125 }
1126 1126
1127 ofFile.seekp(uiOffset, std::ios::beg); 1127 ofFile.seekp(uiOffset, std::ios::beg);
1128 1128
1129 std::vector<unsigned char> vBuffer; 1129 std::vector<unsigned char> vBuffer;
1130 1130
1131 rebuild(vBuffer); 1131 rebuild(vBuffer);
1132 1132
1133 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size())); 1133 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
1134 1134
1135 ofFile.close(); 1135 ofFile.close();
1136 1136
1137 return NO_ERROR; 1137 return NO_ERROR;
1138 } 1138 }
1139 1139
1140 1140
1141 /** 1141 /**
1142 * Overwrites a section's data. 1142 * Overwrites a section's data.
1143 * @param wSecnr Number of the section which will be overwritten. 1143 * @param wSecnr Number of the section which will be overwritten.
1144 * @param strFilename Name of the file where the section will be written to. 1144 * @param strFilename Name of the file where the section will be written to.
1145 * @param wSecnr Number of the section that will be written. 1145 * @param wSecnr Number of the section that will be written.
1146 * @param vBuffer New data of the section. 1146 * @param vBuffer New data of the section.
1147 **/ 1147 **/
1148 template<int x> 1148 template<int x>
1149 int PeHeaderT<x>::writeSectionData(const std::string& strFilename, word wSecnr, const std::vector<byte>& vBuffer) const 1149 int PeHeaderT<x>::writeSectionData(const std::string& strFilename, word wSecnr, const std::vector<byte>& vBuffer) const
1150 { 1150 {
1151 std::fstream ofFile(strFilename.c_str(), std::ios_base::in); 1151 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
1152 1152
1153 if (!ofFile) 1153 if (!ofFile)
1154 { 1154 {
1155 ofFile.clear(); 1155 ofFile.clear();
1156 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary); 1156 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
1157 } 1157 }
1158 else 1158 else
1159 { 1159 {
1160 ofFile.close(); 1160 ofFile.close();
1161 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary); 1161 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
1162 } 1162 }
1163 1163
1164 if (!ofFile) 1164 if (!ofFile)
1165 { 1165 {
1166 ofFile.clear(); 1166 ofFile.clear();
1167 1167
1168 return ERROR_OPENING_FILE; 1168 return ERROR_OPENING_FILE;
1169 } 1169 }
1170 1170
1171 ofFile.seekp(getPointerToRawData(wSecnr), std::ios::beg); 1171 ofFile.seekp(getPointerToRawData(wSecnr), std::ios::beg);
1172 1172
1173 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), std::min(static_cast<unsigned int>(vBuffer.size()), getSizeOfRawData(wSecnr))); 1173 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), std::min(static_cast<unsigned int>(vBuffer.size()), getSizeOfRawData(wSecnr)));
1174 1174
1175 ofFile.close(); 1175 ofFile.close();
1176 1176
1177 return NO_ERROR; 1177 return NO_ERROR;
1178 } 1178 }
1179 1179
1180 template<int x> 1180 template<int x>
1181 int PeHeaderT<x>::writeSections(const std::string& strFilename) const 1181 int PeHeaderT<x>::writeSections(const std::string& strFilename) const
1182 { 1182 {
1183 std::fstream ofFile(strFilename.c_str(), std::ios_base::in); 1183 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
1184 1184
1185 if (!ofFile) 1185 if (!ofFile)
1186 { 1186 {
1187 ofFile.clear(); 1187 ofFile.clear();
1188 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary); 1188 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
1189 } 1189 }
1190 else 1190 else
1191 { 1191 {
1192 ofFile.close(); 1192 ofFile.close();
1193 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary); 1193 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
1194 } 1194 }
1195 1195
1196 if (!ofFile) 1196 if (!ofFile)
1197 { 1197 {
1198 return ERROR_OPENING_FILE; 1198 return ERROR_OPENING_FILE;
1199 } 1199 }
1200 1200
1201 unsigned int uiFilesize = fileSize(ofFile); 1201 unsigned int uiFilesize = fileSize(ofFile);
1202 1202
1203 for (int i=0;i<calcNumberOfSections();i++) 1203 for (int i=0;i<calcNumberOfSections();i++)
1204 { 1204 {
1205 if (uiFilesize < getPointerToRawData(i) + getSizeOfRawData(i)) 1205 if (uiFilesize < getPointerToRawData(i) + getSizeOfRawData(i))
1206 { 1206 {
1207 unsigned int uiToWrite = getPointerToRawData(i) + getSizeOfRawData(i) - uiFilesize; 1207 unsigned int uiToWrite = getPointerToRawData(i) + getSizeOfRawData(i) - uiFilesize;
1208 std::vector<char> vBuffer(uiToWrite); 1208 std::vector<char> vBuffer(uiToWrite);
1209 ofFile.seekp(0, std::ios::end); 1209 ofFile.seekp(0, std::ios::end);
1210 ofFile.write(&vBuffer[0], static_cast<unsigned int>(vBuffer.size())); 1210 ofFile.write(&vBuffer[0], static_cast<unsigned int>(vBuffer.size()));
1211 uiFilesize = getPointerToRawData(i) + getSizeOfRawData(i); 1211 uiFilesize = getPointerToRawData(i) + getSizeOfRawData(i);
1212 } 1212 }
1213 } 1213 }
1214 1214
1215 ofFile.close(); 1215 ofFile.close();
1216 1216
1217 return NO_ERROR; 1217 return NO_ERROR;
1218 } 1218 }
1219 1219
1220 /** 1220 /**
1221 * Returns the file's Nt signature. 1221 * Returns the file's Nt signature.
1222 * @return The Nt signature value from the PE header. 1222 * @return The Nt signature value from the PE header.
1223 **/ 1223 **/
1224 template<int x> 1224 template<int x>
1225 dword PeHeaderT<x>::getNtSignature() const 1225 dword PeHeaderT<x>::getNtSignature() const
1226 { 1226 {
1227 return m_inthHeader.Signature; 1227 return m_inthHeader.Signature;
1228 } 1228 }
1229 1229
1230 /** 1230 /**
1231 * Returns the file's machine. 1231 * Returns the file's machine.
1232 * @return The Machine value from the PE header. 1232 * @return The Machine value from the PE header.
1233 **/ 1233 **/
1234 template<int x> 1234 template<int x>
1235 word PeHeaderT<x>::getMachine() const 1235 word PeHeaderT<x>::getMachine() const
1236 { 1236 {
1237 return m_inthHeader.FileHeader.Machine; 1237 return m_inthHeader.FileHeader.Machine;
1238 } 1238 }
1239 1239
1240 1240
1241 /** 1241 /**
1242 * Returns the file's number of sections as defined in the header. Note that this value can be different 1242 * Returns the file's number of sections as defined in the header. Note that this value can be different
1243 * from the number of defined sections (#see PeLib::PeHeaderT<x>::getNumberOfSections). 1243 * from the number of defined sections (#see PeLib::PeHeaderT<x>::getNumberOfSections).
1244 * @return The NumberOfSections value from the PE header. 1244 * @return The NumberOfSections value from the PE header.
1245 **/ 1245 **/
1246 template<int x> 1246 template<int x>
1247 word PeHeaderT<x>::getNumberOfSections() const 1247 word PeHeaderT<x>::getNumberOfSections() const
1248 { 1248 {
1249 return m_inthHeader.FileHeader.NumberOfSections; 1249 return m_inthHeader.FileHeader.NumberOfSections;
1250 } 1250 }
1251 1251
1252 /** 1252 /**
1253 * Returns the file's TimeDateStamp. 1253 * Returns the file's TimeDateStamp.
1254 * @return The TimeDateStamp value from the PE header. 1254 * @return The TimeDateStamp value from the PE header.
1255 **/ 1255 **/
1256 template<int x> 1256 template<int x>
1257 dword PeHeaderT<x>::getTimeDateStamp() const 1257 dword PeHeaderT<x>::getTimeDateStamp() const
1258 { 1258 {
1259 return m_inthHeader.FileHeader.TimeDateStamp; 1259 return m_inthHeader.FileHeader.TimeDateStamp;
1260 } 1260 }
1261 1261
1262 /** 1262 /**
1263 * Returns the relative virtual address of the file's symbol table. 1263 * Returns the relative virtual address of the file's symbol table.
1264 * @return The PointerToSymbolTable value from the PE header. 1264 * @return The PointerToSymbolTable value from the PE header.
1265 **/ 1265 **/
1266 template<int x> 1266 template<int x>
1267 dword PeHeaderT<x>::getPointerToSymbolTable() const 1267 dword PeHeaderT<x>::getPointerToSymbolTable() const
1268 { 1268 {
1269 return m_inthHeader.FileHeader.PointerToSymbolTable; 1269 return m_inthHeader.FileHeader.PointerToSymbolTable;
1270 } 1270 }
1271 1271
1272 /** 1272 /**
1273 * Returns the number of symbols of the file's symbol table. 1273 * Returns the number of symbols of the file's symbol table.
1274 * @return The NumberOfSymbols value from the PE header. 1274 * @return The NumberOfSymbols value from the PE header.
1275 **/ 1275 **/
1276 template<int x> 1276 template<int x>
1277 dword PeHeaderT<x>::getNumberOfSymbols() const 1277 dword PeHeaderT<x>::getNumberOfSymbols() const
1278 { 1278 {
1279 return m_inthHeader.FileHeader.NumberOfSymbols; 1279 return m_inthHeader.FileHeader.NumberOfSymbols;
1280 } 1280 }
1281 1281
1282 /** 1282 /**
1283 * Returns the size of optional header of the file. 1283 * Returns the size of optional header of the file.
1284 * @return The SizeOfOptionalHeader value from the PE header. 1284 * @return The SizeOfOptionalHeader value from the PE header.
1285 **/ 1285 **/
1286 template<int x> 1286 template<int x>
1287 word PeHeaderT<x>::getSizeOfOptionalHeader() const 1287 word PeHeaderT<x>::getSizeOfOptionalHeader() const
1288 { 1288 {
1289 return m_inthHeader.FileHeader.SizeOfOptionalHeader; 1289 return m_inthHeader.FileHeader.SizeOfOptionalHeader;
1290 } 1290 }
1291 1291
1292 /** 1292 /**
1293 * @return The Characteristics value from the PE header. 1293 * @return The Characteristics value from the PE header.
1294 **/ 1294 **/
1295 template<int x> 1295 template<int x>
1296 word PeHeaderT<x>::getCharacteristics() const 1296 word PeHeaderT<x>::getCharacteristics() const
1297 { 1297 {
1298 return m_inthHeader.FileHeader.Characteristics; 1298 return m_inthHeader.FileHeader.Characteristics;
1299 } 1299 }
1300 1300
1301 /** 1301 /**
1302 * @return The Magic value from the PE header. 1302 * @return The Magic value from the PE header.
1303 **/ 1303 **/
1304 template<int x> 1304 template<int x>
1305 word PeHeaderT<x>::getMagic() const 1305 word PeHeaderT<x>::getMagic() const
1306 { 1306 {
1307 return m_inthHeader.OptionalHeader.Magic; 1307 return m_inthHeader.OptionalHeader.Magic;
1308 } 1308 }
1309 1309
1310 /** 1310 /**
1311 * @return The MajorLinkerVersion value from the PE header. 1311 * @return The MajorLinkerVersion value from the PE header.
1312 **/ 1312 **/
1313 template<int x> 1313 template<int x>
1314 byte PeHeaderT<x>::getMajorLinkerVersion() const 1314 byte PeHeaderT<x>::getMajorLinkerVersion() const
1315 { 1315 {
1316 return m_inthHeader.OptionalHeader.MajorLinkerVersion; 1316 return m_inthHeader.OptionalHeader.MajorLinkerVersion;
1317 } 1317 }
1318 1318
1319 /** 1319 /**
1320 * @return The MinorLinkerVersion value from the PE header. 1320 * @return The MinorLinkerVersion value from the PE header.
1321 **/ 1321 **/
1322 template<int x> 1322 template<int x>
1323 byte PeHeaderT<x>::getMinorLinkerVersion() const 1323 byte PeHeaderT<x>::getMinorLinkerVersion() const
1324 { 1324 {
1325 return m_inthHeader.OptionalHeader.MinorLinkerVersion; 1325 return m_inthHeader.OptionalHeader.MinorLinkerVersion;
1326 } 1326 }
1327 1327
1328 /** 1328 /**
1329 * @return The SizeOfCode value from the PE header. 1329 * @return The SizeOfCode value from the PE header.
1330 **/ 1330 **/
1331 template<int x> 1331 template<int x>
1332 dword PeHeaderT<x>::getSizeOfCode() const 1332 dword PeHeaderT<x>::getSizeOfCode() const
1333 { 1333 {
1334 return m_inthHeader.OptionalHeader.SizeOfCode; 1334 return m_inthHeader.OptionalHeader.SizeOfCode;
1335 } 1335 }
1336 1336
1337 /** 1337 /**
1338 * @return The SizeOfInitializedData value from the PE header. 1338 * @return The SizeOfInitializedData value from the PE header.
1339 **/ 1339 **/
1340 template<int x> 1340 template<int x>
1341 dword PeHeaderT<x>::getSizeOfInitializedData() const 1341 dword PeHeaderT<x>::getSizeOfInitializedData() const
1342 { 1342 {
1343 return m_inthHeader.OptionalHeader.SizeOfInitializedData; 1343 return m_inthHeader.OptionalHeader.SizeOfInitializedData;
1344 } 1344 }
1345 1345
1346 /** 1346 /**
1347 * @return The SizeOfUninitializedData value from the PE header. 1347 * @return The SizeOfUninitializedData value from the PE header.
1348 **/ 1348 **/
1349 template<int x> 1349 template<int x>
1350 dword PeHeaderT<x>::getSizeOfUninitializedData() const 1350 dword PeHeaderT<x>::getSizeOfUninitializedData() const
1351 { 1351 {
1352 return m_inthHeader.OptionalHeader.SizeOfUninitializedData; 1352 return m_inthHeader.OptionalHeader.SizeOfUninitializedData;
1353 } 1353 }
1354 1354
1355 /** 1355 /**
1356 * @return The AddressOfEntryPoint value from the PE header. 1356 * @return The AddressOfEntryPoint value from the PE header.
1357 **/ 1357 **/
1358 template<int x> 1358 template<int x>
1359 dword PeHeaderT<x>::getAddressOfEntryPoint() const 1359 dword PeHeaderT<x>::getAddressOfEntryPoint() const
1360 { 1360 {
1361 return m_inthHeader.OptionalHeader.AddressOfEntryPoint; 1361 return m_inthHeader.OptionalHeader.AddressOfEntryPoint;
1362 } 1362 }
1363 1363
1364 /** 1364 /**
1365 * @return The BaseOfCode value from the PE header. 1365 * @return The BaseOfCode value from the PE header.
1366 **/ 1366 **/
1367 template<int x> 1367 template<int x>
1368 dword PeHeaderT<x>::getBaseOfCode() const 1368 dword PeHeaderT<x>::getBaseOfCode() const
1369 { 1369 {
1370 return m_inthHeader.OptionalHeader.BaseOfCode; 1370 return m_inthHeader.OptionalHeader.BaseOfCode;
1371 } 1371 }
1372 1372
1373 /** 1373 /**
1374 * @return The ImageBase value from the PE header. 1374 * @return The ImageBase value from the PE header.
1375 **/ 1375 **/
1376 template<int x> 1376 template<int x>
1377 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::getImageBase() const 1377 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::getImageBase() const
1378 { 1378 {
1379 return m_inthHeader.OptionalHeader.ImageBase; 1379 return m_inthHeader.OptionalHeader.ImageBase;
1380 } 1380 }
1381 1381
1382 /** 1382 /**
1383 * @return The SectionAlignment value from the PE header. 1383 * @return The SectionAlignment value from the PE header.
1384 **/ 1384 **/
1385 template<int x> 1385 template<int x>
1386 dword PeHeaderT<x>::getSectionAlignment() const 1386 dword PeHeaderT<x>::getSectionAlignment() const
1387 { 1387 {
1388 return m_inthHeader.OptionalHeader.SectionAlignment; 1388 return m_inthHeader.OptionalHeader.SectionAlignment;
1389 } 1389 }
1390 1390
1391 /** 1391 /**
1392 * @return The FileAlignment value from the PE header. 1392 * @return The FileAlignment value from the PE header.
1393 **/ 1393 **/
1394 template<int x> 1394 template<int x>
1395 dword PeHeaderT<x>::getFileAlignment() const 1395 dword PeHeaderT<x>::getFileAlignment() const
1396 { 1396 {
1397 return m_inthHeader.OptionalHeader.FileAlignment; 1397 return m_inthHeader.OptionalHeader.FileAlignment;
1398 } 1398 }
1399 1399
1400 /** 1400 /**
1401 * @return The MajorOperatingSystemVersion value from the PE header. 1401 * @return The MajorOperatingSystemVersion value from the PE header.
1402 **/ 1402 **/
1403 template<int x> 1403 template<int x>
1404 word PeHeaderT<x>::getMajorOperatingSystemVersion() const 1404 word PeHeaderT<x>::getMajorOperatingSystemVersion() const
1405 { 1405 {
1406 return m_inthHeader.OptionalHeader.MajorOperatingSystemVersion; 1406 return m_inthHeader.OptionalHeader.MajorOperatingSystemVersion;
1407 } 1407 }
1408 1408
1409 /** 1409 /**
1410 * @return The MinorOperatingSystemVersion value from the PE header. 1410 * @return The MinorOperatingSystemVersion value from the PE header.
1411 **/ 1411 **/
1412 template<int x> 1412 template<int x>
1413 word PeHeaderT<x>::getMinorOperatingSystemVersion() const 1413 word PeHeaderT<x>::getMinorOperatingSystemVersion() const
1414 { 1414 {
1415 return m_inthHeader.OptionalHeader.MinorOperatingSystemVersion; 1415 return m_inthHeader.OptionalHeader.MinorOperatingSystemVersion;
1416 } 1416 }
1417 1417
1418 /** 1418 /**
1419 * @return The MajorImageVersion value from the PE header. 1419 * @return The MajorImageVersion value from the PE header.
1420 **/ 1420 **/
1421 template<int x> 1421 template<int x>
1422 word PeHeaderT<x>::getMajorImageVersion() const 1422 word PeHeaderT<x>::getMajorImageVersion() const
1423 { 1423 {
1424 return m_inthHeader.OptionalHeader.MajorImageVersion; 1424 return m_inthHeader.OptionalHeader.MajorImageVersion;
1425 } 1425 }
1426 1426
1427 /** 1427 /**
1428 * @return The MinorImageVersion value from the PE header. 1428 * @return The MinorImageVersion value from the PE header.
1429 **/ 1429 **/
1430 template<int x> 1430 template<int x>
1431 word PeHeaderT<x>::getMinorImageVersion() const 1431 word PeHeaderT<x>::getMinorImageVersion() const
1432 { 1432 {
1433 return m_inthHeader.OptionalHeader.MinorImageVersion; 1433 return m_inthHeader.OptionalHeader.MinorImageVersion;
1434 } 1434 }
1435 1435
1436 /** 1436 /**
1437 * @return The MajorSubsystemVersion value from the PE header. 1437 * @return The MajorSubsystemVersion value from the PE header.
1438 **/ 1438 **/
1439 template<int x> 1439 template<int x>
1440 word PeHeaderT<x>::getMajorSubsystemVersion() const 1440 word PeHeaderT<x>::getMajorSubsystemVersion() const
1441 { 1441 {
1442 return m_inthHeader.OptionalHeader.MajorSubsystemVersion; 1442 return m_inthHeader.OptionalHeader.MajorSubsystemVersion;
1443 } 1443 }
1444 1444
1445 /** 1445 /**
1446 * @return The MinorSubsystemVersion value from the PE header. 1446 * @return The MinorSubsystemVersion value from the PE header.
1447 **/ 1447 **/
1448 template<int x> 1448 template<int x>
1449 word PeHeaderT<x>::getMinorSubsystemVersion() const 1449 word PeHeaderT<x>::getMinorSubsystemVersion() const
1450 { 1450 {
1451 return m_inthHeader.OptionalHeader.MinorSubsystemVersion; 1451 return m_inthHeader.OptionalHeader.MinorSubsystemVersion;
1452 } 1452 }
1453 1453
1454 /** 1454 /**
1455 * @return The WinVersionValue value from the PE header. 1455 * @return The WinVersionValue value from the PE header.
1456 **/ 1456 **/
1457 template<int x> 1457 template<int x>
1458 dword PeHeaderT<x>::getWin32VersionValue() const 1458 dword PeHeaderT<x>::getWin32VersionValue() const
1459 { 1459 {
1460 return m_inthHeader.OptionalHeader.Win32VersionValue; 1460 return m_inthHeader.OptionalHeader.Win32VersionValue;
1461 } 1461 }
1462 1462
1463 /** 1463 /**
1464 * @return The SizeOfImage value from the PE header. 1464 * @return The SizeOfImage value from the PE header.
1465 **/ 1465 **/
1466 template<int x> 1466 template<int x>
1467 dword PeHeaderT<x>::getSizeOfImage() const 1467 dword PeHeaderT<x>::getSizeOfImage() const
1468 { 1468 {
1469 return m_inthHeader.OptionalHeader.SizeOfImage; 1469 return m_inthHeader.OptionalHeader.SizeOfImage;
1470 } 1470 }
1471 1471
1472 /** 1472 /**
1473 * @return The SizeOfHeaders value from the PE header. 1473 * @return The SizeOfHeaders value from the PE header.
1474 **/ 1474 **/
1475 template<int x> 1475 template<int x>
1476 dword PeHeaderT<x>::getSizeOfHeaders() const 1476 dword PeHeaderT<x>::getSizeOfHeaders() const
1477 { 1477 {
1478 return m_inthHeader.OptionalHeader.SizeOfHeaders; 1478 return m_inthHeader.OptionalHeader.SizeOfHeaders;
1479 } 1479 }
1480 1480
1481 /** 1481 /**
1482 * @return The CheckSums value from the PE header. 1482 * @return The CheckSums value from the PE header.
1483 **/ 1483 **/
1484 template<int x> 1484 template<int x>
1485 dword PeHeaderT<x>::getCheckSum() const 1485 dword PeHeaderT<x>::getCheckSum() const
1486 { 1486 {
1487 return m_inthHeader.OptionalHeader.CheckSum; 1487 return m_inthHeader.OptionalHeader.CheckSum;
1488 } 1488 }
1489 1489
1490 /** 1490 /**
1491 * @return The Subsystem value from the PE header. 1491 * @return The Subsystem value from the PE header.
1492 **/ 1492 **/
1493 template<int x> 1493 template<int x>
1494 word PeHeaderT<x>::getSubsystem() const 1494 word PeHeaderT<x>::getSubsystem() const
1495 { 1495 {
1496 return m_inthHeader.OptionalHeader.Subsystem; 1496 return m_inthHeader.OptionalHeader.Subsystem;
1497 } 1497 }
1498 1498
1499 /** 1499 /**
1500 * @return The DllCharacteristics value from the PE header. 1500 * @return The DllCharacteristics value from the PE header.
1501 **/ 1501 **/
1502 template<int x> 1502 template<int x>
1503 word PeHeaderT<x>::getDllCharacteristics() const 1503 word PeHeaderT<x>::getDllCharacteristics() const
1504 { 1504 {
1505 return m_inthHeader.OptionalHeader.DllCharacteristics; 1505 return m_inthHeader.OptionalHeader.DllCharacteristics;
1506 } 1506 }
1507 1507
1508 /** 1508 /**
1509 * @return The SizeOfStackReserve value from the PE header. 1509 * @return The SizeOfStackReserve value from the PE header.
1510 **/ 1510 **/
1511 template<int x> 1511 template<int x>
1512 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::getSizeOfStackReserve() const 1512 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::getSizeOfStackReserve() const
1513 { 1513 {
1514 return m_inthHeader.OptionalHeader.SizeOfStackReserve; 1514 return m_inthHeader.OptionalHeader.SizeOfStackReserve;
1515 } 1515 }
1516 1516
1517 /** 1517 /**
1518 * @return The SizeOfStackCommit value from the PE header. 1518 * @return The SizeOfStackCommit value from the PE header.
1519 **/ 1519 **/
1520 template<int x> 1520 template<int x>
1521 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::getSizeOfStackCommit() const 1521 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::getSizeOfStackCommit() const
1522 { 1522 {
1523 return m_inthHeader.OptionalHeader.SizeOfStackCommit; 1523 return m_inthHeader.OptionalHeader.SizeOfStackCommit;
1524 } 1524 }
1525 1525
1526 /** 1526 /**
1527 * @return The SizeOfHeapReserve value from the PE header. 1527 * @return The SizeOfHeapReserve value from the PE header.
1528 **/ 1528 **/
1529 template<int x> 1529 template<int x>
1530 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::getSizeOfHeapReserve() const 1530 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::getSizeOfHeapReserve() const
1531 { 1531 {
1532 return m_inthHeader.OptionalHeader.SizeOfHeapReserve; 1532 return m_inthHeader.OptionalHeader.SizeOfHeapReserve;
1533 } 1533 }
1534 1534
1535 /** 1535 /**
1536 * @return The SizeOfHeapCommit value from the PE header. 1536 * @return The SizeOfHeapCommit value from the PE header.
1537 **/ 1537 **/
1538 template<int x> 1538 template<int x>
1539 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::getSizeOfHeapCommit() const 1539 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::getSizeOfHeapCommit() const
1540 { 1540 {
1541 return m_inthHeader.OptionalHeader.SizeOfHeapCommit; 1541 return m_inthHeader.OptionalHeader.SizeOfHeapCommit;
1542 } 1542 }
1543 1543
1544 /** 1544 /**
1545 * @return The LoaderFlags value from the PE header. 1545 * @return The LoaderFlags value from the PE header.
1546 **/ 1546 **/
1547 template<int x> 1547 template<int x>
1548 dword PeHeaderT<x>::getLoaderFlags() const 1548 dword PeHeaderT<x>::getLoaderFlags() const
1549 { 1549 {
1550 return m_inthHeader.OptionalHeader.LoaderFlags; 1550 return m_inthHeader.OptionalHeader.LoaderFlags;
1551 } 1551 }
1552 1552
1553 /** 1553 /**
1554 * @return The NumberOfRvaAndSizes value from the PE header. 1554 * @return The NumberOfRvaAndSizes value from the PE header.
1555 **/ 1555 **/
1556 template<int x> 1556 template<int x>
1557 dword PeHeaderT<x>::getNumberOfRvaAndSizes() const 1557 dword PeHeaderT<x>::getNumberOfRvaAndSizes() const
1558 { 1558 {
1559 return m_inthHeader.OptionalHeader.NumberOfRvaAndSizes; 1559 return m_inthHeader.OptionalHeader.NumberOfRvaAndSizes;
1560 } 1560 }
1561 1561
1562 template<int x> 1562 template<int x>
1563 dword PeHeaderT<x>::calcNumberOfRvaAndSizes() const 1563 dword PeHeaderT<x>::calcNumberOfRvaAndSizes() const
1564 { 1564 {
1565 return static_cast<dword>(m_inthHeader.dataDirectories.size()); 1565 return static_cast<dword>(m_inthHeader.dataDirectories.size());
1566 } 1566 }
1567 1567
1568 /** 1568 /**
1569 * Returns the relative virtual address of the current file's export directory. 1569 * Returns the relative virtual address of the current file's export directory.
1570 * @return The Rva of the Export directory. 1570 * @return The Rva of the Export directory.
1571 **/ 1571 **/
1572 template<int x> 1572 template<int x>
1573 dword PeHeaderT<x>::getIddExportRva() const 1573 dword PeHeaderT<x>::getIddExportRva() const
1574 { 1574 {
1575 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress; 1575 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
1576 } 1576 }
1577 1577
1578 /** 1578 /**
1579 * Returns the size of the current file's export directory. 1579 * Returns the size of the current file's export directory.
1580 * @return The sizeof the Export directory. 1580 * @return The sizeof the Export directory.
1581 **/ 1581 **/
1582 template<int x> 1582 template<int x>
1583 dword PeHeaderT<x>::getIddExportSize() const 1583 dword PeHeaderT<x>::getIddExportSize() const
1584 { 1584 {
1585 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXPORT].Size; 1585 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
1586 } 1586 }
1587 1587
1588 /** 1588 /**
1589 * Returns the relative virtual address of the current file's import directory. 1589 * Returns the relative virtual address of the current file's import directory.
1590 * @return The Rva of the Import directory. 1590 * @return The Rva of the Import directory.
1591 **/ 1591 **/
1592 template<int x> 1592 template<int x>
1593 dword PeHeaderT<x>::getIddImportRva() const 1593 dword PeHeaderT<x>::getIddImportRva() const
1594 { 1594 {
1595 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress; 1595 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
1596 } 1596 }
1597 1597
1598 /** 1598 /**
1599 * Returns the size of the current file's import directory. 1599 * Returns the size of the current file's import directory.
1600 * @return The size of the Import directory. 1600 * @return The size of the Import directory.
1601 **/ 1601 **/
1602 template<int x> 1602 template<int x>
1603 dword PeHeaderT<x>::getIddImportSize() const 1603 dword PeHeaderT<x>::getIddImportSize() const
1604 { 1604 {
1605 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IMPORT].Size; 1605 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IMPORT].Size;
1606 } 1606 }
1607 1607
1608 /** 1608 /**
1609 * Returns the relative virtual address of the current file's resource directory. 1609 * Returns the relative virtual address of the current file's resource directory.
1610 * @return The Rva of the Resource directory. 1610 * @return The Rva of the Resource directory.
1611 **/ 1611 **/
1612 template<int x> 1612 template<int x>
1613 dword PeHeaderT<x>::getIddResourceRva() const 1613 dword PeHeaderT<x>::getIddResourceRva() const
1614 { 1614 {
1615 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress; 1615 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
1616 } 1616 }
1617 1617
1618 /** 1618 /**
1619 * Returns the size of the current file'resource resource directory. 1619 * Returns the size of the current file'resource resource directory.
1620 * @return The size of the Resource directory. 1620 * @return The size of the Resource directory.
1621 **/ 1621 **/
1622 template<int x> 1622 template<int x>
1623 dword PeHeaderT<x>::getIddResourceSize() const 1623 dword PeHeaderT<x>::getIddResourceSize() const
1624 { 1624 {
1625 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size; 1625 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size;
1626 } 1626 }
1627 1627
1628 /** 1628 /**
1629 * Returns the relative virtual address of the current file's exception directory. 1629 * Returns the relative virtual address of the current file's exception directory.
1630 * @return The Rva of the Exception directory. 1630 * @return The Rva of the Exception directory.
1631 **/ 1631 **/
1632 template<int x> 1632 template<int x>
1633 dword PeHeaderT<x>::getIddExceptionRva() const 1633 dword PeHeaderT<x>::getIddExceptionRva() const
1634 { 1634 {
1635 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress; 1635 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress;
1636 } 1636 }
1637 1637
1638 /** 1638 /**
1639 * Returns the size of the current file's exception directory. 1639 * Returns the size of the current file's exception directory.
1640 * @return The size of the Exception directory. 1640 * @return The size of the Exception directory.
1641 **/ 1641 **/
1642 template<int x> 1642 template<int x>
1643 dword PeHeaderT<x>::getIddExceptionSize() const 1643 dword PeHeaderT<x>::getIddExceptionSize() const
1644 { 1644 {
1645 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size; 1645 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size;
1646 } 1646 }
1647 1647
1648 /** 1648 /**
1649 * Returns the relative virtual address of the current file's security directory. 1649 * Returns the relative virtual address of the current file's security directory.
1650 * @return The Rva of the Security directory. 1650 * @return The Rva of the Security directory.
1651 **/ 1651 **/
1652 template<int x> 1652 template<int x>
1653 dword PeHeaderT<x>::getIddSecurityRva() const 1653 dword PeHeaderT<x>::getIddSecurityRva() const
1654 { 1654 {
1655 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress; 1655 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress;
1656 } 1656 }
1657 1657
1658 /** 1658 /**
1659 * Returns the size of the current file's security directory. 1659 * Returns the size of the current file's security directory.
1660 * @return The size of the Security directory. 1660 * @return The size of the Security directory.
1661 **/ 1661 **/
1662 template<int x> 1662 template<int x>
1663 dword PeHeaderT<x>::getIddSecuritySize() const 1663 dword PeHeaderT<x>::getIddSecuritySize() const
1664 { 1664 {
1665 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_SECURITY].Size; 1665 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
1666 } 1666 }
1667 1667
1668 /** 1668 /**
1669 * Returns the relative virtual address of the current file's base reloc directory. 1669 * Returns the relative virtual address of the current file's base reloc directory.
1670 * @return The Rva of the Base Reloc directory. 1670 * @return The Rva of the Base Reloc directory.
1671 **/ 1671 **/
1672 template<int x> 1672 template<int x>
1673 dword PeHeaderT<x>::getIddBaseRelocRva() const 1673 dword PeHeaderT<x>::getIddBaseRelocRva() const
1674 { 1674 {
1675 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress; 1675 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress;
1676 } 1676 }
1677 1677
1678 /** 1678 /**
1679 * Returns the size of the current file's base reloc directory. 1679 * Returns the size of the current file's base reloc directory.
1680 * @return The size of the Base Reloc directory. 1680 * @return The size of the Base Reloc directory.
1681 **/ 1681 **/
1682 template<int x> 1682 template<int x>
1683 dword PeHeaderT<x>::getIddBaseRelocSize() const 1683 dword PeHeaderT<x>::getIddBaseRelocSize() const
1684 { 1684 {
1685 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size; 1685 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
1686 } 1686 }
1687 1687
1688 /** 1688 /**
1689 * Returns the relative virtual address of the current file's debug directory. 1689 * Returns the relative virtual address of the current file's debug directory.
1690 * @return The Rva of the Debug directory. 1690 * @return The Rva of the Debug directory.
1691 **/ 1691 **/
1692 template<int x> 1692 template<int x>
1693 dword PeHeaderT<x>::getIddDebugRva() const 1693 dword PeHeaderT<x>::getIddDebugRva() const
1694 { 1694 {
1695 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress; 1695 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress;
1696 } 1696 }
1697 1697
1698 /** 1698 /**
1699 * Returns the size of the current file's debug directory. 1699 * Returns the size of the current file's debug directory.
1700 * @return The size of the Debug directory. 1700 * @return The size of the Debug directory.
1701 **/ 1701 **/
1702 template<int x> 1702 template<int x>
1703 dword PeHeaderT<x>::getIddDebugSize() const 1703 dword PeHeaderT<x>::getIddDebugSize() const
1704 { 1704 {
1705 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DEBUG].Size; 1705 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DEBUG].Size;
1706 } 1706 }
1707 1707
1708 /** 1708 /**
1709 * Returns the relative virtual address of the current file's Architecture directory. 1709 * Returns the relative virtual address of the current file's Architecture directory.
1710 * @return The Rva of the Architecture directory. 1710 * @return The Rva of the Architecture directory.
1711 **/ 1711 **/
1712 template<int x> 1712 template<int x>
1713 dword PeHeaderT<x>::getIddArchitectureRva() const 1713 dword PeHeaderT<x>::getIddArchitectureRva() const
1714 { 1714 {
1715 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_ARCHITECTURE].VirtualAddress; 1715 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_ARCHITECTURE].VirtualAddress;
1716 } 1716 }
1717 1717
1718 /** 1718 /**
1719 * Returns the size of the current file's Architecture directory. 1719 * Returns the size of the current file's Architecture directory.
1720 * @return The size of the Architecture directory. 1720 * @return The size of the Architecture directory.
1721 **/ 1721 **/
1722 template<int x> 1722 template<int x>
1723 dword PeHeaderT<x>::getIddArchitectureSize() const 1723 dword PeHeaderT<x>::getIddArchitectureSize() const
1724 { 1724 {
1725 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_ARCHITECTURE].Size; 1725 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_ARCHITECTURE].Size;
1726 } 1726 }
1727 1727
1728 /** 1728 /**
1729 * Returns the relative virtual address of the current file's global ptr directory. 1729 * Returns the relative virtual address of the current file's global ptr directory.
1730 * @return The Rva of the GlobalPtr directory. 1730 * @return The Rva of the GlobalPtr directory.
1731 **/ 1731 **/
1732 template<int x> 1732 template<int x>
1733 dword PeHeaderT<x>::getIddGlobalPtrRva() const 1733 dword PeHeaderT<x>::getIddGlobalPtrRva() const
1734 { 1734 {
1735 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_GLOBALPTR].VirtualAddress; 1735 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_GLOBALPTR].VirtualAddress;
1736 } 1736 }
1737 1737
1738 /** 1738 /**
1739 * Returns the size of the current file's global ptr directory. 1739 * Returns the size of the current file's global ptr directory.
1740 * @return The size of the GlobalPtr directory. 1740 * @return The size of the GlobalPtr directory.
1741 **/ 1741 **/
1742 template<int x> 1742 template<int x>
1743 dword PeHeaderT<x>::getIddGlobalPtrSize() const 1743 dword PeHeaderT<x>::getIddGlobalPtrSize() const
1744 { 1744 {
1745 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_GLOBALPTR].Size; 1745 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_GLOBALPTR].Size;
1746 } 1746 }
1747 1747
1748 /** 1748 /**
1749 * Returns the relative virtual address of the current file's TLS directory. 1749 * Returns the relative virtual address of the current file's TLS directory.
1750 * @return The Rva of the Tls directory. 1750 * @return The Rva of the Tls directory.
1751 **/ 1751 **/
1752 template<int x> 1752 template<int x>
1753 dword PeHeaderT<x>::getIddTlsRva() const 1753 dword PeHeaderT<x>::getIddTlsRva() const
1754 { 1754 {
1755 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_TLS].VirtualAddress; 1755 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_TLS].VirtualAddress;
1756 } 1756 }
1757 1757
1758 /** 1758 /**
1759 * Returns the size of the current file's TLS directory. 1759 * Returns the size of the current file's TLS directory.
1760 * @return The size of the Tls directory. 1760 * @return The size of the Tls directory.
1761 **/ 1761 **/
1762 template<int x> 1762 template<int x>
1763 dword PeHeaderT<x>::getIddTlsSize() const 1763 dword PeHeaderT<x>::getIddTlsSize() const
1764 { 1764 {
1765 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_TLS].Size; 1765 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_TLS].Size;
1766 } 1766 }
1767 1767
1768 /** 1768 /**
1769 * Returns the relative virtual address of the current file's load config directory. 1769 * Returns the relative virtual address of the current file's load config directory.
1770 * @return The Rva of the LoadConfig directory. 1770 * @return The Rva of the LoadConfig directory.
1771 **/ 1771 **/
1772 template<int x> 1772 template<int x>
1773 dword PeHeaderT<x>::getIddLoadConfigRva() const 1773 dword PeHeaderT<x>::getIddLoadConfigRva() const
1774 { 1774 {
1775 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].VirtualAddress; 1775 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].VirtualAddress;
1776 } 1776 }
1777 1777
1778 /** 1778 /**
1779 * Returns the size of the current file's load config directory. 1779 * Returns the size of the current file's load config directory.
1780 * @return The size of the LoadConfig directory. 1780 * @return The size of the LoadConfig directory.
1781 **/ 1781 **/
1782 template<int x> 1782 template<int x>
1783 dword PeHeaderT<x>::getIddLoadConfigSize() const 1783 dword PeHeaderT<x>::getIddLoadConfigSize() const
1784 { 1784 {
1785 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].Size; 1785 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].Size;
1786 } 1786 }
1787 1787
1788 /** 1788 /**
1789 * Returns the relative virtual address of the current file's bound import directory. 1789 * Returns the relative virtual address of the current file's bound import directory.
1790 * @return The Rva of the BoundImport directory. 1790 * @return The Rva of the BoundImport directory.
1791 **/ 1791 **/
1792 template<int x> 1792 template<int x>
1793 dword PeHeaderT<x>::getIddBoundImportRva() const 1793 dword PeHeaderT<x>::getIddBoundImportRva() const
1794 { 1794 {
1795 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT].VirtualAddress; 1795 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT].VirtualAddress;
1796 } 1796 }
1797 1797
1798 /** 1798 /**
1799 * Returns the size of the current file's bound import directory. 1799 * Returns the size of the current file's bound import directory.
1800 * @return The size of the BoundImport directory. 1800 * @return The size of the BoundImport directory.
1801 **/ 1801 **/
1802 template<int x> 1802 template<int x>
1803 dword PeHeaderT<x>::getIddBoundImportSize() const 1803 dword PeHeaderT<x>::getIddBoundImportSize() const
1804 { 1804 {
1805 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT].Size; 1805 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT].Size;
1806 } 1806 }
1807 1807
1808 /** 1808 /**
1809 * Returns the relative virtual address of the current file's IAT directory. 1809 * Returns the relative virtual address of the current file's IAT directory.
1810 * @return The Rva of the IAT directory. 1810 * @return The Rva of the IAT directory.
1811 **/ 1811 **/
1812 template<int x> 1812 template<int x>
1813 dword PeHeaderT<x>::getIddIatRva() const 1813 dword PeHeaderT<x>::getIddIatRva() const
1814 { 1814 {
1815 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress; 1815 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress;
1816 } 1816 }
1817 1817
1818 /** 1818 /**
1819 * Returns the size of the current file's IAT directory. 1819 * Returns the size of the current file's IAT directory.
1820 * @return The size of the IAT directory. 1820 * @return The size of the IAT directory.
1821 **/ 1821 **/
1822 template<int x> 1822 template<int x>
1823 dword PeHeaderT<x>::getIddIatSize() const 1823 dword PeHeaderT<x>::getIddIatSize() const
1824 { 1824 {
1825 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IAT].Size; 1825 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IAT].Size;
1826 } 1826 }
1827 1827
1828 /** 1828 /**
1829 * Returns the relative virtual address of the current file's Delay Import directory. 1829 * Returns the relative virtual address of the current file's Delay Import directory.
1830 * @return The Rva of the DelayImport directory. 1830 * @return The Rva of the DelayImport directory.
1831 **/ 1831 **/
1832 template<int x> 1832 template<int x>
1833 dword PeHeaderT<x>::getIddDelayImportRva() const 1833 dword PeHeaderT<x>::getIddDelayImportRva() const
1834 { 1834 {
1835 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress; 1835 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress;
1836 } 1836 }
1837 1837
1838 /** 1838 /**
1839 * Returns the size of the current file's Delay Import directory. 1839 * Returns the size of the current file's Delay Import directory.
1840 * @return The size of the DelayImport directory. 1840 * @return The size of the DelayImport directory.
1841 **/ 1841 **/
1842 template<int x> 1842 template<int x>
1843 dword PeHeaderT<x>::getIddDelayImportSize() const 1843 dword PeHeaderT<x>::getIddDelayImportSize() const
1844 { 1844 {
1845 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size; 1845 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size;
1846 } 1846 }
1847 1847
1848 /** 1848 /**
1849 * Returns the relative virtual address of the current file's COM Descriptor directory. 1849 * Returns the relative virtual address of the current file's COM Descriptor directory.
1850 * @return The Rva of the COM Descriptor directory. 1850 * @return The Rva of the COM Descriptor directory.
1851 **/ 1851 **/
1852 template<int x> 1852 template<int x>
1853 dword PeHeaderT<x>::getIddComHeaderRva() const 1853 dword PeHeaderT<x>::getIddComHeaderRva() const
1854 { 1854 {
1855 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress; 1855 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress;
1856 } 1856 }
1857 1857
1858 /** 1858 /**
1859 * Returns the size of the current file's COM Descriptor directory. 1859 * Returns the size of the current file's COM Descriptor directory.
1860 * @return The Rva of the COM Descriptor directory. 1860 * @return The Rva of the COM Descriptor directory.
1861 **/ 1861 **/
1862 template<int x> 1862 template<int x>
1863 dword PeHeaderT<x>::getIddComHeaderSize() const 1863 dword PeHeaderT<x>::getIddComHeaderSize() const
1864 { 1864 {
1865 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size; 1865 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size;
1866 } 1866 }
1867 1867
1868 /** 1868 /**
1869 * Returns the relative virtual address of an image directory. 1869 * Returns the relative virtual address of an image directory.
1870 * @param dwDirectory The identifier of an image directory. 1870 * @param dwDirectory The identifier of an image directory.
1871 * @return The Rva of the image directory. 1871 * @return The Rva of the image directory.
1872 **/ 1872 **/
1873 template<int x> 1873 template<int x>
1874 dword PeHeaderT<x>::getImageDataDirectoryRva(dword dwDirectory) const 1874 dword PeHeaderT<x>::getImageDataDirectoryRva(dword dwDirectory) const
1875 { 1875 {
1876 return m_inthHeader.dataDirectories[dwDirectory].VirtualAddress; 1876 return m_inthHeader.dataDirectories[dwDirectory].VirtualAddress;
1877 } 1877 }
1878 1878
1879 template<int x> 1879 template<int x>
1880 void PeHeaderT<x>::setImageDataDirectoryRva(dword dwDirectory, dword value) 1880 void PeHeaderT<x>::setImageDataDirectoryRva(dword dwDirectory, dword value)
1881 { 1881 {
1882 m_inthHeader.dataDirectories[dwDirectory].VirtualAddress = value; 1882 m_inthHeader.dataDirectories[dwDirectory].VirtualAddress = value;
1883 } 1883 }
1884 1884
1885 /** 1885 /**
1886 * Returns the size of an image directory. 1886 * Returns the size of an image directory.
1887 * @param dwDirectory The identifier of an image directory. 1887 * @param dwDirectory The identifier of an image directory.
1888 * @return The size of the image directory. 1888 * @return The size of the image directory.
1889 **/ 1889 **/
1890 template<int x> 1890 template<int x>
1891 dword PeHeaderT<x>::getImageDataDirectorySize(dword dwDirectory) const 1891 dword PeHeaderT<x>::getImageDataDirectorySize(dword dwDirectory) const
1892 { 1892 {
1893 return m_inthHeader.dataDirectories[dwDirectory].Size; 1893 return m_inthHeader.dataDirectories[dwDirectory].Size;
1894 } 1894 }
1895 1895
1896 template<int x> 1896 template<int x>
1897 void PeHeaderT<x>::setImageDataDirectorySize(dword dwDirectory, dword value) 1897 void PeHeaderT<x>::setImageDataDirectorySize(dword dwDirectory, dword value)
1898 { 1898 {
1899 m_inthHeader.dataDirectories[dwDirectory].Size = value; 1899 m_inthHeader.dataDirectories[dwDirectory].Size = value;
1900 } 1900 }
1901 1901
1902 /** 1902 /**
1903 * Returns the name of the section which is specified by the parameter wSectionnr. 1903 * Returns the name of the section which is specified by the parameter wSectionnr.
1904 * @param wSectionnr Index of the section. 1904 * @param wSectionnr Index of the section.
1905 * @return The name of the section. 1905 * @return The name of the section.
1906 **/ 1906 **/
1907 template<int x> 1907 template<int x>
1908 std::string PeHeaderT<x>::getSectionName(word wSectionnr) const 1908 std::string PeHeaderT<x>::getSectionName(word wSectionnr) const
1909 { 1909 {
1910 std::string sectionName = ""; 1910 std::string sectionName = "";
1911 1911
1912 for (unsigned int i=0;i<sizeof(m_vIsh[wSectionnr].Name);i++) 1912 for (unsigned int i=0;i<sizeof(m_vIsh[wSectionnr].Name);i++)
1913 { 1913 {
1914 if (m_vIsh[wSectionnr].Name[i]) sectionName += m_vIsh[wSectionnr].Name[i]; 1914 if (m_vIsh[wSectionnr].Name[i]) sectionName += m_vIsh[wSectionnr].Name[i];
1915 } 1915 }
1916 1916
1917 return sectionName; 1917 return sectionName;
1918 } 1918 }
1919 1919
1920 /** 1920 /**
1921 * Returns the virtual size of the section which is specified by the parameter wSectionnr. 1921 * Returns the virtual size of the section which is specified by the parameter wSectionnr.
1922 * @param wSectionnr Index of the section. 1922 * @param wSectionnr Index of the section.
1923 * @return The virtual size of the section. 1923 * @return The virtual size of the section.
1924 **/ 1924 **/
1925 template<int x> 1925 template<int x>
1926 dword PeHeaderT<x>::getVirtualSize(word wSectionnr) const 1926 dword PeHeaderT<x>::getVirtualSize(word wSectionnr) const
1927 { 1927 {
1928 return m_vIsh[wSectionnr].VirtualSize; 1928 return m_vIsh[wSectionnr].VirtualSize;
1929 } 1929 }
1930 1930
1931 /** 1931 /**
1932 * Returns the relative virtual address of the section which is specified by the parameter wSectionnr. 1932 * Returns the relative virtual address of the section which is specified by the parameter wSectionnr.
1933 * @param wSectionnr Index of the section. 1933 * @param wSectionnr Index of the section.
1934 * @return The Rva of the section. 1934 * @return The Rva of the section.
1935 **/ 1935 **/
1936 template<int x> 1936 template<int x>
1937 dword PeHeaderT<x>::getVirtualAddress(word wSectionnr) const 1937 dword PeHeaderT<x>::getVirtualAddress(word wSectionnr) const
1938 { 1938 {
1939 return m_vIsh[wSectionnr].VirtualAddress; 1939 return m_vIsh[wSectionnr].VirtualAddress;
1940 } 1940 }
1941 1941
1942 /** 1942 /**
1943 * Returns the size of raw data of the section which is specified by the parameter wSectionnr. 1943 * Returns the size of raw data of the section which is specified by the parameter wSectionnr.
1944 * @param wSectionnr Index of the section. 1944 * @param wSectionnr Index of the section.
1945 * @return The size of raw data of the section. 1945 * @return The size of raw data of the section.
1946 **/ 1946 **/
1947 template<int x> 1947 template<int x>
1948 dword PeHeaderT<x>::getSizeOfRawData(word wSectionnr) const 1948 dword PeHeaderT<x>::getSizeOfRawData(word wSectionnr) const
1949 { 1949 {
1950 return m_vIsh[wSectionnr].SizeOfRawData; 1950 return m_vIsh[wSectionnr].SizeOfRawData;
1951 } 1951 }
1952 1952
1953 /** 1953 /**
1954 * Returns the file offset of the section which is specified by the parameter wSectionnr. 1954 * Returns the file offset of the section which is specified by the parameter wSectionnr.
1955 * @param wSectionnr Index of the section. 1955 * @param wSectionnr Index of the section.
1956 * @return The file offset of the section. 1956 * @return The file offset of the section.
1957 **/ 1957 **/
1958 template<int x> 1958 template<int x>
1959 dword PeHeaderT<x>::getPointerToRawData(word wSectionnr) const 1959 dword PeHeaderT<x>::getPointerToRawData(word wSectionnr) const
1960 { 1960 {
1961 return m_vIsh[wSectionnr].PointerToRawData; 1961 return m_vIsh[wSectionnr].PointerToRawData;
1962 } 1962 }
1963 1963
1964 /** 1964 /**
1965 * Returns the pointer to relocations of the section which is specified by the parameter wSectionnr. 1965 * Returns the pointer to relocations of the section which is specified by the parameter wSectionnr.
1966 * @param wSectionnr Index of the section. 1966 * @param wSectionnr Index of the section.
1967 * @return The pointer to relocations of the section. 1967 * @return The pointer to relocations of the section.
1968 **/ 1968 **/
1969 template<int x> 1969 template<int x>
1970 dword PeHeaderT<x>::getPointerToRelocations(word wSectionnr) const 1970 dword PeHeaderT<x>::getPointerToRelocations(word wSectionnr) const
1971 { 1971 {
1972 return m_vIsh[wSectionnr].PointerToRelocations; 1972 return m_vIsh[wSectionnr].PointerToRelocations;
1973 } 1973 }
1974 1974
1975 /** 1975 /**
1976 * Returns the poiner to line numbers of the section which is specified by the parameter wSectionnr. 1976 * Returns the poiner to line numbers of the section which is specified by the parameter wSectionnr.
1977 * @param wSectionnr Index of the section. 1977 * @param wSectionnr Index of the section.
1978 * @return The pointer to line numbers of the section. 1978 * @return The pointer to line numbers of the section.
1979 **/ 1979 **/
1980 template<int x> 1980 template<int x>
1981 dword PeHeaderT<x>::getPointerToLinenumbers(word wSectionnr) const 1981 dword PeHeaderT<x>::getPointerToLinenumbers(word wSectionnr) const
1982 { 1982 {
1983 return m_vIsh[wSectionnr].PointerToLinenumbers; 1983 return m_vIsh[wSectionnr].PointerToLinenumbers;
1984 } 1984 }
1985 1985
1986 /** 1986 /**
1987 * Returns the number of relocations of the section which is specified by the parameter wSectionnr. 1987 * Returns the number of relocations of the section which is specified by the parameter wSectionnr.
1988 * @param wSectionnr Index of the section. 1988 * @param wSectionnr Index of the section.
1989 * @return The number of relocations of the section. 1989 * @return The number of relocations of the section.
1990 **/ 1990 **/
1991 template<int x> 1991 template<int x>
1992 dword PeHeaderT<x>::getNumberOfRelocations(word wSectionnr) const 1992 dword PeHeaderT<x>::getNumberOfRelocations(word wSectionnr) const
1993 { 1993 {
1994 return m_vIsh[wSectionnr].NumberOfRelocations; 1994 return m_vIsh[wSectionnr].NumberOfRelocations;
1995 } 1995 }
1996 1996
1997 /** 1997 /**
1998 * Returns the number of line numbers of the section which is specified by the parameter wSectionnr. 1998 * Returns the number of line numbers of the section which is specified by the parameter wSectionnr.
1999 * @param wSectionnr Index of the section. 1999 * @param wSectionnr Index of the section.
2000 * @return The number of line numbers of the section. 2000 * @return The number of line numbers of the section.
2001 **/ 2001 **/
2002 template<int x> 2002 template<int x>
2003 dword PeHeaderT<x>::getNumberOfLinenumbers(word wSectionnr) const 2003 dword PeHeaderT<x>::getNumberOfLinenumbers(word wSectionnr) const
2004 { 2004 {
2005 return m_vIsh[wSectionnr].NumberOfLinenumbers; 2005 return m_vIsh[wSectionnr].NumberOfLinenumbers;
2006 } 2006 }
2007 2007
2008 /** 2008 /**
2009 * Returns the characteristics of the section which is specified by the parameter wSectionnr. 2009 * Returns the characteristics of the section which is specified by the parameter wSectionnr.
2010 * @param wSectionnr Index of the section. 2010 * @param wSectionnr Index of the section.
2011 * @return The characteristics of the section. 2011 * @return The characteristics of the section.
2012 **/ 2012 **/
2013 template<int x> 2013 template<int x>
2014 dword PeHeaderT<x>::getCharacteristics(word wSectionnr) const 2014 dword PeHeaderT<x>::getCharacteristics(word wSectionnr) const
2015 { 2015 {
2016 return m_vIsh[wSectionnr].Characteristics; 2016 return m_vIsh[wSectionnr].Characteristics;
2017 } 2017 }
2018 2018
2019 /** 2019 /**
2020 * Changes the file's Nt signature. 2020 * Changes the file's Nt signature.
2021 * @param dwValue New value. 2021 * @param dwValue New value.
2022 **/ 2022 **/
2023 template<int x> 2023 template<int x>
2024 void PeHeaderT<x>::setNtSignature(dword dwValue) 2024 void PeHeaderT<x>::setNtSignature(dword dwValue)
2025 { 2025 {
2026 m_inthHeader.Signature = dwValue; 2026 m_inthHeader.Signature = dwValue;
2027 } 2027 }
2028 2028
2029 /** 2029 /**
2030 * Changes the file's Machine. 2030 * Changes the file's Machine.
2031 * @param wValue New value. 2031 * @param wValue New value.
2032 **/ 2032 **/
2033 template<int x> 2033 template<int x>
2034 void PeHeaderT<x>::setMachine(word wValue) 2034 void PeHeaderT<x>::setMachine(word wValue)
2035 { 2035 {
2036 m_inthHeader.FileHeader.Machine = wValue; 2036 m_inthHeader.FileHeader.Machine = wValue;
2037 } 2037 }
2038 2038
2039 /** 2039 /**
2040 * Changes the number of sections. 2040 * Changes the number of sections.
2041 * @param wValue New value. 2041 * @param wValue New value.
2042 **/ 2042 **/
2043 template<int x> 2043 template<int x>
2044 void PeHeaderT<x>::setNumberOfSections(word wValue) 2044 void PeHeaderT<x>::setNumberOfSections(word wValue)
2045 { 2045 {
2046 m_inthHeader.FileHeader.NumberOfSections = wValue; 2046 m_inthHeader.FileHeader.NumberOfSections = wValue;
2047 } 2047 }
2048 2048
2049 /** 2049 /**
2050 * Changes the file's TimeDateStamp. 2050 * Changes the file's TimeDateStamp.
2051 * @param dwValue New value. 2051 * @param dwValue New value.
2052 **/ 2052 **/
2053 template<int x> 2053 template<int x>
2054 void PeHeaderT<x>::setTimeDateStamp(dword dwValue) 2054 void PeHeaderT<x>::setTimeDateStamp(dword dwValue)
2055 { 2055 {
2056 m_inthHeader.FileHeader.TimeDateStamp = dwValue; 2056 m_inthHeader.FileHeader.TimeDateStamp = dwValue;
2057 } 2057 }
2058 2058
2059 /** 2059 /**
2060 * Changes the file's PointerToSymbolTable. 2060 * Changes the file's PointerToSymbolTable.
2061 * @param dwValue New value. 2061 * @param dwValue New value.
2062 **/ 2062 **/
2063 template<int x> 2063 template<int x>
2064 void PeHeaderT<x>::setPointerToSymbolTable(dword dwValue) 2064 void PeHeaderT<x>::setPointerToSymbolTable(dword dwValue)
2065 { 2065 {
2066 m_inthHeader.FileHeader.PointerToSymbolTable = dwValue; 2066 m_inthHeader.FileHeader.PointerToSymbolTable = dwValue;
2067 } 2067 }
2068 2068
2069 /** 2069 /**
2070 * Changes the file's NumberOfSymbols. 2070 * Changes the file's NumberOfSymbols.
2071 * @param dwValue New value. 2071 * @param dwValue New value.
2072 **/ 2072 **/
2073 template<int x> 2073 template<int x>
2074 void PeHeaderT<x>::setNumberOfSymbols(dword dwValue) 2074 void PeHeaderT<x>::setNumberOfSymbols(dword dwValue)
2075 { 2075 {
2076 m_inthHeader.FileHeader.NumberOfSymbols = dwValue; 2076 m_inthHeader.FileHeader.NumberOfSymbols = dwValue;
2077 } 2077 }
2078 2078
2079 /** 2079 /**
2080 * Changes the file's SizeOfOptionalHeader. 2080 * Changes the file's SizeOfOptionalHeader.
2081 * @param wValue New value. 2081 * @param wValue New value.
2082 **/ 2082 **/
2083 template<int x> 2083 template<int x>
2084 void PeHeaderT<x>::setSizeOfOptionalHeader(word wValue) 2084 void PeHeaderT<x>::setSizeOfOptionalHeader(word wValue)
2085 { 2085 {
2086 m_inthHeader.FileHeader.SizeOfOptionalHeader = wValue; 2086 m_inthHeader.FileHeader.SizeOfOptionalHeader = wValue;
2087 } 2087 }
2088 2088
2089 /** 2089 /**
2090 * Changes the file's Characteristics. 2090 * Changes the file's Characteristics.
2091 * @param wValue New value. 2091 * @param wValue New value.
2092 **/ 2092 **/
2093 template<int x> 2093 template<int x>
2094 void PeHeaderT<x>::setCharacteristics(word wValue) 2094 void PeHeaderT<x>::setCharacteristics(word wValue)
2095 { 2095 {
2096 m_inthHeader.FileHeader.Characteristics = wValue; 2096 m_inthHeader.FileHeader.Characteristics = wValue;
2097 } 2097 }
2098 2098
2099 /** 2099 /**
2100 * Changes the file's Magic. 2100 * Changes the file's Magic.
2101 * @param wValue New value. 2101 * @param wValue New value.
2102 **/ 2102 **/
2103 template<int x> 2103 template<int x>
2104 void PeHeaderT<x>::setMagic(word wValue) 2104 void PeHeaderT<x>::setMagic(word wValue)
2105 { 2105 {
2106 m_inthHeader.OptionalHeader.Magic = wValue; 2106 m_inthHeader.OptionalHeader.Magic = wValue;
2107 } 2107 }
2108 2108
2109 /** 2109 /**
2110 * Changes the file's MajorLinkerVersion. 2110 * Changes the file's MajorLinkerVersion.
2111 * @param bValue New value. 2111 * @param bValue New value.
2112 **/ 2112 **/
2113 template<int x> 2113 template<int x>
2114 void PeHeaderT<x>::setMajorLinkerVersion(byte bValue) 2114 void PeHeaderT<x>::setMajorLinkerVersion(byte bValue)
2115 { 2115 {
2116 m_inthHeader.OptionalHeader.MajorLinkerVersion = bValue; 2116 m_inthHeader.OptionalHeader.MajorLinkerVersion = bValue;
2117 } 2117 }
2118 2118
2119 /** 2119 /**
2120 * Changes the file's MinorLinkerVersion. 2120 * Changes the file's MinorLinkerVersion.
2121 * @param bValue New value. 2121 * @param bValue New value.
2122 **/ 2122 **/
2123 template<int x> 2123 template<int x>
2124 void PeHeaderT<x>::setMinorLinkerVersion(byte bValue) 2124 void PeHeaderT<x>::setMinorLinkerVersion(byte bValue)
2125 { 2125 {
2126 m_inthHeader.OptionalHeader.MinorLinkerVersion = bValue; 2126 m_inthHeader.OptionalHeader.MinorLinkerVersion = bValue;
2127 } 2127 }
2128 2128
2129 /** 2129 /**
2130 * Changes the file's SizeOfCode. 2130 * Changes the file's SizeOfCode.
2131 * @param dwValue New value. 2131 * @param dwValue New value.
2132 **/ 2132 **/
2133 template<int x> 2133 template<int x>
2134 void PeHeaderT<x>::setSizeOfCode(dword dwValue) 2134 void PeHeaderT<x>::setSizeOfCode(dword dwValue)
2135 { 2135 {
2136 m_inthHeader.OptionalHeader.SizeOfCode = dwValue; 2136 m_inthHeader.OptionalHeader.SizeOfCode = dwValue;
2137 } 2137 }
2138 2138
2139 /** 2139 /**
2140 * Changes the file's SizeOfInitializedData. 2140 * Changes the file's SizeOfInitializedData.
2141 * @param dwValue New value. 2141 * @param dwValue New value.
2142 **/ 2142 **/
2143 template<int x> 2143 template<int x>
2144 void PeHeaderT<x>::setSizeOfInitializedData(dword dwValue) 2144 void PeHeaderT<x>::setSizeOfInitializedData(dword dwValue)
2145 { 2145 {
2146 m_inthHeader.OptionalHeader.SizeOfInitializedData = dwValue; 2146 m_inthHeader.OptionalHeader.SizeOfInitializedData = dwValue;
2147 } 2147 }
2148 2148
2149 /** 2149 /**
2150 * Changes the file's SizeOfUninitializedData. 2150 * Changes the file's SizeOfUninitializedData.
2151 * @param dwValue New value. 2151 * @param dwValue New value.
2152 **/ 2152 **/
2153 template<int x> 2153 template<int x>
2154 void PeHeaderT<x>::setSizeOfUninitializedData(dword dwValue) 2154 void PeHeaderT<x>::setSizeOfUninitializedData(dword dwValue)
2155 { 2155 {
2156 m_inthHeader.OptionalHeader.SizeOfUninitializedData = dwValue; 2156 m_inthHeader.OptionalHeader.SizeOfUninitializedData = dwValue;
2157 } 2157 }
2158 2158
2159 /** 2159 /**
2160 * Changes the file's AddressOfEntryPoint. 2160 * Changes the file's AddressOfEntryPoint.
2161 * @param dwValue New value. 2161 * @param dwValue New value.
2162 **/ 2162 **/
2163 template<int x> 2163 template<int x>
2164 void PeHeaderT<x>::setAddressOfEntryPoint(dword dwValue) 2164 void PeHeaderT<x>::setAddressOfEntryPoint(dword dwValue)
2165 { 2165 {
2166 m_inthHeader.OptionalHeader.AddressOfEntryPoint = dwValue; 2166 m_inthHeader.OptionalHeader.AddressOfEntryPoint = dwValue;
2167 } 2167 }
2168 2168
2169 /** 2169 /**
2170 * Changes the file's BaseOfCode. 2170 * Changes the file's BaseOfCode.
2171 * @param dwValue New value. 2171 * @param dwValue New value.
2172 **/ 2172 **/
2173 template<int x> 2173 template<int x>
2174 void PeHeaderT<x>::setBaseOfCode(dword dwValue) 2174 void PeHeaderT<x>::setBaseOfCode(dword dwValue)
2175 { 2175 {
2176 m_inthHeader.OptionalHeader.BaseOfCode = dwValue; 2176 m_inthHeader.OptionalHeader.BaseOfCode = dwValue;
2177 } 2177 }
2178 2178
2179 /** 2179 /**
2180 * Changes the file's ImageBase. 2180 * Changes the file's ImageBase.
2181 * @param dwValue New value. 2181 * @param dwValue New value.
2182 **/ 2182 **/
2183 template<int x> 2183 template<int x>
2184 void PeHeaderT<x>::setImageBase(typename FieldSizes<x>::VAR4_8 dwValue) 2184 void PeHeaderT<x>::setImageBase(typename FieldSizes<x>::VAR4_8 dwValue)
2185 { 2185 {
2186 m_inthHeader.OptionalHeader.ImageBase = dwValue; 2186 m_inthHeader.OptionalHeader.ImageBase = dwValue;
2187 } 2187 }
2188 2188
2189 /** 2189 /**
2190 * Changes the file's SectionAlignment. 2190 * Changes the file's SectionAlignment.
2191 * @param dwValue New value. 2191 * @param dwValue New value.
2192 **/ 2192 **/
2193 template<int x> 2193 template<int x>
2194 void PeHeaderT<x>::setSectionAlignment(dword dwValue) 2194 void PeHeaderT<x>::setSectionAlignment(dword dwValue)
2195 { 2195 {
2196 m_inthHeader.OptionalHeader.SectionAlignment = dwValue; 2196 m_inthHeader.OptionalHeader.SectionAlignment = dwValue;
2197 } 2197 }
2198 2198
2199 /** 2199 /**
2200 * Changes the file's FileAlignment. 2200 * Changes the file's FileAlignment.
2201 * @param dwValue New value. 2201 * @param dwValue New value.
2202 **/ 2202 **/
2203 template<int x> 2203 template<int x>
2204 void PeHeaderT<x>::setFileAlignment(dword dwValue) 2204 void PeHeaderT<x>::setFileAlignment(dword dwValue)
2205 { 2205 {
2206 m_inthHeader.OptionalHeader.FileAlignment = dwValue; 2206 m_inthHeader.OptionalHeader.FileAlignment = dwValue;
2207 } 2207 }
2208 2208
2209 /** 2209 /**
2210 * Changes the file's MajorOperatingSystemVersion. 2210 * Changes the file's MajorOperatingSystemVersion.
2211 * @param wValue New value. 2211 * @param wValue New value.
2212 **/ 2212 **/
2213 template<int x> 2213 template<int x>
2214 void PeHeaderT<x>::setMajorOperatingSystemVersion(word wValue) 2214 void PeHeaderT<x>::setMajorOperatingSystemVersion(word wValue)
2215 { 2215 {
2216 m_inthHeader.OptionalHeader.MajorOperatingSystemVersion = wValue; 2216 m_inthHeader.OptionalHeader.MajorOperatingSystemVersion = wValue;
2217 } 2217 }
2218 2218
2219 /** 2219 /**
2220 * Changes the file's MinorOperatingSystemVersion. 2220 * Changes the file's MinorOperatingSystemVersion.
2221 * @param wValue New value. 2221 * @param wValue New value.
2222 **/ 2222 **/
2223 template<int x> 2223 template<int x>
2224 void PeHeaderT<x>::setMinorOperatingSystemVersion(word wValue) 2224 void PeHeaderT<x>::setMinorOperatingSystemVersion(word wValue)
2225 { 2225 {
2226 m_inthHeader.OptionalHeader.MinorOperatingSystemVersion = wValue; 2226 m_inthHeader.OptionalHeader.MinorOperatingSystemVersion = wValue;
2227 } 2227 }
2228 2228
2229 /** 2229 /**
2230 * Changes the file's MajorImageVersion. 2230 * Changes the file's MajorImageVersion.
2231 * @param wValue New value. 2231 * @param wValue New value.
2232 **/ 2232 **/
2233 template<int x> 2233 template<int x>
2234 void PeHeaderT<x>::setMajorImageVersion(word wValue) 2234 void PeHeaderT<x>::setMajorImageVersion(word wValue)
2235 { 2235 {
2236 m_inthHeader.OptionalHeader.MajorImageVersion = wValue; 2236 m_inthHeader.OptionalHeader.MajorImageVersion = wValue;
2237 } 2237 }
2238 2238
2239 /** 2239 /**
2240 * Changes the file's MinorImageVersion. 2240 * Changes the file's MinorImageVersion.
2241 * @param wValue New value. 2241 * @param wValue New value.
2242 **/ 2242 **/
2243 template<int x> 2243 template<int x>
2244 void PeHeaderT<x>::setMinorImageVersion(word wValue) 2244 void PeHeaderT<x>::setMinorImageVersion(word wValue)
2245 { 2245 {
2246 m_inthHeader.OptionalHeader.MinorImageVersion = wValue; 2246 m_inthHeader.OptionalHeader.MinorImageVersion = wValue;
2247 } 2247 }
2248 2248
2249 /** 2249 /**
2250 * Changes the file's MajorSubsystemVersion. 2250 * Changes the file's MajorSubsystemVersion.
2251 * @param wValue New value. 2251 * @param wValue New value.
2252 **/ 2252 **/
2253 template<int x> 2253 template<int x>
2254 void PeHeaderT<x>::setMajorSubsystemVersion(word wValue) 2254 void PeHeaderT<x>::setMajorSubsystemVersion(word wValue)
2255 { 2255 {
2256 m_inthHeader.OptionalHeader.MajorSubsystemVersion = wValue; 2256 m_inthHeader.OptionalHeader.MajorSubsystemVersion = wValue;
2257 } 2257 }
2258 2258
2259 /** 2259 /**
2260 * Changes the file's MinorSubsystemVersion. 2260 * Changes the file's MinorSubsystemVersion.
2261 * @param wValue New value. 2261 * @param wValue New value.
2262 **/ 2262 **/
2263 template<int x> 2263 template<int x>
2264 void PeHeaderT<x>::setMinorSubsystemVersion(word wValue) 2264 void PeHeaderT<x>::setMinorSubsystemVersion(word wValue)
2265 { 2265 {
2266 m_inthHeader.OptionalHeader.MinorSubsystemVersion = wValue; 2266 m_inthHeader.OptionalHeader.MinorSubsystemVersion = wValue;
2267 } 2267 }
2268 2268
2269 /** 2269 /**
2270 * Changes the file's Win32VersionValue. 2270 * Changes the file's Win32VersionValue.
2271 * @param dwValue New value. 2271 * @param dwValue New value.
2272 **/ 2272 **/
2273 template<int x> 2273 template<int x>
2274 void PeHeaderT<x>::setWin32VersionValue(dword dwValue) 2274 void PeHeaderT<x>::setWin32VersionValue(dword dwValue)
2275 { 2275 {
2276 m_inthHeader.OptionalHeader.Win32VersionValue = dwValue; 2276 m_inthHeader.OptionalHeader.Win32VersionValue = dwValue;
2277 } 2277 }
2278 2278
2279 /** 2279 /**
2280 * Changes the file's SizeOfImage. 2280 * Changes the file's SizeOfImage.
2281 * @param dwValue New value. 2281 * @param dwValue New value.
2282 **/ 2282 **/
2283 template<int x> 2283 template<int x>
2284 void PeHeaderT<x>::setSizeOfImage(dword dwValue) 2284 void PeHeaderT<x>::setSizeOfImage(dword dwValue)
2285 { 2285 {
2286 m_inthHeader.OptionalHeader.SizeOfImage = dwValue; 2286 m_inthHeader.OptionalHeader.SizeOfImage = dwValue;
2287 } 2287 }
2288 2288
2289 /** 2289 /**
2290 * Changes the file's SizeOfHeaders. 2290 * Changes the file's SizeOfHeaders.
2291 * @param dwValue New value. 2291 * @param dwValue New value.
2292 **/ 2292 **/
2293 template<int x> 2293 template<int x>
2294 void PeHeaderT<x>::setSizeOfHeaders(dword dwValue) 2294 void PeHeaderT<x>::setSizeOfHeaders(dword dwValue)
2295 { 2295 {
2296 m_inthHeader.OptionalHeader.SizeOfHeaders = dwValue; 2296 m_inthHeader.OptionalHeader.SizeOfHeaders = dwValue;
2297 } 2297 }
2298 2298
2299 /** 2299 /**
2300 * Changes the file's CheckSum. 2300 * Changes the file's CheckSum.
2301 * @param dwValue New value. 2301 * @param dwValue New value.
2302 **/ 2302 **/
2303 template<int x> 2303 template<int x>
2304 void PeHeaderT<x>::setCheckSum(dword dwValue) 2304 void PeHeaderT<x>::setCheckSum(dword dwValue)
2305 { 2305 {
2306 m_inthHeader.OptionalHeader.CheckSum = dwValue; 2306 m_inthHeader.OptionalHeader.CheckSum = dwValue;
2307 } 2307 }
2308 2308
2309 /** 2309 /**
2310 * Changes the file's Subsystem. 2310 * Changes the file's Subsystem.
2311 * @param wValue New value. 2311 * @param wValue New value.
2312 **/ 2312 **/
2313 template<int x> 2313 template<int x>
2314 void PeHeaderT<x>::setSubsystem(word wValue) 2314 void PeHeaderT<x>::setSubsystem(word wValue)
2315 { 2315 {
2316 m_inthHeader.OptionalHeader.Subsystem = wValue; 2316 m_inthHeader.OptionalHeader.Subsystem = wValue;
2317 } 2317 }
2318 2318
2319 /** 2319 /**
2320 * Changes the file's DllCharacteristics. 2320 * Changes the file's DllCharacteristics.
2321 * @param wValue New value. 2321 * @param wValue New value.
2322 **/ 2322 **/
2323 template<int x> 2323 template<int x>
2324 void PeHeaderT<x>::setDllCharacteristics(word wValue) 2324 void PeHeaderT<x>::setDllCharacteristics(word wValue)
2325 { 2325 {
2326 m_inthHeader.OptionalHeader.DllCharacteristics = wValue; 2326 m_inthHeader.OptionalHeader.DllCharacteristics = wValue;
2327 } 2327 }
2328 2328
2329 /** 2329 /**
2330 * Changes the file's SizeOfStackReserve. 2330 * Changes the file's SizeOfStackReserve.
2331 * @param dwValue New value. 2331 * @param dwValue New value.
2332 **/ 2332 **/
2333 template<int x> 2333 template<int x>
2334 void PeHeaderT<x>::setSizeOfStackReserve(typename FieldSizes<x>::VAR4_8 dwValue) 2334 void PeHeaderT<x>::setSizeOfStackReserve(typename FieldSizes<x>::VAR4_8 dwValue)
2335 { 2335 {
2336 m_inthHeader.OptionalHeader.SizeOfStackReserve = dwValue; 2336 m_inthHeader.OptionalHeader.SizeOfStackReserve = dwValue;
2337 } 2337 }
2338 2338
2339 /** 2339 /**
2340 * Changes the file's SizeOfStackCommit. 2340 * Changes the file's SizeOfStackCommit.
2341 * @param dwValue New value. 2341 * @param dwValue New value.
2342 **/ 2342 **/
2343 template<int x> 2343 template<int x>
2344 void PeHeaderT<x>::setSizeOfStackCommit(typename FieldSizes<x>::VAR4_8 dwValue) 2344 void PeHeaderT<x>::setSizeOfStackCommit(typename FieldSizes<x>::VAR4_8 dwValue)
2345 { 2345 {
2346 m_inthHeader.OptionalHeader.SizeOfStackCommit = dwValue; 2346 m_inthHeader.OptionalHeader.SizeOfStackCommit = dwValue;
2347 } 2347 }
2348 2348
2349 /** 2349 /**
2350 * Changes the file's SizeOfHeapReserve. 2350 * Changes the file's SizeOfHeapReserve.
2351 * @param dwValue New value. 2351 * @param dwValue New value.
2352 **/ 2352 **/
2353 template<int x> 2353 template<int x>
2354 void PeHeaderT<x>::setSizeOfHeapReserve(typename FieldSizes<x>::VAR4_8 dwValue) 2354 void PeHeaderT<x>::setSizeOfHeapReserve(typename FieldSizes<x>::VAR4_8 dwValue)
2355 { 2355 {
2356 m_inthHeader.OptionalHeader.SizeOfHeapReserve = dwValue; 2356 m_inthHeader.OptionalHeader.SizeOfHeapReserve = dwValue;
2357 } 2357 }
2358 2358
2359 /** 2359 /**
2360 * Changes the file's SizeOfHeapCommit. 2360 * Changes the file's SizeOfHeapCommit.
2361 * @param dwValue New value. 2361 * @param dwValue New value.
2362 **/ 2362 **/
2363 template<int x> 2363 template<int x>
2364 void PeHeaderT<x>::setSizeOfHeapCommit(typename FieldSizes<x>::VAR4_8 dwValue) 2364 void PeHeaderT<x>::setSizeOfHeapCommit(typename FieldSizes<x>::VAR4_8 dwValue)
2365 { 2365 {
2366 m_inthHeader.OptionalHeader.SizeOfHeapCommit = dwValue; 2366 m_inthHeader.OptionalHeader.SizeOfHeapCommit = dwValue;
2367 } 2367 }
2368 2368
2369 /** 2369 /**
2370 * Changes the file's LoaderFlags. 2370 * Changes the file's LoaderFlags.
2371 * @param dwValue New value. 2371 * @param dwValue New value.
2372 **/ 2372 **/
2373 template<int x> 2373 template<int x>
2374 void PeHeaderT<x>::setLoaderFlags(dword dwValue) 2374 void PeHeaderT<x>::setLoaderFlags(dword dwValue)
2375 { 2375 {
2376 m_inthHeader.OptionalHeader.LoaderFlags = dwValue; 2376 m_inthHeader.OptionalHeader.LoaderFlags = dwValue;
2377 } 2377 }
2378 2378
2379 /** 2379 /**
2380 * Changes the file's NumberOfRvaAndSizes. 2380 * Changes the file's NumberOfRvaAndSizes.
2381 * @param dwValue New value. 2381 * @param dwValue New value.
2382 **/ 2382 **/
2383 template<int x> 2383 template<int x>
2384 void PeHeaderT<x>::setNumberOfRvaAndSizes(dword dwValue) 2384 void PeHeaderT<x>::setNumberOfRvaAndSizes(dword dwValue)
2385 { 2385 {
2386 m_inthHeader.OptionalHeader.NumberOfRvaAndSizes = dwValue; 2386 m_inthHeader.OptionalHeader.NumberOfRvaAndSizes = dwValue;
2387 } 2387 }
2388 2388
2389 template<int x> 2389 template<int x>
2390 void PeHeaderT<x>::setIddDebugRva(dword dwValue) 2390 void PeHeaderT<x>::setIddDebugRva(dword dwValue)
2391 { 2391 {
2392 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress = dwValue; 2392 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress = dwValue;
2393 } 2393 }
2394 2394
2395 template<int x> 2395 template<int x>
2396 void PeHeaderT<x>::setIddDebugSize(dword dwValue) 2396 void PeHeaderT<x>::setIddDebugSize(dword dwValue)
2397 { 2397 {
2398 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DEBUG].Size = dwValue; 2398 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DEBUG].Size = dwValue;
2399 } 2399 }
2400 2400
2401 template<int x> 2401 template<int x>
2402 void PeHeaderT<x>::setIddDelayImportRva(dword dwValue) 2402 void PeHeaderT<x>::setIddDelayImportRva(dword dwValue)
2403 { 2403 {
2404 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress = dwValue; 2404 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress = dwValue;
2405 } 2405 }
2406 2406
2407 template<int x> 2407 template<int x>
2408 void PeHeaderT<x>::setIddDelayImportSize(dword dwValue) 2408 void PeHeaderT<x>::setIddDelayImportSize(dword dwValue)
2409 { 2409 {
2410 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size = dwValue; 2410 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size = dwValue;
2411 } 2411 }
2412 2412
2413 template<int x> 2413 template<int x>
2414 void PeHeaderT<x>::setIddExceptionRva(dword dwValue) 2414 void PeHeaderT<x>::setIddExceptionRva(dword dwValue)
2415 { 2415 {
2416 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress = dwValue; 2416 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress = dwValue;
2417 } 2417 }
2418 2418
2419 template<int x> 2419 template<int x>
2420 void PeHeaderT<x>::setIddExceptionSize(dword dwValue) 2420 void PeHeaderT<x>::setIddExceptionSize(dword dwValue)
2421 { 2421 {
2422 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size = dwValue; 2422 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size = dwValue;
2423 } 2423 }
2424 2424
2425 template<int x> 2425 template<int x>
2426 void PeHeaderT<x>::setIddGlobalPtrRva(dword dwValue) 2426 void PeHeaderT<x>::setIddGlobalPtrRva(dword dwValue)
2427 { 2427 {
2428 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_GLOBALPTR].VirtualAddress = dwValue; 2428 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_GLOBALPTR].VirtualAddress = dwValue;
2429 } 2429 }
2430 2430
2431 template<int x> 2431 template<int x>
2432 void PeHeaderT<x>::setIddGlobalPtrSize(dword dwValue) 2432 void PeHeaderT<x>::setIddGlobalPtrSize(dword dwValue)
2433 { 2433 {
2434 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_GLOBALPTR].Size = dwValue; 2434 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_GLOBALPTR].Size = dwValue;
2435 } 2435 }
2436 2436
2437 template<int x> 2437 template<int x>
2438 void PeHeaderT<x>::setIddIatRva(dword dwValue) 2438 void PeHeaderT<x>::setIddIatRva(dword dwValue)
2439 { 2439 {
2440 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress = dwValue; 2440 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress = dwValue;
2441 } 2441 }
2442 2442
2443 template<int x> 2443 template<int x>
2444 void PeHeaderT<x>::setIddIatSize(dword dwValue) 2444 void PeHeaderT<x>::setIddIatSize(dword dwValue)
2445 { 2445 {
2446 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IAT].Size = dwValue; 2446 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IAT].Size = dwValue;
2447 } 2447 }
2448 2448
2449 template<int x> 2449 template<int x>
2450 void PeHeaderT<x>::setIddLoadConfigRva(dword dwValue) 2450 void PeHeaderT<x>::setIddLoadConfigRva(dword dwValue)
2451 { 2451 {
2452 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].VirtualAddress = dwValue; 2452 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].VirtualAddress = dwValue;
2453 } 2453 }
2454 2454
2455 template<int x> 2455 template<int x>
2456 void PeHeaderT<x>::setIddLoadConfigSize(dword dwValue) 2456 void PeHeaderT<x>::setIddLoadConfigSize(dword dwValue)
2457 { 2457 {
2458 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].Size = dwValue; 2458 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].Size = dwValue;
2459 } 2459 }
2460 2460
2461 template<int x> 2461 template<int x>
2462 void PeHeaderT<x>::setIddResourceRva(dword dwValue) 2462 void PeHeaderT<x>::setIddResourceRva(dword dwValue)
2463 { 2463 {
2464 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress = dwValue; 2464 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress = dwValue;
2465 } 2465 }
2466 2466
2467 template<int x> 2467 template<int x>
2468 void PeHeaderT<x>::setIddResourceSize(dword dwValue) 2468 void PeHeaderT<x>::setIddResourceSize(dword dwValue)
2469 { 2469 {
2470 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = dwValue; 2470 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = dwValue;
2471 } 2471 }
2472 2472
2473 template<int x> 2473 template<int x>
2474 void PeHeaderT<x>::setIddSecurityRva(dword dwValue) 2474 void PeHeaderT<x>::setIddSecurityRva(dword dwValue)
2475 { 2475 {
2476 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress = dwValue; 2476 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress = dwValue;
2477 } 2477 }
2478 2478
2479 template<int x> 2479 template<int x>
2480 void PeHeaderT<x>::setIddSecuritySize(dword dwValue) 2480 void PeHeaderT<x>::setIddSecuritySize(dword dwValue)
2481 { 2481 {
2482 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_SECURITY].Size = dwValue; 2482 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_SECURITY].Size = dwValue;
2483 } 2483 }
2484 2484
2485 template<int x> 2485 template<int x>
2486 void PeHeaderT<x>::setIddTlsRva(dword dwValue) 2486 void PeHeaderT<x>::setIddTlsRva(dword dwValue)
2487 { 2487 {
2488 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_TLS].VirtualAddress = dwValue; 2488 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_TLS].VirtualAddress = dwValue;
2489 } 2489 }
2490 2490
2491 template<int x> 2491 template<int x>
2492 void PeHeaderT<x>::setIddTlsSize(dword dwValue) 2492 void PeHeaderT<x>::setIddTlsSize(dword dwValue)
2493 { 2493 {
2494 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_TLS].Size = dwValue; 2494 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_TLS].Size = dwValue;
2495 } 2495 }
2496 2496
2497 /** 2497 /**
2498 * Changes the rva of the file's export directory. 2498 * Changes the rva of the file's export directory.
2499 * @param dwValue New value. 2499 * @param dwValue New value.
2500 **/ 2500 **/
2501 template<int x> 2501 template<int x>
2502 void PeHeaderT<x>::setIddExportRva(dword dwValue) 2502 void PeHeaderT<x>::setIddExportRva(dword dwValue)
2503 { 2503 {
2504 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress = dwValue; 2504 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress = dwValue;
2505 } 2505 }
2506 2506
2507 /** 2507 /**
2508 * Changes the size of the file's export directory. 2508 * Changes the size of the file's export directory.
2509 * @param dwValue New value. 2509 * @param dwValue New value.
2510 **/ 2510 **/
2511 template<int x> 2511 template<int x>
2512 void PeHeaderT<x>::setIddExportSize(dword dwValue) 2512 void PeHeaderT<x>::setIddExportSize(dword dwValue)
2513 { 2513 {
2514 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXPORT].Size = dwValue; 2514 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXPORT].Size = dwValue;
2515 } 2515 }
2516 2516
2517 template<int x> 2517 template<int x>
2518 void PeHeaderT<x>::setIddBaseRelocRva(dword value) 2518 void PeHeaderT<x>::setIddBaseRelocRva(dword value)
2519 { 2519 {
2520 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress = value; 2520 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress = value;
2521 } 2521 }
2522 2522
2523 template<int x> 2523 template<int x>
2524 void PeHeaderT<x>::setIddBaseRelocSize(dword value) 2524 void PeHeaderT<x>::setIddBaseRelocSize(dword value)
2525 { 2525 {
2526 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size = value; 2526 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size = value;
2527 } 2527 }
2528 2528
2529 template<int x> 2529 template<int x>
2530 void PeHeaderT<x>::setIddArchitectureRva(dword value) 2530 void PeHeaderT<x>::setIddArchitectureRva(dword value)
2531 { 2531 {
2532 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_ARCHITECTURE].VirtualAddress = value; 2532 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_ARCHITECTURE].VirtualAddress = value;
2533 } 2533 }
2534 2534
2535 template<int x> 2535 template<int x>
2536 void PeHeaderT<x>::setIddArchitectureSize(dword value) 2536 void PeHeaderT<x>::setIddArchitectureSize(dword value)
2537 { 2537 {
2538 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_ARCHITECTURE].Size = value; 2538 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_ARCHITECTURE].Size = value;
2539 } 2539 }
2540 2540
2541 template<int x> 2541 template<int x>
2542 void PeHeaderT<x>::setIddComHeaderRva(dword value) 2542 void PeHeaderT<x>::setIddComHeaderRva(dword value)
2543 { 2543 {
2544 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress = value; 2544 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress = value;
2545 } 2545 }
2546 2546
2547 template<int x> 2547 template<int x>
2548 void PeHeaderT<x>::setIddComHeaderSize(dword value) 2548 void PeHeaderT<x>::setIddComHeaderSize(dword value)
2549 { 2549 {
2550 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size = value; 2550 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size = value;
2551 } 2551 }
2552 2552
2553 /** 2553 /**
2554 * Changes the rva of the file's import directory. 2554 * Changes the rva of the file's import directory.
2555 * @param dwValue New value. 2555 * @param dwValue New value.
2556 **/ 2556 **/
2557 template<int x> 2557 template<int x>
2558 void PeHeaderT<x>::setIddImportRva(dword dwValue) 2558 void PeHeaderT<x>::setIddImportRva(dword dwValue)
2559 { 2559 {
2560 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress = dwValue; 2560 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress = dwValue;
2561 } 2561 }
2562 2562
2563 /** 2563 /**
2564 * Changes the size of the file's import directory. 2564 * Changes the size of the file's import directory.
2565 * @param dwValue New value. 2565 * @param dwValue New value.
2566 **/ 2566 **/
2567 template<int x> 2567 template<int x>
2568 void PeHeaderT<x>::setIddImportSize(dword dwValue) 2568 void PeHeaderT<x>::setIddImportSize(dword dwValue)
2569 { 2569 {
2570 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IMPORT].Size = dwValue; 2570 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IMPORT].Size = dwValue;
2571 } 2571 }
2572 2572
2573 /** 2573 /**
2574 * Changes the name of a section. 2574 * Changes the name of a section.
2575 * @param wSectionnr Identifier of the section 2575 * @param wSectionnr Identifier of the section
2576 * @param strName New name. 2576 * @param strName New name.
2577 **/ 2577 **/
2578 template<int x> 2578 template<int x>
2579 void PeHeaderT<x>::setSectionName(word wSectionnr, std::string strName) 2579 void PeHeaderT<x>::setSectionName(word wSectionnr, std::string strName)
2580 { 2580 {
2581 strncpy(reinterpret_cast<char*>(m_vIsh[wSectionnr].Name), strName.c_str(), sizeof(m_vIsh[wSectionnr].Name)); 2581 strncpy(reinterpret_cast<char*>(m_vIsh[wSectionnr].Name), strName.c_str(), sizeof(m_vIsh[wSectionnr].Name));
2582 } 2582 }
2583 2583
2584 /** 2584 /**
2585 * Changes the virtual size of a section. 2585 * Changes the virtual size of a section.
2586 * @param wSectionnr Identifier of the section 2586 * @param wSectionnr Identifier of the section
2587 * @param dwValue New value. 2587 * @param dwValue New value.
2588 **/ 2588 **/
2589 template<int x> 2589 template<int x>
2590 void PeHeaderT<x>::setVirtualSize(word wSectionnr, dword dwValue) 2590 void PeHeaderT<x>::setVirtualSize(word wSectionnr, dword dwValue)
2591 { 2591 {
2592 m_vIsh[wSectionnr].VirtualSize = dwValue; 2592 m_vIsh[wSectionnr].VirtualSize = dwValue;
2593 } 2593 }
2594 2594
2595 /** 2595 /**
2596 * Changes the virtual address of a section. 2596 * Changes the virtual address of a section.
2597 * @param wSectionnr Identifier of the section 2597 * @param wSectionnr Identifier of the section
2598 * @param dwValue New value. 2598 * @param dwValue New value.
2599 **/ 2599 **/
2600 template<int x> 2600 template<int x>
2601 void PeHeaderT<x>::setVirtualAddress(word wSectionnr, dword dwValue) 2601 void PeHeaderT<x>::setVirtualAddress(word wSectionnr, dword dwValue)
2602 { 2602 {
2603 m_vIsh[wSectionnr].VirtualAddress = dwValue; 2603 m_vIsh[wSectionnr].VirtualAddress = dwValue;
2604 } 2604 }
2605 2605
2606 /** 2606 /**
2607 * Changes the size of raw data of a section. 2607 * Changes the size of raw data of a section.
2608 * @param wSectionnr Identifier of the section 2608 * @param wSectionnr Identifier of the section
2609 * @param dwValue New value. 2609 * @param dwValue New value.
2610 **/ 2610 **/
2611 template<int x> 2611 template<int x>
2612 void PeHeaderT<x>::setSizeOfRawData(word wSectionnr, dword dwValue) 2612 void PeHeaderT<x>::setSizeOfRawData(word wSectionnr, dword dwValue)
2613 { 2613 {
2614 m_vIsh[wSectionnr].SizeOfRawData = dwValue; 2614 m_vIsh[wSectionnr].SizeOfRawData = dwValue;
2615 } 2615 }
2616 2616
2617 /** 2617 /**
2618 * Changes the size of raw data of a section. 2618 * Changes the size of raw data of a section.
2619 * @param wSectionnr Identifier of the section 2619 * @param wSectionnr Identifier of the section
2620 * @param dwValue New value. 2620 * @param dwValue New value.
2621 **/ 2621 **/
2622 template<int x> 2622 template<int x>
2623 void PeHeaderT<x>::setPointerToRawData(word wSectionnr, dword dwValue) 2623 void PeHeaderT<x>::setPointerToRawData(word wSectionnr, dword dwValue)
2624 { 2624 {
2625 m_vIsh[wSectionnr].PointerToRawData = dwValue; 2625 m_vIsh[wSectionnr].PointerToRawData = dwValue;
2626 } 2626 }
2627 2627
2628 /** 2628 /**
2629 * Changes the pointer to relocations of a section. 2629 * Changes the pointer to relocations of a section.
2630 * @param wSectionnr Identifier of the section 2630 * @param wSectionnr Identifier of the section
2631 * @param dwValue New value. 2631 * @param dwValue New value.
2632 **/ 2632 **/
2633 template<int x> 2633 template<int x>
2634 void PeHeaderT<x>::setPointerToRelocations(word wSectionnr, dword dwValue) 2634 void PeHeaderT<x>::setPointerToRelocations(word wSectionnr, dword dwValue)
2635 { 2635 {
2636 m_vIsh[wSectionnr].PointerToRelocations = dwValue; 2636 m_vIsh[wSectionnr].PointerToRelocations = dwValue;
2637 } 2637 }
2638 2638
2639 /** 2639 /**
2640 * Changes the pointer to line numbers of a section. 2640 * Changes the pointer to line numbers of a section.
2641 * @param wSectionnr Identifier of the section 2641 * @param wSectionnr Identifier of the section
2642 * @param dwValue New value. 2642 * @param dwValue New value.
2643 **/ 2643 **/
2644 template<int x> 2644 template<int x>
2645 void PeHeaderT<x>::setPointerToLinenumbers(word wSectionnr, dword dwValue) 2645 void PeHeaderT<x>::setPointerToLinenumbers(word wSectionnr, dword dwValue)
2646 { 2646 {
2647 m_vIsh[wSectionnr].PointerToLinenumbers = dwValue; 2647 m_vIsh[wSectionnr].PointerToLinenumbers = dwValue;
2648 } 2648 }
2649 2649
2650 /** 2650 /**
2651 * Changes the number of relocations of a section. 2651 * Changes the number of relocations of a section.
2652 * @param wSectionnr Identifier of the section 2652 * @param wSectionnr Identifier of the section
2653 * @param dwValue New value. 2653 * @param dwValue New value.
2654 **/ 2654 **/
2655 template<int x> 2655 template<int x>
2656 void PeHeaderT<x>::setNumberOfRelocations(word wSectionnr, dword dwValue) 2656 void PeHeaderT<x>::setNumberOfRelocations(word wSectionnr, dword dwValue)
2657 { 2657 {
2658 m_vIsh[wSectionnr].NumberOfRelocations = dwValue; 2658 m_vIsh[wSectionnr].NumberOfRelocations = dwValue;
2659 } 2659 }
2660 2660
2661 /** 2661 /**
2662 * Changes the number of line numbers of a section. 2662 * Changes the number of line numbers of a section.
2663 * @param wSectionnr Identifier of the section 2663 * @param wSectionnr Identifier of the section
2664 * @param dwValue New value. 2664 * @param dwValue New value.
2665 **/ 2665 **/
2666 template<int x> 2666 template<int x>
2667 void PeHeaderT<x>::setNumberOfLinenumbers(word wSectionnr, dword dwValue) 2667 void PeHeaderT<x>::setNumberOfLinenumbers(word wSectionnr, dword dwValue)
2668 { 2668 {
2669 m_vIsh[wSectionnr].NumberOfLinenumbers = dwValue; 2669 m_vIsh[wSectionnr].NumberOfLinenumbers = dwValue;
2670 } 2670 }
2671 2671
2672 /** 2672 /**
2673 * Changes the characteristics of a section. 2673 * Changes the characteristics of a section.
2674 * @param wSectionnr Identifier of the section 2674 * @param wSectionnr Identifier of the section
2675 * @param dwValue New value. 2675 * @param dwValue New value.
2676 **/ 2676 **/
2677 template<int x> 2677 template<int x>
2678 void PeHeaderT<x>::setCharacteristics(word wSectionnr, dword dwValue) 2678 void PeHeaderT<x>::setCharacteristics(word wSectionnr, dword dwValue)
2679 { 2679 {
2680 m_vIsh[wSectionnr].Characteristics = dwValue; 2680 m_vIsh[wSectionnr].Characteristics = dwValue;
2681 } 2681 }
2682 2682
2683} 2683}
2684 2684
2685#endif 2685#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/PeLib.h b/utils/zenutils/libraries/pelib-0.9/pelib/PeLib.h
index 870c873606..12f9693dda 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/PeLib.h
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/PeLib.h
@@ -1,27 +1,27 @@
1/* 1/*
2* PeLib.h - Part of the PeLib library. 2* PeLib.h - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13 13
14/** \mainpage PeLib - An open-source C++ library to modify PE files. 14/** \mainpage PeLib - An open-source C++ library to modify PE files.
15* 15*
16* \section intro Introduction 16* \section intro Introduction
17* 17*
18* <b>What is PeLib?</b><br> 18* <b>What is PeLib?</b><br>
19* PeLib is an open source C++ library with the purpose to ease the access and modification of PE (Portable executable) files. This is done through a multitude of classes which represent all important PE header and directory structures and which provide the necessary functions to read, modify and write these structures. As this library is fully ISO C++ compliant it should compile with all popular compilers for the Windows platform. For people who don't use C++ in their projects a dynamic link library is provided which encapsulates all of PeLib's functionality so that projects using programming languages as diverse as Win32 assembler, C# or Delphi can still benefit from PeLib's power 19* PeLib is an open source C++ library with the purpose to ease the access and modification of PE (Portable executable) files. This is done through a multitude of classes which represent all important PE header and directory structures and which provide the necessary functions to read, modify and write these structures. As this library is fully ISO C++ compliant it should compile with all popular compilers for the Windows platform. For people who don't use C++ in their projects a dynamic link library is provided which encapsulates all of PeLib's functionality so that projects using programming languages as diverse as Win32 assembler, C# or Delphi can still benefit from PeLib's power
20*/ 20*/
21 21
22#ifndef PELIB_H 22#ifndef PELIB_H
23#define PELIB_H 23#define PELIB_H
24 24
25#include "PeFile.h" 25#include "PeFile.h"
26 26
27#endif 27#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/PeLibAux.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/PeLibAux.cpp
index 1e06bae620..0a420ebecf 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/PeLibAux.cpp
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/PeLibAux.cpp
@@ -1,275 +1,275 @@
1/* 1/*
2* PeLibAux.cpp - Part of the PeLib library. 2* PeLibAux.cpp - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#include "PeLibInc.h" 13#include "PeLibInc.h"
14#include "PeLibAux.h" 14#include "PeLibAux.h"
15#include "PeFile.h" 15#include "PeFile.h"
16 16
17#ifdef _MSC_VER 17#ifdef _MSC_VER
18 #include <ctype.h> 18 #include <ctype.h>
19#endif 19#endif
20 20
21namespace PeLib 21namespace PeLib
22{ 22{
23 const qword PELIB_IMAGE_ORDINAL_FLAGS<64>::IMAGE_ORDINAL_FLAG = 0x8000000000000000ULL; 23 const qword PELIB_IMAGE_ORDINAL_FLAGS<64>::IMAGE_ORDINAL_FLAG = 0x8000000000000000ULL;
24 24
25 bool PELIB_IMAGE_SECTION_HEADER::biggerFileOffset(const PELIB_IMAGE_SECTION_HEADER& ish) const 25 bool PELIB_IMAGE_SECTION_HEADER::biggerFileOffset(const PELIB_IMAGE_SECTION_HEADER& ish) const
26 { 26 {
27 return PointerToRawData < ish.PointerToRawData; 27 return PointerToRawData < ish.PointerToRawData;
28 } 28 }
29 29
30 bool PELIB_IMAGE_SECTION_HEADER::biggerVirtualAddress(const PELIB_IMAGE_SECTION_HEADER& ish) const 30 bool PELIB_IMAGE_SECTION_HEADER::biggerVirtualAddress(const PELIB_IMAGE_SECTION_HEADER& ish) const
31 { 31 {
32 return VirtualAddress < ish.VirtualAddress; 32 return VirtualAddress < ish.VirtualAddress;
33 } 33 }
34 34
35 unsigned int alignOffset(unsigned int uiOffset, unsigned int uiAlignment) 35 unsigned int alignOffset(unsigned int uiOffset, unsigned int uiAlignment)
36 { 36 {
37 if (!uiAlignment) return uiAlignment; 37 if (!uiAlignment) return uiAlignment;
38 return (uiOffset % uiAlignment) ? uiOffset + (uiAlignment - uiOffset % uiAlignment) : uiOffset; 38 return (uiOffset % uiAlignment) ? uiOffset + (uiAlignment - uiOffset % uiAlignment) : uiOffset;
39 } 39 }
40 40
41 unsigned int fileSize(const std::string& filename) 41 unsigned int fileSize(const std::string& filename)
42 { 42 {
43 std::fstream file(filename.c_str()); 43 std::fstream file(filename.c_str());
44 file.seekg(0, std::ios::end); 44 file.seekg(0, std::ios::end);
45 return file.tellg(); 45 return file.tellg();
46 } 46 }
47 47
48 unsigned int fileSize(std::ifstream& file) 48 unsigned int fileSize(std::ifstream& file)
49 { 49 {
50 unsigned int oldpos = file.tellg(); 50 unsigned int oldpos = file.tellg();
51 file.seekg(0, std::ios::end); 51 file.seekg(0, std::ios::end);
52 unsigned int filesize = file.tellg(); 52 unsigned int filesize = file.tellg();
53 file.seekg(oldpos, std::ios::beg); 53 file.seekg(oldpos, std::ios::beg);
54 return filesize; 54 return filesize;
55 } 55 }
56 56
57 unsigned int fileSize(std::fstream& file) 57 unsigned int fileSize(std::fstream& file)
58 { 58 {
59 unsigned int oldpos = file.tellg(); 59 unsigned int oldpos = file.tellg();
60 file.seekg(0, std::ios::end); 60 file.seekg(0, std::ios::end);
61 unsigned int filesize = file.tellg(); 61 unsigned int filesize = file.tellg();
62 file.seekg(oldpos, std::ios::beg); 62 file.seekg(oldpos, std::ios::beg);
63 return filesize; 63 return filesize;
64 } 64 }
65 65
66 unsigned int fileSize(std::ofstream& file) 66 unsigned int fileSize(std::ofstream& file)
67 { 67 {
68 unsigned int oldpos = file.tellp(); 68 unsigned int oldpos = file.tellp();
69 file.seekp(0, std::ios::end); 69 file.seekp(0, std::ios::end);
70 unsigned int filesize = file.tellp(); 70 unsigned int filesize = file.tellp();
71 file.seekp(oldpos, std::ios::beg); 71 file.seekp(oldpos, std::ios::beg);
72 return filesize; 72 return filesize;
73 } 73 }
74 74
75 bool isEqualNc(const std::string& s1, const std::string& s2) 75 bool isEqualNc(const std::string& s1, const std::string& s2)
76 { 76 {
77 std::string t1 = s1; 77 std::string t1 = s1;
78 std::string t2 = s2; 78 std::string t2 = s2;
79 79
80 // No std:: to make VC++ happy 80 // No std:: to make VC++ happy
81 #ifdef _MSC_VER 81 #ifdef _MSC_VER
82 std::transform(t1.begin(), t1.end(), t1.begin(), toupper); 82 std::transform(t1.begin(), t1.end(), t1.begin(), toupper);
83 std::transform(t2.begin(), t2.end(), t2.begin(), toupper); 83 std::transform(t2.begin(), t2.end(), t2.begin(), toupper);
84 #else 84 #else
85 // Weird syntax to make Borland C++ happy 85 // Weird syntax to make Borland C++ happy
86 std::transform(t1.begin(), t1.end(), t1.begin(), (int(*)(int))std::toupper); 86 std::transform(t1.begin(), t1.end(), t1.begin(), (int(*)(int))std::toupper);
87 std::transform(t2.begin(), t2.end(), t2.begin(), (int(*)(int))std::toupper); 87 std::transform(t2.begin(), t2.end(), t2.begin(), (int(*)(int))std::toupper);
88 #endif 88 #endif
89 return t1 == t2; 89 return t1 == t2;
90 } 90 }
91 91
92 PELIB_IMAGE_DOS_HEADER::PELIB_IMAGE_DOS_HEADER() 92 PELIB_IMAGE_DOS_HEADER::PELIB_IMAGE_DOS_HEADER()
93 { 93 {
94 e_magic = 0; 94 e_magic = 0;
95 e_cblp = 0; 95 e_cblp = 0;
96 e_cp = 0; 96 e_cp = 0;
97 e_crlc = 0; 97 e_crlc = 0;
98 e_cparhdr = 0; 98 e_cparhdr = 0;
99 e_minalloc = 0; 99 e_minalloc = 0;
100 e_maxalloc = 0; 100 e_maxalloc = 0;
101 e_ss = 0; 101 e_ss = 0;
102 e_sp = 0; 102 e_sp = 0;
103 e_csum = 0; 103 e_csum = 0;
104 e_ip = 0; 104 e_ip = 0;
105 e_cs = 0; 105 e_cs = 0;
106 e_lfarlc = 0; 106 e_lfarlc = 0;
107 e_ovno = 0; 107 e_ovno = 0;
108 108
109 for (unsigned int i=0;i<sizeof(e_res)/sizeof(e_res[0]);i++) 109 for (unsigned int i=0;i<sizeof(e_res)/sizeof(e_res[0]);i++)
110 { 110 {
111 e_res[i] = 0; 111 e_res[i] = 0;
112 } 112 }
113 113
114 e_oemid = 0; 114 e_oemid = 0;
115 e_oeminfo = 0; 115 e_oeminfo = 0;
116 116
117 for (unsigned int i=0;i<sizeof(e_res2)/sizeof(e_res2[0]);i++) 117 for (unsigned int i=0;i<sizeof(e_res2)/sizeof(e_res2[0]);i++)
118 { 118 {
119 e_res2[i] = 0; 119 e_res2[i] = 0;
120 } 120 }
121 121
122 e_lfanew = 0; 122 e_lfanew = 0;
123 } 123 }
124 124
125 PELIB_EXP_FUNC_INFORMATION::PELIB_EXP_FUNC_INFORMATION() 125 PELIB_EXP_FUNC_INFORMATION::PELIB_EXP_FUNC_INFORMATION()
126 { 126 {
127 addroffunc = 0; 127 addroffunc = 0;
128 addrofname = 0; 128 addrofname = 0;
129 ordinal = 0; 129 ordinal = 0;
130 } 130 }
131 131
132 PELIB_IMAGE_RESOURCE_DIRECTORY::PELIB_IMAGE_RESOURCE_DIRECTORY() 132 PELIB_IMAGE_RESOURCE_DIRECTORY::PELIB_IMAGE_RESOURCE_DIRECTORY()
133 { 133 {
134 Characteristics = 0; 134 Characteristics = 0;
135 TimeDateStamp = 0; 135 TimeDateStamp = 0;
136 MajorVersion = 0; 136 MajorVersion = 0;
137 MinorVersion = 0; 137 MinorVersion = 0;
138 NumberOfNamedEntries = 0; 138 NumberOfNamedEntries = 0;
139 NumberOfIdEntries = 0; 139 NumberOfIdEntries = 0;
140 } 140 }
141 141
142 PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY::PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY() 142 PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY::PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY()
143 { 143 {
144 Name = 0; 144 Name = 0;
145 OffsetToData = 0; 145 OffsetToData = 0;
146 } 146 }
147 147
148 bool PELIB_IMG_RES_DIR_ENTRY::operator<(const PELIB_IMG_RES_DIR_ENTRY& first) const 148 bool PELIB_IMG_RES_DIR_ENTRY::operator<(const PELIB_IMG_RES_DIR_ENTRY& first) const
149 { 149 {
150 if (irde.Name & PELIB_IMAGE_RESOURCE_NAME_IS_STRING && first.irde.Name & PELIB_IMAGE_RESOURCE_NAME_IS_STRING) 150 if (irde.Name & PELIB_IMAGE_RESOURCE_NAME_IS_STRING && first.irde.Name & PELIB_IMAGE_RESOURCE_NAME_IS_STRING)
151 { 151 {
152 return wstrName < first.wstrName; 152 return wstrName < first.wstrName;
153 } 153 }
154 else if (irde.Name & PELIB_IMAGE_RESOURCE_NAME_IS_STRING) 154 else if (irde.Name & PELIB_IMAGE_RESOURCE_NAME_IS_STRING)
155 { 155 {
156 return true; 156 return true;
157 } 157 }
158 else if (first.irde.Name & PELIB_IMAGE_RESOURCE_NAME_IS_STRING) 158 else if (first.irde.Name & PELIB_IMAGE_RESOURCE_NAME_IS_STRING)
159 { 159 {
160 return false; 160 return false;
161 } 161 }
162 else 162 else
163 { 163 {
164 return irde.Name < first.irde.Name; 164 return irde.Name < first.irde.Name;
165 } 165 }
166 } 166 }
167 167
168 PELIB_IMAGE_BASE_RELOCATION::PELIB_IMAGE_BASE_RELOCATION() 168 PELIB_IMAGE_BASE_RELOCATION::PELIB_IMAGE_BASE_RELOCATION()
169 { 169 {
170 VirtualAddress = 0; 170 VirtualAddress = 0;
171 SizeOfBlock = 0; 171 SizeOfBlock = 0;
172 } 172 }
173 173
174 PELIB_IMAGE_COR20_HEADER::PELIB_IMAGE_COR20_HEADER() 174 PELIB_IMAGE_COR20_HEADER::PELIB_IMAGE_COR20_HEADER()
175 { 175 {
176 cb = 0; 176 cb = 0;
177 MajorRuntimeVersion = 0; 177 MajorRuntimeVersion = 0;
178 MinorRuntimeVersion = 0; 178 MinorRuntimeVersion = 0;
179 MetaData.VirtualAddress = 0; 179 MetaData.VirtualAddress = 0;
180 MetaData.Size = 0; 180 MetaData.Size = 0;
181 Flags = 0; 181 Flags = 0;
182 EntryPointToken = 0; 182 EntryPointToken = 0;
183 Resources.VirtualAddress = 0; 183 Resources.VirtualAddress = 0;
184 Resources.Size = 0; 184 Resources.Size = 0;
185 StrongNameSignature.VirtualAddress = 0; 185 StrongNameSignature.VirtualAddress = 0;
186 StrongNameSignature.Size = 0; 186 StrongNameSignature.Size = 0;
187 CodeManagerTable.VirtualAddress = 0; 187 CodeManagerTable.VirtualAddress = 0;
188 CodeManagerTable.Size = 0; 188 CodeManagerTable.Size = 0;
189 VTableFixups.VirtualAddress = 0; 189 VTableFixups.VirtualAddress = 0;
190 VTableFixups.Size = 0; 190 VTableFixups.Size = 0;
191 ExportAddressTableJumps.VirtualAddress = 0; 191 ExportAddressTableJumps.VirtualAddress = 0;
192 ExportAddressTableJumps.Size = 0; 192 ExportAddressTableJumps.Size = 0;
193 ManagedNativeHeader.VirtualAddress = 0; 193 ManagedNativeHeader.VirtualAddress = 0;
194 ManagedNativeHeader.Size = 0; 194 ManagedNativeHeader.Size = 0;
195 } 195 }
196 196
197 /** Compares the passed filename to the struct's filename. 197 /** Compares the passed filename to the struct's filename.
198 * @param strModuleName A filename. 198 * @param strModuleName A filename.
199 * @return True, if the passed filename equals the struct's filename. The comparison is case-sensitive. 199 * @return True, if the passed filename equals the struct's filename. The comparison is case-sensitive.
200 **/ 200 **/
201 bool PELIB_IMAGE_BOUND_DIRECTORY::equal(const std::string strModuleName) const 201 bool PELIB_IMAGE_BOUND_DIRECTORY::equal(const std::string strModuleName) const
202 { 202 {
203 return this->strModuleName == strModuleName; 203 return this->strModuleName == strModuleName;
204 } 204 }
205 205
206 bool PELIB_EXP_FUNC_INFORMATION::equal(const std::string strFunctionName) const 206 bool PELIB_EXP_FUNC_INFORMATION::equal(const std::string strFunctionName) const
207 { 207 {
208 return isEqualNc(this->funcname, strFunctionName); 208 return isEqualNc(this->funcname, strFunctionName);
209 } 209 }
210 210
211 /** 211 /**
212 * @param strFilename Name of a file. 212 * @param strFilename Name of a file.
213 * @return Either PEFILE32, PEFILE64 or PEFILE_UNKNOWN 213 * @return Either PEFILE32, PEFILE64 or PEFILE_UNKNOWN
214 **/ 214 **/
215 unsigned int getFileType(const std::string strFilename) 215 unsigned int getFileType(const std::string strFilename)
216 { 216 {
217 word machine, magic; 217 word machine, magic;
218 218
219 PeFile32 pef(strFilename); 219 PeFile32 pef(strFilename);
220 if (pef.readMzHeader() != NO_ERROR) return PEFILE_UNKNOWN; 220 if (pef.readMzHeader() != NO_ERROR) return PEFILE_UNKNOWN;
221 if (pef.readPeHeader() != NO_ERROR) return PEFILE_UNKNOWN; 221 if (pef.readPeHeader() != NO_ERROR) return PEFILE_UNKNOWN;
222 222
223 machine = pef.peHeader().getMachine(); 223 machine = pef.peHeader().getMachine();
224 magic = pef.peHeader().getMagic(); 224 magic = pef.peHeader().getMagic();
225 225
226 if (machine == PELIB_IMAGE_FILE_MACHINE_I386 && magic == PELIB_IMAGE_NT_OPTIONAL_HDR32_MAGIC) 226 if (machine == PELIB_IMAGE_FILE_MACHINE_I386 && magic == PELIB_IMAGE_NT_OPTIONAL_HDR32_MAGIC)
227 { 227 {
228 return PEFILE32; 228 return PEFILE32;
229 } 229 }
230 // 0x8664 == AMD64; no named constant yet 230 // 0x8664 == AMD64; no named constant yet
231 else if ((machine == 0x8664 || machine == PELIB_IMAGE_FILE_MACHINE_IA64) && magic == PELIB_IMAGE_NT_OPTIONAL_HDR64_MAGIC) 231 else if ((machine == 0x8664 || machine == PELIB_IMAGE_FILE_MACHINE_IA64) && magic == PELIB_IMAGE_NT_OPTIONAL_HDR64_MAGIC)
232 { 232 {
233 return PEFILE64; 233 return PEFILE64;
234 } 234 }
235 else 235 else
236 { 236 {
237 return PEFILE_UNKNOWN; 237 return PEFILE_UNKNOWN;
238 } 238 }
239 } 239 }
240 240
241 /** 241 /**
242 * Opens a PE file. The return type is either PeFile32 or PeFile64 object. If an error occurs the return 242 * Opens a PE file. The return type is either PeFile32 or PeFile64 object. If an error occurs the return
243 * value is 0. 243 * value is 0.
244 * @param strFilename Name of a file. 244 * @param strFilename Name of a file.
245 * @return Either a PeFile32 object, a PeFil64 object or 0. 245 * @return Either a PeFile32 object, a PeFil64 object or 0.
246 **/ 246 **/
247 PeFile* openPeFile(const std::string& strFilename) 247 PeFile* openPeFile(const std::string& strFilename)
248 { 248 {
249 unsigned int type = getFileType(strFilename); 249 unsigned int type = getFileType(strFilename);
250 250
251 if (type == PEFILE32) 251 if (type == PEFILE32)
252 { 252 {
253 return new PeFile32(strFilename); 253 return new PeFile32(strFilename);
254 } 254 }
255 else if (type == PEFILE64) 255 else if (type == PEFILE64)
256 { 256 {
257 return new PeFile64(strFilename); 257 return new PeFile64(strFilename);
258 } 258 }
259 else 259 else
260 { 260 {
261 return 0; 261 return 0;
262 } 262 }
263 } 263 }
264 264
265 unsigned int PELIB_IMAGE_BOUND_DIRECTORY::size() const 265 unsigned int PELIB_IMAGE_BOUND_DIRECTORY::size() const
266 { 266 {
267 unsigned int size = 0; 267 unsigned int size = 0;
268 for (unsigned int i=0;i<moduleForwarders.size();i++) 268 for (unsigned int i=0;i<moduleForwarders.size();i++)
269 { 269 {
270 size += moduleForwarders[i].size(); 270 size += moduleForwarders[i].size();
271 } 271 }
272 272
273 return size + PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size() + strModuleName.size() + 1; 273 return size + PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size() + strModuleName.size() + 1;
274 } 274 }
275} 275}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/PeLibAux.h b/utils/zenutils/libraries/pelib-0.9/pelib/PeLibAux.h
index 4aed866a7d..cfce60796f 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/PeLibAux.h
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/PeLibAux.h
@@ -1,884 +1,884 @@
1/* 1/*
2* PeLibAux.cpp - Part of the PeLib library. 2* PeLibAux.cpp - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#ifndef PELIBAUX_H 13#ifndef PELIBAUX_H
14#define PELIBAUX_H 14#define PELIBAUX_H
15 15
16//#include "PeLibInc.h" 16//#include "PeLibInc.h"
17//#include "PeHeader.h" 17//#include "PeHeader.h"
18#include "buffer/OutputBuffer.h" 18#include "buffer/OutputBuffer.h"
19#include "buffer/InputBuffer.h" 19#include "buffer/InputBuffer.h"
20//#include "buffer/ResTree.h" 20//#include "buffer/ResTree.h"
21#include <numeric> 21#include <numeric>
22#include <limits> 22#include <limits>
23 23
24namespace PeLib 24namespace PeLib
25{ 25{
26 enum errorCodes 26 enum errorCodes
27 { 27 {
28 NO_ERROR = 0, 28 NO_ERROR = 0,
29 ERROR_OPENING_FILE = -1, 29 ERROR_OPENING_FILE = -1,
30 ERROR_INVALID_FILE = -2, 30 ERROR_INVALID_FILE = -2,
31 ERROR_TOO_MANY_SECTIONS = -3, 31 ERROR_TOO_MANY_SECTIONS = -3,
32 ERROR_NOT_ENOUGH_SPACE = -4, 32 ERROR_NOT_ENOUGH_SPACE = -4,
33 ERROR_NO_FILE_ALIGNMENT = -5, 33 ERROR_NO_FILE_ALIGNMENT = -5,
34 ERROR_NO_SECTION_ALIGNMENT = -6, 34 ERROR_NO_SECTION_ALIGNMENT = -6,
35 ERROR_ENTRY_NOT_FOUND = -7, 35 ERROR_ENTRY_NOT_FOUND = -7,
36 ERROR_DUPLICATE_ENTRY = -8, 36 ERROR_DUPLICATE_ENTRY = -8,
37 ERROR_DIRECTORY_DOES_NOT_EXIST = -9 37 ERROR_DIRECTORY_DOES_NOT_EXIST = -9
38 }; 38 };
39 39
40 class PeFile; 40 class PeFile;
41 bool isEqualNc(const std::string& s1, const std::string& s2); 41 bool isEqualNc(const std::string& s1, const std::string& s2);
42 42
43// It's necessary to make sure that a byte has 8 bits and that the platform has a 8 bit type, 43// It's necessary to make sure that a byte has 8 bits and that the platform has a 8 bit type,
44// a 16bit type and a bit type. That's because binary PE files are pretty picky about their 44// a 16bit type and a bit type. That's because binary PE files are pretty picky about their
45// structure. 45// structure.
46 46
47 #if CHAR_BIT == 8 47 #if CHAR_BIT == 8
48 #if UCHAR_MAX == 255 48 #if UCHAR_MAX == 255
49 typedef unsigned char byte; 49 typedef unsigned char byte;
50 // typedef std::bitset<8> byte; 50 // typedef std::bitset<8> byte;
51 #else 51 #else
52 #error You need to change some typedefs (Code: 8). Please read the PeLib documentation. 52 #error You need to change some typedefs (Code: 8). Please read the PeLib documentation.
53 #endif 53 #endif
54 54
55 #if USHRT_MAX == 65535U 55 #if USHRT_MAX == 65535U
56 typedef unsigned short word; 56 typedef unsigned short word;
57 // typedef std::bitset<16> word; 57 // typedef std::bitset<16> word;
58 #else 58 #else
59 #error You need to change some typedefs (Code: 16). Please read the PeLib documentation. 59 #error You need to change some typedefs (Code: 16). Please read the PeLib documentation.
60 #endif 60 #endif
61 61
62 #if UINT_MAX == 4294967295UL 62 #if UINT_MAX == 4294967295UL
63 typedef unsigned int dword; 63 typedef unsigned int dword;
64 // typedef std::bitset<32> dword; 64 // typedef std::bitset<32> dword;
65 #else 65 #else
66 #error You need to change some typedefs (Code: 32). Please read the PeLib documentation. 66 #error You need to change some typedefs (Code: 32). Please read the PeLib documentation.
67 #endif 67 #endif
68 68
69 typedef unsigned long long qword; 69 typedef unsigned long long qword;
70 70
71// #if ULLONG_MAX == 18446744073709551615 71// #if ULLONG_MAX == 18446744073709551615
72// typedef unsigned long long qword; 72// typedef unsigned long long qword;
73// #else 73// #else
74// #error You need to change some typedefs (Code: 32). Please read the PeLib documentation. 74// #error You need to change some typedefs (Code: 32). Please read the PeLib documentation.
75// #endif 75// #endif
76 #else 76 #else
77 #error You need to change some typedefs. Please read the PeLib documentation. 77 #error You need to change some typedefs. Please read the PeLib documentation.
78 #endif 78 #endif
79 79
80 80
81/* enum bits {BITS_BYTE = 8, BITS_WORD = 16, BITS_DWORD = 32}; 81/* enum bits {BITS_BYTE = 8, BITS_WORD = 16, BITS_DWORD = 32};
82 82
83 template<bits value> 83 template<bits value>
84 class DataType 84 class DataType
85 { 85 {
86 private: 86 private:
87 std::bitset<value> bsValue; 87 std::bitset<value> bsValue;
88 unsigned long ulValue; 88 unsigned long ulValue;
89 89
90 public: 90 public:
91 void operator=(unsigned long ulValue) 91 void operator=(unsigned long ulValue)
92 { 92 {
93 bsValue = ulValue; 93 bsValue = ulValue;
94 } 94 }
95 95
96 operator unsigned long() const 96 operator unsigned long() const
97 { 97 {
98 return bsValue.to_ulong(); 98 return bsValue.to_ulong();
99 } 99 }
100 100
101 const int operator&() 101 const int operator&()
102 { 102 {
103 ulValue = bsValue; 103 ulValue = bsValue;
104 return ulValue; 104 return ulValue;
105 } 105 }
106 106
107 }; 107 };
108 108
109 typedef DataType<BITS_BYTE> byte; 109 typedef DataType<BITS_BYTE> byte;
110 typedef DataType<BITS_WORD> word; 110 typedef DataType<BITS_WORD> word;
111 typedef DataType<BITS_DWORD> dword; 111 typedef DataType<BITS_DWORD> dword;
112*/ 112*/
113 113
114 enum {PEFILE32 = 32, 114 enum {PEFILE32 = 32,
115 PEFILE64 = 64, 115 PEFILE64 = 64,
116 PEFILE_UNKNOWN = 0}; 116 PEFILE_UNKNOWN = 0};
117 117
118 enum {BoundImportDirectoryId = 1, 118 enum {BoundImportDirectoryId = 1,
119 ComHeaderDirectoryId, 119 ComHeaderDirectoryId,
120 ExportDirectoryId, 120 ExportDirectoryId,
121 IatDirectoryId, 121 IatDirectoryId,
122 ImportDirectoryId, 122 ImportDirectoryId,
123 MzHeaderId, 123 MzHeaderId,
124 PeHeaderId, 124 PeHeaderId,
125 RelocationsId, 125 RelocationsId,
126 PeFileId, 126 PeFileId,
127 ResourceDirectoryId, 127 ResourceDirectoryId,
128 DebugDirectoryId, 128 DebugDirectoryId,
129 TlsDirectoryId 129 TlsDirectoryId
130 }; 130 };
131 131
132 const word PELIB_IMAGE_DOS_SIGNATURE = 0x5A4D; 132 const word PELIB_IMAGE_DOS_SIGNATURE = 0x5A4D;
133 133
134 const dword PELIB_IMAGE_NT_SIGNATURE = 0x00004550; 134 const dword PELIB_IMAGE_NT_SIGNATURE = 0x00004550;
135 135
136 template<int bits> 136 template<int bits>
137 struct PELIB_IMAGE_ORDINAL_FLAGS; 137 struct PELIB_IMAGE_ORDINAL_FLAGS;
138 138
139 template<> 139 template<>
140 struct PELIB_IMAGE_ORDINAL_FLAGS<32> 140 struct PELIB_IMAGE_ORDINAL_FLAGS<32>
141 { 141 {
142 static const dword IMAGE_ORDINAL_FLAG = 0x80000000; 142 static const dword IMAGE_ORDINAL_FLAG = 0x80000000;
143 }; 143 };
144 144
145 template<> 145 template<>
146 struct PELIB_IMAGE_ORDINAL_FLAGS<64> 146 struct PELIB_IMAGE_ORDINAL_FLAGS<64>
147 { 147 {
148 static const qword IMAGE_ORDINAL_FLAG; 148 static const qword IMAGE_ORDINAL_FLAG;
149 }; 149 };
150 150
151 const unsigned long PELIB_IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16; 151 const unsigned long PELIB_IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
152 152
153 const unsigned long PELIB_IMAGE_RESOURCE_NAME_IS_STRING = 0x80000000; 153 const unsigned long PELIB_IMAGE_RESOURCE_NAME_IS_STRING = 0x80000000;
154 154
155 const unsigned long PELIB_IMAGE_RESOURCE_DATA_IS_DIRECTORY = 0x80000000; 155 const unsigned long PELIB_IMAGE_RESOURCE_DATA_IS_DIRECTORY = 0x80000000;
156 156
157 enum 157 enum
158 { 158 {
159 PELIB_IMAGE_DIRECTORY_ENTRY_EXPORT, // OK 159 PELIB_IMAGE_DIRECTORY_ENTRY_EXPORT, // OK
160 PELIB_IMAGE_DIRECTORY_ENTRY_IMPORT, // OK 160 PELIB_IMAGE_DIRECTORY_ENTRY_IMPORT, // OK
161 PELIB_IMAGE_DIRECTORY_ENTRY_RESOURCE, // OK 161 PELIB_IMAGE_DIRECTORY_ENTRY_RESOURCE, // OK
162 PELIB_IMAGE_DIRECTORY_ENTRY_EXCEPTION, 162 PELIB_IMAGE_DIRECTORY_ENTRY_EXCEPTION,
163 PELIB_IMAGE_DIRECTORY_ENTRY_SECURITY, 163 PELIB_IMAGE_DIRECTORY_ENTRY_SECURITY,
164 PELIB_IMAGE_DIRECTORY_ENTRY_BASERELOC, // OK 164 PELIB_IMAGE_DIRECTORY_ENTRY_BASERELOC, // OK
165 PELIB_IMAGE_DIRECTORY_ENTRY_DEBUG, 165 PELIB_IMAGE_DIRECTORY_ENTRY_DEBUG,
166 PELIB_IMAGE_DIRECTORY_ENTRY_ARCHITECTURE, 166 PELIB_IMAGE_DIRECTORY_ENTRY_ARCHITECTURE,
167 PELIB_IMAGE_DIRECTORY_ENTRY_GLOBALPTR, 167 PELIB_IMAGE_DIRECTORY_ENTRY_GLOBALPTR,
168 PELIB_IMAGE_DIRECTORY_ENTRY_TLS, 168 PELIB_IMAGE_DIRECTORY_ENTRY_TLS,
169 PELIB_IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, 169 PELIB_IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG,
170 PELIB_IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT, // OK 170 PELIB_IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT, // OK
171 PELIB_IMAGE_DIRECTORY_ENTRY_IAT, // OK 171 PELIB_IMAGE_DIRECTORY_ENTRY_IAT, // OK
172 PELIB_IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT, 172 PELIB_IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT,
173 PELIB_IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 173 PELIB_IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
174 }; 174 };
175 175
176 enum 176 enum
177 { 177 {
178 PELIB_IMAGE_SCN_TYPE_NO_PAD = 0x00000008, 178 PELIB_IMAGE_SCN_TYPE_NO_PAD = 0x00000008,
179 PELIB_IMAGE_SCN_CNT_CODE = 0x00000020, 179 PELIB_IMAGE_SCN_CNT_CODE = 0x00000020,
180 PELIB_IMAGE_SCN_CNT_INITIALIZED_DATA = 0x00000040, 180 PELIB_IMAGE_SCN_CNT_INITIALIZED_DATA = 0x00000040,
181 PELIB_IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080, 181 PELIB_IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080,
182 PELIB_IMAGE_SCN_LNK_OTHER = 0x00000100, 182 PELIB_IMAGE_SCN_LNK_OTHER = 0x00000100,
183 PELIB_IMAGE_SCN_LNK_INFO = 0x00000200, 183 PELIB_IMAGE_SCN_LNK_INFO = 0x00000200,
184 PELIB_IMAGE_SCN_LNK_REMOVE = 0x00000800, 184 PELIB_IMAGE_SCN_LNK_REMOVE = 0x00000800,
185 PELIB_IMAGE_SCN_LNK_COMDAT = 0x00001000, 185 PELIB_IMAGE_SCN_LNK_COMDAT = 0x00001000,
186 PELIB_IMAGE_SCN_NO_DEFER_SPEC_EXC = 0x00004000, 186 PELIB_IMAGE_SCN_NO_DEFER_SPEC_EXC = 0x00004000,
187 PELIB_IMAGE_SCN_GPREL = 0x00008000, 187 PELIB_IMAGE_SCN_GPREL = 0x00008000,
188 PELIB_IMAGE_SCN_MEM_FARDATA = 0x00008000, 188 PELIB_IMAGE_SCN_MEM_FARDATA = 0x00008000,
189 PELIB_IMAGE_SCN_MEM_PURGEABLE = 0x00020000, 189 PELIB_IMAGE_SCN_MEM_PURGEABLE = 0x00020000,
190 PELIB_IMAGE_SCN_MEM_16BIT = 0x00020000, 190 PELIB_IMAGE_SCN_MEM_16BIT = 0x00020000,
191 PELIB_IMAGE_SCN_MEM_LOCKED = 0x00040000, 191 PELIB_IMAGE_SCN_MEM_LOCKED = 0x00040000,
192 PELIB_IMAGE_SCN_MEM_PRELOAD = 0x00080000, 192 PELIB_IMAGE_SCN_MEM_PRELOAD = 0x00080000,
193 PELIB_IMAGE_SCN_ALIGN_1BYTES = 0x00100000, 193 PELIB_IMAGE_SCN_ALIGN_1BYTES = 0x00100000,
194 PELIB_IMAGE_SCN_ALIGN_2BYTES = 0x00200000, 194 PELIB_IMAGE_SCN_ALIGN_2BYTES = 0x00200000,
195 PELIB_IMAGE_SCN_ALIGN_4BYTES = 0x00300000, 195 PELIB_IMAGE_SCN_ALIGN_4BYTES = 0x00300000,
196 PELIB_IMAGE_SCN_ALIGN_8BYTES = 0x00400000, 196 PELIB_IMAGE_SCN_ALIGN_8BYTES = 0x00400000,
197 PELIB_IMAGE_SCN_ALIGN_16BYTES = 0x00500000, 197 PELIB_IMAGE_SCN_ALIGN_16BYTES = 0x00500000,
198 PELIB_IMAGE_SCN_ALIGN_BYTES = 0x00600000, 198 PELIB_IMAGE_SCN_ALIGN_BYTES = 0x00600000,
199 PELIB_IMAGE_SCN_ALIGN_64BYTES = 0x00700000, 199 PELIB_IMAGE_SCN_ALIGN_64BYTES = 0x00700000,
200 PELIB_IMAGE_SCN_ALIGN_128BYTES = 0x00800000, 200 PELIB_IMAGE_SCN_ALIGN_128BYTES = 0x00800000,
201 PELIB_IMAGE_SCN_ALIGN_256BYTES = 0x00900000, 201 PELIB_IMAGE_SCN_ALIGN_256BYTES = 0x00900000,
202 PELIB_IMAGE_SCN_ALIGN_512BYTES = 0x00A00000, 202 PELIB_IMAGE_SCN_ALIGN_512BYTES = 0x00A00000,
203 PELIB_IMAGE_SCN_ALIGN_1024BYTES = 0x00B00000, 203 PELIB_IMAGE_SCN_ALIGN_1024BYTES = 0x00B00000,
204 PELIB_IMAGE_SCN_ALIGN_2048BYTES = 0x00C00000, 204 PELIB_IMAGE_SCN_ALIGN_2048BYTES = 0x00C00000,
205 PELIB_IMAGE_SCN_ALIGN_4096BYTES = 0x00D00000, 205 PELIB_IMAGE_SCN_ALIGN_4096BYTES = 0x00D00000,
206 PELIB_IMAGE_SCN_ALIGN_8192BYTES = 0x00E00000, 206 PELIB_IMAGE_SCN_ALIGN_8192BYTES = 0x00E00000,
207 PELIB_IMAGE_SCN_LNK_NRELOC_OVFL = 0x01000000, 207 PELIB_IMAGE_SCN_LNK_NRELOC_OVFL = 0x01000000,
208 PELIB_IMAGE_SCN_MEM_DISCARDABLE = 0x02000000, 208 PELIB_IMAGE_SCN_MEM_DISCARDABLE = 0x02000000,
209 PELIB_IMAGE_SCN_MEM_NOT_CACHED = 0x04000000, 209 PELIB_IMAGE_SCN_MEM_NOT_CACHED = 0x04000000,
210 PELIB_IMAGE_SCN_MEM_NOT_PAGED = 0x08000000, 210 PELIB_IMAGE_SCN_MEM_NOT_PAGED = 0x08000000,
211 PELIB_IMAGE_SCN_MEM_SHARED = 0x10000000, 211 PELIB_IMAGE_SCN_MEM_SHARED = 0x10000000,
212 PELIB_IMAGE_SCN_MEM_EXECUTE = 0x20000000, 212 PELIB_IMAGE_SCN_MEM_EXECUTE = 0x20000000,
213 PELIB_IMAGE_SCN_MEM_READ = 0x40000000, 213 PELIB_IMAGE_SCN_MEM_READ = 0x40000000,
214 PELIB_IMAGE_SCN_MEM_WRITE = 0x80000000 214 PELIB_IMAGE_SCN_MEM_WRITE = 0x80000000
215 }; 215 };
216 216
217 enum 217 enum
218 { 218 {
219 PELIB_IMAGE_FILE_MACHINE_UNKNOWN = 0, 219 PELIB_IMAGE_FILE_MACHINE_UNKNOWN = 0,
220 PELIB_IMAGE_FILE_MACHINE_I386 = 0x014c, 220 PELIB_IMAGE_FILE_MACHINE_I386 = 0x014c,
221 PELIB_IMAGE_FILE_MACHINE_R3000 = 0x0162, 221 PELIB_IMAGE_FILE_MACHINE_R3000 = 0x0162,
222 PELIB_IMAGE_FILE_MACHINE_R4000 = 0x0166, 222 PELIB_IMAGE_FILE_MACHINE_R4000 = 0x0166,
223 PELIB_IMAGE_FILE_MACHINE_R10000 = 0x0168, 223 PELIB_IMAGE_FILE_MACHINE_R10000 = 0x0168,
224 PELIB_IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x0169, 224 PELIB_IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x0169,
225 PELIB_IMAGE_FILE_MACHINE_ALPHA = 0x0184, 225 PELIB_IMAGE_FILE_MACHINE_ALPHA = 0x0184,
226 PELIB_IMAGE_FILE_MACHINE_POWERPC = 0x01F0, 226 PELIB_IMAGE_FILE_MACHINE_POWERPC = 0x01F0,
227 PELIB_IMAGE_FILE_MACHINE_SH3 = 0x01a2, 227 PELIB_IMAGE_FILE_MACHINE_SH3 = 0x01a2,
228 PELIB_IMAGE_FILE_MACHINE_SH3E = 0x01a4, 228 PELIB_IMAGE_FILE_MACHINE_SH3E = 0x01a4,
229 PELIB_IMAGE_FILE_MACHINE_SH4 = 0x01a6, 229 PELIB_IMAGE_FILE_MACHINE_SH4 = 0x01a6,
230 PELIB_IMAGE_FILE_MACHINE_ARM = 0x01c0, 230 PELIB_IMAGE_FILE_MACHINE_ARM = 0x01c0,
231 PELIB_IMAGE_FILE_MACHINE_THUMB = 0x01c2, 231 PELIB_IMAGE_FILE_MACHINE_THUMB = 0x01c2,
232 PELIB_IMAGE_FILE_MACHINE_IA64 = 0x0200, 232 PELIB_IMAGE_FILE_MACHINE_IA64 = 0x0200,
233 PELIB_IMAGE_FILE_MACHINE_MIPS16 = 0x0266, 233 PELIB_IMAGE_FILE_MACHINE_MIPS16 = 0x0266,
234 PELIB_IMAGE_FILE_MACHINE_MIPSFPU = 0x0366, 234 PELIB_IMAGE_FILE_MACHINE_MIPSFPU = 0x0366,
235 PELIB_IMAGE_FILE_MACHINE_MIPSFPU16 = 0x0466, 235 PELIB_IMAGE_FILE_MACHINE_MIPSFPU16 = 0x0466,
236 PELIB_IMAGE_FILE_MACHINE_ALPHA64 = 0x0284, 236 PELIB_IMAGE_FILE_MACHINE_ALPHA64 = 0x0284,
237 PELIB_IMAGE_FILE_MACHINE_AXP64 = PELIB_IMAGE_FILE_MACHINE_ALPHA64 237 PELIB_IMAGE_FILE_MACHINE_AXP64 = PELIB_IMAGE_FILE_MACHINE_ALPHA64
238 }; 238 };
239 239
240 enum 240 enum
241 { 241 {
242 PELIB_IMAGE_FILE_RELOCS_STRIPPED = 0x0001, 242 PELIB_IMAGE_FILE_RELOCS_STRIPPED = 0x0001,
243 PELIB_IMAGE_FILE_EXECUTABLE_IMAGE = 0x0002, 243 PELIB_IMAGE_FILE_EXECUTABLE_IMAGE = 0x0002,
244 PELIB_IMAGE_FILE_LINE_NUMS_STRIPPED = 0x0004, 244 PELIB_IMAGE_FILE_LINE_NUMS_STRIPPED = 0x0004,
245 PELIB_IMAGE_FILE_LOCAL_SYMS_STRIPPED = 0x0008, 245 PELIB_IMAGE_FILE_LOCAL_SYMS_STRIPPED = 0x0008,
246 PELIB_IMAGE_FILE_AGGRESIVE_WS_TRIM = 0x0010, 246 PELIB_IMAGE_FILE_AGGRESIVE_WS_TRIM = 0x0010,
247 PELIB_IMAGE_FILE_LARGE_ADDRESS_AWARE = 0x0020, 247 PELIB_IMAGE_FILE_LARGE_ADDRESS_AWARE = 0x0020,
248 PELIB_IMAGE_FILE_BYTES_REVERSED_LO = 0x0080, 248 PELIB_IMAGE_FILE_BYTES_REVERSED_LO = 0x0080,
249 PELIB_IMAGE_FILE_32BIT_MACHINE = 0x0100, 249 PELIB_IMAGE_FILE_32BIT_MACHINE = 0x0100,
250 PELIB_IMAGE_FILE_DEBUG_STRIPPED = 0x0200, 250 PELIB_IMAGE_FILE_DEBUG_STRIPPED = 0x0200,
251 PELIB_IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP = 0x0400, 251 PELIB_IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP = 0x0400,
252 PELIB_IMAGE_FILE_NET_RUN_FROM_SWAP = 0x0800, 252 PELIB_IMAGE_FILE_NET_RUN_FROM_SWAP = 0x0800,
253 PELIB_IMAGE_FILE_SYSTEM = 0x1000, 253 PELIB_IMAGE_FILE_SYSTEM = 0x1000,
254 PELIB_IMAGE_FILE_DLL = 0x2000, 254 PELIB_IMAGE_FILE_DLL = 0x2000,
255 PELIB_IMAGE_FILE_UP_SYSTEM_ONLY = 0x4000, 255 PELIB_IMAGE_FILE_UP_SYSTEM_ONLY = 0x4000,
256 PELIB_IMAGE_FILE_BYTES_REVERSED_HI = 0x8000 256 PELIB_IMAGE_FILE_BYTES_REVERSED_HI = 0x8000
257 }; 257 };
258 258
259 enum 259 enum
260 { 260 {
261 PELIB_IMAGE_NT_OPTIONAL_HDR32_MAGIC = 0x10b, 261 PELIB_IMAGE_NT_OPTIONAL_HDR32_MAGIC = 0x10b,
262 PELIB_IMAGE_NT_OPTIONAL_HDR64_MAGIC = 0x20b, 262 PELIB_IMAGE_NT_OPTIONAL_HDR64_MAGIC = 0x20b,
263 PELIB_IMAGE_ROM_OPTIONAL_HDR_MAGIC = 0x107 263 PELIB_IMAGE_ROM_OPTIONAL_HDR_MAGIC = 0x107
264 }; 264 };
265 265
266 enum 266 enum
267 { 267 {
268 PELIB_IMAGE_SUBSYSTEM_UNKNOWN = 0, 268 PELIB_IMAGE_SUBSYSTEM_UNKNOWN = 0,
269 PELIB_IMAGE_SUBSYSTEM_NATIVE = 1, 269 PELIB_IMAGE_SUBSYSTEM_NATIVE = 1,
270 PELIB_IMAGE_SUBSYSTEM_WINDOWS_GUI = 2, 270 PELIB_IMAGE_SUBSYSTEM_WINDOWS_GUI = 2,
271 PELIB_IMAGE_SUBSYSTEM_WINDOWS_CUI = 3, 271 PELIB_IMAGE_SUBSYSTEM_WINDOWS_CUI = 3,
272 PELIB_IMAGE_SUBSYSTEM_OS2_CUI = 5, 272 PELIB_IMAGE_SUBSYSTEM_OS2_CUI = 5,
273 PELIB_IMAGE_SUBSYSTEM_POSIX_CUI = 7, 273 PELIB_IMAGE_SUBSYSTEM_POSIX_CUI = 7,
274 PELIB_IMAGE_SUBSYSTEM_NATIVE_WINDOWS = 8, 274 PELIB_IMAGE_SUBSYSTEM_NATIVE_WINDOWS = 8,
275 PELIB_IMAGE_SUBSYSTEM_WINDOWS_CE_GUI = 9 275 PELIB_IMAGE_SUBSYSTEM_WINDOWS_CE_GUI = 9
276 }; 276 };
277 277
278 enum 278 enum
279 { 279 {
280 PELIB_RT_CURSOR = 1, // 1 280 PELIB_RT_CURSOR = 1, // 1
281 PELIB_RT_BITMAP, // 2 281 PELIB_RT_BITMAP, // 2
282 PELIB_RT_ICON, // 3 282 PELIB_RT_ICON, // 3
283 PELIB_RT_MENU, // 4 283 PELIB_RT_MENU, // 4
284 PELIB_RT_DIALOG, // 5 284 PELIB_RT_DIALOG, // 5
285 PELIB_RT_STRING, // 6 285 PELIB_RT_STRING, // 6
286 PELIB_RT_FONTDIR, // 7 286 PELIB_RT_FONTDIR, // 7
287 PELIB_RT_FONT, // 8 287 PELIB_RT_FONT, // 8
288 PELIB_RT_ACCELERATOR, // 9 288 PELIB_RT_ACCELERATOR, // 9
289 PELIB_RT_RCDATA, // 10 289 PELIB_RT_RCDATA, // 10
290 PELIB_RT_MESSAGETABLE, // 11 290 PELIB_RT_MESSAGETABLE, // 11
291 PELIB_RT_GROUP_CURSOR, // 12 291 PELIB_RT_GROUP_CURSOR, // 12
292 PELIB_RT_GROUP_ICON = 14, // 14 292 PELIB_RT_GROUP_ICON = 14, // 14
293 PELIB_RT_VERSION = 16, 293 PELIB_RT_VERSION = 16,
294 PELIB_RT_DLGINCLUDE, 294 PELIB_RT_DLGINCLUDE,
295 PELIB_RT_PLUGPLAY = 19, 295 PELIB_RT_PLUGPLAY = 19,
296 PELIB_RT_VXD, 296 PELIB_RT_VXD,
297 PELIB_RT_ANICURSOR, 297 PELIB_RT_ANICURSOR,
298 PELIB_RT_ANIICON, 298 PELIB_RT_ANIICON,
299 PELIB_RT_HTML, 299 PELIB_RT_HTML,
300 PELIB_RT_MANIFEST 300 PELIB_RT_MANIFEST
301 }; 301 };
302 302
303 template<typename T> 303 template<typename T>
304 unsigned int accumulate(unsigned int size, const T& v) 304 unsigned int accumulate(unsigned int size, const T& v)
305 { 305 {
306 return size + v.size(); 306 return size + v.size();
307 } 307 }
308 308
309 309
310 struct PELIB_IMAGE_DOS_HEADER 310 struct PELIB_IMAGE_DOS_HEADER
311 { 311 {
312 word e_magic; 312 word e_magic;
313 word e_cblp; 313 word e_cblp;
314 word e_cp; 314 word e_cp;
315 word e_crlc; 315 word e_crlc;
316 word e_cparhdr; 316 word e_cparhdr;
317 word e_minalloc; 317 word e_minalloc;
318 word e_maxalloc; 318 word e_maxalloc;
319 word e_ss; 319 word e_ss;
320 word e_sp; 320 word e_sp;
321 word e_csum; 321 word e_csum;
322 word e_ip; 322 word e_ip;
323 word e_cs; 323 word e_cs;
324 word e_lfarlc; 324 word e_lfarlc;
325 word e_ovno; 325 word e_ovno;
326 word e_res[4]; 326 word e_res[4];
327 word e_oemid; 327 word e_oemid;
328 word e_oeminfo; 328 word e_oeminfo;
329 word e_res2[10]; 329 word e_res2[10];
330 dword e_lfanew; 330 dword e_lfanew;
331 331
332 PELIB_IMAGE_DOS_HEADER(); 332 PELIB_IMAGE_DOS_HEADER();
333 333
334 static inline unsigned int size() {return 64;} 334 static inline unsigned int size() {return 64;}
335 }; 335 };
336 336
337 struct PELIB_IMAGE_FILE_HEADER 337 struct PELIB_IMAGE_FILE_HEADER
338 { 338 {
339 word Machine; 339 word Machine;
340 word NumberOfSections; 340 word NumberOfSections;
341 dword TimeDateStamp; 341 dword TimeDateStamp;
342 dword PointerToSymbolTable; 342 dword PointerToSymbolTable;
343 dword NumberOfSymbols; 343 dword NumberOfSymbols;
344 word SizeOfOptionalHeader; 344 word SizeOfOptionalHeader;
345 word Characteristics; 345 word Characteristics;
346 346
347 PELIB_IMAGE_FILE_HEADER() 347 PELIB_IMAGE_FILE_HEADER()
348 { 348 {
349 Machine = 0; 349 Machine = 0;
350 NumberOfSections = 0; 350 NumberOfSections = 0;
351 TimeDateStamp = 0; 351 TimeDateStamp = 0;
352 PointerToSymbolTable = 0; 352 PointerToSymbolTable = 0;
353 NumberOfSymbols = 0; 353 NumberOfSymbols = 0;
354 SizeOfOptionalHeader = 0; 354 SizeOfOptionalHeader = 0;
355 Characteristics = 0; 355 Characteristics = 0;
356 } 356 }
357 357
358 static inline unsigned int size() {return 20;} 358 static inline unsigned int size() {return 20;}
359 }; 359 };
360 360
361 struct PELIB_IMAGE_DATA_DIRECTORY 361 struct PELIB_IMAGE_DATA_DIRECTORY
362 { 362 {
363 dword VirtualAddress; 363 dword VirtualAddress;
364 dword Size; 364 dword Size;
365 365
366 PELIB_IMAGE_DATA_DIRECTORY() 366 PELIB_IMAGE_DATA_DIRECTORY()
367 { 367 {
368 VirtualAddress = 0; 368 VirtualAddress = 0;
369 Size = 0; 369 Size = 0;
370 } 370 }
371 371
372 static inline unsigned int size() {return 8;} 372 static inline unsigned int size() {return 8;}
373 }; 373 };
374 374
375 template<int> 375 template<int>
376 struct FieldSizes; 376 struct FieldSizes;
377 377
378 template<> 378 template<>
379 struct FieldSizes<32> 379 struct FieldSizes<32>
380 { 380 {
381 typedef dword VAR4_8; 381 typedef dword VAR4_8;
382 }; 382 };
383 383
384 template<> 384 template<>
385 struct FieldSizes<64> 385 struct FieldSizes<64>
386 { 386 {
387 typedef qword VAR4_8; 387 typedef qword VAR4_8;
388 }; 388 };
389 389
390 template<int x> 390 template<int x>
391 struct PELIB_IMAGE_OPTIONAL_HEADER_BASE 391 struct PELIB_IMAGE_OPTIONAL_HEADER_BASE
392 { 392 {
393 typedef typename FieldSizes<x>::VAR4_8 VAR4_8; 393 typedef typename FieldSizes<x>::VAR4_8 VAR4_8;
394 394
395 word Magic; 395 word Magic;
396 byte MajorLinkerVersion; 396 byte MajorLinkerVersion;
397 byte MinorLinkerVersion; 397 byte MinorLinkerVersion;
398 dword SizeOfCode; 398 dword SizeOfCode;
399 dword SizeOfInitializedData; 399 dword SizeOfInitializedData;
400 dword SizeOfUninitializedData; 400 dword SizeOfUninitializedData;
401 dword AddressOfEntryPoint; 401 dword AddressOfEntryPoint;
402 dword BaseOfCode; 402 dword BaseOfCode;
403 dword BaseOfData; 403 dword BaseOfData;
404 VAR4_8 ImageBase; 404 VAR4_8 ImageBase;
405 dword SectionAlignment; 405 dword SectionAlignment;
406 dword FileAlignment; 406 dword FileAlignment;
407 word MajorOperatingSystemVersion; 407 word MajorOperatingSystemVersion;
408 word MinorOperatingSystemVersion; 408 word MinorOperatingSystemVersion;
409 word MajorImageVersion; 409 word MajorImageVersion;
410 word MinorImageVersion; 410 word MinorImageVersion;
411 word MajorSubsystemVersion; 411 word MajorSubsystemVersion;
412 word MinorSubsystemVersion; 412 word MinorSubsystemVersion;
413 dword Win32VersionValue; 413 dword Win32VersionValue;
414 dword SizeOfImage; 414 dword SizeOfImage;
415 dword SizeOfHeaders; 415 dword SizeOfHeaders;
416 dword CheckSum; 416 dword CheckSum;
417 word Subsystem; 417 word Subsystem;
418 word DllCharacteristics; 418 word DllCharacteristics;
419 VAR4_8 SizeOfStackReserve; 419 VAR4_8 SizeOfStackReserve;
420 VAR4_8 SizeOfStackCommit; 420 VAR4_8 SizeOfStackCommit;
421 VAR4_8 SizeOfHeapReserve; 421 VAR4_8 SizeOfHeapReserve;
422 VAR4_8 SizeOfHeapCommit; 422 VAR4_8 SizeOfHeapCommit;
423 dword LoaderFlags; 423 dword LoaderFlags;
424 dword NumberOfRvaAndSizes; 424 dword NumberOfRvaAndSizes;
425// PELIB_IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; 425// PELIB_IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
426 426
427 PELIB_IMAGE_OPTIONAL_HEADER_BASE(); 427 PELIB_IMAGE_OPTIONAL_HEADER_BASE();
428 }; 428 };
429 429
430 template<int x> 430 template<int x>
431 PELIB_IMAGE_OPTIONAL_HEADER_BASE<x>::PELIB_IMAGE_OPTIONAL_HEADER_BASE() 431 PELIB_IMAGE_OPTIONAL_HEADER_BASE<x>::PELIB_IMAGE_OPTIONAL_HEADER_BASE()
432 { 432 {
433 Magic = 0; 433 Magic = 0;
434 MajorLinkerVersion = 0; 434 MajorLinkerVersion = 0;
435 MinorLinkerVersion = 0; 435 MinorLinkerVersion = 0;
436 SizeOfCode = 0; 436 SizeOfCode = 0;
437 SizeOfInitializedData = 0; 437 SizeOfInitializedData = 0;
438 SizeOfUninitializedData = 0; 438 SizeOfUninitializedData = 0;
439 AddressOfEntryPoint = 0; 439 AddressOfEntryPoint = 0;
440 BaseOfCode = 0; 440 BaseOfCode = 0;
441// BaseOfData = 0; 441// BaseOfData = 0;
442 ImageBase = 0; 442 ImageBase = 0;
443 SectionAlignment = 0; 443 SectionAlignment = 0;
444 FileAlignment = 0; 444 FileAlignment = 0;
445 MajorOperatingSystemVersion = 0; 445 MajorOperatingSystemVersion = 0;
446 MinorOperatingSystemVersion = 0; 446 MinorOperatingSystemVersion = 0;
447 MajorImageVersion = 0; 447 MajorImageVersion = 0;
448 MinorImageVersion = 0; 448 MinorImageVersion = 0;
449 MajorSubsystemVersion = 0; 449 MajorSubsystemVersion = 0;
450 MinorSubsystemVersion = 0; 450 MinorSubsystemVersion = 0;
451 Win32VersionValue = 0; 451 Win32VersionValue = 0;
452 SizeOfImage = 0; 452 SizeOfImage = 0;
453 SizeOfHeaders = 0; 453 SizeOfHeaders = 0;
454 CheckSum = 0; 454 CheckSum = 0;
455 Subsystem = 0; 455 Subsystem = 0;
456 DllCharacteristics = 0; 456 DllCharacteristics = 0;
457 SizeOfStackReserve = 0; 457 SizeOfStackReserve = 0;
458 SizeOfStackCommit = 0; 458 SizeOfStackCommit = 0;
459 SizeOfHeapReserve = 0; 459 SizeOfHeapReserve = 0;
460 SizeOfHeapCommit = 0; 460 SizeOfHeapCommit = 0;
461 LoaderFlags = 0; 461 LoaderFlags = 0;
462 NumberOfRvaAndSizes = 0; 462 NumberOfRvaAndSizes = 0;
463 } 463 }
464 464
465 template<int> 465 template<int>
466 struct PELIB_IMAGE_OPTIONAL_HEADER; 466 struct PELIB_IMAGE_OPTIONAL_HEADER;
467 467
468 template<> 468 template<>
469 struct PELIB_IMAGE_OPTIONAL_HEADER<32> : public PELIB_IMAGE_OPTIONAL_HEADER_BASE<32> 469 struct PELIB_IMAGE_OPTIONAL_HEADER<32> : public PELIB_IMAGE_OPTIONAL_HEADER_BASE<32>
470 { 470 {
471 dword BaseOfData; 471 dword BaseOfData;
472 472
473 static inline unsigned int size() {return 224 - 0x10 * 8;} 473 static inline unsigned int size() {return 224 - 0x10 * 8;}
474 }; 474 };
475 475
476 template<> 476 template<>
477 struct PELIB_IMAGE_OPTIONAL_HEADER<64> : public PELIB_IMAGE_OPTIONAL_HEADER_BASE<64> 477 struct PELIB_IMAGE_OPTIONAL_HEADER<64> : public PELIB_IMAGE_OPTIONAL_HEADER_BASE<64>
478 { 478 {
479 static inline unsigned int size() {return 240 - 0x10 * 8;} 479 static inline unsigned int size() {return 240 - 0x10 * 8;}
480 }; 480 };
481 481
482 template<int x> 482 template<int x>
483 struct PELIB_IMAGE_NT_HEADERS 483 struct PELIB_IMAGE_NT_HEADERS
484 { 484 {
485 dword Signature; 485 dword Signature;
486 PELIB_IMAGE_FILE_HEADER FileHeader; 486 PELIB_IMAGE_FILE_HEADER FileHeader;
487 PELIB_IMAGE_OPTIONAL_HEADER<x> OptionalHeader; 487 PELIB_IMAGE_OPTIONAL_HEADER<x> OptionalHeader;
488 std::vector<PELIB_IMAGE_DATA_DIRECTORY> dataDirectories; 488 std::vector<PELIB_IMAGE_DATA_DIRECTORY> dataDirectories;
489 489
490 unsigned int size() const 490 unsigned int size() const
491 { 491 {
492 return sizeof(dword) 492 return sizeof(dword)
493 + PELIB_IMAGE_FILE_HEADER::size() 493 + PELIB_IMAGE_FILE_HEADER::size()
494 + PELIB_IMAGE_OPTIONAL_HEADER<x>::size() 494 + PELIB_IMAGE_OPTIONAL_HEADER<x>::size()
495 + static_cast<unsigned int>(dataDirectories.size()) * PELIB_IMAGE_DATA_DIRECTORY::size(); 495 + static_cast<unsigned int>(dataDirectories.size()) * PELIB_IMAGE_DATA_DIRECTORY::size();
496 } 496 }
497 497
498 PELIB_IMAGE_NT_HEADERS() 498 PELIB_IMAGE_NT_HEADERS()
499 { 499 {
500 Signature = 0; 500 Signature = 0;
501 } 501 }
502 }; 502 };
503 503
504 const unsigned int PELIB_IMAGE_SIZEOF_SHORT_NAME = 8; 504 const unsigned int PELIB_IMAGE_SIZEOF_SHORT_NAME = 8;
505 505
506 struct PELIB_IMAGE_SECTION_HEADER 506 struct PELIB_IMAGE_SECTION_HEADER
507 { 507 {
508 byte Name[PELIB_IMAGE_SIZEOF_SHORT_NAME]; 508 byte Name[PELIB_IMAGE_SIZEOF_SHORT_NAME];
509 dword VirtualSize; 509 dword VirtualSize;
510 dword VirtualAddress; 510 dword VirtualAddress;
511 dword SizeOfRawData; 511 dword SizeOfRawData;
512 dword PointerToRawData; 512 dword PointerToRawData;
513 dword PointerToRelocations; 513 dword PointerToRelocations;
514 dword PointerToLinenumbers; 514 dword PointerToLinenumbers;
515 word NumberOfRelocations; 515 word NumberOfRelocations;
516 word NumberOfLinenumbers; 516 word NumberOfLinenumbers;
517 dword Characteristics; 517 dword Characteristics;
518 518
519 PELIB_IMAGE_SECTION_HEADER() 519 PELIB_IMAGE_SECTION_HEADER()
520 { 520 {
521 VirtualSize = 0; 521 VirtualSize = 0;
522 VirtualAddress = 0; 522 VirtualAddress = 0;
523 SizeOfRawData = 0; 523 SizeOfRawData = 0;
524 PointerToRawData = 0; 524 PointerToRawData = 0;
525 PointerToRelocations = 0; 525 PointerToRelocations = 0;
526 PointerToLinenumbers = 0; 526 PointerToLinenumbers = 0;
527 NumberOfRelocations = 0; 527 NumberOfRelocations = 0;
528 NumberOfLinenumbers = 0; 528 NumberOfLinenumbers = 0;
529 Characteristics = 0; 529 Characteristics = 0;
530 } 530 }
531 531
532 static inline unsigned int size() {return 40;} 532 static inline unsigned int size() {return 40;}
533 bool biggerFileOffset(const PELIB_IMAGE_SECTION_HEADER& ish) const; 533 bool biggerFileOffset(const PELIB_IMAGE_SECTION_HEADER& ish) const;
534 bool biggerVirtualAddress(const PELIB_IMAGE_SECTION_HEADER& ish) const; 534 bool biggerVirtualAddress(const PELIB_IMAGE_SECTION_HEADER& ish) const;
535 }; 535 };
536 536
537 template<int bits> 537 template<int bits>
538 struct PELIB_IMAGE_THUNK_DATA 538 struct PELIB_IMAGE_THUNK_DATA
539 { 539 {
540 typename FieldSizes<bits>::VAR4_8 Ordinal; 540 typename FieldSizes<bits>::VAR4_8 Ordinal;
541 541
542 PELIB_IMAGE_THUNK_DATA() 542 PELIB_IMAGE_THUNK_DATA()
543 { 543 {
544 Ordinal = 0; 544 Ordinal = 0;
545 } 545 }
546 546
547 static inline unsigned int size() {return 4;} 547 static inline unsigned int size() {return 4;}
548 }; 548 };
549 549
550 struct PELIB_IMAGE_IMPORT_DESCRIPTOR 550 struct PELIB_IMAGE_IMPORT_DESCRIPTOR
551 { 551 {
552 dword OriginalFirstThunk; 552 dword OriginalFirstThunk;
553 dword TimeDateStamp; 553 dword TimeDateStamp;
554 dword ForwarderChain; 554 dword ForwarderChain;
555 dword Name; 555 dword Name;
556 dword FirstThunk; 556 dword FirstThunk;
557 557
558 PELIB_IMAGE_IMPORT_DESCRIPTOR() 558 PELIB_IMAGE_IMPORT_DESCRIPTOR()
559 { 559 {
560 OriginalFirstThunk = 0; 560 OriginalFirstThunk = 0;
561 TimeDateStamp = 0; 561 TimeDateStamp = 0;
562 ForwarderChain = 0; 562 ForwarderChain = 0;
563 Name = 0; 563 Name = 0;
564 FirstThunk = 0; 564 FirstThunk = 0;
565 } 565 }
566 566
567 static inline unsigned int size() {return 20;} 567 static inline unsigned int size() {return 20;}
568 }; 568 };
569 569
570 struct PELIB_IMAGE_EXPORT_DIRECTORY 570 struct PELIB_IMAGE_EXPORT_DIRECTORY
571 { 571 {
572 dword Characteristics; 572 dword Characteristics;
573 dword TimeDateStamp; 573 dword TimeDateStamp;
574 word MajorVersion; 574 word MajorVersion;
575 word MinorVersion; 575 word MinorVersion;
576 dword Name; 576 dword Name;
577 dword Base; 577 dword Base;
578 dword NumberOfFunctions; 578 dword NumberOfFunctions;
579 dword NumberOfNames; 579 dword NumberOfNames;
580 dword AddressOfFunctions; 580 dword AddressOfFunctions;
581 dword AddressOfNames; 581 dword AddressOfNames;
582 dword AddressOfNameOrdinals; 582 dword AddressOfNameOrdinals;
583 583
584 PELIB_IMAGE_EXPORT_DIRECTORY() 584 PELIB_IMAGE_EXPORT_DIRECTORY()
585 { 585 {
586 Characteristics = 0; 586 Characteristics = 0;
587 TimeDateStamp = 0; 587 TimeDateStamp = 0;
588 MajorVersion = 0; 588 MajorVersion = 0;
589 MinorVersion = 0; 589 MinorVersion = 0;
590 Name = 0; 590 Name = 0;
591 Base = 0; 591 Base = 0;
592 NumberOfFunctions = 0; 592 NumberOfFunctions = 0;
593 NumberOfNames = 0; 593 NumberOfNames = 0;
594 AddressOfFunctions = 0; 594 AddressOfFunctions = 0;
595 NumberOfNames = 0; 595 NumberOfNames = 0;
596 AddressOfNameOrdinals = 0; 596 AddressOfNameOrdinals = 0;
597 } 597 }
598 598
599 static inline unsigned int size() {return 40;} 599 static inline unsigned int size() {return 40;}
600 }; 600 };
601 601
602 struct PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR 602 struct PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR
603 { 603 {
604 dword TimeDateStamp; 604 dword TimeDateStamp;
605 word OffsetModuleName; 605 word OffsetModuleName;
606 word NumberOfModuleForwarderRefs; 606 word NumberOfModuleForwarderRefs;
607 607
608 PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR() 608 PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR()
609 { 609 {
610 TimeDateStamp = 0; 610 TimeDateStamp = 0;
611 OffsetModuleName = 0; 611 OffsetModuleName = 0;
612 NumberOfModuleForwarderRefs = 0; 612 NumberOfModuleForwarderRefs = 0;
613 } 613 }
614 614
615 static unsigned int size() 615 static unsigned int size()
616 { 616 {
617 return 8; 617 return 8;
618 } 618 }
619 }; 619 };
620 620
621 // Stores all necessary information about a BoundImport field. 621 // Stores all necessary information about a BoundImport field.
622 struct PELIB_IMAGE_BOUND_DIRECTORY 622 struct PELIB_IMAGE_BOUND_DIRECTORY
623 { 623 {
624 PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR ibdDescriptor; ///< Information about the imported file. 624 PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR ibdDescriptor; ///< Information about the imported file.
625 std::string strModuleName; ///< Name of the imported file. 625 std::string strModuleName; ///< Name of the imported file.
626 std::vector<PELIB_IMAGE_BOUND_DIRECTORY> moduleForwarders; 626 std::vector<PELIB_IMAGE_BOUND_DIRECTORY> moduleForwarders;
627 627
628 // Will be used in std::find_if 628 // Will be used in std::find_if
629 // Passing by-reference not possible (see C++ Standard Core Language Defect Reports, Revision 29, Issue 106) 629 // Passing by-reference not possible (see C++ Standard Core Language Defect Reports, Revision 29, Issue 106)
630 /// Compares the passed filename to the struct's filename. 630 /// Compares the passed filename to the struct's filename.
631 bool equal(const std::string strModuleName) const; 631 bool equal(const std::string strModuleName) const;
632 632
633 unsigned int size() const; 633 unsigned int size() const;
634 }; 634 };
635 635
636 struct PELIB_EXP_FUNC_INFORMATION 636 struct PELIB_EXP_FUNC_INFORMATION
637 { 637 {
638 dword addroffunc; 638 dword addroffunc;
639 dword addrofname; 639 dword addrofname;
640 word ordinal; 640 word ordinal;
641 std::string funcname; 641 std::string funcname;
642 642
643 PELIB_EXP_FUNC_INFORMATION(); 643 PELIB_EXP_FUNC_INFORMATION();
644 644
645 bool equal(const std::string strFunctionName) const; 645 bool equal(const std::string strFunctionName) const;
646 inline unsigned int size() const 646 inline unsigned int size() const
647 { 647 {
648 unsigned int uiSize = 4; 648 unsigned int uiSize = 4;
649 if (addroffunc) uiSize += 2;// + 4; 649 if (addroffunc) uiSize += 2;// + 4;
650 if (!funcname.empty()) uiSize += 4 + (unsigned int)funcname.size() + 1; 650 if (!funcname.empty()) uiSize += 4 + (unsigned int)funcname.size() + 1;
651 return uiSize; 651 return uiSize;
652 } 652 }
653 }; 653 };
654 654
655 struct PELIB_IMAGE_RESOURCE_DIRECTORY 655 struct PELIB_IMAGE_RESOURCE_DIRECTORY
656 { 656 {
657 dword Characteristics; 657 dword Characteristics;
658 dword TimeDateStamp; 658 dword TimeDateStamp;
659 word MajorVersion; 659 word MajorVersion;
660 word MinorVersion; 660 word MinorVersion;
661 word NumberOfNamedEntries; 661 word NumberOfNamedEntries;
662 word NumberOfIdEntries; 662 word NumberOfIdEntries;
663 663
664 PELIB_IMAGE_RESOURCE_DIRECTORY(); 664 PELIB_IMAGE_RESOURCE_DIRECTORY();
665 665
666 static inline unsigned int size() {return 16;} 666 static inline unsigned int size() {return 16;}
667 }; 667 };
668 668
669 struct PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY 669 struct PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY
670 { 670 {
671 dword Name; 671 dword Name;
672 dword OffsetToData; 672 dword OffsetToData;
673 PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY(); 673 PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY();
674 static inline unsigned int size() {return 8;} 674 static inline unsigned int size() {return 8;}
675 }; 675 };
676 676
677 const unsigned int PELIB_IMAGE_SIZEOF_BASE_RELOCATION = 8; 677 const unsigned int PELIB_IMAGE_SIZEOF_BASE_RELOCATION = 8;
678 678
679 struct PELIB_IMG_RES_DIR_ENTRY 679 struct PELIB_IMG_RES_DIR_ENTRY
680 { 680 {
681 PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY irde; 681 PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY irde;
682 std::string wstrName; 682 std::string wstrName;
683 683
684 bool operator<(const PELIB_IMG_RES_DIR_ENTRY& first) const; 684 bool operator<(const PELIB_IMG_RES_DIR_ENTRY& first) const;
685 685
686 }; 686 };
687 687
688 struct PELIB_IMAGE_BASE_RELOCATION 688 struct PELIB_IMAGE_BASE_RELOCATION
689 { 689 {
690 dword VirtualAddress; 690 dword VirtualAddress;
691 dword SizeOfBlock; 691 dword SizeOfBlock;
692 692
693 PELIB_IMAGE_BASE_RELOCATION(); 693 PELIB_IMAGE_BASE_RELOCATION();
694 static inline unsigned int size() {return 8;} 694 static inline unsigned int size() {return 8;}
695 }; 695 };
696 696
697 struct PELIB_IMAGE_COR20_HEADER 697 struct PELIB_IMAGE_COR20_HEADER
698 { 698 {
699 dword cb; 699 dword cb;
700 word MajorRuntimeVersion; 700 word MajorRuntimeVersion;
701 word MinorRuntimeVersion; 701 word MinorRuntimeVersion;
702 PELIB_IMAGE_DATA_DIRECTORY MetaData; 702 PELIB_IMAGE_DATA_DIRECTORY MetaData;
703 dword Flags; 703 dword Flags;
704 dword EntryPointToken; 704 dword EntryPointToken;
705 PELIB_IMAGE_DATA_DIRECTORY Resources; 705 PELIB_IMAGE_DATA_DIRECTORY Resources;
706 PELIB_IMAGE_DATA_DIRECTORY StrongNameSignature; 706 PELIB_IMAGE_DATA_DIRECTORY StrongNameSignature;
707 PELIB_IMAGE_DATA_DIRECTORY CodeManagerTable; 707 PELIB_IMAGE_DATA_DIRECTORY CodeManagerTable;
708 PELIB_IMAGE_DATA_DIRECTORY VTableFixups; 708 PELIB_IMAGE_DATA_DIRECTORY VTableFixups;
709 PELIB_IMAGE_DATA_DIRECTORY ExportAddressTableJumps; 709 PELIB_IMAGE_DATA_DIRECTORY ExportAddressTableJumps;
710 PELIB_IMAGE_DATA_DIRECTORY ManagedNativeHeader; 710 PELIB_IMAGE_DATA_DIRECTORY ManagedNativeHeader;
711 711
712 PELIB_IMAGE_COR20_HEADER(); 712 PELIB_IMAGE_COR20_HEADER();
713 static inline unsigned int size() {return 72;} 713 static inline unsigned int size() {return 72;}
714 }; 714 };
715 715
716 // Used to store a file's export table. 716 // Used to store a file's export table.
717 struct PELIB_IMAGE_EXP_DIRECTORY 717 struct PELIB_IMAGE_EXP_DIRECTORY
718 { 718 {
719 /// The IMAGE_EXPORTED_DIRECTORY of a file's export table. 719 /// The IMAGE_EXPORTED_DIRECTORY of a file's export table.
720 PELIB_IMAGE_EXPORT_DIRECTORY ied; 720 PELIB_IMAGE_EXPORT_DIRECTORY ied;
721 /// The original filename of current file. 721 /// The original filename of current file.
722 std::string name; 722 std::string name;
723 std::vector<PELIB_EXP_FUNC_INFORMATION> functions; 723 std::vector<PELIB_EXP_FUNC_INFORMATION> functions;
724 inline unsigned int size() const 724 inline unsigned int size() const
725 { 725 {
726 return PELIB_IMAGE_EXPORT_DIRECTORY::size() + name.size() + 1 + 726 return PELIB_IMAGE_EXPORT_DIRECTORY::size() + name.size() + 1 +
727 std::accumulate(functions.begin(), functions.end(), 0, accumulate<PELIB_EXP_FUNC_INFORMATION>); 727 std::accumulate(functions.begin(), functions.end(), 0, accumulate<PELIB_EXP_FUNC_INFORMATION>);
728 } 728 }
729 }; 729 };
730 730
731 // Used for parsing a file's import table. It combines the function name, the hint 731 // Used for parsing a file's import table. It combines the function name, the hint
732 // and the IMAGE_THUNK_DATA of an imported function. 732 // and the IMAGE_THUNK_DATA of an imported function.
733 template<int bits> 733 template<int bits>
734 struct PELIB_THUNK_DATA 734 struct PELIB_THUNK_DATA
735 { 735 {
736 /// The IMAGE_THUNK_DATA struct of an imported function. 736 /// The IMAGE_THUNK_DATA struct of an imported function.
737 PELIB_IMAGE_THUNK_DATA<bits> itd; 737 PELIB_IMAGE_THUNK_DATA<bits> itd;
738 /// The hint of an imported function. 738 /// The hint of an imported function.
739 word hint; 739 word hint;
740 /// The function name of an imported function. 740 /// The function name of an imported function.
741 std::string fname; 741 std::string fname;
742 742
743 bool equalHint(word wHint) const 743 bool equalHint(word wHint) const
744 { 744 {
745 return hint == wHint; 745 return hint == wHint;
746// return itd.Ordinal == (wHint | IMAGE_ORDINAL_FLAGS<bits>::IMAGE_ORDINAL_FLAG); 746// return itd.Ordinal == (wHint | IMAGE_ORDINAL_FLAGS<bits>::IMAGE_ORDINAL_FLAG);
747 } 747 }
748 748
749 bool equalFunctionName(std::string strFunctionName) const 749 bool equalFunctionName(std::string strFunctionName) const
750 { 750 {
751 return isEqualNc(fname, strFunctionName); 751 return isEqualNc(fname, strFunctionName);
752 } 752 }
753 753
754 unsigned int size() const {return PELIB_IMAGE_THUNK_DATA<bits>::size() + fname.size() + 1 + sizeof(hint);} 754 unsigned int size() const {return PELIB_IMAGE_THUNK_DATA<bits>::size() + fname.size() + 1 + sizeof(hint);}
755 }; 755 };
756 756
757 // Used to store a file's import table. Every struct of this sort 757 // Used to store a file's import table. Every struct of this sort
758 // can store import information of one DLL. 758 // can store import information of one DLL.
759 template<int bits> 759 template<int bits>
760 struct PELIB_IMAGE_IMPORT_DIRECTORY 760 struct PELIB_IMAGE_IMPORT_DIRECTORY
761 { 761 {
762 /// The IMAGE_IMPORT_DESCRIPTOR of an imported DLL. 762 /// The IMAGE_IMPORT_DESCRIPTOR of an imported DLL.
763 PELIB_IMAGE_IMPORT_DESCRIPTOR impdesc; 763 PELIB_IMAGE_IMPORT_DESCRIPTOR impdesc;
764 /// The name of an imported DLL. 764 /// The name of an imported DLL.
765 std::string name; 765 std::string name;
766 /// All original first thunk values of an imported DLL. 766 /// All original first thunk values of an imported DLL.
767 std::vector<PELIB_THUNK_DATA<bits> > originalfirstthunk; 767 std::vector<PELIB_THUNK_DATA<bits> > originalfirstthunk;
768 /// All first thunk value of an imported DLL. 768 /// All first thunk value of an imported DLL.
769 std::vector<PELIB_THUNK_DATA<bits> > firstthunk; 769 std::vector<PELIB_THUNK_DATA<bits> > firstthunk;
770 770
771// bool operator==(std::string strFilename) const; 771// bool operator==(std::string strFilename) const;
772 inline unsigned int size() const 772 inline unsigned int size() const
773 { 773 {
774 return PELIB_IMAGE_IMPORT_DESCRIPTOR::size() + name.size() + 1 + // descriptor + dllname 774 return PELIB_IMAGE_IMPORT_DESCRIPTOR::size() + name.size() + 1 + // descriptor + dllname
775 std::accumulate(originalfirstthunk.begin(), originalfirstthunk.end(), 0, accumulate<PELIB_THUNK_DATA<bits> >) + // thunks (PeLib uses only one thunk) 775 std::accumulate(originalfirstthunk.begin(), originalfirstthunk.end(), 0, accumulate<PELIB_THUNK_DATA<bits> >) + // thunks (PeLib uses only one thunk)
776 PELIB_IMAGE_THUNK_DATA<bits>::size(); // zero-termination 776 PELIB_IMAGE_THUNK_DATA<bits>::size(); // zero-termination
777 } 777 }
778 778
779 bool operator==(std::string strFilename) const 779 bool operator==(std::string strFilename) const
780 { 780 {
781 return isEqualNc(this->name, strFilename); 781 return isEqualNc(this->name, strFilename);
782 } 782 }
783 }; 783 };
784 784
785 struct PELIB_IMAGE_RESOURCE_DATA_ENTRY 785 struct PELIB_IMAGE_RESOURCE_DATA_ENTRY
786 { 786 {
787 dword OffsetToData; 787 dword OffsetToData;
788 dword Size; 788 dword Size;
789 dword CodePage; 789 dword CodePage;
790 dword Reserved; 790 dword Reserved;
791 791
792 static inline unsigned int size() {return 16;} 792 static inline unsigned int size() {return 16;}
793 }; 793 };
794 794
795 struct PELIB_IMAGE_RESOURCE_DATA 795 struct PELIB_IMAGE_RESOURCE_DATA
796 { 796 {
797 PELIB_IMAGE_RESOURCE_DATA_ENTRY irdEntry; 797 PELIB_IMAGE_RESOURCE_DATA_ENTRY irdEntry;
798 std::vector<byte> vData; 798 std::vector<byte> vData;
799 }; 799 };
800 800
801 struct IMG_BASE_RELOC 801 struct IMG_BASE_RELOC
802 { 802 {
803 PELIB_IMAGE_BASE_RELOCATION ibrRelocation; 803 PELIB_IMAGE_BASE_RELOCATION ibrRelocation;
804 std::vector<word> vRelocData; 804 std::vector<word> vRelocData;
805 }; 805 };
806 806
807 struct PELIB_IMAGE_DEBUG_DIRECTORY 807 struct PELIB_IMAGE_DEBUG_DIRECTORY
808 { 808 {
809 dword Characteristics; 809 dword Characteristics;
810 dword TimeDateStamp; 810 dword TimeDateStamp;
811 word MajorVersion; 811 word MajorVersion;
812 word MinorVersion; 812 word MinorVersion;
813 dword Type; 813 dword Type;
814 dword SizeOfData; 814 dword SizeOfData;
815 dword AddressOfRawData; 815 dword AddressOfRawData;
816 dword PointerToRawData; 816 dword PointerToRawData;
817 817
818 static unsigned int size() {return 28;} 818 static unsigned int size() {return 28;}
819 }; 819 };
820 820
821 struct PELIB_IMG_DEBUG_DIRECTORY 821 struct PELIB_IMG_DEBUG_DIRECTORY
822 { 822 {
823 PELIB_IMAGE_DEBUG_DIRECTORY idd; 823 PELIB_IMAGE_DEBUG_DIRECTORY idd;
824 std::vector<byte> data; 824 std::vector<byte> data;
825 }; 825 };
826 826
827 template<int bits> 827 template<int bits>
828 struct PELIB_IMAGE_TLS_DIRECTORY_BASE 828 struct PELIB_IMAGE_TLS_DIRECTORY_BASE
829 { 829 {
830 typename FieldSizes<bits>::VAR4_8 StartAddressOfRawData; 830 typename FieldSizes<bits>::VAR4_8 StartAddressOfRawData;
831 typename FieldSizes<bits>::VAR4_8 EndAddressOfRawData; 831 typename FieldSizes<bits>::VAR4_8 EndAddressOfRawData;
832 typename FieldSizes<bits>::VAR4_8 AddressOfIndex; 832 typename FieldSizes<bits>::VAR4_8 AddressOfIndex;
833 typename FieldSizes<bits>::VAR4_8 AddressOfCallBacks; 833 typename FieldSizes<bits>::VAR4_8 AddressOfCallBacks;
834 dword SizeOfZeroFill; 834 dword SizeOfZeroFill;
835 dword Characteristics; 835 dword Characteristics;
836 }; 836 };
837 837
838 template<int bits> 838 template<int bits>
839 struct PELIB_IMAGE_TLS_DIRECTORY;// : public PELIB_IMAGE_TLS_DIRECTORY_BASE<bits> 839 struct PELIB_IMAGE_TLS_DIRECTORY;// : public PELIB_IMAGE_TLS_DIRECTORY_BASE<bits>
840 840
841 template<> 841 template<>
842 struct PELIB_IMAGE_TLS_DIRECTORY<32> : public PELIB_IMAGE_TLS_DIRECTORY_BASE<32> 842 struct PELIB_IMAGE_TLS_DIRECTORY<32> : public PELIB_IMAGE_TLS_DIRECTORY_BASE<32>
843 { 843 {
844// enum {size = 24}; 844// enum {size = 24};
845 static unsigned int size(){return 24;} 845 static unsigned int size(){return 24;}
846 }; 846 };
847 847
848 template<> 848 template<>
849 struct PELIB_IMAGE_TLS_DIRECTORY<64> : public PELIB_IMAGE_TLS_DIRECTORY_BASE<64> 849 struct PELIB_IMAGE_TLS_DIRECTORY<64> : public PELIB_IMAGE_TLS_DIRECTORY_BASE<64>
850 { 850 {
851// enum {size = 40}; 851// enum {size = 40};
852 static unsigned int size(){return 40;} 852 static unsigned int size(){return 40;}
853 }; 853 };
854 854
855 unsigned int fileSize(const std::string& filename); 855 unsigned int fileSize(const std::string& filename);
856 unsigned int fileSize(std::ifstream& file); 856 unsigned int fileSize(std::ifstream& file);
857 unsigned int fileSize(std::ofstream& file); 857 unsigned int fileSize(std::ofstream& file);
858 unsigned int fileSize(std::fstream& file); 858 unsigned int fileSize(std::fstream& file);
859 unsigned int alignOffset(unsigned int uiOffset, unsigned int uiAlignment); 859 unsigned int alignOffset(unsigned int uiOffset, unsigned int uiAlignment);
860 860
861 /// Determines if a file is a 32bit or 64bit PE file. 861 /// Determines if a file is a 32bit or 64bit PE file.
862 unsigned int getFileType(const std::string strFilename); 862 unsigned int getFileType(const std::string strFilename);
863 863
864 /// Opens a PE file. 864 /// Opens a PE file.
865 PeFile* openPeFile(const std::string& strFilename); 865 PeFile* openPeFile(const std::string& strFilename);
866 866
867 /* enum MzHeader_Field {e_magic, e_cblp, e_cp, e_crlc, e_cparhdr, e_minalloc, e_maxalloc, 867 /* enum MzHeader_Field {e_magic, e_cblp, e_cp, e_crlc, e_cparhdr, e_minalloc, e_maxalloc,
868 e_ss, e_sp, e_csum, e_ip, e_cs, e_lfarlc, e_ovno, e_res, e_oemid, 868 e_ss, e_sp, e_csum, e_ip, e_cs, e_lfarlc, e_ovno, e_res, e_oemid,
869 e_oeminfo, e_res2, e_lfanew}; 869 e_oeminfo, e_res2, e_lfanew};
870 enum PeHeader_Field {NtSignature, Machine, NumberOfSections, TimeDateStamp, PointerToSymbolTable, 870 enum PeHeader_Field {NtSignature, Machine, NumberOfSections, TimeDateStamp, PointerToSymbolTable,
871 NumberOfSymbols, SizeOfOptionalHeader, Characteristics, Magic, 871 NumberOfSymbols, SizeOfOptionalHeader, Characteristics, Magic,
872 MajorLinkerVersion, MinorLinkerVersion, SizeOfCode, SizeOfInitializedData, 872 MajorLinkerVersion, MinorLinkerVersion, SizeOfCode, SizeOfInitializedData,
873 SizeOfUninitializedData, AddressOfEntryPoint, BaseOfCode, BaseOfData, ImageBase, 873 SizeOfUninitializedData, AddressOfEntryPoint, BaseOfCode, BaseOfData, ImageBase,
874 SectionAlignment, FileAlignment, MajorOperatingSystemVersion, MinorOperatingSystemVersion, 874 SectionAlignment, FileAlignment, MajorOperatingSystemVersion, MinorOperatingSystemVersion,
875 MajorImageVersion, MinorImageVersion, MajorSubsystemVersion, MinorSubsystemVersion, 875 MajorImageVersion, MinorImageVersion, MajorSubsystemVersion, MinorSubsystemVersion,
876 Win32VersionValue, SizeOfImage, SizeOfHeaders, CheckSum, Subsystem, DllCharacteristics, 876 Win32VersionValue, SizeOfImage, SizeOfHeaders, CheckSum, Subsystem, DllCharacteristics,
877 SizeOfStackReserve, SizeOfStackCommit, SizeOfHeapReserve, SizeOfHeapCommit, 877 SizeOfStackReserve, SizeOfStackCommit, SizeOfHeapReserve, SizeOfHeapCommit,
878 LoaderFlags, NumberOfRvaAndSizes, DataDirectoryRva, DataDirectorySize}; 878 LoaderFlags, NumberOfRvaAndSizes, DataDirectoryRva, DataDirectorySize};
879 enum Section_Field {SectionName, VirtualSize, VirtualAddress, SizeOfRawData, PointerToRawData, PointerToRelocations, 879 enum Section_Field {SectionName, VirtualSize, VirtualAddress, SizeOfRawData, PointerToRawData, PointerToRelocations,
880 PointerToLinenumbers, NumberOfRelocations, NumberOfLinenumbers, SectionCharacteristics}; 880 PointerToLinenumbers, NumberOfRelocations, NumberOfLinenumbers, SectionCharacteristics};
881*/ 881*/
882} 882}
883 883
884#endif 884#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/PeLibInc.h b/utils/zenutils/libraries/pelib-0.9/pelib/PeLibInc.h
index 84538bd2dd..7d3cabaa6b 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/PeLibInc.h
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/PeLibInc.h
@@ -1,32 +1,32 @@
1/* 1/*
2* PeLibInc.h - Part of the PeLib library. 2* PeLibInc.h - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#ifndef STD_H 13#ifndef STD_H
14#define STD_H 14#define STD_H
15 15
16#ifdef _MSC_VER 16#ifdef _MSC_VER
17 #ifndef for 17 #ifndef for
18 #define for if (0) {} else for 18 #define for if (0) {} else for
19 #endif 19 #endif
20#endif 20#endif
21 21
22#include <algorithm> 22#include <algorithm>
23#include <climits> 23#include <climits>
24#include <fstream> 24#include <fstream>
25#include <iostream> 25#include <iostream>
26#include <string> 26#include <string>
27#include <vector> 27#include <vector>
28#include <functional> 28#include <functional>
29// #include "PeLib.h" 29// #include "PeLib.h"
30#include "PeLibAux.h" 30#include "PeLibAux.h"
31 31
32#endif 32#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/RelocationsDirectory.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/RelocationsDirectory.cpp
index d8b5035abf..392261d242 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/RelocationsDirectory.cpp
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/RelocationsDirectory.cpp
@@ -1,211 +1,211 @@
1/* 1/*
2* Relocations.cpp - Part of the PeLib library. 2* Relocations.cpp - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#include "PeLibInc.h" 13#include "PeLibInc.h"
14#include "RelocationsDirectory.h" 14#include "RelocationsDirectory.h"
15 15
16namespace PeLib 16namespace PeLib
17{ 17{
18 void RelocationsDirectory::setRelocationData(unsigned int ulRelocation, unsigned int ulDataNumber, word wData) 18 void RelocationsDirectory::setRelocationData(unsigned int ulRelocation, unsigned int ulDataNumber, word wData)
19 { 19 {
20 m_vRelocations[ulRelocation].vRelocData[ulDataNumber] = wData; 20 m_vRelocations[ulRelocation].vRelocData[ulDataNumber] = wData;
21 } 21 }
22 22
23 void RelocationsDirectory::read(InputBuffer& inputbuffer, unsigned int uiSize) 23 void RelocationsDirectory::read(InputBuffer& inputbuffer, unsigned int uiSize)
24 { 24 {
25 IMG_BASE_RELOC ibrCurr; 25 IMG_BASE_RELOC ibrCurr;
26 26
27 std::vector<IMG_BASE_RELOC> vCurrReloc; 27 std::vector<IMG_BASE_RELOC> vCurrReloc;
28 28
29 do 29 do
30 { 30 {
31 inputbuffer >> ibrCurr.ibrRelocation.VirtualAddress; 31 inputbuffer >> ibrCurr.ibrRelocation.VirtualAddress;
32 inputbuffer >> ibrCurr.ibrRelocation.SizeOfBlock; 32 inputbuffer >> ibrCurr.ibrRelocation.SizeOfBlock;
33 33
34 ibrCurr.vRelocData.clear(); 34 ibrCurr.vRelocData.clear();
35 35
36 // That's not how to check if there are relocations, some DLLs start at VA 0. 36 // That's not how to check if there are relocations, some DLLs start at VA 0.
37 // if (!ibrCurr.ibrRelocation.VirtualAddress) break; 37 // if (!ibrCurr.ibrRelocation.VirtualAddress) break;
38 38
39 for (unsigned int i=0;i<(ibrCurr.ibrRelocation.SizeOfBlock - PELIB_IMAGE_SIZEOF_BASE_RELOCATION) / sizeof(word);i++) 39 for (unsigned int i=0;i<(ibrCurr.ibrRelocation.SizeOfBlock - PELIB_IMAGE_SIZEOF_BASE_RELOCATION) / sizeof(word);i++)
40 { 40 {
41 word wData; 41 word wData;
42 inputbuffer >> wData; 42 inputbuffer >> wData;
43 ibrCurr.vRelocData.push_back(wData); 43 ibrCurr.vRelocData.push_back(wData);
44 } 44 }
45 45
46 vCurrReloc.push_back(ibrCurr); 46 vCurrReloc.push_back(ibrCurr);
47 } while (ibrCurr.ibrRelocation.VirtualAddress && inputbuffer.get() < uiSize); 47 } while (ibrCurr.ibrRelocation.VirtualAddress && inputbuffer.get() < uiSize);
48 48
49 std::swap(vCurrReloc, m_vRelocations); 49 std::swap(vCurrReloc, m_vRelocations);
50 } 50 }
51 51
52 // TODO: Return value is wrong if buffer was too small. 52 // TODO: Return value is wrong if buffer was too small.
53 int RelocationsDirectory::read(const unsigned char* buffer, unsigned int buffersize) 53 int RelocationsDirectory::read(const unsigned char* buffer, unsigned int buffersize)
54 { 54 {
55 std::vector<unsigned char> vRelocDirectory(buffer, buffer + buffersize); 55 std::vector<unsigned char> vRelocDirectory(buffer, buffer + buffersize);
56 56
57 InputBuffer ibBuffer(vRelocDirectory); 57 InputBuffer ibBuffer(vRelocDirectory);
58 read(ibBuffer, buffersize); 58 read(ibBuffer, buffersize);
59 59
60 return NO_ERROR; 60 return NO_ERROR;
61 } 61 }
62 62
63 int RelocationsDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize) 63 int RelocationsDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize)
64 { 64 {
65 std::ifstream ifFile(strFilename.c_str(), std::ios::binary); 65 std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
66 unsigned int ulFileSize = fileSize(ifFile); 66 unsigned int ulFileSize = fileSize(ifFile);
67 67
68 if (!ifFile) 68 if (!ifFile)
69 { 69 {
70 return ERROR_OPENING_FILE; 70 return ERROR_OPENING_FILE;
71 } 71 }
72 72
73 if (ulFileSize < uiOffset + uiSize) 73 if (ulFileSize < uiOffset + uiSize)
74 { 74 {
75 return ERROR_INVALID_FILE; 75 return ERROR_INVALID_FILE;
76 } 76 }
77 77
78 ifFile.seekg(uiOffset, std::ios::beg); 78 ifFile.seekg(uiOffset, std::ios::beg);
79 79
80 std::vector<unsigned char> vRelocDirectory(uiSize); 80 std::vector<unsigned char> vRelocDirectory(uiSize);
81 ifFile.read(reinterpret_cast<char*>(&vRelocDirectory[0]), uiSize); 81 ifFile.read(reinterpret_cast<char*>(&vRelocDirectory[0]), uiSize);
82 82
83 InputBuffer ibBuffer(vRelocDirectory); 83 InputBuffer ibBuffer(vRelocDirectory);
84 read(ibBuffer, uiSize); 84 read(ibBuffer, uiSize);
85 85
86 return NO_ERROR; 86 return NO_ERROR;
87 } 87 }
88 88
89 unsigned int RelocationsDirectory::size() const 89 unsigned int RelocationsDirectory::size() const
90 { 90 {
91 unsigned int size = static_cast<unsigned int>(m_vRelocations.size()) * PELIB_IMAGE_BASE_RELOCATION::size(); 91 unsigned int size = static_cast<unsigned int>(m_vRelocations.size()) * PELIB_IMAGE_BASE_RELOCATION::size();
92 92
93 for (unsigned int i=0;i<m_vRelocations.size();i++) 93 for (unsigned int i=0;i<m_vRelocations.size();i++)
94 { 94 {
95 size += static_cast<unsigned int>(m_vRelocations[i].vRelocData.size()) * sizeof(word); 95 size += static_cast<unsigned int>(m_vRelocations[i].vRelocData.size()) * sizeof(word);
96 } 96 }
97 97
98 return size; 98 return size;
99 } 99 }
100 100
101 void RelocationsDirectory::rebuild(std::vector<byte>& vBuffer) const 101 void RelocationsDirectory::rebuild(std::vector<byte>& vBuffer) const
102 { 102 {
103 OutputBuffer obBuffer(vBuffer); 103 OutputBuffer obBuffer(vBuffer);
104 104
105 for (unsigned int i=0;i<m_vRelocations.size();i++) 105 for (unsigned int i=0;i<m_vRelocations.size();i++)
106 { 106 {
107 obBuffer << m_vRelocations[i].ibrRelocation.VirtualAddress; 107 obBuffer << m_vRelocations[i].ibrRelocation.VirtualAddress;
108 obBuffer << m_vRelocations[i].ibrRelocation.SizeOfBlock; 108 obBuffer << m_vRelocations[i].ibrRelocation.SizeOfBlock;
109 109
110 for (unsigned int j=0;j<m_vRelocations[i].vRelocData.size();j++) 110 for (unsigned int j=0;j<m_vRelocations[i].vRelocData.size();j++)
111 { 111 {
112 obBuffer << m_vRelocations[i].vRelocData[j]; 112 obBuffer << m_vRelocations[i].vRelocData[j];
113 } 113 }
114 } 114 }
115 } 115 }
116 116
117 unsigned int RelocationsDirectory::calcNumberOfRelocations() const 117 unsigned int RelocationsDirectory::calcNumberOfRelocations() const
118 { 118 {
119 return static_cast<unsigned int>(m_vRelocations.size()); 119 return static_cast<unsigned int>(m_vRelocations.size());
120 } 120 }
121 121
122 dword RelocationsDirectory::getVirtualAddress(unsigned int ulRelocation) const 122 dword RelocationsDirectory::getVirtualAddress(unsigned int ulRelocation) const
123 { 123 {
124 return m_vRelocations[ulRelocation].ibrRelocation.VirtualAddress; 124 return m_vRelocations[ulRelocation].ibrRelocation.VirtualAddress;
125 } 125 }
126 126
127 dword RelocationsDirectory::getSizeOfBlock(unsigned int ulRelocation) const 127 dword RelocationsDirectory::getSizeOfBlock(unsigned int ulRelocation) const
128 { 128 {
129 return m_vRelocations[ulRelocation].ibrRelocation.SizeOfBlock; 129 return m_vRelocations[ulRelocation].ibrRelocation.SizeOfBlock;
130 } 130 }
131 131
132 unsigned int RelocationsDirectory::calcNumberOfRelocationData(unsigned int ulRelocation) const 132 unsigned int RelocationsDirectory::calcNumberOfRelocationData(unsigned int ulRelocation) const
133 { 133 {
134 return static_cast<unsigned int>(m_vRelocations[ulRelocation].vRelocData.size()); 134 return static_cast<unsigned int>(m_vRelocations[ulRelocation].vRelocData.size());
135 } 135 }
136 136
137 word RelocationsDirectory::getRelocationData(unsigned int ulRelocation, unsigned int ulDataNumber) const 137 word RelocationsDirectory::getRelocationData(unsigned int ulRelocation, unsigned int ulDataNumber) const
138 { 138 {
139 return m_vRelocations[ulRelocation].vRelocData[ulDataNumber]; 139 return m_vRelocations[ulRelocation].vRelocData[ulDataNumber];
140 } 140 }
141 141
142 void RelocationsDirectory::setVirtualAddress(unsigned int ulRelocation, dword dwValue) 142 void RelocationsDirectory::setVirtualAddress(unsigned int ulRelocation, dword dwValue)
143 { 143 {
144 m_vRelocations[ulRelocation].ibrRelocation.VirtualAddress = dwValue; 144 m_vRelocations[ulRelocation].ibrRelocation.VirtualAddress = dwValue;
145 } 145 }
146 146
147 void RelocationsDirectory::setSizeOfBlock(unsigned int ulRelocation, dword dwValue) 147 void RelocationsDirectory::setSizeOfBlock(unsigned int ulRelocation, dword dwValue)
148 { 148 {
149 m_vRelocations[ulRelocation].ibrRelocation.SizeOfBlock = dwValue; 149 m_vRelocations[ulRelocation].ibrRelocation.SizeOfBlock = dwValue;
150 } 150 }
151 151
152 void RelocationsDirectory::addRelocation() 152 void RelocationsDirectory::addRelocation()
153 { 153 {
154 IMG_BASE_RELOC newrelocation; 154 IMG_BASE_RELOC newrelocation;
155 m_vRelocations.push_back(newrelocation); 155 m_vRelocations.push_back(newrelocation);
156 } 156 }
157 157
158 void RelocationsDirectory::addRelocationData(unsigned int ulRelocation, word wValue) 158 void RelocationsDirectory::addRelocationData(unsigned int ulRelocation, word wValue)
159 { 159 {
160 m_vRelocations[ulRelocation].vRelocData.push_back(wValue); 160 m_vRelocations[ulRelocation].vRelocData.push_back(wValue);
161 } 161 }
162 162
163/* void RelocationsDirectory::removeRelocationData(unsigned int ulRelocation, word wValue) 163/* void RelocationsDirectory::removeRelocationData(unsigned int ulRelocation, word wValue)
164 { 164 {
165 // If you get an error with Borland C++ here you have two options: Upgrade your compiler 165 // If you get an error with Borland C++ here you have two options: Upgrade your compiler
166 // or use the commented line instead of the line below. 166 // or use the commented line instead of the line below.
167 m_vRelocations[ulRelocation].vRelocData.erase(std::remove(m_vRelocations[ulRelocation].vRelocData.begin(), m_vRelocations[ulRelocation].vRelocData.end(), wValue), m_vRelocations[ulRelocation].vRelocData.end()); 167 m_vRelocations[ulRelocation].vRelocData.erase(std::remove(m_vRelocations[ulRelocation].vRelocData.begin(), m_vRelocations[ulRelocation].vRelocData.end(), wValue), m_vRelocations[ulRelocation].vRelocData.end());
168 } 168 }
169*/ 169*/
170 void RelocationsDirectory::removeRelocation(unsigned int index) 170 void RelocationsDirectory::removeRelocation(unsigned int index)
171 { 171 {
172 m_vRelocations.erase(m_vRelocations.begin() + index); 172 m_vRelocations.erase(m_vRelocations.begin() + index);
173 } 173 }
174 174
175 void RelocationsDirectory::removeRelocationData(unsigned int relocindex, unsigned int dataindex) 175 void RelocationsDirectory::removeRelocationData(unsigned int relocindex, unsigned int dataindex)
176 { 176 {
177 m_vRelocations[relocindex].vRelocData.erase(m_vRelocations[relocindex].vRelocData.begin() + dataindex); 177 m_vRelocations[relocindex].vRelocData.erase(m_vRelocations[relocindex].vRelocData.begin() + dataindex);
178 } 178 }
179 179
180 int RelocationsDirectory::write(const std::string& strFilename, unsigned int uiOffset) const 180 int RelocationsDirectory::write(const std::string& strFilename, unsigned int uiOffset) const
181 { 181 {
182 std::fstream ofFile(strFilename.c_str(), std::ios_base::in); 182 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
183 183
184 if (!ofFile) 184 if (!ofFile)
185 { 185 {
186 ofFile.clear(); 186 ofFile.clear();
187 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary); 187 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
188 } 188 }
189 else 189 else
190 { 190 {
191 ofFile.close(); 191 ofFile.close();
192 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary); 192 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
193 } 193 }
194 194
195 if (!ofFile) 195 if (!ofFile)
196 { 196 {
197 return ERROR_OPENING_FILE; 197 return ERROR_OPENING_FILE;
198 } 198 }
199 199
200 ofFile.seekp(uiOffset, std::ios::beg); 200 ofFile.seekp(uiOffset, std::ios::beg);
201 201
202 std::vector<unsigned char> vBuffer; 202 std::vector<unsigned char> vBuffer;
203 rebuild(vBuffer); 203 rebuild(vBuffer);
204 204
205 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<std::streamsize>(vBuffer.size())); 205 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<std::streamsize>(vBuffer.size()));
206 206
207 ofFile.close(); 207 ofFile.close();
208 208
209 return NO_ERROR; 209 return NO_ERROR;
210 } 210 }
211} 211}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/RelocationsDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/RelocationsDirectory.h
index 60383381a3..0fc10500e0 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/RelocationsDirectory.h
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/RelocationsDirectory.h
@@ -1,70 +1,70 @@
1/* 1/*
2* Relocations.h - Part of the PeLib library. 2* Relocations.h - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#ifndef RELOCATIONSDIRECTORY_H 13#ifndef RELOCATIONSDIRECTORY_H
14#define RELOCATIONSDIRECTORY_H 14#define RELOCATIONSDIRECTORY_H
15 15
16namespace PeLib 16namespace PeLib
17{ 17{
18 /// Class that handles the relocations directory. 18 /// Class that handles the relocations directory.
19 /** 19 /**
20 * This class handles the relocations directory. 20 * This class handles the relocations directory.
21 **/ 21 **/
22 class RelocationsDirectory 22 class RelocationsDirectory
23 { 23 {
24 private: 24 private:
25 std::vector<IMG_BASE_RELOC> m_vRelocations; ///< Used to store the relocation data. 25 std::vector<IMG_BASE_RELOC> m_vRelocations; ///< Used to store the relocation data.
26 26
27 void read(InputBuffer& inputbuffer, unsigned int uiSize); 27 void read(InputBuffer& inputbuffer, unsigned int uiSize);
28 28
29 public: 29 public:
30 /// Returns the number of relocations in the relocations directory. 30 /// Returns the number of relocations in the relocations directory.
31 unsigned int calcNumberOfRelocations() const; // EXPORT 31 unsigned int calcNumberOfRelocations() const; // EXPORT
32 /// Returns the number of relocation data entries of a specific relocation. 32 /// Returns the number of relocation data entries of a specific relocation.
33 unsigned int calcNumberOfRelocationData(unsigned int ulRelocation) const; // EXPORT 33 unsigned int calcNumberOfRelocationData(unsigned int ulRelocation) const; // EXPORT
34 34
35 /// Read a file's relocations directory. 35 /// Read a file's relocations directory.
36 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize); // EXPORT 36 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize); // EXPORT
37 int read(const unsigned char* buffer, unsigned int buffersize); // EXPORT 37 int read(const unsigned char* buffer, unsigned int buffersize); // EXPORT
38 /// Rebuilds the relocations directory. 38 /// Rebuilds the relocations directory.
39 void rebuild(std::vector<byte>& vBuffer) const; // EXPORT 39 void rebuild(std::vector<byte>& vBuffer) const; // EXPORT
40 /// Returns the size of the relocations directory. 40 /// Returns the size of the relocations directory.
41 unsigned int size() const; // EXPORT 41 unsigned int size() const; // EXPORT
42 /// Writes the relocations directory to a file. 42 /// Writes the relocations directory to a file.
43 int write(const std::string& strFilename, unsigned int dwOffset) const; // EXPORT 43 int write(const std::string& strFilename, unsigned int dwOffset) const; // EXPORT
44 44
45 /// Returns the VA of a relocation. 45 /// Returns the VA of a relocation.
46 dword getVirtualAddress(unsigned int ulRelocation) const; // EXPORT 46 dword getVirtualAddress(unsigned int ulRelocation) const; // EXPORT
47 /// Returns the SizeOfBlock value of a relocation. 47 /// Returns the SizeOfBlock value of a relocation.
48 dword getSizeOfBlock(unsigned int ulRelocation) const; // EXPORT 48 dword getSizeOfBlock(unsigned int ulRelocation) const; // EXPORT
49 /// Returns the RelocationData of a relocation. 49 /// Returns the RelocationData of a relocation.
50 word getRelocationData(unsigned int ulRelocation, unsigned int ulDataNumber) const; // EXPORT 50 word getRelocationData(unsigned int ulRelocation, unsigned int ulDataNumber) const; // EXPORT
51 51
52 /// Changes the relocation data of a relocation. 52 /// Changes the relocation data of a relocation.
53 void setRelocationData(unsigned int ulRelocation, unsigned int ulDataNumber, word wData); // EXPORT 53 void setRelocationData(unsigned int ulRelocation, unsigned int ulDataNumber, word wData); // EXPORT
54 54
55 /// Changes the VirtualAddress of a relocation. 55 /// Changes the VirtualAddress of a relocation.
56 void setVirtualAddress(unsigned int ulRelocation, dword dwValue); // EXPORT 56 void setVirtualAddress(unsigned int ulRelocation, dword dwValue); // EXPORT
57 /// Changes the SizeOfBlock of a relocation. 57 /// Changes the SizeOfBlock of a relocation.
58 void setSizeOfBlock(unsigned int ulRelocation, dword dwValue); // EXPORT 58 void setSizeOfBlock(unsigned int ulRelocation, dword dwValue); // EXPORT
59 59
60 void addRelocation(); // EXPORT 60 void addRelocation(); // EXPORT
61 /// Adds new data to a relocation. 61 /// Adds new data to a relocation.
62 void addRelocationData(unsigned int ulRelocation, word wValue); // EXPORT 62 void addRelocationData(unsigned int ulRelocation, word wValue); // EXPORT
63 /// Removes data from a relocation. 63 /// Removes data from a relocation.
64// void removeRelocationData(unsigned int ulRelocation, word wValue); // EXPORT 64// void removeRelocationData(unsigned int ulRelocation, word wValue); // EXPORT
65 void removeRelocation(unsigned int index); // EXPORT 65 void removeRelocation(unsigned int index); // EXPORT
66 void removeRelocationData(unsigned int relocindex, unsigned int dataindex); // EXPORT 66 void removeRelocationData(unsigned int relocindex, unsigned int dataindex); // EXPORT
67 }; 67 };
68} 68}
69 69
70#endif 70#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/ResourceDirectory.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/ResourceDirectory.cpp
index 5e4d3010bf..d1e4c59e5a 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/ResourceDirectory.cpp
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/ResourceDirectory.cpp
@@ -1,1497 +1,1497 @@
1/* 1/*
2* ResourceDirectory.h - Part of the PeLib library. 2* ResourceDirectory.h - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#include "ResourceDirectory.h" 13#include "ResourceDirectory.h"
14 14
15namespace PeLib 15namespace PeLib
16{ 16{
17// -------------------------------------------------- ResourceChild ------------------------------------------- 17// -------------------------------------------------- ResourceChild -------------------------------------------
18 18
19 ResourceChild::ResourceChild() 19 ResourceChild::ResourceChild()
20 { 20 {
21 } 21 }
22 22
23 ResourceChild::ResourceChild(const ResourceChild& rhs) 23 ResourceChild::ResourceChild(const ResourceChild& rhs)
24 { 24 {
25 if (dynamic_cast<ResourceNode*>(rhs.child)) 25 if (dynamic_cast<ResourceNode*>(rhs.child))
26 { 26 {
27 ResourceNode* oldnode = static_cast<ResourceNode*>(rhs.child); 27 ResourceNode* oldnode = static_cast<ResourceNode*>(rhs.child);
28 28
29 entry = rhs.entry; 29 entry = rhs.entry;
30 30
31 child = new ResourceNode; 31 child = new ResourceNode;
32 child->uiElementRva = rhs.child->getElementRva(); 32 child->uiElementRva = rhs.child->getElementRva();
33 static_cast<ResourceNode*>(child)->header = oldnode->header; 33 static_cast<ResourceNode*>(child)->header = oldnode->header;
34 static_cast<ResourceNode*>(child)->children = oldnode->children; 34 static_cast<ResourceNode*>(child)->children = oldnode->children;
35 } 35 }
36 else 36 else
37 { 37 {
38 ResourceLeaf* oldnode = static_cast<ResourceLeaf*>(rhs.child); 38 ResourceLeaf* oldnode = static_cast<ResourceLeaf*>(rhs.child);
39 39
40 child = new ResourceLeaf; 40 child = new ResourceLeaf;
41 child->uiElementRva = rhs.child->getElementRva(); 41 child->uiElementRva = rhs.child->getElementRva();
42 static_cast<ResourceLeaf*>(child)->m_data = oldnode->m_data; 42 static_cast<ResourceLeaf*>(child)->m_data = oldnode->m_data;
43 static_cast<ResourceLeaf*>(child)->entry = oldnode->entry; 43 static_cast<ResourceLeaf*>(child)->entry = oldnode->entry;
44 } 44 }
45 } 45 }
46 46
47 ResourceChild& ResourceChild::operator=(const ResourceChild& rhs) 47 ResourceChild& ResourceChild::operator=(const ResourceChild& rhs)
48 { 48 {
49 if (this != &rhs) 49 if (this != &rhs)
50 { 50 {
51 if (dynamic_cast<ResourceNode*>(rhs.child)) 51 if (dynamic_cast<ResourceNode*>(rhs.child))
52 { 52 {
53 ResourceNode* oldnode = static_cast<ResourceNode*>(rhs.child); 53 ResourceNode* oldnode = static_cast<ResourceNode*>(rhs.child);
54 54
55 entry = rhs.entry; 55 entry = rhs.entry;
56 56
57 child = new ResourceNode; 57 child = new ResourceNode;
58 child->uiElementRva = rhs.child->getElementRva(); 58 child->uiElementRva = rhs.child->getElementRva();
59 static_cast<ResourceNode*>(child)->header = oldnode->header; 59 static_cast<ResourceNode*>(child)->header = oldnode->header;
60 static_cast<ResourceNode*>(child)->children = oldnode->children; 60 static_cast<ResourceNode*>(child)->children = oldnode->children;
61 } 61 }
62 else 62 else
63 { 63 {
64 ResourceLeaf* oldnode = static_cast<ResourceLeaf*>(rhs.child); 64 ResourceLeaf* oldnode = static_cast<ResourceLeaf*>(rhs.child);
65 65
66 child = new ResourceLeaf; 66 child = new ResourceLeaf;
67 child->uiElementRva = rhs.child->getElementRva(); 67 child->uiElementRva = rhs.child->getElementRva();
68 static_cast<ResourceLeaf*>(child)->m_data = oldnode->m_data; 68 static_cast<ResourceLeaf*>(child)->m_data = oldnode->m_data;
69 static_cast<ResourceLeaf*>(child)->entry = oldnode->entry; 69 static_cast<ResourceLeaf*>(child)->entry = oldnode->entry;
70 } 70 }
71 } 71 }
72 72
73 return *this; 73 return *this;
74 } 74 }
75 75
76 ResourceChild::~ResourceChild() 76 ResourceChild::~ResourceChild()
77 { 77 {
78 delete child; 78 delete child;
79 } 79 }
80 80
81 /** 81 /**
82 * Compares the resource child's id to the parameter dwId. 82 * Compares the resource child's id to the parameter dwId.
83 * @param dwId ID of a resource. 83 * @param dwId ID of a resource.
84 * @return True, if the resource child's id equals the parameter. 84 * @return True, if the resource child's id equals the parameter.
85 **/ 85 **/
86 bool ResourceChild::equalId(dword dwId) const 86 bool ResourceChild::equalId(dword dwId) const
87 { 87 {
88 return entry.irde.Name == dwId; 88 return entry.irde.Name == dwId;
89 } 89 }
90 90
91 /** 91 /**
92 * Compares the resource child's name to the parameter strName. 92 * Compares the resource child's name to the parameter strName.
93 * @param strName ID of a resource. 93 * @param strName ID of a resource.
94 * @return True, if the resource child's name equals the parameter. 94 * @return True, if the resource child's name equals the parameter.
95 **/ 95 **/
96 bool ResourceChild::equalName(std::string strName) const 96 bool ResourceChild::equalName(std::string strName) const
97 { 97 {
98 return entry.wstrName == strName; 98 return entry.wstrName == strName;
99 } 99 }
100 100
101 /** 101 /**
102 * Returns true if the resource was given a name. 102 * Returns true if the resource was given a name.
103 **/ 103 **/
104 bool ResourceChild::isNamedResource() const 104 bool ResourceChild::isNamedResource() const
105 { 105 {
106 return entry.wstrName.size() != 0; 106 return entry.wstrName.size() != 0;
107 } 107 }
108 108
109 /** 109 /**
110 * The children of a resource must be ordered in a certain way. First come the named resources 110 * The children of a resource must be ordered in a certain way. First come the named resources
111 * in sorted order, afterwards followed the unnamed resources in sorted order. 111 * in sorted order, afterwards followed the unnamed resources in sorted order.
112 **/ 112 **/
113 bool ResourceChild::operator<(const ResourceChild& rc) const 113 bool ResourceChild::operator<(const ResourceChild& rc) const
114 { 114 {
115 if (this->isNamedResource() && !rc.isNamedResource()) 115 if (this->isNamedResource() && !rc.isNamedResource())
116 { 116 {
117 return true; 117 return true;
118 } 118 }
119 else if (!this->isNamedResource() && rc.isNamedResource()) 119 else if (!this->isNamedResource() && rc.isNamedResource())
120 { 120 {
121 return false; 121 return false;
122 } 122 }
123 else if (this->isNamedResource() && rc.isNamedResource()) 123 else if (this->isNamedResource() && rc.isNamedResource())
124 { 124 {
125 return this->entry.wstrName < rc.entry.wstrName; 125 return this->entry.wstrName < rc.entry.wstrName;
126 } 126 }
127 else 127 else
128 { 128 {
129 return this->entry.irde.Name < rc.entry.irde.Name; 129 return this->entry.irde.Name < rc.entry.irde.Name;
130 } 130 }
131 } 131 }
132 132
133/* unsigned int ResourceChild::size() const 133/* unsigned int ResourceChild::size() const
134 { 134 {
135 return PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY::size() 135 return PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY::size()
136 + child->size() 136 + child->size()
137 + (entry.wstrName.size() ? entry.wstrName.size() + 2 : 0); 137 + (entry.wstrName.size() ? entry.wstrName.size() + 2 : 0);
138 } 138 }
139*/ 139*/
140// -------------------------------------------------- ResourceElement ------------------------------------------- 140// -------------------------------------------------- ResourceElement -------------------------------------------
141 141
142 /** 142 /**
143 * Returns the RVA of a ResourceElement. This is the RVA where the ResourceElement can be 143 * Returns the RVA of a ResourceElement. This is the RVA where the ResourceElement can be
144 * found in the file. 144 * found in the file.
145 * @return RVA of the ResourceElement. 145 * @return RVA of the ResourceElement.
146 **/ 146 **/
147 unsigned int ResourceElement::getElementRva() const 147 unsigned int ResourceElement::getElementRva() const
148 { 148 {
149 return uiElementRva; 149 return uiElementRva;
150 } 150 }
151 151
152// -------------------------------------------------- ResourceLeaf ------------------------------------------- 152// -------------------------------------------------- ResourceLeaf -------------------------------------------
153 153
154 /** 154 /**
155 * Checks if a ResourceElement is a leaf or not. 155 * Checks if a ResourceElement is a leaf or not.
156 * @return Always returns true. 156 * @return Always returns true.
157 **/ 157 **/
158 bool ResourceLeaf::isLeaf() const 158 bool ResourceLeaf::isLeaf() const
159 { 159 {
160 return true; 160 return true;
161 } 161 }
162 162
163 /** 163 /**
164 * Reads the next resource leaf from the InputBuffer. 164 * Reads the next resource leaf from the InputBuffer.
165 * @param inpBuffer An InputBuffer that holds the complete resource directory. 165 * @param inpBuffer An InputBuffer that holds the complete resource directory.
166 * @param uiOffset Offset of the resource leaf that's to be read. 166 * @param uiOffset Offset of the resource leaf that's to be read.
167 * @param uiRva RVA of the beginning of the resource directory. 167 * @param uiRva RVA of the beginning of the resource directory.
168 * @param pad Used for debugging purposes. 168 * @param pad Used for debugging purposes.
169 **/ 169 **/
170 int ResourceLeaf::read(InputBuffer& inpBuffer, unsigned int uiOffset, unsigned int uiRva/*, const std::string& pad*/) 170 int ResourceLeaf::read(InputBuffer& inpBuffer, unsigned int uiOffset, unsigned int uiRva/*, const std::string& pad*/)
171 { 171 {
172// std::cout << pad << "Leaf:" << std::endl; 172// std::cout << pad << "Leaf:" << std::endl;
173 173
174 // Invalid leaf. 174 // Invalid leaf.
175 if (uiOffset + PELIB_IMAGE_RESOURCE_DATA_ENTRY::size() > inpBuffer.size()) 175 if (uiOffset + PELIB_IMAGE_RESOURCE_DATA_ENTRY::size() > inpBuffer.size())
176 { 176 {
177 return 1; 177 return 1;
178 } 178 }
179 179
180 uiElementRva = uiOffset + uiRva; 180 uiElementRva = uiOffset + uiRva;
181 181
182 inpBuffer.set(uiOffset); 182 inpBuffer.set(uiOffset);
183 183
184 inpBuffer >> entry.OffsetToData; 184 inpBuffer >> entry.OffsetToData;
185 inpBuffer >> entry.Size; 185 inpBuffer >> entry.Size;
186 inpBuffer >> entry.CodePage; 186 inpBuffer >> entry.CodePage;
187 inpBuffer >> entry.Reserved; 187 inpBuffer >> entry.Reserved;
188 188
189/* std::cout << pad << std::hex << "Offset: " << entry.OffsetToData << std::endl; 189/* std::cout << pad << std::hex << "Offset: " << entry.OffsetToData << std::endl;
190 std::cout << pad << std::hex << "Size: " << entry.Size << std::endl; 190 std::cout << pad << std::hex << "Size: " << entry.Size << std::endl;
191 std::cout << pad << std::hex << "CodePage: " << entry.CodePage << std::endl; 191 std::cout << pad << std::hex << "CodePage: " << entry.CodePage << std::endl;
192 std::cout << pad << std::hex << "Reserved: " << entry.Reserved << std::endl; 192 std::cout << pad << std::hex << "Reserved: " << entry.Reserved << std::endl;
193*/ 193*/
194 // Invalid leaf. 194 // Invalid leaf.
195 if (entry.OffsetToData - uiRva + entry.Size > inpBuffer.size()) 195 if (entry.OffsetToData - uiRva + entry.Size > inpBuffer.size())
196 { 196 {
197// std::cout << entry.OffsetToData << " XXX " << uiRva << " - " << entry.Size << " - " << inpBuffer.size() << std::endl; 197// std::cout << entry.OffsetToData << " XXX " << uiRva << " - " << entry.Size << " - " << inpBuffer.size() << std::endl;
198 return 1; 198 return 1;
199 } 199 }
200 200
201// std::cout << entry.OffsetToData << " - " << uiRva << " - " << entry.Size << " - " << inpBuffer.size() << std::endl; 201// std::cout << entry.OffsetToData << " - " << uiRva << " - " << entry.Size << " - " << inpBuffer.size() << std::endl;
202 inpBuffer.set(entry.OffsetToData - uiRva); 202 inpBuffer.set(entry.OffsetToData - uiRva);
203 m_data.assign(inpBuffer.data() + inpBuffer.get(), inpBuffer.data() + inpBuffer.get() + entry.Size); 203 m_data.assign(inpBuffer.data() + inpBuffer.get(), inpBuffer.data() + inpBuffer.get() + entry.Size);
204// std::cout << pad << std::hex << "Vector: " << m_data.size() << std::endl; 204// std::cout << pad << std::hex << "Vector: " << m_data.size() << std::endl;
205// std::copy(m_data.begin(), m_data.end(), std::ostream_iterator<int>(std::cout << std::hex, " ")); 205// std::copy(m_data.begin(), m_data.end(), std::ostream_iterator<int>(std::cout << std::hex, " "));
206 return 0; 206 return 0;
207 } 207 }
208 208
209 /** 209 /**
210 * Rebuilds the current resource leaf. 210 * Rebuilds the current resource leaf.
211 * @param obBuffer OutputBuffer where the rebuilt resource leaf is stored. 211 * @param obBuffer OutputBuffer where the rebuilt resource leaf is stored.
212 * @param uiOffset Offset of the resource leaf inside the resource directory. 212 * @param uiOffset Offset of the resource leaf inside the resource directory.
213 * @param uiRva RVA of the resource directory. 213 * @param uiRva RVA of the resource directory.
214 **/ 214 **/
215 void ResourceLeaf::rebuild(OutputBuffer& obBuffer, unsigned int& uiOffset, unsigned int uiRva, const std::string&) const 215 void ResourceLeaf::rebuild(OutputBuffer& obBuffer, unsigned int& uiOffset, unsigned int uiRva, const std::string&) const
216 { 216 {
217// std::cout << std::hex << pad << "Leaf: " << uiOffset << std::endl; 217// std::cout << std::hex << pad << "Leaf: " << uiOffset << std::endl;
218 uiOffset += PELIB_IMAGE_RESOURCE_DATA_ENTRY::size(); 218 uiOffset += PELIB_IMAGE_RESOURCE_DATA_ENTRY::size();
219 219
220// obBuffer << entry.OffsetToData; 220// obBuffer << entry.OffsetToData;
221// obBuffer << uiOffset; 221// obBuffer << uiOffset;
222 obBuffer << uiRva + uiOffset + (uiOffset % 4); 222 obBuffer << uiRva + uiOffset + (uiOffset % 4);
223 obBuffer << entry.Size; 223 obBuffer << entry.Size;
224 obBuffer << entry.CodePage; 224 obBuffer << entry.CodePage;
225 obBuffer << entry.Reserved; 225 obBuffer << entry.Reserved;
226 226
227 while (uiOffset % 4) 227 while (uiOffset % 4)
228 { 228 {
229 uiOffset++; 229 uiOffset++;
230 obBuffer << (byte)0; 230 obBuffer << (byte)0;
231 } 231 }
232 232
233 uiOffset += static_cast<unsigned int>(m_data.size()); 233 uiOffset += static_cast<unsigned int>(m_data.size());
234 234
235 for (unsigned int i=0;i<m_data.size();i++) 235 for (unsigned int i=0;i<m_data.size();i++)
236 { 236 {
237 obBuffer << m_data[i]; 237 obBuffer << m_data[i];
238 } 238 }
239// std::cout << "LeafChild: " << std::endl; 239// std::cout << "LeafChild: " << std::endl;
240 } 240 }
241 241
242 void ResourceLeaf::makeValid() 242 void ResourceLeaf::makeValid()
243 { 243 {
244 entry.Size = static_cast<unsigned int>(m_data.size()); 244 entry.Size = static_cast<unsigned int>(m_data.size());
245 } 245 }
246 246
247/* /// Returns the size of a resource leaf. 247/* /// Returns the size of a resource leaf.
248 unsigned int ResourceLeaf::size() const 248 unsigned int ResourceLeaf::size() const
249 { 249 {
250 return PELIB_IMAGE_RESOURCE_DATA_ENTRY::size() + m_data.size(); 250 return PELIB_IMAGE_RESOURCE_DATA_ENTRY::size() + m_data.size();
251 } 251 }
252*/ 252*/
253 253
254 /** 254 /**
255 * Returns a vector that contains the raw data of a resource leaf. 255 * Returns a vector that contains the raw data of a resource leaf.
256 * @return Raw data of the resource. 256 * @return Raw data of the resource.
257 **/ 257 **/
258 std::vector<byte> ResourceLeaf::getData() const 258 std::vector<byte> ResourceLeaf::getData() const
259 { 259 {
260 return m_data; 260 return m_data;
261 } 261 }
262 262
263 /** 263 /**
264 * Overwrites the raw data of a resource. 264 * Overwrites the raw data of a resource.
265 * @param vData New data of the resource. 265 * @param vData New data of the resource.
266 **/ 266 **/
267 void ResourceLeaf::setData(const std::vector<byte>& vData) 267 void ResourceLeaf::setData(const std::vector<byte>& vData)
268 { 268 {
269 m_data = vData; 269 m_data = vData;
270 } 270 }
271 271
272 /** 272 /**
273 * Returns the leaf's OffsetToData value. That's the RVA where the raw data of the resource 273 * Returns the leaf's OffsetToData value. That's the RVA where the raw data of the resource
274 * can be found. 274 * can be found.
275 * @return The leaf's OffsetToData value. 275 * @return The leaf's OffsetToData value.
276 **/ 276 **/
277 dword ResourceLeaf::getOffsetToData() const 277 dword ResourceLeaf::getOffsetToData() const
278 { 278 {
279 return entry.OffsetToData; 279 return entry.OffsetToData;
280 } 280 }
281 281
282 /** 282 /**
283 * Returns the leaf's Size value. That's the size of the raw data of the resource. 283 * Returns the leaf's Size value. That's the size of the raw data of the resource.
284 * @return The leaf's Size value. 284 * @return The leaf's Size value.
285 **/ 285 **/
286 dword ResourceLeaf::getSize() const 286 dword ResourceLeaf::getSize() const
287 { 287 {
288 return entry.Size; 288 return entry.Size;
289 } 289 }
290 290
291 /** 291 /**
292 * Returns the leaf's CodePage value. 292 * Returns the leaf's CodePage value.
293 * @return The leaf's CodePage value. 293 * @return The leaf's CodePage value.
294 **/ 294 **/
295 dword ResourceLeaf::getCodePage() const 295 dword ResourceLeaf::getCodePage() const
296 { 296 {
297 return entry.CodePage; 297 return entry.CodePage;
298 } 298 }
299 299
300 /** 300 /**
301 * Returns the leaf's Reserved value. 301 * Returns the leaf's Reserved value.
302 * @return The leaf's Reserved value. 302 * @return The leaf's Reserved value.
303 **/ 303 **/
304 dword ResourceLeaf::getReserved() const 304 dword ResourceLeaf::getReserved() const
305 { 305 {
306 return entry.Reserved; 306 return entry.Reserved;
307 } 307 }
308 308
309 /** 309 /**
310 * Sets the leaf's OffsetToData value. 310 * Sets the leaf's OffsetToData value.
311 * @param dwValue The leaf's new OffsetToData value. 311 * @param dwValue The leaf's new OffsetToData value.
312 **/ 312 **/
313 void ResourceLeaf::setOffsetToData(dword dwValue) 313 void ResourceLeaf::setOffsetToData(dword dwValue)
314 { 314 {
315 entry.OffsetToData = dwValue; 315 entry.OffsetToData = dwValue;
316 } 316 }
317 317
318 /** 318 /**
319 * Sets the leaf's Size value. 319 * Sets the leaf's Size value.
320 * @param dwValue The leaf's new Size value. 320 * @param dwValue The leaf's new Size value.
321 **/ 321 **/
322 void ResourceLeaf::setSize(dword dwValue) 322 void ResourceLeaf::setSize(dword dwValue)
323 { 323 {
324 entry.Size = dwValue; 324 entry.Size = dwValue;
325 } 325 }
326 326
327 /** 327 /**
328 * Sets the leaf's CodePage value. 328 * Sets the leaf's CodePage value.
329 * @param dwValue The leaf's new CodePage value. 329 * @param dwValue The leaf's new CodePage value.
330 **/ 330 **/
331 void ResourceLeaf::setCodePage(dword dwValue) 331 void ResourceLeaf::setCodePage(dword dwValue)
332 { 332 {
333 entry.CodePage = dwValue; 333 entry.CodePage = dwValue;
334 } 334 }
335 335
336 /** 336 /**
337 * Sets the leaf's Reserved value. 337 * Sets the leaf's Reserved value.
338 * @param dwValue The leaf's new Reserved value. 338 * @param dwValue The leaf's new Reserved value.
339 **/ 339 **/
340 void ResourceLeaf::setReserved(dword dwValue) 340 void ResourceLeaf::setReserved(dword dwValue)
341 { 341 {
342 entry.Reserved = dwValue; 342 entry.Reserved = dwValue;
343 } 343 }
344 344
345 345
346// -------------------------------------------------- ResourceNode ------------------------------------------- 346// -------------------------------------------------- ResourceNode -------------------------------------------
347 347
348 /** 348 /**
349 * Checks if a ResourceElement is a leaf or not. 349 * Checks if a ResourceElement is a leaf or not.
350 * @return Always returns false. 350 * @return Always returns false.
351 **/ 351 **/
352 bool ResourceNode::isLeaf() const 352 bool ResourceNode::isLeaf() const
353 { 353 {
354 return false; 354 return false;
355 } 355 }
356 356
357 /** 357 /**
358 * Sorts the node's children and corrects the node's header. 358 * Sorts the node's children and corrects the node's header.
359 **/ 359 **/
360 void ResourceNode::makeValid() 360 void ResourceNode::makeValid()
361 { 361 {
362 std::sort(children.begin(), children.end()); 362 std::sort(children.begin(), children.end());
363 header.NumberOfNamedEntries = static_cast<PeLib::word>(std::count_if(children.begin(), children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource))); 363 header.NumberOfNamedEntries = static_cast<PeLib::word>(std::count_if(children.begin(), children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource)));
364 header.NumberOfIdEntries = static_cast<unsigned int>(children.size()) - header.NumberOfNamedEntries; 364 header.NumberOfIdEntries = static_cast<unsigned int>(children.size()) - header.NumberOfNamedEntries;
365 } 365 }
366 366
367 /** 367 /**
368 * Rebuilds the current resource node. 368 * Rebuilds the current resource node.
369 * @param obBuffer OutputBuffer where the rebuilt resource node is stored. 369 * @param obBuffer OutputBuffer where the rebuilt resource node is stored.
370 * @param uiOffset Offset of the resource node inside the resource directory. 370 * @param uiOffset Offset of the resource node inside the resource directory.
371 * @param uiRva RVA of the resource directory. 371 * @param uiRva RVA of the resource directory.
372 * @param pad Used for debugging. 372 * @param pad Used for debugging.
373 **/ 373 **/
374 void ResourceNode::rebuild(OutputBuffer& obBuffer, unsigned int& uiOffset, unsigned int uiRva, const std::string& pad) const 374 void ResourceNode::rebuild(OutputBuffer& obBuffer, unsigned int& uiOffset, unsigned int uiRva, const std::string& pad) const
375 { 375 {
376/* std::cout << std::hex << pad << uiOffset << std::endl; 376/* std::cout << std::hex << pad << uiOffset << std::endl;
377 377
378 std::cout << std::hex << pad << "header.Characteristics: " << header.Characteristics << std::endl; 378 std::cout << std::hex << pad << "header.Characteristics: " << header.Characteristics << std::endl;
379 std::cout << std::hex << pad << "header.TimeDateStamp: " << header.TimeDateStamp << std::endl; 379 std::cout << std::hex << pad << "header.TimeDateStamp: " << header.TimeDateStamp << std::endl;
380 std::cout << std::hex << pad << "header.MajorVersion: " << header.MajorVersion << std::endl; 380 std::cout << std::hex << pad << "header.MajorVersion: " << header.MajorVersion << std::endl;
381 std::cout << std::hex << pad << "header.MinorVersion: " << header.MinorVersion << std::endl; 381 std::cout << std::hex << pad << "header.MinorVersion: " << header.MinorVersion << std::endl;
382 std::cout << std::hex << pad << "header.NumberOfNamedEntries: " << header.NumberOfNamedEntries << std::endl; 382 std::cout << std::hex << pad << "header.NumberOfNamedEntries: " << header.NumberOfNamedEntries << std::endl;
383 std::cout << std::hex << pad << "header.NumberOfIdEntries: " << header.NumberOfIdEntries << std::endl; 383 std::cout << std::hex << pad << "header.NumberOfIdEntries: " << header.NumberOfIdEntries << std::endl;
384*/ 384*/
385 obBuffer << header.Characteristics; 385 obBuffer << header.Characteristics;
386 obBuffer << header.TimeDateStamp; 386 obBuffer << header.TimeDateStamp;
387 obBuffer << header.MajorVersion; 387 obBuffer << header.MajorVersion;
388 obBuffer << header.MinorVersion; 388 obBuffer << header.MinorVersion;
389 //std::cout << pad << "Children: " << children.size() << std::endl; 389 //std::cout << pad << "Children: " << children.size() << std::endl;
390 //std::cout << pad << std::count_if(children.begin(), children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource)) << std::endl; 390 //std::cout << pad << std::count_if(children.begin(), children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource)) << std::endl;
391 //std::cout << pad << children.size() - std::count_if(children.begin(), children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource)) << std::endl; 391 //std::cout << pad << children.size() - std::count_if(children.begin(), children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource)) << std::endl;
392// obBuffer << std::count_if(children.begin(), children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource)); 392// obBuffer << std::count_if(children.begin(), children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource));
393// obBuffer << children.size() - std::count_if(children.begin(), children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource)); 393// obBuffer << children.size() - std::count_if(children.begin(), children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource));
394 obBuffer << header.NumberOfNamedEntries; 394 obBuffer << header.NumberOfNamedEntries;
395 obBuffer << header.NumberOfIdEntries; 395 obBuffer << header.NumberOfIdEntries;
396 396
397 uiOffset += PELIB_IMAGE_RESOURCE_DIRECTORY::size(); 397 uiOffset += PELIB_IMAGE_RESOURCE_DIRECTORY::size();
398 398
399 for (unsigned int i=0;i<children.size();i++) 399 for (unsigned int i=0;i<children.size();i++)
400 { 400 {
401 obBuffer << (dword)0; 401 obBuffer << (dword)0;
402 obBuffer << (dword)0; 402 obBuffer << (dword)0;
403 } 403 }
404 404
405 unsigned int newoffs = (uiOffset + children.size() * 8); 405 unsigned int newoffs = (uiOffset + children.size() * 8);
406 406
407 for (unsigned int i=0;i<children.size();i++) 407 for (unsigned int i=0;i<children.size();i++)
408 { 408 {
409 if (!children[i].entry.wstrName.size()) 409 if (!children[i].entry.wstrName.size())
410 { 410 {
411 obBuffer.update(uiOffset, children[i].entry.irde.Name); 411 obBuffer.update(uiOffset, children[i].entry.irde.Name);
412 } 412 }
413 else 413 else
414 { 414 {
415 obBuffer.update(uiOffset, newoffs | PELIB_IMAGE_RESOURCE_NAME_IS_STRING); 415 obBuffer.update(uiOffset, newoffs | PELIB_IMAGE_RESOURCE_NAME_IS_STRING);
416 obBuffer << (word)children[i].entry.wstrName.size(); 416 obBuffer << (word)children[i].entry.wstrName.size();
417 newoffs += 2; 417 newoffs += 2;
418 for (unsigned int j=0;j<children[i].entry.wstrName.size();j++) 418 for (unsigned int j=0;j<children[i].entry.wstrName.size();j++)
419 { 419 {
420// std::cout << children[i].entry.wstrName[j]; 420// std::cout << children[i].entry.wstrName[j];
421 obBuffer << (word)children[i].entry.wstrName[j]; 421 obBuffer << (word)children[i].entry.wstrName[j];
422 newoffs += 2; 422 newoffs += 2;
423 } 423 }
424 } 424 }
425 uiOffset += 4; 425 uiOffset += 4;
426// obBuffer << children[i].entry.OffsetToData; 426// obBuffer << children[i].entry.OffsetToData;
427 obBuffer.update(uiOffset, newoffs | (children[i].entry.irde.OffsetToData & PELIB_IMAGE_RESOURCE_DATA_IS_DIRECTORY)); 427 obBuffer.update(uiOffset, newoffs | (children[i].entry.irde.OffsetToData & PELIB_IMAGE_RESOURCE_DATA_IS_DIRECTORY));
428 uiOffset += 4; 428 uiOffset += 4;
429 children[i].child->rebuild(obBuffer, newoffs, uiRva, pad + " "); 429 children[i].child->rebuild(obBuffer, newoffs, uiRva, pad + " ");
430 } 430 }
431 uiOffset = newoffs; 431 uiOffset = newoffs;
432 } 432 }
433 433
434 /** 434 /**
435 * Reads the next resource node from the InputBuffer. 435 * Reads the next resource node from the InputBuffer.
436 * @param inpBuffer An InputBuffer that holds the complete resource directory. 436 * @param inpBuffer An InputBuffer that holds the complete resource directory.
437 * @param uiOffset Offset of the resource node that's to be read. 437 * @param uiOffset Offset of the resource node that's to be read.
438 * @param uiRva RVA of the beginning of the resource directory. 438 * @param uiRva RVA of the beginning of the resource directory.
439 * @param pad Something I need for debugging. Will be removed soon. 439 * @param pad Something I need for debugging. Will be removed soon.
440 **/ 440 **/
441 int ResourceNode::read(InputBuffer& inpBuffer, unsigned int uiOffset, unsigned int uiRva/*, const std::string& pad*/) 441 int ResourceNode::read(InputBuffer& inpBuffer, unsigned int uiOffset, unsigned int uiRva/*, const std::string& pad*/)
442 { 442 {
443 // Not enough space to be a valid node. 443 // Not enough space to be a valid node.
444 if (uiOffset + PELIB_IMAGE_RESOURCE_DIRECTORY::size() > inpBuffer.size()) 444 if (uiOffset + PELIB_IMAGE_RESOURCE_DIRECTORY::size() > inpBuffer.size())
445 { 445 {
446 return 1; 446 return 1;
447 } 447 }
448 448
449 uiElementRva = uiOffset + uiRva; 449 uiElementRva = uiOffset + uiRva;
450 450
451 inpBuffer.set(uiOffset); 451 inpBuffer.set(uiOffset);
452 452
453 inpBuffer >> header.Characteristics; 453 inpBuffer >> header.Characteristics;
454 inpBuffer >> header.TimeDateStamp; 454 inpBuffer >> header.TimeDateStamp;
455 inpBuffer >> header.MajorVersion; 455 inpBuffer >> header.MajorVersion;
456 inpBuffer >> header.MinorVersion; 456 inpBuffer >> header.MinorVersion;
457 inpBuffer >> header.NumberOfNamedEntries; 457 inpBuffer >> header.NumberOfNamedEntries;
458 inpBuffer >> header.NumberOfIdEntries; 458 inpBuffer >> header.NumberOfIdEntries;
459 459
460 // Not enough space to be a valid node. 460 // Not enough space to be a valid node.
461 if (uiOffset + PELIB_IMAGE_RESOURCE_DIRECTORY::size() 461 if (uiOffset + PELIB_IMAGE_RESOURCE_DIRECTORY::size()
462 + (header.NumberOfNamedEntries + header.NumberOfIdEntries) * PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY::size() 462 + (header.NumberOfNamedEntries + header.NumberOfIdEntries) * PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY::size()
463 > inpBuffer.size()) 463 > inpBuffer.size())
464 { 464 {
465 return 1; 465 return 1;
466 } 466 }
467 467
468// std::cout << std::hex << pad << "Characteristics: " << header.Characteristics << std::endl; 468// std::cout << std::hex << pad << "Characteristics: " << header.Characteristics << std::endl;
469// std::cout << std::hex << pad << "TimeDateStamp: " << header.TimeDateStamp << std::endl; 469// std::cout << std::hex << pad << "TimeDateStamp: " << header.TimeDateStamp << std::endl;
470// std::cout << std::hex << pad << "MajorVersion: " << header.MajorVersion << std::endl; 470// std::cout << std::hex << pad << "MajorVersion: " << header.MajorVersion << std::endl;
471// std::cout << std::hex << pad << "MinorVersion: " << header.MinorVersion << std::endl; 471// std::cout << std::hex << pad << "MinorVersion: " << header.MinorVersion << std::endl;
472// std::cout << std::hex << pad << "NumberOfNamedEntries: " << header.NumberOfNamedEntries << std::endl; 472// std::cout << std::hex << pad << "NumberOfNamedEntries: " << header.NumberOfNamedEntries << std::endl;
473// std::cout << std::hex << pad << "NumberOfIdEntries: " << header.NumberOfIdEntries << std::endl; 473// std::cout << std::hex << pad << "NumberOfIdEntries: " << header.NumberOfIdEntries << std::endl;
474 474
475 for (int i=0;i<header.NumberOfNamedEntries + header.NumberOfIdEntries;i++) 475 for (int i=0;i<header.NumberOfNamedEntries + header.NumberOfIdEntries;i++)
476 { 476 {
477 ResourceChild rc; 477 ResourceChild rc;
478 inpBuffer >> rc.entry.irde.Name; 478 inpBuffer >> rc.entry.irde.Name;
479 inpBuffer >> rc.entry.irde.OffsetToData; 479 inpBuffer >> rc.entry.irde.OffsetToData;
480 480
481 unsigned int lastPos = inpBuffer.get(); 481 unsigned int lastPos = inpBuffer.get();
482 482
483 if (rc.entry.irde.Name & PELIB_IMAGE_RESOURCE_NAME_IS_STRING) 483 if (rc.entry.irde.Name & PELIB_IMAGE_RESOURCE_NAME_IS_STRING)
484 { 484 {
485 // Enough space to read string length? 485 // Enough space to read string length?
486 if ((rc.entry.irde.Name & ~PELIB_IMAGE_RESOURCE_NAME_IS_STRING) + 2 < inpBuffer.size()) 486 if ((rc.entry.irde.Name & ~PELIB_IMAGE_RESOURCE_NAME_IS_STRING) + 2 < inpBuffer.size())
487 { 487 {
488 inpBuffer.set(rc.entry.irde.Name & ~PELIB_IMAGE_RESOURCE_NAME_IS_STRING); 488 inpBuffer.set(rc.entry.irde.Name & ~PELIB_IMAGE_RESOURCE_NAME_IS_STRING);
489 word strlen; 489 word strlen;
490 inpBuffer >> strlen; 490 inpBuffer >> strlen;
491 491
492 // Enough space to read string? 492 // Enough space to read string?
493 if ((rc.entry.irde.Name & ~PELIB_IMAGE_RESOURCE_NAME_IS_STRING) + 2 * strlen < inpBuffer.size()) 493 if ((rc.entry.irde.Name & ~PELIB_IMAGE_RESOURCE_NAME_IS_STRING) + 2 * strlen < inpBuffer.size())
494 { 494 {
495 wchar_t c; 495 wchar_t c;
496 for (word i=0;i<strlen;i++) 496 for (word i=0;i<strlen;i++)
497 { 497 {
498 inpBuffer >> c; 498 inpBuffer >> c;
499 rc.entry.wstrName += c; 499 rc.entry.wstrName += c;
500 } 500 }
501 } 501 }
502 } 502 }
503 503
504// std::wcout << rc.entry.wstrName << std::endl; 504// std::wcout << rc.entry.wstrName << std::endl;
505 505
506// std::cout << strlen << std::endl; 506// std::cout << strlen << std::endl;
507 inpBuffer.set(lastPos); 507 inpBuffer.set(lastPos);
508 } 508 }
509 509
510 if (rc.entry.irde.OffsetToData & PELIB_IMAGE_RESOURCE_DATA_IS_DIRECTORY) 510 if (rc.entry.irde.OffsetToData & PELIB_IMAGE_RESOURCE_DATA_IS_DIRECTORY)
511 { 511 {
512 rc.child = new ResourceNode; 512 rc.child = new ResourceNode;
513 rc.child->read(inpBuffer, rc.entry.irde.OffsetToData & ~PELIB_IMAGE_RESOURCE_DATA_IS_DIRECTORY, uiRva/*, pad + " "*/); 513 rc.child->read(inpBuffer, rc.entry.irde.OffsetToData & ~PELIB_IMAGE_RESOURCE_DATA_IS_DIRECTORY, uiRva/*, pad + " "*/);
514 } 514 }
515 else 515 else
516 { 516 {
517 rc.child = new ResourceLeaf; 517 rc.child = new ResourceLeaf;
518 rc.child->read(inpBuffer, rc.entry.irde.OffsetToData, uiRva/*, pad + " "*/); 518 rc.child->read(inpBuffer, rc.entry.irde.OffsetToData, uiRva/*, pad + " "*/);
519 } 519 }
520// std::cout << std::hex << pad << "Entry " << i << "(Name): " << rc.entry.irde.Name << std::endl; 520// std::cout << std::hex << pad << "Entry " << i << "(Name): " << rc.entry.irde.Name << std::endl;
521// std::cout << std::hex << pad << "Entry " << i << "(Offset): " << rc.entry.irde.OffsetToData << std::endl; 521// std::cout << std::hex << pad << "Entry " << i << "(Offset): " << rc.entry.irde.OffsetToData << std::endl;
522 522
523 children.push_back(rc); 523 children.push_back(rc);
524 inpBuffer.set(lastPos); 524 inpBuffer.set(lastPos);
525 } 525 }
526 526
527 return 0; 527 return 0;
528 } 528 }
529 529
530 /** 530 /**
531 * Returns the number of children of the current node. Note that this number is the number 531 * Returns the number of children of the current node. Note that this number is the number
532 * of defined children, not the value from the header. 532 * of defined children, not the value from the header.
533 * @return Number of node's children. 533 * @return Number of node's children.
534 **/ 534 **/
535 unsigned int ResourceNode::getNumberOfChildren() const 535 unsigned int ResourceNode::getNumberOfChildren() const
536 { 536 {
537 return static_cast<unsigned int>(children.size()); 537 return static_cast<unsigned int>(children.size());
538 } 538 }
539 539
540 /** 540 /**
541 * Adds another child to the current node. 541 * Adds another child to the current node.
542 **/ 542 **/
543 void ResourceNode::addChild() 543 void ResourceNode::addChild()
544 { 544 {
545 ResourceChild c; 545 ResourceChild c;
546 c.child = 0; 546 c.child = 0;
547 children.push_back(c); 547 children.push_back(c);
548 } 548 }
549 549
550 /** 550 /**
551 * Returns a node's child. 551 * Returns a node's child.
552 * @param uiIndex Index of the child. 552 * @param uiIndex Index of the child.
553 * @return The child identified by uiIndex. This child can be either a ResourceNode or a ResourceLeaf. 553 * @return The child identified by uiIndex. This child can be either a ResourceNode or a ResourceLeaf.
554 **/ 554 **/
555 ResourceElement* ResourceNode::getChild(unsigned int uiIndex) 555 ResourceElement* ResourceNode::getChild(unsigned int uiIndex)
556 { 556 {
557 return children[uiIndex].child; 557 return children[uiIndex].child;
558 } 558 }
559 559
560 /** 560 /**
561 * Removes a child from the current node. 561 * Removes a child from the current node.
562 * @param uiIndex Index of the child. 562 * @param uiIndex Index of the child.
563 **/ 563 **/
564 void ResourceNode::removeChild(unsigned int uiIndex) 564 void ResourceNode::removeChild(unsigned int uiIndex)
565 { 565 {
566 children.erase(children.begin() + uiIndex); 566 children.erase(children.begin() + uiIndex);
567 } 567 }
568 568
569 /** 569 /**
570 * Returns the name of a child. 570 * Returns the name of a child.
571 * @param uiIndex Index of the child. 571 * @param uiIndex Index of the child.
572 * @return Either the name of the specified child or an empty string. 572 * @return Either the name of the specified child or an empty string.
573 **/ 573 **/
574 std::string ResourceNode::getChildName(unsigned int uiIndex) const 574 std::string ResourceNode::getChildName(unsigned int uiIndex) const
575 { 575 {
576 return children[uiIndex].entry.wstrName; 576 return children[uiIndex].entry.wstrName;
577 } 577 }
578 578
579 /** 579 /**
580 * Returns the Name value of a child. 580 * Returns the Name value of a child.
581 * @param uiIndex Index of the child. 581 * @param uiIndex Index of the child.
582 * @return Name value of a child. 582 * @return Name value of a child.
583 **/ 583 **/
584 dword ResourceNode::getOffsetToChildName(unsigned int uiIndex) const 584 dword ResourceNode::getOffsetToChildName(unsigned int uiIndex) const
585 { 585 {
586 return children[uiIndex].entry.irde.Name; 586 return children[uiIndex].entry.irde.Name;
587 } 587 }
588 588
589 /** 589 /**
590 * Returns the OffsetToData value of a child. 590 * Returns the OffsetToData value of a child.
591 * @param uiIndex Index of the child. 591 * @param uiIndex Index of the child.
592 * @return OffsetToData value of a child. 592 * @return OffsetToData value of a child.
593 **/ 593 **/
594 dword ResourceNode::getOffsetToChildData(unsigned int uiIndex) const 594 dword ResourceNode::getOffsetToChildData(unsigned int uiIndex) const
595 { 595 {
596 return children[uiIndex].entry.irde.OffsetToData; 596 return children[uiIndex].entry.irde.OffsetToData;
597 } 597 }
598 598
599 599
600 /** 600 /**
601 * Sets the name of a child. 601 * Sets the name of a child.
602 * @param uiIndex Index of the child. 602 * @param uiIndex Index of the child.
603 * @param strNewName New name of the resource. 603 * @param strNewName New name of the resource.
604 **/ 604 **/
605 void ResourceNode::setChildName(unsigned int uiIndex, const std::string& strNewName) 605 void ResourceNode::setChildName(unsigned int uiIndex, const std::string& strNewName)
606 { 606 {
607 children[uiIndex].entry.wstrName = strNewName; 607 children[uiIndex].entry.wstrName = strNewName;
608 } 608 }
609 609
610 /** 610 /**
611 * Sets the Name value of a child. 611 * Sets the Name value of a child.
612 * @param uiIndex Index of the child. 612 * @param uiIndex Index of the child.
613 * @param dwNewOffset New Name value of the resource. 613 * @param dwNewOffset New Name value of the resource.
614 **/ 614 **/
615 void ResourceNode::setOffsetToChildName(unsigned int uiIndex, dword dwNewOffset) 615 void ResourceNode::setOffsetToChildName(unsigned int uiIndex, dword dwNewOffset)
616 { 616 {
617 children[uiIndex].entry.irde.Name = dwNewOffset; 617 children[uiIndex].entry.irde.Name = dwNewOffset;
618 } 618 }
619 619
620 /** 620 /**
621 * Sets the OffsetToData value of a child. 621 * Sets the OffsetToData value of a child.
622 * @param uiIndex Index of the child. 622 * @param uiIndex Index of the child.
623 * @param dwNewOffset New OffsetToData value of the resource. 623 * @param dwNewOffset New OffsetToData value of the resource.
624 **/ 624 **/
625 void ResourceNode::setOffsetToChildData(unsigned int uiIndex, dword dwNewOffset) 625 void ResourceNode::setOffsetToChildData(unsigned int uiIndex, dword dwNewOffset)
626 { 626 {
627 children[uiIndex].entry.irde.OffsetToData = dwNewOffset; 627 children[uiIndex].entry.irde.OffsetToData = dwNewOffset;
628 } 628 }
629 629
630 /** 630 /**
631 * Returns the Characteristics value of the node. 631 * Returns the Characteristics value of the node.
632 * @return Characteristics value of the node. 632 * @return Characteristics value of the node.
633 **/ 633 **/
634 dword ResourceNode::getCharacteristics() const 634 dword ResourceNode::getCharacteristics() const
635 { 635 {
636 return header.Characteristics; 636 return header.Characteristics;
637 } 637 }
638 638
639 /** 639 /**
640 * Returns the TimeDateStamp value of the node. 640 * Returns the TimeDateStamp value of the node.
641 * @return TimeDateStamp value of the node. 641 * @return TimeDateStamp value of the node.
642 **/ 642 **/
643 dword ResourceNode::getTimeDateStamp() const 643 dword ResourceNode::getTimeDateStamp() const
644 { 644 {
645 return header.TimeDateStamp; 645 return header.TimeDateStamp;
646 } 646 }
647 647
648 /** 648 /**
649 * Returns the MajorVersion value of the node. 649 * Returns the MajorVersion value of the node.
650 * @return MajorVersion value of the node. 650 * @return MajorVersion value of the node.
651 **/ 651 **/
652 word ResourceNode::getMajorVersion() const 652 word ResourceNode::getMajorVersion() const
653 { 653 {
654 return header.MajorVersion; 654 return header.MajorVersion;
655 } 655 }
656 656
657 /** 657 /**
658 * Returns the MinorVersion value of the node. 658 * Returns the MinorVersion value of the node.
659 * @return MinorVersion value of the node. 659 * @return MinorVersion value of the node.
660 **/ 660 **/
661 word ResourceNode::getMinorVersion() const 661 word ResourceNode::getMinorVersion() const
662 { 662 {
663 return header.MinorVersion; 663 return header.MinorVersion;
664 } 664 }
665 665
666 /** 666 /**
667 * Returns the NumberOfNamedEntries value of the node. 667 * Returns the NumberOfNamedEntries value of the node.
668 * @return NumberOfNamedEntries value of the node. 668 * @return NumberOfNamedEntries value of the node.
669 **/ 669 **/
670 word ResourceNode::getNumberOfNamedEntries() const 670 word ResourceNode::getNumberOfNamedEntries() const
671 { 671 {
672 return header.NumberOfNamedEntries; 672 return header.NumberOfNamedEntries;
673 } 673 }
674 674
675 /** 675 /**
676 * Returns the NumberOfIdEntries value of the node. 676 * Returns the NumberOfIdEntries value of the node.
677 * @return NumberOfIdEntries value of the node. 677 * @return NumberOfIdEntries value of the node.
678 **/ 678 **/
679 word ResourceNode::getNumberOfIdEntries() const 679 word ResourceNode::getNumberOfIdEntries() const
680 { 680 {
681 return header.NumberOfIdEntries; 681 return header.NumberOfIdEntries;
682 } 682 }
683 683
684 /** 684 /**
685 * Sets the Characteristics value of the node. 685 * Sets the Characteristics value of the node.
686 * @param value New Characteristics value of the node. 686 * @param value New Characteristics value of the node.
687 **/ 687 **/
688 void ResourceNode::setCharacteristics(dword value) 688 void ResourceNode::setCharacteristics(dword value)
689 { 689 {
690 header.Characteristics = value; 690 header.Characteristics = value;
691 } 691 }
692 692
693 /** 693 /**
694 * Sets the TimeDateStamp value of the node. 694 * Sets the TimeDateStamp value of the node.
695 * @param value New TimeDateStamp value of the node. 695 * @param value New TimeDateStamp value of the node.
696 **/ 696 **/
697 void ResourceNode::setTimeDateStamp(dword value) 697 void ResourceNode::setTimeDateStamp(dword value)
698 { 698 {
699 header.TimeDateStamp = value; 699 header.TimeDateStamp = value;
700 } 700 }
701 701
702 /** 702 /**
703 * Sets the MajorVersion value of the node. 703 * Sets the MajorVersion value of the node.
704 * @param value New MajorVersion value of the node. 704 * @param value New MajorVersion value of the node.
705 **/ 705 **/
706 void ResourceNode::setMajorVersion(word value) 706 void ResourceNode::setMajorVersion(word value)
707 { 707 {
708 header.MajorVersion = value; 708 header.MajorVersion = value;
709 } 709 }
710 710
711 /** 711 /**
712 * Sets the MinorVersion value of the node. 712 * Sets the MinorVersion value of the node.
713 * @param value New MinorVersion value of the node. 713 * @param value New MinorVersion value of the node.
714 **/ 714 **/
715 void ResourceNode::setMinorVersion(word value) 715 void ResourceNode::setMinorVersion(word value)
716 { 716 {
717 header.MinorVersion = value; 717 header.MinorVersion = value;
718 } 718 }
719 719
720 /** 720 /**
721 * Sets the NumberOfNamedEntries value of the node. 721 * Sets the NumberOfNamedEntries value of the node.
722 * @param value New NumberOfNamedEntries value of the node. 722 * @param value New NumberOfNamedEntries value of the node.
723 **/ 723 **/
724 void ResourceNode::setNumberOfNamedEntries(word value) 724 void ResourceNode::setNumberOfNamedEntries(word value)
725 { 725 {
726 header.NumberOfNamedEntries = value; 726 header.NumberOfNamedEntries = value;
727 } 727 }
728 728
729 /** 729 /**
730 * Sets the NumberOfIdEntries value of the node. 730 * Sets the NumberOfIdEntries value of the node.
731 * @param value New NumberOfIdEntries value of the node. 731 * @param value New NumberOfIdEntries value of the node.
732 **/ 732 **/
733 void ResourceNode::setNumberOfIdEntries(word value) 733 void ResourceNode::setNumberOfIdEntries(word value)
734 { 734 {
735 header.NumberOfIdEntries = value; 735 header.NumberOfIdEntries = value;
736 } 736 }
737 737
738 738
739/* /// Returns the size of a resource node. 739/* /// Returns the size of a resource node.
740 unsigned int ResourceNode::size() const 740 unsigned int ResourceNode::size() const
741 { 741 {
742 if (children.size()) 742 if (children.size())
743 { 743 {
744 std::cout << std::accumulate(children.begin(), children.end(), 0, accumulate<ResourceChild>) << std::endl; 744 std::cout << std::accumulate(children.begin(), children.end(), 0, accumulate<ResourceChild>) << std::endl;
745 return PELIB_IMAGE_RESOURCE_DIRECTORY::size() 745 return PELIB_IMAGE_RESOURCE_DIRECTORY::size()
746 + std::accumulate(children.begin(), children.end(), 0, accumulate<ResourceChild>); 746 + std::accumulate(children.begin(), children.end(), 0, accumulate<ResourceChild>);
747 } 747 }
748 else 748 else
749 { 749 {
750 return 0; 750 return 0;
751 } 751 }
752 } 752 }
753*/ 753*/
754// -------------------------------------------------- ResourceDirectory ------------------------------------------- 754// -------------------------------------------------- ResourceDirectory -------------------------------------------
755 755
756 /** 756 /**
757 * Returns the root node of the resource directory. 757 * Returns the root node of the resource directory.
758 * @return Root node of the resource directory. 758 * @return Root node of the resource directory.
759 **/ 759 **/
760 ResourceNode* ResourceDirectory::getRoot() 760 ResourceNode* ResourceDirectory::getRoot()
761 { 761 {
762 return &m_rnRoot; 762 return &m_rnRoot;
763 } 763 }
764 764
765 /** 765 /**
766 * Correctly sorts the resource nodes of the resource tree. This function should be called 766 * Correctly sorts the resource nodes of the resource tree. This function should be called
767 * before calling rebuild. 767 * before calling rebuild.
768 **/ 768 **/
769 void ResourceDirectory::makeValid() 769 void ResourceDirectory::makeValid()
770 { 770 {
771 m_rnRoot.makeValid(); 771 m_rnRoot.makeValid();
772 } 772 }
773 773
774 /** 774 /**
775 * Reads the resource directory from a file. 775 * Reads the resource directory from a file.
776 * @param strFilename Name of the file. 776 * @param strFilename Name of the file.
777 * @param uiOffset File offset of the resource directory. 777 * @param uiOffset File offset of the resource directory.
778 * @param uiSize Raw size of the resource directory. 778 * @param uiSize Raw size of the resource directory.
779 * @param uiResDirRva RVA of the beginning of the resource directory. 779 * @param uiResDirRva RVA of the beginning of the resource directory.
780 **/ 780 **/
781 int ResourceDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, unsigned int uiResDirRva) 781 int ResourceDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, unsigned int uiResDirRva)
782 { 782 {
783 if (!uiSize || !uiOffset) 783 if (!uiSize || !uiOffset)
784 { 784 {
785 return 1; 785 return 1;
786 } 786 }
787 787
788 std::ifstream ifFile(strFilename.c_str(), std::ios::binary); 788 std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
789 789
790 if (!ifFile) 790 if (!ifFile)
791 { 791 {
792// throw Exceptions::CannotOpenFile(ResourceDirectoryId, __LINE__); 792// throw Exceptions::CannotOpenFile(ResourceDirectoryId, __LINE__);
793 return 1; 793 return 1;
794 } 794 }
795 795
796 if (fileSize(ifFile) < uiOffset + uiSize) 796 if (fileSize(ifFile) < uiOffset + uiSize)
797 { 797 {
798// throw Exceptions::InvalidFormat(ResourceDirectoryId, __LINE__); 798// throw Exceptions::InvalidFormat(ResourceDirectoryId, __LINE__);
799 return 1; 799 return 1;
800 } 800 }
801 801
802 ifFile.seekg(uiOffset, std::ios::beg); 802 ifFile.seekg(uiOffset, std::ios::beg);
803 803
804 PELIB_IMAGE_RESOURCE_DIRECTORY irdCurrRoot; 804 PELIB_IMAGE_RESOURCE_DIRECTORY irdCurrRoot;
805 805
806 std::vector<byte> vResourceDirectory(uiSize); 806 std::vector<byte> vResourceDirectory(uiSize);
807 ifFile.read(reinterpret_cast<char*>(&vResourceDirectory[0]), uiSize); 807 ifFile.read(reinterpret_cast<char*>(&vResourceDirectory[0]), uiSize);
808 808
809 InputBuffer inpBuffer(vResourceDirectory); 809 InputBuffer inpBuffer(vResourceDirectory);
810 810
811// ResourceNode currNode; 811// ResourceNode currNode;
812 return m_rnRoot.read(inpBuffer, 0, uiResDirRva/*, ""*/); 812 return m_rnRoot.read(inpBuffer, 0, uiResDirRva/*, ""*/);
813// std::swap(currNode, m_rnRoot); 813// std::swap(currNode, m_rnRoot);
814 } 814 }
815 815
816 /** 816 /**
817 * Rebuilds the resource directory. 817 * Rebuilds the resource directory.
818 * @param vBuffer Buffer the source directory will be written to. 818 * @param vBuffer Buffer the source directory will be written to.
819 * @param uiRva RVA of the resource directory. 819 * @param uiRva RVA of the resource directory.
820 **/ 820 **/
821 void ResourceDirectory::rebuild(std::vector<byte>& vBuffer, unsigned int uiRva) const 821 void ResourceDirectory::rebuild(std::vector<byte>& vBuffer, unsigned int uiRva) const
822 { 822 {
823 OutputBuffer obBuffer(vBuffer); 823 OutputBuffer obBuffer(vBuffer);
824 unsigned int offs = 0; 824 unsigned int offs = 0;
825// std::cout << "Root: " << m_rnRoot.children.size() << std::endl; 825// std::cout << "Root: " << m_rnRoot.children.size() << std::endl;
826 m_rnRoot.rebuild(obBuffer, offs, uiRva, ""); 826 m_rnRoot.rebuild(obBuffer, offs, uiRva, "");
827 } 827 }
828 828
829 /** 829 /**
830 * Returns the size of the entire rebuilt resource directory. That's the size of the entire 830 * Returns the size of the entire rebuilt resource directory. That's the size of the entire
831 * structure as it's written back to a file. 831 * structure as it's written back to a file.
832 **/ 832 **/
833/* unsigned int ResourceDirectory::size() const 833/* unsigned int ResourceDirectory::size() const
834 { 834 {
835 return m_rnRoot.size(); 835 return m_rnRoot.size();
836 } 836 }
837*/ 837*/
838 /** 838 /**
839 * Writes the current resource directory back into a file. 839 * Writes the current resource directory back into a file.
840 * @param strFilename Name of the output file. 840 * @param strFilename Name of the output file.
841 * @param uiOffset File offset where the resource directory will be written to. 841 * @param uiOffset File offset where the resource directory will be written to.
842 * @param uiRva RVA of the file offset. 842 * @param uiRva RVA of the file offset.
843 **/ 843 **/
844 int ResourceDirectory::write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva) const 844 int ResourceDirectory::write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva) const
845 { 845 {
846 std::fstream ofFile(strFilename.c_str(), std::ios_base::in); 846 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
847 847
848 if (!ofFile) 848 if (!ofFile)
849 { 849 {
850 ofFile.clear(); 850 ofFile.clear();
851 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary); 851 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
852 } 852 }
853 else 853 else
854 { 854 {
855 ofFile.close(); 855 ofFile.close();
856 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary); 856 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
857 } 857 }
858 858
859 if (!ofFile) 859 if (!ofFile)
860 { 860 {
861 return ERROR_OPENING_FILE; 861 return ERROR_OPENING_FILE;
862 } 862 }
863 863
864 ofFile.seekp(uiOffset, std::ios::beg); 864 ofFile.seekp(uiOffset, std::ios::beg);
865 865
866 std::vector<unsigned char> vBuffer; 866 std::vector<unsigned char> vBuffer;
867 rebuild(vBuffer, uiRva); 867 rebuild(vBuffer, uiRva);
868 868
869 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size())); 869 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
870 870
871 ofFile.close(); 871 ofFile.close();
872 872
873 return 0; 873 return 0;
874 } 874 }
875 875
876 /** 876 /**
877 * Adds another resource type. The new resource type is identified by the ID dwResTypeId. 877 * Adds another resource type. The new resource type is identified by the ID dwResTypeId.
878 * @param dwResTypeId ID which identifies the resource type. 878 * @param dwResTypeId ID which identifies the resource type.
879 **/ 879 **/
880 int ResourceDirectory::addResourceType(dword dwResTypeId) 880 int ResourceDirectory::addResourceType(dword dwResTypeId)
881 { 881 {
882 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalId), dwResTypeId)); 882 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalId), dwResTypeId));
883 if (Iter != m_rnRoot.children.end()) 883 if (Iter != m_rnRoot.children.end())
884 { 884 {
885 return 1; 885 return 1;
886 // throw Exceptions::EntryAlreadyExists(ResourceDirectoryId, __LINE__); 886 // throw Exceptions::EntryAlreadyExists(ResourceDirectoryId, __LINE__);
887 } 887 }
888 888
889 ResourceChild rcCurr; 889 ResourceChild rcCurr;
890 rcCurr.child = new ResourceNode; 890 rcCurr.child = new ResourceNode;
891 rcCurr.entry.irde.Name = dwResTypeId; 891 rcCurr.entry.irde.Name = dwResTypeId;
892 m_rnRoot.children.push_back(rcCurr); 892 m_rnRoot.children.push_back(rcCurr);
893 893
894 return 0; 894 return 0;
895 } 895 }
896 896
897 /** 897 /**
898 * Adds another resource type. The new resource type is identified by the name strResTypeName. 898 * Adds another resource type. The new resource type is identified by the name strResTypeName.
899 * @param strResTypeName Name which identifies the resource type. 899 * @param strResTypeName Name which identifies the resource type.
900 **/ 900 **/
901 int ResourceDirectory::addResourceType(const std::string& strResTypeName) 901 int ResourceDirectory::addResourceType(const std::string& strResTypeName)
902 { 902 {
903 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalName), strResTypeName)); 903 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalName), strResTypeName));
904 if (Iter != m_rnRoot.children.end()) 904 if (Iter != m_rnRoot.children.end())
905 { 905 {
906 return 1; 906 return 1;
907// throw Exceptions::EntryAlreadyExists(ResourceDirectoryId, __LINE__); 907// throw Exceptions::EntryAlreadyExists(ResourceDirectoryId, __LINE__);
908 } 908 }
909 909
910 ResourceChild rcCurr; 910 ResourceChild rcCurr;
911 rcCurr.entry.wstrName = strResTypeName; 911 rcCurr.entry.wstrName = strResTypeName;
912 rcCurr.child = new ResourceNode; 912 rcCurr.child = new ResourceNode;
913 m_rnRoot.children.push_back(rcCurr); 913 m_rnRoot.children.push_back(rcCurr);
914 914
915 return 0; 915 return 0;
916 } 916 }
917 917
918 /** 918 /**
919 * Removes the resource type identified by the ID dwResTypeId. 919 * Removes the resource type identified by the ID dwResTypeId.
920 * @param dwResTypeId ID which identifies the resource type. 920 * @param dwResTypeId ID which identifies the resource type.
921 **/ 921 **/
922 int ResourceDirectory::removeResourceType(dword dwResTypeId) 922 int ResourceDirectory::removeResourceType(dword dwResTypeId)
923 { 923 {
924 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalId), dwResTypeId)); 924 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalId), dwResTypeId));
925 if (Iter == m_rnRoot.children.end()) 925 if (Iter == m_rnRoot.children.end())
926 { 926 {
927 return 1; 927 return 1;
928// throw Exceptions::ResourceTypeDoesNotExist(ResourceDirectoryId, __LINE__); 928// throw Exceptions::ResourceTypeDoesNotExist(ResourceDirectoryId, __LINE__);
929 } 929 }
930 930
931 bool isNamed = false; 931 bool isNamed = false;
932 if (Iter->isNamedResource()) isNamed = true; 932 if (Iter->isNamedResource()) isNamed = true;
933 933
934 m_rnRoot.children.erase(Iter); 934 m_rnRoot.children.erase(Iter);
935 935
936 if (isNamed) m_rnRoot.header.NumberOfNamedEntries = static_cast<PeLib::word>(m_rnRoot.children.size()); 936 if (isNamed) m_rnRoot.header.NumberOfNamedEntries = static_cast<PeLib::word>(m_rnRoot.children.size());
937 else m_rnRoot.header.NumberOfIdEntries = static_cast<PeLib::word>(m_rnRoot.children.size()); 937 else m_rnRoot.header.NumberOfIdEntries = static_cast<PeLib::word>(m_rnRoot.children.size());
938 938
939 return 0; 939 return 0;
940 } 940 }
941 941
942 /** 942 /**
943 * Removes the resource type identified by the name strResTypeName. 943 * Removes the resource type identified by the name strResTypeName.
944 * @param strResTypeName Name which identifies the resource type. 944 * @param strResTypeName Name which identifies the resource type.
945 **/ 945 **/
946 int ResourceDirectory::removeResourceType(const std::string& strResTypeName) 946 int ResourceDirectory::removeResourceType(const std::string& strResTypeName)
947 { 947 {
948 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalName), strResTypeName)); 948 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalName), strResTypeName));
949 if (Iter == m_rnRoot.children.end()) 949 if (Iter == m_rnRoot.children.end())
950 { 950 {
951 return 1; 951 return 1;
952 // throw Exceptions::ResourceTypeDoesNotExist(ResourceDirectoryId, __LINE__); 952 // throw Exceptions::ResourceTypeDoesNotExist(ResourceDirectoryId, __LINE__);
953 } 953 }
954 954
955 bool isNamed = false; 955 bool isNamed = false;
956 if (Iter->isNamedResource()) isNamed = true; 956 if (Iter->isNamedResource()) isNamed = true;
957 957
958 m_rnRoot.children.erase(Iter); 958 m_rnRoot.children.erase(Iter);
959 959
960 if (isNamed) m_rnRoot.header.NumberOfNamedEntries = static_cast<PeLib::word>(m_rnRoot.children.size()); 960 if (isNamed) m_rnRoot.header.NumberOfNamedEntries = static_cast<PeLib::word>(m_rnRoot.children.size());
961 else m_rnRoot.header.NumberOfIdEntries = static_cast<PeLib::word>(m_rnRoot.children.size()); 961 else m_rnRoot.header.NumberOfIdEntries = static_cast<PeLib::word>(m_rnRoot.children.size());
962 962
963 return 0; 963 return 0;
964 } 964 }
965 965
966 /** 966 /**
967 * Removes the resource type identified by the index uiIndex. 967 * Removes the resource type identified by the index uiIndex.
968 * @param uiIndex Index which identifies the resource type. 968 * @param uiIndex Index which identifies the resource type.
969 **/ 969 **/
970 int ResourceDirectory::removeResourceTypeByIndex(unsigned int uiIndex) 970 int ResourceDirectory::removeResourceTypeByIndex(unsigned int uiIndex)
971 { 971 {
972 bool isNamed = false; 972 bool isNamed = false;
973 if (m_rnRoot.children[uiIndex].isNamedResource()) isNamed = true; 973 if (m_rnRoot.children[uiIndex].isNamedResource()) isNamed = true;
974 974
975 m_rnRoot.children.erase(m_rnRoot.children.begin() + uiIndex); 975 m_rnRoot.children.erase(m_rnRoot.children.begin() + uiIndex);
976 976
977 if (isNamed) m_rnRoot.header.NumberOfNamedEntries = static_cast<PeLib::word>(m_rnRoot.children.size()); 977 if (isNamed) m_rnRoot.header.NumberOfNamedEntries = static_cast<PeLib::word>(m_rnRoot.children.size());
978 else m_rnRoot.header.NumberOfIdEntries = static_cast<PeLib::word>(m_rnRoot.children.size()); 978 else m_rnRoot.header.NumberOfIdEntries = static_cast<PeLib::word>(m_rnRoot.children.size());
979 979
980 return 0; 980 return 0;
981 } 981 }
982 982
983 /** 983 /**
984 * Adds another resource to the resource tree. The first parameter identifies the resource type 984 * Adds another resource to the resource tree. The first parameter identifies the resource type
985 * of the new resource, the second parameter identifies the resource itself. 985 * of the new resource, the second parameter identifies the resource itself.
986 * @param dwResTypeId ID of the resource type. 986 * @param dwResTypeId ID of the resource type.
987 * @param dwResId ID of the resource. 987 * @param dwResId ID of the resource.
988 **/ 988 **/
989 int ResourceDirectory::addResource(dword dwResTypeId, dword dwResId) 989 int ResourceDirectory::addResource(dword dwResTypeId, dword dwResId)
990 { 990 {
991 ResourceChild rcCurr; 991 ResourceChild rcCurr;
992 rcCurr.entry.irde.Name = dwResId; 992 rcCurr.entry.irde.Name = dwResId;
993 return addResourceT(dwResTypeId, dwResId, rcCurr); 993 return addResourceT(dwResTypeId, dwResId, rcCurr);
994 } 994 }
995 995
996 /** 996 /**
997 * Adds another resource to the resource tree. The first parameter identifies the resource type 997 * Adds another resource to the resource tree. The first parameter identifies the resource type
998 * of the new resource, the second parameter identifies the resource itself. 998 * of the new resource, the second parameter identifies the resource itself.
999 * @param dwResTypeId ID of the resource type. 999 * @param dwResTypeId ID of the resource type.
1000 * @param strResName Name of the resource. 1000 * @param strResName Name of the resource.
1001 **/ 1001 **/
1002 int ResourceDirectory::addResource(dword dwResTypeId, const std::string& strResName) 1002 int ResourceDirectory::addResource(dword dwResTypeId, const std::string& strResName)
1003 { 1003 {
1004 ResourceChild rcCurr; 1004 ResourceChild rcCurr;
1005 rcCurr.entry.wstrName = strResName; 1005 rcCurr.entry.wstrName = strResName;
1006 return addResourceT(dwResTypeId, strResName, rcCurr); 1006 return addResourceT(dwResTypeId, strResName, rcCurr);
1007 } 1007 }
1008 1008
1009 /** 1009 /**
1010 * Adds another resource to the resource tree. The first parameter identifies the resource type 1010 * Adds another resource to the resource tree. The first parameter identifies the resource type
1011 * of the new resource, the second parameter identifies the resource itself. 1011 * of the new resource, the second parameter identifies the resource itself.
1012 * @param strResTypeName Name of the resource type. 1012 * @param strResTypeName Name of the resource type.
1013 * @param dwResId ID of the resource. 1013 * @param dwResId ID of the resource.
1014 **/ 1014 **/
1015 int ResourceDirectory::addResource(const std::string& strResTypeName, dword dwResId) 1015 int ResourceDirectory::addResource(const std::string& strResTypeName, dword dwResId)
1016 { 1016 {
1017 ResourceChild rcCurr; 1017 ResourceChild rcCurr;
1018 rcCurr.entry.irde.Name = dwResId; 1018 rcCurr.entry.irde.Name = dwResId;
1019 return addResourceT(strResTypeName, dwResId, rcCurr); 1019 return addResourceT(strResTypeName, dwResId, rcCurr);
1020 } 1020 }
1021 1021
1022 /** 1022 /**
1023 * Adds another resource to the resource tree. The first parameter identifies the resource type 1023 * Adds another resource to the resource tree. The first parameter identifies the resource type
1024 * of the new resource, the second parameter identifies the resource itself. 1024 * of the new resource, the second parameter identifies the resource itself.
1025 * @param strResTypeName Name of the resource type. 1025 * @param strResTypeName Name of the resource type.
1026 * @param strResName Name of the resource. 1026 * @param strResName Name of the resource.
1027 **/ 1027 **/
1028 int ResourceDirectory::addResource(const std::string& strResTypeName, const std::string& strResName) 1028 int ResourceDirectory::addResource(const std::string& strResTypeName, const std::string& strResName)
1029 { 1029 {
1030 ResourceChild rcCurr; 1030 ResourceChild rcCurr;
1031 rcCurr.entry.wstrName = strResName; 1031 rcCurr.entry.wstrName = strResName;
1032 return addResourceT(strResTypeName, strResName, rcCurr); 1032 return addResourceT(strResTypeName, strResName, rcCurr);
1033 } 1033 }
1034 1034
1035 /** 1035 /**
1036 * Removes a resource from the resource tree. The first parameter identifies the resource type 1036 * Removes a resource from the resource tree. The first parameter identifies the resource type
1037 * of the new resource, the second parameter identifies the resource itself. 1037 * of the new resource, the second parameter identifies the resource itself.
1038 * @param dwResTypeIndex ID of the resource type. 1038 * @param dwResTypeIndex ID of the resource type.
1039 * @param dwResId ID of the resource. 1039 * @param dwResId ID of the resource.
1040 **/ 1040 **/
1041 int ResourceDirectory::removeResource(dword dwResTypeIndex, dword dwResId) 1041 int ResourceDirectory::removeResource(dword dwResTypeIndex, dword dwResId)
1042 { 1042 {
1043 return removeResourceT(dwResTypeIndex, dwResId); 1043 return removeResourceT(dwResTypeIndex, dwResId);
1044 } 1044 }
1045 1045
1046 /** 1046 /**
1047 * Removes a resource from the resource tree. The first parameter identifies the resource type 1047 * Removes a resource from the resource tree. The first parameter identifies the resource type
1048 * of the new resource, the second parameter identifies the resource itself. 1048 * of the new resource, the second parameter identifies the resource itself.
1049 * @param dwResTypeIndex ID of the resource type. 1049 * @param dwResTypeIndex ID of the resource type.
1050 * @param strResName Name of the resource. 1050 * @param strResName Name of the resource.
1051 **/ 1051 **/
1052 int ResourceDirectory::removeResource(dword dwResTypeIndex, const std::string& strResName) 1052 int ResourceDirectory::removeResource(dword dwResTypeIndex, const std::string& strResName)
1053 { 1053 {
1054 return removeResourceT(dwResTypeIndex, strResName); 1054 return removeResourceT(dwResTypeIndex, strResName);
1055 } 1055 }
1056 1056
1057 /** 1057 /**
1058 * Removes a resource from the resource tree. The first parameter identifies the resource type 1058 * Removes a resource from the resource tree. The first parameter identifies the resource type
1059 * of the new resource, the second parameter identifies the resource itself. 1059 * of the new resource, the second parameter identifies the resource itself.
1060 * @param strResTypeName Name of the resource type. 1060 * @param strResTypeName Name of the resource type.
1061 * @param dwResId ID of the resource. 1061 * @param dwResId ID of the resource.
1062 **/ 1062 **/
1063 int ResourceDirectory::removeResource(const std::string& strResTypeName, dword dwResId) 1063 int ResourceDirectory::removeResource(const std::string& strResTypeName, dword dwResId)
1064 { 1064 {
1065 return removeResourceT(strResTypeName, dwResId); 1065 return removeResourceT(strResTypeName, dwResId);
1066 } 1066 }
1067 1067
1068 /** 1068 /**
1069 * Removes a resource from the resource tree. The first parameter identifies the resource type 1069 * Removes a resource from the resource tree. The first parameter identifies the resource type
1070 * of the new resource, the second parameter identifies the resource itself. 1070 * of the new resource, the second parameter identifies the resource itself.
1071 * @param strResTypeName Name of the resource type. 1071 * @param strResTypeName Name of the resource type.
1072 * @param strResName Name of the resource. 1072 * @param strResName Name of the resource.
1073 **/ 1073 **/
1074 int ResourceDirectory::removeResource(const std::string& strResTypeName, const std::string& strResName) 1074 int ResourceDirectory::removeResource(const std::string& strResTypeName, const std::string& strResName)
1075 { 1075 {
1076 return removeResourceT(strResTypeName, strResName); 1076 return removeResourceT(strResTypeName, strResName);
1077 } 1077 }
1078 1078
1079 /** 1079 /**
1080 * Returns the number of resource types. 1080 * Returns the number of resource types.
1081 **/ 1081 **/
1082 unsigned int ResourceDirectory::getNumberOfResourceTypes() const 1082 unsigned int ResourceDirectory::getNumberOfResourceTypes() const
1083 { 1083 {
1084 return static_cast<unsigned int>(m_rnRoot.children.size()); 1084 return static_cast<unsigned int>(m_rnRoot.children.size());
1085 } 1085 }
1086 1086
1087 /** 1087 /**
1088 * Returns the ID of a resource type which was specified through an index. 1088 * Returns the ID of a resource type which was specified through an index.
1089 * The valid range of the parameter uiIndex is 0...getNumberOfResourceTypes() - 1. 1089 * The valid range of the parameter uiIndex is 0...getNumberOfResourceTypes() - 1.
1090 * Leaving the invalid range leads to undefined behaviour. 1090 * Leaving the invalid range leads to undefined behaviour.
1091 * @param uiIndex Index which identifies a resource type. 1091 * @param uiIndex Index which identifies a resource type.
1092 * @return The ID of the specified resource type. 1092 * @return The ID of the specified resource type.
1093 **/ 1093 **/
1094 dword ResourceDirectory::getResourceTypeIdByIndex(unsigned int uiIndex) const 1094 dword ResourceDirectory::getResourceTypeIdByIndex(unsigned int uiIndex) const
1095 { 1095 {
1096 return m_rnRoot.children[uiIndex].entry.irde.Name; 1096 return m_rnRoot.children[uiIndex].entry.irde.Name;
1097 } 1097 }
1098 1098
1099 /** 1099 /**
1100 * Returns the name of a resource type which was specified through an index. 1100 * Returns the name of a resource type which was specified through an index.
1101 * The valid range of the parameter uiIndex is 0...getNumberOfResourceTypes() - 1. 1101 * The valid range of the parameter uiIndex is 0...getNumberOfResourceTypes() - 1.
1102 * Leaving the invalid range leads to undefined behaviour. 1102 * Leaving the invalid range leads to undefined behaviour.
1103 * @param uiIndex Index which identifies a resource type. 1103 * @param uiIndex Index which identifies a resource type.
1104 * @return The name of the specified resource type. 1104 * @return The name of the specified resource type.
1105 **/ 1105 **/
1106 std::string ResourceDirectory::getResourceTypeNameByIndex(unsigned int uiIndex) const 1106 std::string ResourceDirectory::getResourceTypeNameByIndex(unsigned int uiIndex) const
1107 { 1107 {
1108 return m_rnRoot.children[uiIndex].entry.wstrName; 1108 return m_rnRoot.children[uiIndex].entry.wstrName;
1109 } 1109 }
1110 1110
1111 /** 1111 /**
1112 * Converts the ID of a resource type to an index. 1112 * Converts the ID of a resource type to an index.
1113 * @param dwResTypeId ID of the resource type. 1113 * @param dwResTypeId ID of the resource type.
1114 * @return Index of that resource type. 1114 * @return Index of that resource type.
1115 **/ 1115 **/
1116 int ResourceDirectory::resourceTypeIdToIndex(dword dwResTypeId) const 1116 int ResourceDirectory::resourceTypeIdToIndex(dword dwResTypeId) const
1117 { 1117 {
1118 std::vector<ResourceChild>::const_iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalId), dwResTypeId)); 1118 std::vector<ResourceChild>::const_iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalId), dwResTypeId));
1119 if (Iter == m_rnRoot.children.end()) return -1; 1119 if (Iter == m_rnRoot.children.end()) return -1;
1120 return static_cast<unsigned int>(std::distance(m_rnRoot.children.begin(), Iter)); 1120 return static_cast<unsigned int>(std::distance(m_rnRoot.children.begin(), Iter));
1121 } 1121 }
1122 1122
1123 /** 1123 /**
1124 * Converts the name of a resource type to an index. 1124 * Converts the name of a resource type to an index.
1125 * @param strResTypeName ID of the resource type. 1125 * @param strResTypeName ID of the resource type.
1126 * @return Index of that resource type. 1126 * @return Index of that resource type.
1127 **/ 1127 **/
1128 int ResourceDirectory::resourceTypeNameToIndex(const std::string& strResTypeName) const 1128 int ResourceDirectory::resourceTypeNameToIndex(const std::string& strResTypeName) const
1129 { 1129 {
1130 std::vector<ResourceChild>::const_iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalName), strResTypeName)); 1130 std::vector<ResourceChild>::const_iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalName), strResTypeName));
1131 if (Iter == m_rnRoot.children.end()) return -1; 1131 if (Iter == m_rnRoot.children.end()) return -1;
1132 return static_cast<unsigned int>(std::distance(m_rnRoot.children.begin(), Iter)); 1132 return static_cast<unsigned int>(std::distance(m_rnRoot.children.begin(), Iter));
1133 } 1133 }
1134 1134
1135 /** 1135 /**
1136 * Returns the number of resources of a specific resource type. 1136 * Returns the number of resources of a specific resource type.
1137 * @param dwId ID of the resource type. 1137 * @param dwId ID of the resource type.
1138 * @return Number of resources of resource type dwId. 1138 * @return Number of resources of resource type dwId.
1139 **/ 1139 **/
1140 unsigned int ResourceDirectory::getNumberOfResources(dword dwId) const 1140 unsigned int ResourceDirectory::getNumberOfResources(dword dwId) const
1141 { 1141 {
1142// std::vector<ResourceChild>::const_iterator IterD = m_rnRoot.children.begin(); 1142// std::vector<ResourceChild>::const_iterator IterD = m_rnRoot.children.begin();
1143// std::cout << dwId << std::endl; 1143// std::cout << dwId << std::endl;
1144// while (IterD != m_rnRoot.children.end()) 1144// while (IterD != m_rnRoot.children.end())
1145// { 1145// {
1146// std::cout << IterD->entry.irde.Name << std::endl; 1146// std::cout << IterD->entry.irde.Name << std::endl;
1147// ++IterD; 1147// ++IterD;
1148// } 1148// }
1149 1149
1150 std::vector<ResourceChild>::const_iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalId), dwId)); 1150 std::vector<ResourceChild>::const_iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalId), dwId));
1151 if (Iter == m_rnRoot.children.end()) 1151 if (Iter == m_rnRoot.children.end())
1152 { 1152 {
1153 return 0xFFFFFFFF; 1153 return 0xFFFFFFFF;
1154 } 1154 }
1155 else 1155 else
1156 { 1156 {
1157 ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child); 1157 ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child);
1158 return static_cast<unsigned int>(currNode->children.size()); 1158 return static_cast<unsigned int>(currNode->children.size());
1159 } 1159 }
1160 } 1160 }
1161 1161
1162 /** 1162 /**
1163 * Returns the number of resources of a specific resource type. 1163 * Returns the number of resources of a specific resource type.
1164 * @param strResTypeName Name of the resource type. 1164 * @param strResTypeName Name of the resource type.
1165 * @return Number of resources of resource type strResTypeName. 1165 * @return Number of resources of resource type strResTypeName.
1166 **/ 1166 **/
1167 unsigned int ResourceDirectory::getNumberOfResources(const std::string& strResTypeName) const 1167 unsigned int ResourceDirectory::getNumberOfResources(const std::string& strResTypeName) const
1168 { 1168 {
1169 std::vector<ResourceChild>::const_iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalName), strResTypeName)); 1169 std::vector<ResourceChild>::const_iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalName), strResTypeName));
1170 if (Iter == m_rnRoot.children.end()) 1170 if (Iter == m_rnRoot.children.end())
1171 { 1171 {
1172 return 0xFFFFFFFF; 1172 return 0xFFFFFFFF;
1173 } 1173 }
1174 else 1174 else
1175 { 1175 {
1176 ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child); 1176 ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child);
1177 return static_cast<unsigned int>(currNode->children.size()); 1177 return static_cast<unsigned int>(currNode->children.size());
1178 } 1178 }
1179 } 1179 }
1180 1180
1181 /** 1181 /**
1182 * Returns the number of resources of a resource type which was specified through an index. 1182 * Returns the number of resources of a resource type which was specified through an index.
1183 * The valid range of the parameter uiIndex is 0...getNumberOfResourceTypes() - 1. 1183 * The valid range of the parameter uiIndex is 0...getNumberOfResourceTypes() - 1.
1184 * Leaving the invalid range leads to undefined behaviour. 1184 * Leaving the invalid range leads to undefined behaviour.
1185 * @param uiIndex Index which identifies a resource type. 1185 * @param uiIndex Index which identifies a resource type.
1186 * @return The number of resources of the specified resource type. 1186 * @return The number of resources of the specified resource type.
1187 **/ 1187 **/
1188 unsigned int ResourceDirectory::getNumberOfResourcesByIndex(unsigned int uiIndex) const 1188 unsigned int ResourceDirectory::getNumberOfResourcesByIndex(unsigned int uiIndex) const
1189 { 1189 {
1190 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiIndex].child); 1190 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiIndex].child);
1191 return static_cast<unsigned int>(currNode->children.size()); 1191 return static_cast<unsigned int>(currNode->children.size());
1192 } 1192 }
1193 1193
1194 /** 1194 /**
1195 * Gets the resource data of a specific resource. 1195 * Gets the resource data of a specific resource.
1196 * @param dwResTypeId Identifies the resource type of the resource. 1196 * @param dwResTypeId Identifies the resource type of the resource.
1197 * @param dwResId Identifies the resource. 1197 * @param dwResId Identifies the resource.
1198 * @param data Vector where the data is stored. 1198 * @param data Vector where the data is stored.
1199 **/ 1199 **/
1200 void ResourceDirectory::getResourceData(dword dwResTypeId, dword dwResId, std::vector<byte>& data) const 1200 void ResourceDirectory::getResourceData(dword dwResTypeId, dword dwResId, std::vector<byte>& data) const
1201 { 1201 {
1202 getResourceDataT(dwResTypeId, dwResId, data); 1202 getResourceDataT(dwResTypeId, dwResId, data);
1203 } 1203 }
1204 1204
1205 /** 1205 /**
1206 * Gets the resource data of a specific resource. 1206 * Gets the resource data of a specific resource.
1207 * @param dwResTypeId Identifies the resource type of the resource. 1207 * @param dwResTypeId Identifies the resource type of the resource.
1208 * @param strResName Identifies the resource. 1208 * @param strResName Identifies the resource.
1209 * @param data Vector where the data is stored. 1209 * @param data Vector where the data is stored.
1210 **/ 1210 **/
1211 void ResourceDirectory::getResourceData(dword dwResTypeId, const std::string& strResName, std::vector<byte>& data) const 1211 void ResourceDirectory::getResourceData(dword dwResTypeId, const std::string& strResName, std::vector<byte>& data) const
1212 { 1212 {
1213 getResourceDataT(dwResTypeId, strResName, data); 1213 getResourceDataT(dwResTypeId, strResName, data);
1214 } 1214 }
1215 1215
1216 /** 1216 /**
1217 * Gets the resource data of a specific resource. 1217 * Gets the resource data of a specific resource.
1218 * @param strResTypeName Identifies the resource type of the resource. 1218 * @param strResTypeName Identifies the resource type of the resource.
1219 * @param dwResId Identifies the resource. 1219 * @param dwResId Identifies the resource.
1220 * @param data Vector where the data is stored. 1220 * @param data Vector where the data is stored.
1221 **/ 1221 **/
1222 void ResourceDirectory::getResourceData(const std::string& strResTypeName, dword dwResId, std::vector<byte>& data) const 1222 void ResourceDirectory::getResourceData(const std::string& strResTypeName, dword dwResId, std::vector<byte>& data) const
1223 { 1223 {
1224 getResourceDataT(strResTypeName, dwResId, data); 1224 getResourceDataT(strResTypeName, dwResId, data);
1225 } 1225 }
1226 1226
1227 /** 1227 /**
1228 * Gets the resource data of a specific resource. 1228 * Gets the resource data of a specific resource.
1229 * @param strResTypeName Identifies the resource type of the resource. 1229 * @param strResTypeName Identifies the resource type of the resource.
1230 * @param strResName Identifies the resource. 1230 * @param strResName Identifies the resource.
1231 * @param data Vector where the data is stored. 1231 * @param data Vector where the data is stored.
1232 **/ 1232 **/
1233 void ResourceDirectory::getResourceData(const std::string& strResTypeName, const std::string& strResName, std::vector<byte>& data) const 1233 void ResourceDirectory::getResourceData(const std::string& strResTypeName, const std::string& strResName, std::vector<byte>& data) const
1234 { 1234 {
1235 getResourceDataT(strResTypeName, strResName, data); 1235 getResourceDataT(strResTypeName, strResName, data);
1236 } 1236 }
1237 1237
1238 /** 1238 /**
1239 * Gets the resource data of a specific resource by index. 1239 * Gets the resource data of a specific resource by index.
1240 * The valid range of the parameter uiResTypeIndex is 0...getNumberOfResourceTypes() - 1. 1240 * The valid range of the parameter uiResTypeIndex is 0...getNumberOfResourceTypes() - 1.
1241 * The valid range of the parameter uiResIndex is 0...getNumberOfResources() - 1. 1241 * The valid range of the parameter uiResIndex is 0...getNumberOfResources() - 1.
1242 * Leaving the invalid range leads to undefined behaviour. 1242 * Leaving the invalid range leads to undefined behaviour.
1243 * @param uiResTypeIndex Identifies the resource type of the resource. 1243 * @param uiResTypeIndex Identifies the resource type of the resource.
1244 * @param uiResIndex Identifies the resource. 1244 * @param uiResIndex Identifies the resource.
1245 * @param data Vector where the data is stored. 1245 * @param data Vector where the data is stored.
1246 **/ 1246 **/
1247 void ResourceDirectory::getResourceDataByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, std::vector<byte>& data) const 1247 void ResourceDirectory::getResourceDataByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, std::vector<byte>& data) const
1248 { 1248 {
1249 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiResTypeIndex].child); 1249 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiResTypeIndex].child);
1250 currNode = static_cast<ResourceNode*>(currNode->children[uiResIndex].child); 1250 currNode = static_cast<ResourceNode*>(currNode->children[uiResIndex].child);
1251 ResourceLeaf* currLeaf = static_cast<ResourceLeaf*>(currNode->children[0].child); 1251 ResourceLeaf* currLeaf = static_cast<ResourceLeaf*>(currNode->children[0].child);
1252 1252
1253 data.assign(currLeaf->m_data.begin(), currLeaf->m_data.end()); 1253 data.assign(currLeaf->m_data.begin(), currLeaf->m_data.end());
1254 } 1254 }
1255 1255
1256 /** 1256 /**
1257 * Sets the resource data of a specific resource. 1257 * Sets the resource data of a specific resource.
1258 * @param dwResTypeId Identifies the resource type of the resource. 1258 * @param dwResTypeId Identifies the resource type of the resource.
1259 * @param dwResId Identifies the resource. 1259 * @param dwResId Identifies the resource.
1260 * @param data The new resource data. 1260 * @param data The new resource data.
1261 **/ 1261 **/
1262 void ResourceDirectory::setResourceData(dword dwResTypeId, dword dwResId, std::vector<byte>& data) 1262 void ResourceDirectory::setResourceData(dword dwResTypeId, dword dwResId, std::vector<byte>& data)
1263 { 1263 {
1264 setResourceDataT(dwResTypeId, dwResId, data); 1264 setResourceDataT(dwResTypeId, dwResId, data);
1265 } 1265 }
1266 1266
1267 /** 1267 /**
1268 * Sets the resource data of a specific resource. 1268 * Sets the resource data of a specific resource.
1269 * @param dwResTypeId Identifies the resource type of the resource. 1269 * @param dwResTypeId Identifies the resource type of the resource.
1270 * @param strResName Identifies the resource. 1270 * @param strResName Identifies the resource.
1271 * @param data The new resource data. 1271 * @param data The new resource data.
1272 **/ 1272 **/
1273 void ResourceDirectory::setResourceData(dword dwResTypeId, const std::string& strResName, std::vector<byte>& data) 1273 void ResourceDirectory::setResourceData(dword dwResTypeId, const std::string& strResName, std::vector<byte>& data)
1274 { 1274 {
1275 setResourceDataT(dwResTypeId, strResName, data); 1275 setResourceDataT(dwResTypeId, strResName, data);
1276 } 1276 }
1277 1277
1278 /** 1278 /**
1279 * Sets the resource data of a specific resource. 1279 * Sets the resource data of a specific resource.
1280 * @param strResTypeName Identifies the resource type of the resource. 1280 * @param strResTypeName Identifies the resource type of the resource.
1281 * @param dwResId Identifies the resource. 1281 * @param dwResId Identifies the resource.
1282 * @param data The new resource data. 1282 * @param data The new resource data.
1283 **/ 1283 **/
1284 void ResourceDirectory::setResourceData(const std::string& strResTypeName, dword dwResId, std::vector<byte>& data) 1284 void ResourceDirectory::setResourceData(const std::string& strResTypeName, dword dwResId, std::vector<byte>& data)
1285 { 1285 {
1286 setResourceDataT(strResTypeName, dwResId, data); 1286 setResourceDataT(strResTypeName, dwResId, data);
1287 } 1287 }
1288 1288
1289 /** 1289 /**
1290 * Sets the resource data of a specific resource. 1290 * Sets the resource data of a specific resource.
1291 * @param strResTypeName Identifies the resource type of the resource. 1291 * @param strResTypeName Identifies the resource type of the resource.
1292 * @param strResName Identifies the resource. 1292 * @param strResName Identifies the resource.
1293 * @param data The new resource data. 1293 * @param data The new resource data.
1294 **/ 1294 **/
1295 void ResourceDirectory::setResourceData(const std::string& strResTypeName, const std::string& strResName, std::vector<byte>& data) 1295 void ResourceDirectory::setResourceData(const std::string& strResTypeName, const std::string& strResName, std::vector<byte>& data)
1296 { 1296 {
1297 setResourceDataT(strResTypeName, strResName, data); 1297 setResourceDataT(strResTypeName, strResName, data);
1298 } 1298 }
1299 1299
1300 /** 1300 /**
1301 * Sets the resource data of a specific resource by index. 1301 * Sets the resource data of a specific resource by index.
1302 * The valid range of the parameter uiResTypeIndex is 0...getNumberOfResourceTypes() - 1. 1302 * The valid range of the parameter uiResTypeIndex is 0...getNumberOfResourceTypes() - 1.
1303 * The valid range of the parameter uiResIndex is 0...getNumberOfResources() - 1. 1303 * The valid range of the parameter uiResIndex is 0...getNumberOfResources() - 1.
1304 * Leaving the invalid range leads to undefined behaviour. 1304 * Leaving the invalid range leads to undefined behaviour.
1305 * @param uiResTypeIndex Identifies the resource type of the resource. 1305 * @param uiResTypeIndex Identifies the resource type of the resource.
1306 * @param uiResIndex Identifies the resource. 1306 * @param uiResIndex Identifies the resource.
1307 * @param data The new resource data. 1307 * @param data The new resource data.
1308 **/ 1308 **/
1309 void ResourceDirectory::setResourceDataByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, std::vector<byte>& data) 1309 void ResourceDirectory::setResourceDataByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, std::vector<byte>& data)
1310 { 1310 {
1311 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiResTypeIndex].child); 1311 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiResTypeIndex].child);
1312 currNode = static_cast<ResourceNode*>(currNode->children[uiResIndex].child); 1312 currNode = static_cast<ResourceNode*>(currNode->children[uiResIndex].child);
1313 ResourceLeaf* currLeaf = static_cast<ResourceLeaf*>(currNode->children[0].child); 1313 ResourceLeaf* currLeaf = static_cast<ResourceLeaf*>(currNode->children[0].child);
1314 currLeaf->m_data.assign(data.begin(), data.end()); 1314 currLeaf->m_data.assign(data.begin(), data.end());
1315 } 1315 }
1316 1316
1317 /** 1317 /**
1318 * Gets the ID of a specific resource. 1318 * Gets the ID of a specific resource.
1319 * @param dwResTypeId Identifies the resource type of the resource. 1319 * @param dwResTypeId Identifies the resource type of the resource.
1320 * @param strResName Identifies the resource. 1320 * @param strResName Identifies the resource.
1321 * @return ID of the specified resource. 1321 * @return ID of the specified resource.
1322 **/ 1322 **/
1323 dword ResourceDirectory::getResourceId(dword dwResTypeId, const std::string& strResName) const 1323 dword ResourceDirectory::getResourceId(dword dwResTypeId, const std::string& strResName) const
1324 { 1324 {
1325 return getResourceIdT(dwResTypeId, strResName); 1325 return getResourceIdT(dwResTypeId, strResName);
1326 } 1326 }
1327 1327
1328 /** 1328 /**
1329 * Gets the ID of a specific resource. 1329 * Gets the ID of a specific resource.
1330 * @param strResTypeName Identifies the resource type of the resource. 1330 * @param strResTypeName Identifies the resource type of the resource.
1331 * @param strResName Identifies the resource. 1331 * @param strResName Identifies the resource.
1332 * @return ID of the specified resource. 1332 * @return ID of the specified resource.
1333 **/ 1333 **/
1334 dword ResourceDirectory::getResourceId(const std::string& strResTypeName, const std::string& strResName) const 1334 dword ResourceDirectory::getResourceId(const std::string& strResTypeName, const std::string& strResName) const
1335 { 1335 {
1336 return getResourceIdT(strResTypeName, strResName); 1336 return getResourceIdT(strResTypeName, strResName);
1337 } 1337 }
1338 1338
1339 /** 1339 /**
1340 * Gets the ID of a specific resource by index. 1340 * Gets the ID of a specific resource by index.
1341 * @param uiResTypeIndex Identifies the resource type of the resource. 1341 * @param uiResTypeIndex Identifies the resource type of the resource.
1342 * @param uiResIndex Identifies the resource. 1342 * @param uiResIndex Identifies the resource.
1343 * @return ID of the specified resource. 1343 * @return ID of the specified resource.
1344 **/ 1344 **/
1345 dword ResourceDirectory::getResourceIdByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex) const 1345 dword ResourceDirectory::getResourceIdByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex) const
1346 { 1346 {
1347 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiResTypeIndex].child); 1347 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiResTypeIndex].child);
1348 return currNode->children[uiResIndex].entry.irde.Name; 1348 return currNode->children[uiResIndex].entry.irde.Name;
1349 } 1349 }
1350 1350
1351 /** 1351 /**
1352 * Sets the ID of a specific resource. 1352 * Sets the ID of a specific resource.
1353 * @param dwResTypeId Identifies the resource type of the resource. 1353 * @param dwResTypeId Identifies the resource type of the resource.
1354 * @param dwResId Identifies the resource. 1354 * @param dwResId Identifies the resource.
1355 * @param dwNewResId New ID of the resource. 1355 * @param dwNewResId New ID of the resource.
1356 **/ 1356 **/
1357 void ResourceDirectory::setResourceId(dword dwResTypeId, dword dwResId, dword dwNewResId) 1357 void ResourceDirectory::setResourceId(dword dwResTypeId, dword dwResId, dword dwNewResId)
1358 { 1358 {
1359 setResourceIdT(dwResTypeId, dwResId, dwNewResId); 1359 setResourceIdT(dwResTypeId, dwResId, dwNewResId);
1360 } 1360 }
1361 1361
1362 /** 1362 /**
1363 * Sets the ID of a specific resource. 1363 * Sets the ID of a specific resource.
1364 * @param dwResTypeId Identifies the resource type of the resource. 1364 * @param dwResTypeId Identifies the resource type of the resource.
1365 * @param strResName Identifies the resource. 1365 * @param strResName Identifies the resource.
1366 * @param dwNewResId New ID of the resource. 1366 * @param dwNewResId New ID of the resource.
1367 **/ 1367 **/
1368 void ResourceDirectory::setResourceId(dword dwResTypeId, const std::string& strResName, dword dwNewResId) 1368 void ResourceDirectory::setResourceId(dword dwResTypeId, const std::string& strResName, dword dwNewResId)
1369 { 1369 {
1370 setResourceIdT(dwResTypeId, strResName, dwNewResId); 1370 setResourceIdT(dwResTypeId, strResName, dwNewResId);
1371 } 1371 }
1372 1372
1373 /** 1373 /**
1374 * Sets the ID of a specific resource. 1374 * Sets the ID of a specific resource.
1375 * @param strResTypeName Identifies the resource type of the resource. 1375 * @param strResTypeName Identifies the resource type of the resource.
1376 * @param dwResId Identifies the resource. 1376 * @param dwResId Identifies the resource.
1377 * @param dwNewResId New ID of the resource. 1377 * @param dwNewResId New ID of the resource.
1378 **/ 1378 **/
1379 void ResourceDirectory::setResourceId(const std::string& strResTypeName, dword dwResId, dword dwNewResId) 1379 void ResourceDirectory::setResourceId(const std::string& strResTypeName, dword dwResId, dword dwNewResId)
1380 { 1380 {
1381 setResourceIdT(strResTypeName, dwResId, dwNewResId); 1381 setResourceIdT(strResTypeName, dwResId, dwNewResId);
1382 } 1382 }
1383 1383
1384 /** 1384 /**
1385 * Sets the ID of a specific resource. 1385 * Sets the ID of a specific resource.
1386 * @param strResTypeName Identifies the resource type of the resource. 1386 * @param strResTypeName Identifies the resource type of the resource.
1387 * @param strResName Identifies the resource. 1387 * @param strResName Identifies the resource.
1388 * @param dwNewResId New ID of the resource. 1388 * @param dwNewResId New ID of the resource.
1389 **/ 1389 **/
1390 void ResourceDirectory::setResourceId(const std::string& strResTypeName, const std::string& strResName, dword dwNewResId) 1390 void ResourceDirectory::setResourceId(const std::string& strResTypeName, const std::string& strResName, dword dwNewResId)
1391 { 1391 {
1392 setResourceIdT(strResTypeName, strResName, dwNewResId); 1392 setResourceIdT(strResTypeName, strResName, dwNewResId);
1393 } 1393 }
1394 1394
1395 /** 1395 /**
1396 * Sets the ID of a specific resource by index. 1396 * Sets the ID of a specific resource by index.
1397 * @param uiResTypeIndex Identifies the resource type of the resource. 1397 * @param uiResTypeIndex Identifies the resource type of the resource.
1398 * @param uiResIndex Identifies the resource. 1398 * @param uiResIndex Identifies the resource.
1399 * @param dwNewResId New ID of the specified resource. 1399 * @param dwNewResId New ID of the specified resource.
1400 **/ 1400 **/
1401 void ResourceDirectory::setResourceIdByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, dword dwNewResId) 1401 void ResourceDirectory::setResourceIdByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, dword dwNewResId)
1402 { 1402 {
1403 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiResTypeIndex].child); 1403 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiResTypeIndex].child);
1404 currNode->children[uiResIndex].entry.irde.Name = dwNewResId; 1404 currNode->children[uiResIndex].entry.irde.Name = dwNewResId;
1405 } 1405 }
1406 1406
1407 /** 1407 /**
1408 * Gets the Name of a specific resource. 1408 * Gets the Name of a specific resource.
1409 * @param dwResTypeId Identifies the resource type of the resource. 1409 * @param dwResTypeId Identifies the resource type of the resource.
1410 * @param dwResId Identifies the resource. 1410 * @param dwResId Identifies the resource.
1411 * @return Name of the specified resource. 1411 * @return Name of the specified resource.
1412 **/ 1412 **/
1413 std::string ResourceDirectory::getResourceName(dword dwResTypeId, dword dwResId) const 1413 std::string ResourceDirectory::getResourceName(dword dwResTypeId, dword dwResId) const
1414 { 1414 {
1415 return getResourceNameT(dwResTypeId, dwResId); 1415 return getResourceNameT(dwResTypeId, dwResId);
1416 } 1416 }
1417 1417
1418 /** 1418 /**
1419 * Gets the Name of a specific resource. 1419 * Gets the Name of a specific resource.
1420 * @param strResTypeName Identifies the resource type of the resource. 1420 * @param strResTypeName Identifies the resource type of the resource.
1421 * @param dwResId Identifies the resource. 1421 * @param dwResId Identifies the resource.
1422 * @return Name of the specified resource. 1422 * @return Name of the specified resource.
1423 **/ 1423 **/
1424 std::string ResourceDirectory::getResourceName(const std::string& strResTypeName, dword dwResId) const 1424 std::string ResourceDirectory::getResourceName(const std::string& strResTypeName, dword dwResId) const
1425 { 1425 {
1426 return getResourceNameT(strResTypeName, dwResId); 1426 return getResourceNameT(strResTypeName, dwResId);
1427 } 1427 }
1428 1428
1429 /** 1429 /**
1430 * Gets the name of a specific resource by index. 1430 * Gets the name of a specific resource by index.
1431 * @param uiResTypeIndex Identifies the resource type of the resource. 1431 * @param uiResTypeIndex Identifies the resource type of the resource.
1432 * @param uiResIndex Identifies the resource. 1432 * @param uiResIndex Identifies the resource.
1433 * @return Name of the specified resource. 1433 * @return Name of the specified resource.
1434 **/ 1434 **/
1435 std::string ResourceDirectory::getResourceNameByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex) const 1435 std::string ResourceDirectory::getResourceNameByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex) const
1436 { 1436 {
1437 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiResTypeIndex].child); 1437 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiResTypeIndex].child);
1438 return currNode->children[uiResIndex].entry.wstrName; 1438 return currNode->children[uiResIndex].entry.wstrName;
1439 } 1439 }
1440 1440
1441 /** 1441 /**
1442 * Sets the name of a specific resource. 1442 * Sets the name of a specific resource.
1443 * @param dwResTypeId Identifies the resource type of the resource. 1443 * @param dwResTypeId Identifies the resource type of the resource.
1444 * @param dwResId Identifies the resource. 1444 * @param dwResId Identifies the resource.
1445 * @param strNewResName New name of the specified resource. 1445 * @param strNewResName New name of the specified resource.
1446 **/ 1446 **/
1447 void ResourceDirectory::setResourceName(dword dwResTypeId, dword dwResId, const std::string& strNewResName) 1447 void ResourceDirectory::setResourceName(dword dwResTypeId, dword dwResId, const std::string& strNewResName)
1448 { 1448 {
1449 setResourceNameT(dwResTypeId, dwResId, strNewResName); 1449 setResourceNameT(dwResTypeId, dwResId, strNewResName);
1450 } 1450 }
1451 1451
1452 /** 1452 /**
1453 * Sets the name of a specific resource. 1453 * Sets the name of a specific resource.
1454 * @param dwResTypeId Identifies the resource type of the resource. 1454 * @param dwResTypeId Identifies the resource type of the resource.
1455 * @param strResName Identifies the resource. 1455 * @param strResName Identifies the resource.
1456 * @param strNewResName New name of the specified resource. 1456 * @param strNewResName New name of the specified resource.
1457 **/ 1457 **/
1458 void ResourceDirectory::setResourceName(dword dwResTypeId, const std::string& strResName, const std::string& strNewResName) 1458 void ResourceDirectory::setResourceName(dword dwResTypeId, const std::string& strResName, const std::string& strNewResName)
1459 { 1459 {
1460 setResourceNameT(dwResTypeId, strResName, strNewResName); 1460 setResourceNameT(dwResTypeId, strResName, strNewResName);
1461 } 1461 }
1462 1462
1463 /** 1463 /**
1464 * Sets the name of a specific resource. 1464 * Sets the name of a specific resource.
1465 * @param strResTypeName Identifies the resource type of the resource. 1465 * @param strResTypeName Identifies the resource type of the resource.
1466 * @param dwResId Identifies the resource. 1466 * @param dwResId Identifies the resource.
1467 * @param strNewResName New name of the specified resource. 1467 * @param strNewResName New name of the specified resource.
1468 **/ 1468 **/
1469 void ResourceDirectory::setResourceName(const std::string& strResTypeName, dword dwResId, const std::string& strNewResName) 1469 void ResourceDirectory::setResourceName(const std::string& strResTypeName, dword dwResId, const std::string& strNewResName)
1470 { 1470 {
1471 setResourceNameT(strResTypeName, dwResId, strNewResName); 1471 setResourceNameT(strResTypeName, dwResId, strNewResName);
1472 } 1472 }
1473 1473
1474 /** 1474 /**
1475 * Sets the name of a specific resource. 1475 * Sets the name of a specific resource.
1476 * @param strResTypeName Identifies the resource type of the resource. 1476 * @param strResTypeName Identifies the resource type of the resource.
1477 * @param strResName Identifies the resource. 1477 * @param strResName Identifies the resource.
1478 * @param strNewResName New name of the specified resource. 1478 * @param strNewResName New name of the specified resource.
1479 **/ 1479 **/
1480 void ResourceDirectory::setResourceName(const std::string& strResTypeName, const std::string& strResName, const std::string& strNewResName) 1480 void ResourceDirectory::setResourceName(const std::string& strResTypeName, const std::string& strResName, const std::string& strNewResName)
1481 { 1481 {
1482 setResourceNameT(strResTypeName, strResName, strNewResName); 1482 setResourceNameT(strResTypeName, strResName, strNewResName);
1483 } 1483 }
1484 1484
1485 /** 1485 /**
1486 * Sets the name of a specific resource by index. 1486 * Sets the name of a specific resource by index.
1487 * @param uiResTypeIndex Identifies the resource type of the resource. 1487 * @param uiResTypeIndex Identifies the resource type of the resource.
1488 * @param uiResIndex Identifies the resource. 1488 * @param uiResIndex Identifies the resource.
1489 * @param strNewResName New name of the specified resource. 1489 * @param strNewResName New name of the specified resource.
1490 **/ 1490 **/
1491 void ResourceDirectory::setResourceNameByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, const std::string& strNewResName) 1491 void ResourceDirectory::setResourceNameByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, const std::string& strNewResName)
1492 { 1492 {
1493 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiResTypeIndex].child); 1493 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiResTypeIndex].child);
1494 currNode->children[uiResIndex].entry.wstrName = strNewResName; 1494 currNode->children[uiResIndex].entry.wstrName = strNewResName;
1495 } 1495 }
1496 1496
1497} 1497}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/ResourceDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/ResourceDirectory.h
index a0bba4c9b3..6a3dc3caef 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/ResourceDirectory.h
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/ResourceDirectory.h
@@ -1,735 +1,735 @@
1/* 1/*
2* ResourceDirectory.cpp - Part of the PeLib library. 2* ResourceDirectory.cpp - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#ifndef RESOURCEDIRECTORY_H 13#ifndef RESOURCEDIRECTORY_H
14#define RESOURCEDIRECTORY_H 14#define RESOURCEDIRECTORY_H
15 15
16#include "PeLibInc.h" 16#include "PeLibInc.h"
17 17
18namespace PeLib 18namespace PeLib
19{ 19{
20 class ResourceElement; 20 class ResourceElement;
21 21
22 /// The class ResourceChild is used to store information about a resource node. 22 /// The class ResourceChild is used to store information about a resource node.
23 class ResourceChild 23 class ResourceChild
24 { 24 {
25 friend class ResourceElement; 25 friend class ResourceElement;
26 friend class ResourceDirectory; 26 friend class ResourceDirectory;
27 friend class ResourceNode; 27 friend class ResourceNode;
28 friend class ResourceLeaf; 28 friend class ResourceLeaf;
29 29
30 /// Stores name and offset of a resource node. 30 /// Stores name and offset of a resource node.
31 PELIB_IMG_RES_DIR_ENTRY entry; 31 PELIB_IMG_RES_DIR_ENTRY entry;
32 /// A pointer to one of the node's child nodes. 32 /// A pointer to one of the node's child nodes.
33 ResourceElement* child; 33 ResourceElement* child;
34 34
35 public: 35 public:
36 /// Function which compares a resource ID to the node's resource ID. 36 /// Function which compares a resource ID to the node's resource ID.
37 bool equalId(dword wId) const; // EXPORT 37 bool equalId(dword wId) const; // EXPORT
38 /// Function which compares a string to the node's resource name. 38 /// Function which compares a string to the node's resource name.
39 bool equalName(std::string strName) const; // EXPORT 39 bool equalName(std::string strName) const; // EXPORT
40 /// Predicate that determines if a child is identified by name or by ID. 40 /// Predicate that determines if a child is identified by name or by ID.
41 bool isNamedResource() const; // EXPORT 41 bool isNamedResource() const; // EXPORT
42 /// Used for sorting a node's children. 42 /// Used for sorting a node's children.
43 bool operator<(const ResourceChild& rc) const; // EXPORT 43 bool operator<(const ResourceChild& rc) const; // EXPORT
44 /// Returns the size of a resource child. 44 /// Returns the size of a resource child.
45// unsigned int size() const; 45// unsigned int size() const;
46 46
47 /// Standard constructor. Does absolutely nothing. 47 /// Standard constructor. Does absolutely nothing.
48 ResourceChild(); 48 ResourceChild();
49 /// Makes a deep copy of a ResourceChild object. 49 /// Makes a deep copy of a ResourceChild object.
50 ResourceChild(const ResourceChild& rhs); 50 ResourceChild(const ResourceChild& rhs);
51 /// Makes a deep copy of a ResourceChild object. 51 /// Makes a deep copy of a ResourceChild object.
52 ResourceChild& operator=(const ResourceChild& rhs); 52 ResourceChild& operator=(const ResourceChild& rhs);
53 /// Deletes a ResourceChild object. 53 /// Deletes a ResourceChild object.
54 ~ResourceChild(); 54 ~ResourceChild();
55 }; 55 };
56 56
57 /// Base class for ResourceNode and ResourceLeaf, the elements of the resource tree. 57 /// Base class for ResourceNode and ResourceLeaf, the elements of the resource tree.
58 /// \todo write 58 /// \todo write
59 class ResourceElement 59 class ResourceElement
60 { 60 {
61 friend class ResourceChild; 61 friend class ResourceChild;
62 friend class ResourceNode; 62 friend class ResourceNode;
63 friend class ResourceLeaf; 63 friend class ResourceLeaf;
64 64
65 protected: 65 protected:
66 /// Stores RVA of the resource element in the file. 66 /// Stores RVA of the resource element in the file.
67 unsigned int uiElementRva; 67 unsigned int uiElementRva;
68 68
69 /// Reads the next resource element from the InputBuffer. 69 /// Reads the next resource element from the InputBuffer.
70 virtual int read(InputBuffer&, unsigned int, unsigned int/*, const std::string&*/) = 0; 70 virtual int read(InputBuffer&, unsigned int, unsigned int/*, const std::string&*/) = 0;
71 /// Writes the next resource element into the OutputBuffer. 71 /// Writes the next resource element into the OutputBuffer.
72 virtual void rebuild(OutputBuffer&, unsigned int&, unsigned int, const std::string&) const = 0; 72 virtual void rebuild(OutputBuffer&, unsigned int&, unsigned int, const std::string&) const = 0;
73 73
74 public: 74 public:
75 /// Returns the RVA of the element in the file. 75 /// Returns the RVA of the element in the file.
76 unsigned int getElementRva() const; // EXPORT 76 unsigned int getElementRva() const; // EXPORT
77 /// Indicates if the resource element is a leaf or a node. 77 /// Indicates if the resource element is a leaf or a node.
78 virtual bool isLeaf() const = 0; // EXPORT 78 virtual bool isLeaf() const = 0; // EXPORT
79 /// Corrects erroneous valeus in the ResourceElement. 79 /// Corrects erroneous valeus in the ResourceElement.
80 virtual void makeValid() = 0; // EXPORT 80 virtual void makeValid() = 0; // EXPORT
81 /// Returns the size of a resource element. 81 /// Returns the size of a resource element.
82// virtual unsigned int size() const = 0; 82// virtual unsigned int size() const = 0;
83 /// Necessary virtual destructor. 83 /// Necessary virtual destructor.
84 virtual ~ResourceElement() {} 84 virtual ~ResourceElement() {}
85 }; 85 };
86 86
87 /// ResourceLeafs represent the leafs of the resource tree: The actual resources. 87 /// ResourceLeafs represent the leafs of the resource tree: The actual resources.
88 class ResourceLeaf : public ResourceElement 88 class ResourceLeaf : public ResourceElement
89 { 89 {
90 friend class ResourceChild; 90 friend class ResourceChild;
91 friend class ResourceDirectory; 91 friend class ResourceDirectory;
92 template<typename T> friend struct fixNumberOfEntries; 92 template<typename T> friend struct fixNumberOfEntries;
93 93
94 private: 94 private:
95 /// The resource data. 95 /// The resource data.
96 std::vector<byte> m_data; 96 std::vector<byte> m_data;
97 /// PeLib equivalent of the Win32 structure IMAGE_RESOURCE_DATA_ENTRY 97 /// PeLib equivalent of the Win32 structure IMAGE_RESOURCE_DATA_ENTRY
98 PELIB_IMAGE_RESOURCE_DATA_ENTRY entry; 98 PELIB_IMAGE_RESOURCE_DATA_ENTRY entry;
99 99
100 protected: 100 protected:
101 int read(InputBuffer& inpBuffer, unsigned int uiOffset, unsigned int rva/*, const std::string&*/); 101 int read(InputBuffer& inpBuffer, unsigned int uiOffset, unsigned int rva/*, const std::string&*/);
102 /// Writes the next resource leaf into the OutputBuffer. 102 /// Writes the next resource leaf into the OutputBuffer.
103 void rebuild(OutputBuffer&, unsigned int& uiOffset, unsigned int uiRva, const std::string&) const; 103 void rebuild(OutputBuffer&, unsigned int& uiOffset, unsigned int uiRva, const std::string&) const;
104 104
105 public: 105 public:
106 /// Indicates if the resource element is a leaf or a node. 106 /// Indicates if the resource element is a leaf or a node.
107 bool isLeaf() const; // EXPORT 107 bool isLeaf() const; // EXPORT
108 /// Corrects erroneous valeus in the ResourceLeaf. 108 /// Corrects erroneous valeus in the ResourceLeaf.
109 void makeValid(); // EXPORT 109 void makeValid(); // EXPORT
110 /// Reads the next resource leaf from the InputBuffer. 110 /// Reads the next resource leaf from the InputBuffer.
111 /// Returns the size of a resource lead. 111 /// Returns the size of a resource lead.
112// unsigned int size() const; 112// unsigned int size() const;
113 113
114 /// Returns the resource data of this resource leaf. 114 /// Returns the resource data of this resource leaf.
115 std::vector<byte> getData() const; // EXPORT 115 std::vector<byte> getData() const; // EXPORT
116 /// Sets the resource data of this resource leaf. 116 /// Sets the resource data of this resource leaf.
117 void setData(const std::vector<byte>& vData); // EXPORT 117 void setData(const std::vector<byte>& vData); // EXPORT
118 118
119 /// Returns the OffsetToData value of this resource leaf. 119 /// Returns the OffsetToData value of this resource leaf.
120 dword getOffsetToData() const; // EXPORT 120 dword getOffsetToData() const; // EXPORT
121 /// Returns the Size value of this resource leaf. 121 /// Returns the Size value of this resource leaf.
122 dword getSize() const; // EXPORT 122 dword getSize() const; // EXPORT
123 /// Returns the CodePage value of this resource leaf. 123 /// Returns the CodePage value of this resource leaf.
124 dword getCodePage() const; // EXPORT 124 dword getCodePage() const; // EXPORT
125 /// Returns the Reserved value of this resource leaf. 125 /// Returns the Reserved value of this resource leaf.
126 dword getReserved() const; // EXPORT 126 dword getReserved() const; // EXPORT
127 127
128 /// Sets the OffsetToData value of this resource leaf. 128 /// Sets the OffsetToData value of this resource leaf.
129 void setOffsetToData(dword dwValue); // EXPORT 129 void setOffsetToData(dword dwValue); // EXPORT
130 /// Sets the Size value of this resource leaf. 130 /// Sets the Size value of this resource leaf.
131 void setSize(dword dwValue); // EXPORT 131 void setSize(dword dwValue); // EXPORT
132 /// Sets the CodePage value of this resource leaf. 132 /// Sets the CodePage value of this resource leaf.
133 void setCodePage(dword dwValue); // EXPORT 133 void setCodePage(dword dwValue); // EXPORT
134 /// Sets the Reserved value of this resource leaf. 134 /// Sets the Reserved value of this resource leaf.
135 void setReserved(dword dwValue); // EXPORT 135 void setReserved(dword dwValue); // EXPORT
136 }; 136 };
137 137
138 /// ResourceNodes represent the nodes in the resource tree. 138 /// ResourceNodes represent the nodes in the resource tree.
139 class ResourceNode : public ResourceElement 139 class ResourceNode : public ResourceElement
140 { 140 {
141 friend class ResourceChild; 141 friend class ResourceChild;
142 friend class ResourceDirectory; 142 friend class ResourceDirectory;
143 template<typename T> friend struct fixNumberOfEntries; 143 template<typename T> friend struct fixNumberOfEntries;
144 144
145 /// The node's children. 145 /// The node's children.
146 std::vector<ResourceChild> children; 146 std::vector<ResourceChild> children;
147 /// The node's header. Equivalent to IMAGE_RESOURCE_DIRECTORY from the Win32 API. 147 /// The node's header. Equivalent to IMAGE_RESOURCE_DIRECTORY from the Win32 API.
148 PELIB_IMAGE_RESOURCE_DIRECTORY header; 148 PELIB_IMAGE_RESOURCE_DIRECTORY header;
149 149
150 protected: 150 protected:
151 /// Reads the next resource node. 151 /// Reads the next resource node.
152 int read(InputBuffer& inpBuffer, unsigned int uiOffset, unsigned int rva/*, const std::string&*/); 152 int read(InputBuffer& inpBuffer, unsigned int uiOffset, unsigned int rva/*, const std::string&*/);
153 /// Writes the next resource node into the OutputBuffer. 153 /// Writes the next resource node into the OutputBuffer.
154 void rebuild(OutputBuffer&, unsigned int& uiOffset, unsigned int uiRva, const std::string&) const; 154 void rebuild(OutputBuffer&, unsigned int& uiOffset, unsigned int uiRva, const std::string&) const;
155 155
156 public: 156 public:
157 /// Indicates if the resource element is a leaf or a node. 157 /// Indicates if the resource element is a leaf or a node.
158 bool isLeaf() const; // EXPORT 158 bool isLeaf() const; // EXPORT
159 /// Corrects erroneous valeus in the ResourceNode. 159 /// Corrects erroneous valeus in the ResourceNode.
160 void makeValid(); // EXPORT 160 void makeValid(); // EXPORT
161 161
162 /// Returns the node's number of children. 162 /// Returns the node's number of children.
163 unsigned int getNumberOfChildren() const; // EXPORT 163 unsigned int getNumberOfChildren() const; // EXPORT
164 /// Adds another child to node. 164 /// Adds another child to node.
165 void addChild(); // EXPORT 165 void addChild(); // EXPORT
166 /// Returns a node's child. 166 /// Returns a node's child.
167 ResourceElement* getChild(unsigned int uiIndex); // EXPORT 167 ResourceElement* getChild(unsigned int uiIndex); // EXPORT
168 /// Removes a node's child. 168 /// Removes a node's child.
169 void removeChild(unsigned int uiIndex); // EXPORT 169 void removeChild(unsigned int uiIndex); // EXPORT
170 170
171 /// Returns the name of one of the node's children. 171 /// Returns the name of one of the node's children.
172 std::string getChildName(unsigned int uiIndex) const; // EXPORT 172 std::string getChildName(unsigned int uiIndex) const; // EXPORT
173 /// Returns the Name value of one of the node's children. 173 /// Returns the Name value of one of the node's children.
174 dword getOffsetToChildName(unsigned int uiIndex) const; // EXPORT 174 dword getOffsetToChildName(unsigned int uiIndex) const; // EXPORT
175 /// Returns the OffsetToData value of one of the node's children. 175 /// Returns the OffsetToData value of one of the node's children.
176 dword getOffsetToChildData(unsigned int uiIndex) const; // EXPORT 176 dword getOffsetToChildData(unsigned int uiIndex) const; // EXPORT
177 177
178 /// Sets the name of one of the node's children. 178 /// Sets the name of one of the node's children.
179 void setChildName(unsigned int uiIndex, const std::string& strNewName); // EXPORT 179 void setChildName(unsigned int uiIndex, const std::string& strNewName); // EXPORT
180 /// Sets the Name value of one of the node's children. 180 /// Sets the Name value of one of the node's children.
181 void setOffsetToChildName(unsigned int uiIndex, dword dwNewOffset); // EXPORT 181 void setOffsetToChildName(unsigned int uiIndex, dword dwNewOffset); // EXPORT
182 /// Sets the OffsetToData value of one of the node's children. 182 /// Sets the OffsetToData value of one of the node's children.
183 void setOffsetToChildData(unsigned int uiIndex, dword dwNewOffset); // EXPORT 183 void setOffsetToChildData(unsigned int uiIndex, dword dwNewOffset); // EXPORT
184 184
185 /// Returns the node's Characteristics value. 185 /// Returns the node's Characteristics value.
186 dword getCharacteristics() const; // EXPORT 186 dword getCharacteristics() const; // EXPORT
187 /// Returns the node's TimeDateStamp value. 187 /// Returns the node's TimeDateStamp value.
188 dword getTimeDateStamp() const; // EXPORT 188 dword getTimeDateStamp() const; // EXPORT
189 /// Returns the node's MajorVersion value. 189 /// Returns the node's MajorVersion value.
190 word getMajorVersion() const; // EXPORT 190 word getMajorVersion() const; // EXPORT
191 /// Returns the node's MinorVersion value. 191 /// Returns the node's MinorVersion value.
192 word getMinorVersion() const; // EXPORT 192 word getMinorVersion() const; // EXPORT
193 /// Returns the node's NumberOfNamedEntries value. 193 /// Returns the node's NumberOfNamedEntries value.
194 word getNumberOfNamedEntries() const; // EXPORT 194 word getNumberOfNamedEntries() const; // EXPORT
195 /// Returns the node's NumberOfIdEntries value. 195 /// Returns the node's NumberOfIdEntries value.
196 word getNumberOfIdEntries() const; // EXPORT 196 word getNumberOfIdEntries() const; // EXPORT
197 197
198 /// Sets the node's Characteristics value. 198 /// Sets the node's Characteristics value.
199 void setCharacteristics(dword value); // EXPORT 199 void setCharacteristics(dword value); // EXPORT
200 /// Sets the node's TimeDateStamp value. 200 /// Sets the node's TimeDateStamp value.
201 void setTimeDateStamp(dword value); // EXPORT 201 void setTimeDateStamp(dword value); // EXPORT
202 /// Sets the node's MajorVersion value. 202 /// Sets the node's MajorVersion value.
203 void setMajorVersion(word value); // EXPORT 203 void setMajorVersion(word value); // EXPORT
204 /// Sets the node's MinorVersion value. 204 /// Sets the node's MinorVersion value.
205 void setMinorVersion(word value); // EXPORT 205 void setMinorVersion(word value); // EXPORT
206 /// Sets the node's NumberOfNamedEntries value. 206 /// Sets the node's NumberOfNamedEntries value.
207 void setNumberOfNamedEntries(word value); // EXPORT 207 void setNumberOfNamedEntries(word value); // EXPORT
208 /// Sets the node's NumberOfIdEntries value. 208 /// Sets the node's NumberOfIdEntries value.
209 void setNumberOfIdEntries(word value); // EXPORT 209 void setNumberOfIdEntries(word value); // EXPORT
210 210
211 /// Returns the size of a resource node. 211 /// Returns the size of a resource node.
212// unsigned int size() const; 212// unsigned int size() const;
213 }; 213 };
214 214
215 /// Auxiliary functor which is used to search through the resource tree. 215 /// Auxiliary functor which is used to search through the resource tree.
216 /** 216 /**
217 * Traits class for the template functions of ResourceDirectory. 217 * Traits class for the template functions of ResourceDirectory.
218 * It's used to find out which function to use when searching for resource nodes or resource leafs 218 * It's used to find out which function to use when searching for resource nodes or resource leafs
219 * in a node's children vector. 219 * in a node's children vector.
220 **/ 220 **/
221 template<typename T> 221 template<typename T>
222 struct ResComparer 222 struct ResComparer
223 { 223 {
224 /// Pointer to a member function of ResourceChild 224 /// Pointer to a member function of ResourceChild
225 typedef bool(ResourceChild::*CompFunc)(T) const; 225 typedef bool(ResourceChild::*CompFunc)(T) const;
226 226
227 /// Return 0 for all unspecialized versions of ResComparer. 227 /// Return 0 for all unspecialized versions of ResComparer.
228 static CompFunc comp(); 228 static CompFunc comp();
229 }; 229 };
230 230
231 /// Auxiliary functor which is used to search through the resource tree. 231 /// Auxiliary functor which is used to search through the resource tree.
232 /** 232 /**
233 * ResComparer<dword> is used when a resource element is searched for by ID. 233 * ResComparer<dword> is used when a resource element is searched for by ID.
234 **/ 234 **/
235 template<> 235 template<>
236 struct ResComparer<dword> 236 struct ResComparer<dword>
237 { 237 {
238 /// Pointer to a member function of ResourceChild 238 /// Pointer to a member function of ResourceChild
239 typedef bool(ResourceChild::*CompFunc)(dword) const; 239 typedef bool(ResourceChild::*CompFunc)(dword) const;
240 240
241 /// Return the address of the ResourceChild member function that compares the ids of resource elements. 241 /// Return the address of the ResourceChild member function that compares the ids of resource elements.
242 static CompFunc comp() 242 static CompFunc comp()
243 { 243 {
244 return &ResourceChild::equalId; 244 return &ResourceChild::equalId;
245 } 245 }
246 }; 246 };
247 247
248 /// Auxiliary functor which is used to search through the resource tree. 248 /// Auxiliary functor which is used to search through the resource tree.
249 /** 249 /**
250 * This specializd version of ResComparer is used when a resource element is searched for by name. 250 * This specializd version of ResComparer is used when a resource element is searched for by name.
251 **/ 251 **/
252 template<> 252 template<>
253 struct ResComparer<std::string> 253 struct ResComparer<std::string>
254 { 254 {
255 /// Pointer to a member function of ResourceChild 255 /// Pointer to a member function of ResourceChild
256 typedef bool(ResourceChild::*CompFunc)(std::string) const; 256 typedef bool(ResourceChild::*CompFunc)(std::string) const;
257 257
258 /// Return the address of the ResourceChild member function that compares the names of resource elements. 258 /// Return the address of the ResourceChild member function that compares the names of resource elements.
259 static CompFunc comp() 259 static CompFunc comp()
260 { 260 {
261 return &ResourceChild::equalName; 261 return &ResourceChild::equalName;
262 } 262 }
263 }; 263 };
264 264
265 /// Unspecialized function that's used as base template for the specialized versions below. 265 /// Unspecialized function that's used as base template for the specialized versions below.
266 template<typename T> 266 template<typename T>
267 struct fixNumberOfEntries 267 struct fixNumberOfEntries
268 { 268 {
269 /// Fixes a resource node's header. 269 /// Fixes a resource node's header.
270 static void fix(ResourceNode*); 270 static void fix(ResourceNode*);
271 }; 271 };
272 272
273 /// Fixes NumberOfIdEntries value of a node. 273 /// Fixes NumberOfIdEntries value of a node.
274 template<> 274 template<>
275 struct fixNumberOfEntries<dword> 275 struct fixNumberOfEntries<dword>
276 { 276 {
277 /// Fixes a resource node's NumberOfIdEntries value. 277 /// Fixes a resource node's NumberOfIdEntries value.
278 static void fix(ResourceNode* node) 278 static void fix(ResourceNode* node)
279 { 279 {
280 node->header.NumberOfIdEntries = (unsigned int)node->children.size() - std::count_if(node->children.begin(), node->children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource)); 280 node->header.NumberOfIdEntries = (unsigned int)node->children.size() - std::count_if(node->children.begin(), node->children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource));
281 } 281 }
282 }; 282 };
283 283
284 /// Fixes NumberOfNamedEntries value of a node. 284 /// Fixes NumberOfNamedEntries value of a node.
285 template<> 285 template<>
286 struct fixNumberOfEntries<std::string> 286 struct fixNumberOfEntries<std::string>
287 { 287 {
288 /// Fixes a resource node's NumberOfNamedEntries value. 288 /// Fixes a resource node's NumberOfNamedEntries value.
289 static void fix(ResourceNode* node) 289 static void fix(ResourceNode* node)
290 { 290 {
291 node->header.NumberOfNamedEntries = static_cast<PeLib::word>(std::count_if(node->children.begin(), node->children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource))); 291 node->header.NumberOfNamedEntries = static_cast<PeLib::word>(std::count_if(node->children.begin(), node->children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource)));
292 } 292 }
293 }; 293 };
294 294
295 /// Class that represents the resource directory of a PE file. 295 /// Class that represents the resource directory of a PE file.
296 /** 296 /**
297 * The class ResourceDirectory represents the resource directory of a PE file. This class is fundamentally 297 * The class ResourceDirectory represents the resource directory of a PE file. This class is fundamentally
298 * different from the other classes of the PeLib library due to the structure of the ResourceDirectory. 298 * different from the other classes of the PeLib library due to the structure of the ResourceDirectory.
299 * For once, it's possible to manipulate the ResourceDirectory through a set of "high level" functions and 299 * For once, it's possible to manipulate the ResourceDirectory through a set of "high level" functions and
300 * and through a set of "low level" functions. The "high level" functions are the functions inside the 300 * and through a set of "low level" functions. The "high level" functions are the functions inside the
301 * ResourceDirectory class with the exception of getRoot.<br><br> 301 * ResourceDirectory class with the exception of getRoot.<br><br>
302 * getRoot on the other hand is the first "low level" function. Use it to retrieve the root node of the 302 * getRoot on the other hand is the first "low level" function. Use it to retrieve the root node of the
303 * resource tree. Then you can traverse through the tree and manipulate individual nodes and leafs 303 * resource tree. Then you can traverse through the tree and manipulate individual nodes and leafs
304 * directly using the functions provided by the classes ResourceNode and ResourceLeaf.<br><br> 304 * directly using the functions provided by the classes ResourceNode and ResourceLeaf.<br><br>
305 * There's another difference between the ResourceDirectory class and the other PeLib classes, which is 305 * There's another difference between the ResourceDirectory class and the other PeLib classes, which is
306 * once again caused by the special structure of the PE resource directory. The nodes of the resource 306 * once again caused by the special structure of the PE resource directory. The nodes of the resource
307 * tree must be in a certain order. Manipulating the resource tree does not directly sort the nodes 307 * tree must be in a certain order. Manipulating the resource tree does not directly sort the nodes
308 * correctly as this would cause more trouble than it fixes. That means it's your responsibility to 308 * correctly as this would cause more trouble than it fixes. That means it's your responsibility to
309 * fix the resource tree after manipulating it. PeLib makes the job easy for you, just call the 309 * fix the resource tree after manipulating it. PeLib makes the job easy for you, just call the
310 * ResourceDirectory::makeValid function.<br><br> 310 * ResourceDirectory::makeValid function.<br><br>
311 * You might also wonder why there's no size() function in this class. I did not forget it. It's just 311 * You might also wonder why there's no size() function in this class. I did not forget it. It's just
312 * that it's impossible to calculate the size of the resource directory without rebuilding it. So why 312 * that it's impossible to calculate the size of the resource directory without rebuilding it. So why
313 * should PeLib do this if you can do it just as easily by calling rebuild() and then checking the length 313 * should PeLib do this if you can do it just as easily by calling rebuild() and then checking the length
314 * of the returned vector.<br><br> 314 * of the returned vector.<br><br>
315 * There are also different ways to serialize (rebuild) the resource tree as it's not a fixed structure 315 * There are also different ways to serialize (rebuild) the resource tree as it's not a fixed structure
316 * that can easily be minimized like most other PE directories.<br><br> 316 * that can easily be minimized like most other PE directories.<br><br>
317 * This means it's entirely possible that the resource tree you read from a file differs from the one 317 * This means it's entirely possible that the resource tree you read from a file differs from the one
318 * PeLib creates. This might cause a minor issue. The original resource tree might be smaller (due to 318 * PeLib creates. This might cause a minor issue. The original resource tree might be smaller (due to
319 * different padding) so it's crucial that you check if there's enough space in the original resource 319 * different padding) so it's crucial that you check if there's enough space in the original resource
320 * directory before you write the rebuilt resource directory back to the file. 320 * directory before you write the rebuilt resource directory back to the file.
321 **/ 321 **/
322 class ResourceDirectory 322 class ResourceDirectory
323 { 323 {
324 private: 324 private:
325 /// The root node of the resource directory. 325 /// The root node of the resource directory.
326 ResourceNode m_rnRoot; 326 ResourceNode m_rnRoot;
327 327
328 // Prepare for some crazy syntax below to make Digital Mars happy. 328 // Prepare for some crazy syntax below to make Digital Mars happy.
329 329
330 /// Retrieves an iterator to a specified resource child. 330 /// Retrieves an iterator to a specified resource child.
331 template<typename S, typename T> 331 template<typename S, typename T>
332 std::vector<ResourceChild>::const_iterator locateResourceT(S restypeid, T resid) const; 332 std::vector<ResourceChild>::const_iterator locateResourceT(S restypeid, T resid) const;
333 333
334 /// Retrieves an iterator to a specified resource child. 334 /// Retrieves an iterator to a specified resource child.
335 template<typename S, typename T> 335 template<typename S, typename T>
336 std::vector<ResourceChild>::iterator locateResourceT(S restypeid, T resid); 336 std::vector<ResourceChild>::iterator locateResourceT(S restypeid, T resid);
337 337
338 /// Adds a new resource. 338 /// Adds a new resource.
339 template<typename S, typename T> 339 template<typename S, typename T>
340 int addResourceT(S restypeid, T resid, ResourceChild& rc); 340 int addResourceT(S restypeid, T resid, ResourceChild& rc);
341 341
342 /// Removes new resource. 342 /// Removes new resource.
343 template<typename S, typename T> 343 template<typename S, typename T>
344 int removeResourceT(S restypeid, T resid); 344 int removeResourceT(S restypeid, T resid);
345 345
346 /// Returns the data of a resource. 346 /// Returns the data of a resource.
347 template<typename S, typename T> 347 template<typename S, typename T>
348 int getResourceDataT(S restypeid, T resid, std::vector<byte>& data) const; 348 int getResourceDataT(S restypeid, T resid, std::vector<byte>& data) const;
349 349
350 /// Sets the data of a resource. 350 /// Sets the data of a resource.
351 template<typename S, typename T> 351 template<typename S, typename T>
352 int setResourceDataT(S restypeid, T resid, std::vector<byte>& data); 352 int setResourceDataT(S restypeid, T resid, std::vector<byte>& data);
353 353
354 /// Returns the ID of a resource. 354 /// Returns the ID of a resource.
355 template<typename S, typename T> 355 template<typename S, typename T>
356 dword getResourceIdT(S restypeid, T resid) const; 356 dword getResourceIdT(S restypeid, T resid) const;
357 357
358 /// Sets the ID of a resource. 358 /// Sets the ID of a resource.
359 template<typename S, typename T> 359 template<typename S, typename T>
360 int setResourceIdT(S restypeid, T resid, dword dwNewResId); 360 int setResourceIdT(S restypeid, T resid, dword dwNewResId);
361 361
362 /// Returns the name of a resource. 362 /// Returns the name of a resource.
363 template<typename S, typename T> 363 template<typename S, typename T>
364 std::string getResourceNameT(S restypeid, T resid) const; 364 std::string getResourceNameT(S restypeid, T resid) const;
365 365
366 /// Sets the name of a resource. 366 /// Sets the name of a resource.
367 template<typename S, typename T> 367 template<typename S, typename T>
368 int setResourceNameT(S restypeid, T resid, std::string strNewResName); 368 int setResourceNameT(S restypeid, T resid, std::string strNewResName);
369 369
370 public: 370 public:
371 ResourceNode* getRoot(); 371 ResourceNode* getRoot();
372 /// Corrects a erroneous resource directory. 372 /// Corrects a erroneous resource directory.
373 void makeValid(); 373 void makeValid();
374 /// Reads the resource directory from a file. 374 /// Reads the resource directory from a file.
375 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, unsigned int uiResDirRva); 375 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, unsigned int uiResDirRva);
376 /// Rebuilds the resource directory. 376 /// Rebuilds the resource directory.
377 void rebuild(std::vector<byte>& vBuffer, unsigned int uiRva) const; 377 void rebuild(std::vector<byte>& vBuffer, unsigned int uiRva) const;
378 /// Returns the size of the rebuilt resource directory. 378 /// Returns the size of the rebuilt resource directory.
379// unsigned int size() const; 379// unsigned int size() const;
380 /// Writes the resource directory to a file. 380 /// Writes the resource directory to a file.
381 int write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva) const; 381 int write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva) const;
382 382
383 /// Adds a new resource type. 383 /// Adds a new resource type.
384 int addResourceType(dword dwResTypeId); 384 int addResourceType(dword dwResTypeId);
385 /// Adds a new resource type. 385 /// Adds a new resource type.
386 int addResourceType(const std::string& strResTypeName); 386 int addResourceType(const std::string& strResTypeName);
387 387
388 /// Removes a resource type and all of it's resources. 388 /// Removes a resource type and all of it's resources.
389 int removeResourceType(dword dwResTypeId); 389 int removeResourceType(dword dwResTypeId);
390 /// Removes a resource type and all of it's resources. 390 /// Removes a resource type and all of it's resources.
391 int removeResourceType(const std::string& strResTypeName); 391 int removeResourceType(const std::string& strResTypeName);
392 392
393 /// Removes a resource type and all of it's resources. 393 /// Removes a resource type and all of it's resources.
394 int removeResourceTypeByIndex(unsigned int uiIndex); 394 int removeResourceTypeByIndex(unsigned int uiIndex);
395 395
396 /// Adds a new resource. 396 /// Adds a new resource.
397 int addResource(dword dwResTypeId, dword dwResId); 397 int addResource(dword dwResTypeId, dword dwResId);
398 /// Adds a new resource. 398 /// Adds a new resource.
399 int addResource(dword dwResTypeId, const std::string& strResName); 399 int addResource(dword dwResTypeId, const std::string& strResName);
400 /// Adds a new resource. 400 /// Adds a new resource.
401 int addResource(const std::string& strResTypeName, dword dwResId); 401 int addResource(const std::string& strResTypeName, dword dwResId);
402 /// Adds a new resource. 402 /// Adds a new resource.
403 int addResource(const std::string& strResTypeName, const std::string& strResName); 403 int addResource(const std::string& strResTypeName, const std::string& strResName);
404 404
405 /// Removes a resource. 405 /// Removes a resource.
406 int removeResource(dword dwResTypeId, dword dwResId); 406 int removeResource(dword dwResTypeId, dword dwResId);
407 /// Removes a resource. 407 /// Removes a resource.
408 int removeResource(dword dwResTypeId, const std::string& strResName); 408 int removeResource(dword dwResTypeId, const std::string& strResName);
409 /// Removes a resource. 409 /// Removes a resource.
410 int removeResource(const std::string& strResTypeName, dword dwResId); 410 int removeResource(const std::string& strResTypeName, dword dwResId);
411 /// Removes a resource. 411 /// Removes a resource.
412 int removeResource(const std::string& strResTypeName, const std::string& strResName); 412 int removeResource(const std::string& strResTypeName, const std::string& strResName);
413 413
414 /// Returns the number of resource types. 414 /// Returns the number of resource types.
415 unsigned int getNumberOfResourceTypes() const; 415 unsigned int getNumberOfResourceTypes() const;
416 416
417 /// Returns the ID of a resource type. 417 /// Returns the ID of a resource type.
418 dword getResourceTypeIdByIndex(unsigned int uiIndex) const; 418 dword getResourceTypeIdByIndex(unsigned int uiIndex) const;
419 /// Returns the name of a resource type. 419 /// Returns the name of a resource type.
420 std::string getResourceTypeNameByIndex(unsigned int uiIndex) const; 420 std::string getResourceTypeNameByIndex(unsigned int uiIndex) const;
421 421
422 /// Converts a resource type ID to an index. 422 /// Converts a resource type ID to an index.
423 int resourceTypeIdToIndex(dword dwResTypeId) const; 423 int resourceTypeIdToIndex(dword dwResTypeId) const;
424 /// Converts a resource type name to an index. 424 /// Converts a resource type name to an index.
425 int resourceTypeNameToIndex(const std::string& strResTypeName) const; 425 int resourceTypeNameToIndex(const std::string& strResTypeName) const;
426 426
427 /// Returns the number of resources of a certain resource type. 427 /// Returns the number of resources of a certain resource type.
428 unsigned int getNumberOfResources(dword dwId) const; 428 unsigned int getNumberOfResources(dword dwId) const;
429 /// Returns the number of resources of a certain resource type. 429 /// Returns the number of resources of a certain resource type.
430 unsigned int getNumberOfResources(const std::string& strResTypeName) const; 430 unsigned int getNumberOfResources(const std::string& strResTypeName) const;
431 431
432 /// Returns the number of resources of a certain resource type. 432 /// Returns the number of resources of a certain resource type.
433 unsigned int getNumberOfResourcesByIndex(unsigned int uiIndex) const; 433 unsigned int getNumberOfResourcesByIndex(unsigned int uiIndex) const;
434 434
435 /// Returns the data of a certain resource. 435 /// Returns the data of a certain resource.
436 void getResourceData(dword dwResTypeId, dword dwResId, std::vector<byte>& data) const; 436 void getResourceData(dword dwResTypeId, dword dwResId, std::vector<byte>& data) const;
437 /// Returns the data of a certain resource. 437 /// Returns the data of a certain resource.
438 void getResourceData(dword dwResTypeId, const std::string& strResName, std::vector<byte>& data) const; 438 void getResourceData(dword dwResTypeId, const std::string& strResName, std::vector<byte>& data) const;
439 /// Returns the data of a certain resource. 439 /// Returns the data of a certain resource.
440 void getResourceData(const std::string& strResTypeName, dword dwResId, std::vector<byte>& data) const; 440 void getResourceData(const std::string& strResTypeName, dword dwResId, std::vector<byte>& data) const;
441 /// Returns the data of a certain resource. 441 /// Returns the data of a certain resource.
442 void getResourceData(const std::string& strResTypeName, const std::string& strResName, std::vector<byte>& data) const; 442 void getResourceData(const std::string& strResTypeName, const std::string& strResName, std::vector<byte>& data) const;
443 443
444 /// Returns the data of a certain resource. 444 /// Returns the data of a certain resource.
445 void getResourceDataByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, std::vector<byte>& data) const; 445 void getResourceDataByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, std::vector<byte>& data) const;
446 446
447 /// Sets the data of a certain resource. 447 /// Sets the data of a certain resource.
448 void setResourceData(dword dwResTypeId, dword dwResId, std::vector<byte>& data); 448 void setResourceData(dword dwResTypeId, dword dwResId, std::vector<byte>& data);
449 /// Sets the data of a certain resource. 449 /// Sets the data of a certain resource.
450 void setResourceData(dword dwResTypeId, const std::string& strResName, std::vector<byte>& data); 450 void setResourceData(dword dwResTypeId, const std::string& strResName, std::vector<byte>& data);
451 /// Sets the data of a certain resource. 451 /// Sets the data of a certain resource.
452 void setResourceData(const std::string& strResTypeName, dword dwResId, std::vector<byte>& data); 452 void setResourceData(const std::string& strResTypeName, dword dwResId, std::vector<byte>& data);
453 /// Sets the data of a certain resource. 453 /// Sets the data of a certain resource.
454 void setResourceData(const std::string& strResTypeName, const std::string& strResName, std::vector<byte>& data); 454 void setResourceData(const std::string& strResTypeName, const std::string& strResName, std::vector<byte>& data);
455 455
456 /// Sets the data of a certain resource. 456 /// Sets the data of a certain resource.
457 void setResourceDataByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, std::vector<byte>& data); 457 void setResourceDataByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, std::vector<byte>& data);
458 458
459 /// Returns the ID of a certain resource. 459 /// Returns the ID of a certain resource.
460 dword getResourceId(dword dwResTypeId, const std::string& strResName) const; 460 dword getResourceId(dword dwResTypeId, const std::string& strResName) const;
461 /// Returns the ID of a certain resource. 461 /// Returns the ID of a certain resource.
462 dword getResourceId(const std::string& strResTypeName, const std::string& strResName) const; 462 dword getResourceId(const std::string& strResTypeName, const std::string& strResName) const;
463 463
464 /// Returns the ID of a certain resource. 464 /// Returns the ID of a certain resource.
465 dword getResourceIdByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex) const; 465 dword getResourceIdByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex) const;
466 466
467 /// Sets the ID of a certain resource. 467 /// Sets the ID of a certain resource.
468 void setResourceId(dword dwResTypeId, dword dwResId, dword dwNewResId); 468 void setResourceId(dword dwResTypeId, dword dwResId, dword dwNewResId);
469 /// Sets the ID of a certain resource. 469 /// Sets the ID of a certain resource.
470 void setResourceId(dword dwResTypeId, const std::string& strResName, dword dwNewResId); 470 void setResourceId(dword dwResTypeId, const std::string& strResName, dword dwNewResId);
471 /// Sets the ID of a certain resource. 471 /// Sets the ID of a certain resource.
472 void setResourceId(const std::string& strResTypeName, dword dwResId, dword dwNewResId); 472 void setResourceId(const std::string& strResTypeName, dword dwResId, dword dwNewResId);
473 /// Sets the ID of a certain resource. 473 /// Sets the ID of a certain resource.
474 void setResourceId(const std::string& strResTypeName, const std::string& strResName, dword dwNewResId); 474 void setResourceId(const std::string& strResTypeName, const std::string& strResName, dword dwNewResId);
475 475
476 /// Sets the ID of a certain resource. 476 /// Sets the ID of a certain resource.
477 void setResourceIdByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, dword dwNewResId); 477 void setResourceIdByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, dword dwNewResId);
478 478
479 /// Returns the name of a certain resource. 479 /// Returns the name of a certain resource.
480 std::string getResourceName(dword dwResTypeId, dword dwResId) const; 480 std::string getResourceName(dword dwResTypeId, dword dwResId) const;
481 /// Returns the name of a certain resource. 481 /// Returns the name of a certain resource.
482 std::string getResourceName(const std::string& strResTypeName, dword dwResId) const; 482 std::string getResourceName(const std::string& strResTypeName, dword dwResId) const;
483 483
484 /// Returns the name of a certain resource. 484 /// Returns the name of a certain resource.
485 std::string getResourceNameByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex) const; 485 std::string getResourceNameByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex) const;
486 486
487 /// Sets the name of a certain resource. 487 /// Sets the name of a certain resource.
488 void setResourceName(dword dwResTypeId, dword dwResId, const std::string& strNewResName); 488 void setResourceName(dword dwResTypeId, dword dwResId, const std::string& strNewResName);
489 /// Sets the name of a certain resource. 489 /// Sets the name of a certain resource.
490 void setResourceName(dword dwResTypeId, const std::string& strResName, const std::string& strNewResName); 490 void setResourceName(dword dwResTypeId, const std::string& strResName, const std::string& strNewResName);
491 /// Sets the name of a certain resource. 491 /// Sets the name of a certain resource.
492 void setResourceName(const std::string& strResTypeName, dword dwResId, const std::string& strNewResName); 492 void setResourceName(const std::string& strResTypeName, dword dwResId, const std::string& strNewResName);
493 /// Sets the name of a certain resource. 493 /// Sets the name of a certain resource.
494 void setResourceName(const std::string& strResTypeName, const std::string& strResName, const std::string& strNewResName); 494 void setResourceName(const std::string& strResTypeName, const std::string& strResName, const std::string& strNewResName);
495 495
496 /// Sets the name of a certain resource. 496 /// Sets the name of a certain resource.
497 void setResourceNameByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, const std::string& strNewResName); 497 void setResourceNameByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, const std::string& strNewResName);
498 }; 498 };
499 499
500 /** 500 /**
501 * Looks through the entire resource tree and returns a const_iterator to the resource specified 501 * Looks through the entire resource tree and returns a const_iterator to the resource specified
502 * by the parameters. 502 * by the parameters.
503 * @param restypeid Identifier of the resource type (either ID or name). 503 * @param restypeid Identifier of the resource type (either ID or name).
504 * @param resid Identifier of the resource (either ID or name). 504 * @param resid Identifier of the resource (either ID or name).
505 * @return A const_iterator to the specified resource. 505 * @return A const_iterator to the specified resource.
506 **/ 506 **/
507 template<typename S, typename T> 507 template<typename S, typename T>
508 std::vector<ResourceChild>::const_iterator ResourceDirectory::locateResourceT(S restypeid, T resid) const 508 std::vector<ResourceChild>::const_iterator ResourceDirectory::locateResourceT(S restypeid, T resid) const
509 { 509 {
510 typedef bool(ResourceChild::*CompFunc1)(S) const; 510 typedef bool(ResourceChild::*CompFunc1)(S) const;
511 typedef bool(ResourceChild::*CompFunc2)(T) const; 511 typedef bool(ResourceChild::*CompFunc2)(T) const;
512 512
513 CompFunc1 comp1 = ResComparer<S>::comp(); 513 CompFunc1 comp1 = ResComparer<S>::comp();
514 CompFunc2 comp2 = ResComparer<T>::comp(); 514 CompFunc2 comp2 = ResComparer<T>::comp();
515 515
516 std::vector<ResourceChild>::const_iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(comp1), restypeid)); 516 std::vector<ResourceChild>::const_iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(comp1), restypeid));
517 if (Iter == m_rnRoot.children.end()) 517 if (Iter == m_rnRoot.children.end())
518 { 518 {
519 return Iter; 519 return Iter;
520 } 520 }
521 521
522 ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child); 522 ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child);
523 std::vector<ResourceChild>::const_iterator ResIter = std::find_if(currNode->children.begin(), currNode->children.end(), std::bind2nd(std::mem_fun_ref(comp2), resid)); 523 std::vector<ResourceChild>::const_iterator ResIter = std::find_if(currNode->children.begin(), currNode->children.end(), std::bind2nd(std::mem_fun_ref(comp2), resid));
524 if (ResIter == currNode->children.end()) 524 if (ResIter == currNode->children.end())
525 { 525 {
526 return ResIter; 526 return ResIter;
527 } 527 }
528 528
529 return ResIter; 529 return ResIter;
530 } 530 }
531 531
532 /** 532 /**
533 * Looks through the entire resource tree and returns an iterator to the resource specified 533 * Looks through the entire resource tree and returns an iterator to the resource specified
534 * by the parameters. 534 * by the parameters.
535 * @param restypeid Identifier of the resource type (either ID or name). 535 * @param restypeid Identifier of the resource type (either ID or name).
536 * @param resid Identifier of the resource (either ID or name). 536 * @param resid Identifier of the resource (either ID or name).
537 * @return An iterator to the specified resource. 537 * @return An iterator to the specified resource.
538 **/ 538 **/
539 template<typename S, typename T> 539 template<typename S, typename T>
540 std::vector<ResourceChild>::iterator ResourceDirectory::locateResourceT(S restypeid, T resid) 540 std::vector<ResourceChild>::iterator ResourceDirectory::locateResourceT(S restypeid, T resid)
541 { 541 {
542 typedef bool(ResourceChild::*CompFunc1)(S) const; 542 typedef bool(ResourceChild::*CompFunc1)(S) const;
543 typedef bool(ResourceChild::*CompFunc2)(T) const; 543 typedef bool(ResourceChild::*CompFunc2)(T) const;
544 544
545 CompFunc1 comp1 = ResComparer<S>::comp(); 545 CompFunc1 comp1 = ResComparer<S>::comp();
546 CompFunc2 comp2 = ResComparer<T>::comp(); 546 CompFunc2 comp2 = ResComparer<T>::comp();
547 547
548 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(comp1), restypeid)); 548 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(comp1), restypeid));
549 if (Iter == m_rnRoot.children.end()) 549 if (Iter == m_rnRoot.children.end())
550 { 550 {
551 return Iter; 551 return Iter;
552 } 552 }
553 553
554 ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child); 554 ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child);
555 std::vector<ResourceChild>::iterator ResIter = std::find_if(currNode->children.begin(), currNode->children.end(), std::bind2nd(std::mem_fun_ref(comp2), resid)); 555 std::vector<ResourceChild>::iterator ResIter = std::find_if(currNode->children.begin(), currNode->children.end(), std::bind2nd(std::mem_fun_ref(comp2), resid));
556 if (ResIter == currNode->children.end()) 556 if (ResIter == currNode->children.end())
557 { 557 {
558 return ResIter; 558 return ResIter;
559 } 559 }
560 560
561 return ResIter; 561 return ResIter;
562 } 562 }
563 563
564 /** 564 /**
565 * Adds a new resource, resource type and ID are specified by the parameters. 565 * Adds a new resource, resource type and ID are specified by the parameters.
566 * @param restypeid Identifier of the resource type (either ID or name). 566 * @param restypeid Identifier of the resource type (either ID or name).
567 * @param resid Identifier of the resource (either ID or name). 567 * @param resid Identifier of the resource (either ID or name).
568 * @param rc ResourceChild that will be added. 568 * @param rc ResourceChild that will be added.
569 **/ 569 **/
570 template<typename S, typename T> 570 template<typename S, typename T>
571 int ResourceDirectory::addResourceT(S restypeid, T resid, ResourceChild& rc) 571 int ResourceDirectory::addResourceT(S restypeid, T resid, ResourceChild& rc)
572 { 572 {
573 typedef bool(ResourceChild::*CompFunc1)(S) const; 573 typedef bool(ResourceChild::*CompFunc1)(S) const;
574 typedef bool(ResourceChild::*CompFunc2)(T) const; 574 typedef bool(ResourceChild::*CompFunc2)(T) const;
575 575
576 CompFunc1 comp1 = ResComparer<S>::comp(); 576 CompFunc1 comp1 = ResComparer<S>::comp();
577 CompFunc2 comp2 = ResComparer<T>::comp(); 577 CompFunc2 comp2 = ResComparer<T>::comp();
578 578
579 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(comp1), restypeid)); 579 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(comp1), restypeid));
580 if (Iter == m_rnRoot.children.end()) 580 if (Iter == m_rnRoot.children.end())
581 { 581 {
582 return 1; 582 return 1;
583 // throw Exceptions::ResourceTypeDoesNotExist(ResourceDirectoryId, __LINE__); 583 // throw Exceptions::ResourceTypeDoesNotExist(ResourceDirectoryId, __LINE__);
584 } 584 }
585 585
586 ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child); 586 ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child);
587 std::vector<ResourceChild>::iterator ResIter = std::find_if(currNode->children.begin(), currNode->children.end(), std::bind2nd(std::mem_fun_ref(comp2), resid)); 587 std::vector<ResourceChild>::iterator ResIter = std::find_if(currNode->children.begin(), currNode->children.end(), std::bind2nd(std::mem_fun_ref(comp2), resid));
588 if (ResIter != currNode->children.end()) 588 if (ResIter != currNode->children.end())
589 { 589 {
590 return 1; 590 return 1;
591// throw Exceptions::EntryAlreadyExists(ResourceDirectoryId, __LINE__); 591// throw Exceptions::EntryAlreadyExists(ResourceDirectoryId, __LINE__);
592 } 592 }
593 593
594 rc.child = new ResourceNode; 594 rc.child = new ResourceNode;
595 ResourceChild rlnew; 595 ResourceChild rlnew;
596 rlnew.child = new ResourceLeaf; 596 rlnew.child = new ResourceLeaf;
597 ResourceNode* currNode2 = static_cast<ResourceNode*>(rc.child); 597 ResourceNode* currNode2 = static_cast<ResourceNode*>(rc.child);
598 currNode2->children.push_back(rlnew); 598 currNode2->children.push_back(rlnew);
599 currNode->children.push_back(rc); 599 currNode->children.push_back(rc);
600 600
601 fixNumberOfEntries<T>::fix(currNode); 601 fixNumberOfEntries<T>::fix(currNode);
602 fixNumberOfEntries<T>::fix(currNode2); 602 fixNumberOfEntries<T>::fix(currNode2);
603 603
604 return 0; 604 return 0;
605 } 605 }
606 606
607 /** 607 /**
608 * Removes a resource, resource type and ID are specified by the parameters. 608 * Removes a resource, resource type and ID are specified by the parameters.
609 * @param restypeid Identifier of the resource type (either ID or name). 609 * @param restypeid Identifier of the resource type (either ID or name).
610 * @param resid Identifier of the resource (either ID or name). 610 * @param resid Identifier of the resource (either ID or name).
611 **/ 611 **/
612 template<typename S, typename T> 612 template<typename S, typename T>
613 int ResourceDirectory::removeResourceT(S restypeid, T resid) 613 int ResourceDirectory::removeResourceT(S restypeid, T resid)
614 { 614 {
615 typedef bool(ResourceChild::*CompFunc1)(S) const; 615 typedef bool(ResourceChild::*CompFunc1)(S) const;
616 typedef bool(ResourceChild::*CompFunc2)(T) const; 616 typedef bool(ResourceChild::*CompFunc2)(T) const;
617 617
618 CompFunc1 comp1 = ResComparer<S>::comp(); 618 CompFunc1 comp1 = ResComparer<S>::comp();
619 CompFunc2 comp2 = ResComparer<T>::comp(); 619 CompFunc2 comp2 = ResComparer<T>::comp();
620 620
621 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(comp1), restypeid)); 621 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(comp1), restypeid));
622 if (Iter == m_rnRoot.children.end()) 622 if (Iter == m_rnRoot.children.end())
623 { 623 {
624 return 1; 624 return 1;
625 //throw Exceptions::ResourceTypeDoesNotExist(ResourceDirectoryId, __LINE__); 625 //throw Exceptions::ResourceTypeDoesNotExist(ResourceDirectoryId, __LINE__);
626 } 626 }
627 627
628 ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child); 628 ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child);
629 std::vector<ResourceChild>::iterator ResIter = std::find_if(currNode->children.begin(), currNode->children.end(), std::bind2nd(std::mem_fun_ref(comp2), resid)); 629 std::vector<ResourceChild>::iterator ResIter = std::find_if(currNode->children.begin(), currNode->children.end(), std::bind2nd(std::mem_fun_ref(comp2), resid));
630 if (ResIter == currNode->children.end()) 630 if (ResIter == currNode->children.end())
631 { 631 {
632 return 1; 632 return 1;
633 // throw Exceptions::InvalidName(ResourceDirectoryId, __LINE__); 633 // throw Exceptions::InvalidName(ResourceDirectoryId, __LINE__);
634 } 634 }
635 635
636 currNode->children.erase(ResIter); 636 currNode->children.erase(ResIter);
637 637
638 fixNumberOfEntries<T>::fix(currNode); 638 fixNumberOfEntries<T>::fix(currNode);
639 639
640 return 0; 640 return 0;
641 } 641 }
642 642
643 /** 643 /**
644 * Returns the data of a resource, resource type and ID are specified by the parameters. 644 * Returns the data of a resource, resource type and ID are specified by the parameters.
645 * @param restypeid Identifier of the resource type (either ID or name). 645 * @param restypeid Identifier of the resource type (either ID or name).
646 * @param resid Identifier of the resource (either ID or name). 646 * @param resid Identifier of the resource (either ID or name).
647 * @param data The data of the resource will be written into this vector. 647 * @param data The data of the resource will be written into this vector.
648 **/ 648 **/
649 template<typename S, typename T> 649 template<typename S, typename T>
650 int ResourceDirectory::getResourceDataT(S restypeid, T resid, std::vector<byte>& data) const 650 int ResourceDirectory::getResourceDataT(S restypeid, T resid, std::vector<byte>& data) const
651 { 651 {
652 std::vector<ResourceChild>::const_iterator ResIter = locateResourceT(restypeid, resid); 652 std::vector<ResourceChild>::const_iterator ResIter = locateResourceT(restypeid, resid);
653 ResourceNode* currNode = static_cast<ResourceNode*>(ResIter->child); 653 ResourceNode* currNode = static_cast<ResourceNode*>(ResIter->child);
654 ResourceLeaf* currLeaf = static_cast<ResourceLeaf*>(currNode->children[0].child); 654 ResourceLeaf* currLeaf = static_cast<ResourceLeaf*>(currNode->children[0].child);
655 data.assign(currLeaf->m_data.begin(), currLeaf->m_data.end()); 655 data.assign(currLeaf->m_data.begin(), currLeaf->m_data.end());
656 656
657 return 0; 657 return 0;
658 } 658 }
659 659
660 /** 660 /**
661 * Sets the data of a resource, resource type and ID are specified by the parameters. 661 * Sets the data of a resource, resource type and ID are specified by the parameters.
662 * @param restypeid Identifier of the resource type (either ID or name). 662 * @param restypeid Identifier of the resource type (either ID or name).
663 * @param resid Identifier of the resource (either ID or name). 663 * @param resid Identifier of the resource (either ID or name).
664 * @param data The new data of the resource is taken from this vector. 664 * @param data The new data of the resource is taken from this vector.
665 **/ 665 **/
666 template<typename S, typename T> 666 template<typename S, typename T>
667 int ResourceDirectory::setResourceDataT(S restypeid, T resid, std::vector<byte>& data) 667 int ResourceDirectory::setResourceDataT(S restypeid, T resid, std::vector<byte>& data)
668 { 668 {
669 std::vector<ResourceChild>::iterator ResIter = locateResourceT(restypeid, resid); 669 std::vector<ResourceChild>::iterator ResIter = locateResourceT(restypeid, resid);
670 ResourceNode* currNode = static_cast<ResourceNode*>(ResIter->child); 670 ResourceNode* currNode = static_cast<ResourceNode*>(ResIter->child);
671 ResourceLeaf* currLeaf = static_cast<ResourceLeaf*>(currNode->children[0].child); 671 ResourceLeaf* currLeaf = static_cast<ResourceLeaf*>(currNode->children[0].child);
672 currLeaf->m_data.assign(data.begin(), data.end()); 672 currLeaf->m_data.assign(data.begin(), data.end());
673 673
674 return 0; 674 return 0;
675 } 675 }
676 676
677 /** 677 /**
678 * Returns the id of a resource, resource type and ID are specified by the parameters. 678 * Returns the id of a resource, resource type and ID are specified by the parameters.
679 * Note: Calling this function with resid == the ID of the resource makes no sense at all. 679 * Note: Calling this function with resid == the ID of the resource makes no sense at all.
680 * @param restypeid Identifier of the resource type (either ID or name). 680 * @param restypeid Identifier of the resource type (either ID or name).
681 * @param resid Identifier of the resource (either ID or name). 681 * @param resid Identifier of the resource (either ID or name).
682 * @return The ID of the specified resource. 682 * @return The ID of the specified resource.
683 **/ 683 **/
684 template<typename S, typename T> 684 template<typename S, typename T>
685 dword ResourceDirectory::getResourceIdT(S restypeid, T resid) const 685 dword ResourceDirectory::getResourceIdT(S restypeid, T resid) const
686 { 686 {
687 std::vector<ResourceChild>::const_iterator ResIter = locateResourceT(restypeid, resid); 687 std::vector<ResourceChild>::const_iterator ResIter = locateResourceT(restypeid, resid);
688 return ResIter->entry.irde.Name; 688 return ResIter->entry.irde.Name;
689 } 689 }
690 690
691 /** 691 /**
692 * Sets the id of a resource, resource type and ID are specified by the parameters. 692 * Sets the id of a resource, resource type and ID are specified by the parameters.
693 * @param restypeid Identifier of the resource type (either ID or name). 693 * @param restypeid Identifier of the resource type (either ID or name).
694 * @param resid Identifier of the resource (either ID or name). 694 * @param resid Identifier of the resource (either ID or name).
695 * @param dwNewResId New ID of the resource. 695 * @param dwNewResId New ID of the resource.
696 **/ 696 **/
697 template<typename S, typename T> 697 template<typename S, typename T>
698 int ResourceDirectory::setResourceIdT(S restypeid, T resid, dword dwNewResId) 698 int ResourceDirectory::setResourceIdT(S restypeid, T resid, dword dwNewResId)
699 { 699 {
700 std::vector<ResourceChild>::iterator ResIter = locateResourceT(restypeid, resid); 700 std::vector<ResourceChild>::iterator ResIter = locateResourceT(restypeid, resid);
701 ResIter->entry.irde.Name = dwNewResId; 701 ResIter->entry.irde.Name = dwNewResId;
702 return 0; 702 return 0;
703 } 703 }
704 704
705 /** 705 /**
706 * Returns the name of a resource, resource type and ID are specified by the parameters. 706 * Returns the name of a resource, resource type and ID are specified by the parameters.
707 * Note: Calling this function with resid == the name of the resource makes no sense at all. 707 * Note: Calling this function with resid == the name of the resource makes no sense at all.
708 * @param restypeid Identifier of the resource type (either ID or name). 708 * @param restypeid Identifier of the resource type (either ID or name).
709 * @param resid Identifier of the resource (either ID or name). 709 * @param resid Identifier of the resource (either ID or name).
710 * @return The name of the specified resource. 710 * @return The name of the specified resource.
711 **/ 711 **/
712 template<typename S, typename T> 712 template<typename S, typename T>
713 std::string ResourceDirectory::getResourceNameT(S restypeid, T resid) const 713 std::string ResourceDirectory::getResourceNameT(S restypeid, T resid) const
714 { 714 {
715 std::vector<ResourceChild>::const_iterator ResIter = locateResourceT(restypeid, resid); 715 std::vector<ResourceChild>::const_iterator ResIter = locateResourceT(restypeid, resid);
716 return ResIter->entry.wstrName; 716 return ResIter->entry.wstrName;
717 } 717 }
718 718
719 /** 719 /**
720 * Sets the name of a resource, resource type and ID are specified by the parameters. 720 * Sets the name of a resource, resource type and ID are specified by the parameters.
721 * @param restypeid Identifier of the resource type (either ID or name). 721 * @param restypeid Identifier of the resource type (either ID or name).
722 * @param resid Identifier of the resource (either ID or name). 722 * @param resid Identifier of the resource (either ID or name).
723 * @param strNewResName The new name of the resource. 723 * @param strNewResName The new name of the resource.
724 **/ 724 **/
725 template<typename S, typename T> 725 template<typename S, typename T>
726 int ResourceDirectory::setResourceNameT(S restypeid, T resid, std::string strNewResName) 726 int ResourceDirectory::setResourceNameT(S restypeid, T resid, std::string strNewResName)
727 { 727 {
728 std::vector<ResourceChild>::iterator ResIter = locateResourceT(restypeid, resid); 728 std::vector<ResourceChild>::iterator ResIter = locateResourceT(restypeid, resid);
729 ResIter->entry.wstrName = strNewResName; 729 ResIter->entry.wstrName = strNewResName;
730 730
731 return 0; 731 return 0;
732 } 732 }
733} 733}
734 734
735#endif 735#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/TlsDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/TlsDirectory.h
index ebea929f94..8190e65c3c 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/TlsDirectory.h
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/TlsDirectory.h
@@ -1,304 +1,304 @@
1/* 1/*
2* TlsDirectory.h - Part of the PeLib library. 2* TlsDirectory.h - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#ifndef TLSDIRECTORY_H 13#ifndef TLSDIRECTORY_H
14#define TLSDIRECTORY_H 14#define TLSDIRECTORY_H
15 15
16namespace PeLib 16namespace PeLib
17{ 17{
18 /// Class that handles the TLS directory. 18 /// Class that handles the TLS directory.
19 /** 19 /**
20 * This class handles the TLS (Thread Local Storage) directory. 20 * This class handles the TLS (Thread Local Storage) directory.
21 **/ 21 **/
22 template<int bits> 22 template<int bits>
23 class TlsDirectory 23 class TlsDirectory
24 { 24 {
25 private: 25 private:
26 PELIB_IMAGE_TLS_DIRECTORY<bits> m_tls; ///< Structure that holds all information about the directory. 26 PELIB_IMAGE_TLS_DIRECTORY<bits> m_tls; ///< Structure that holds all information about the directory.
27 27
28 void read(InputBuffer& inputbuffer); 28 void read(InputBuffer& inputbuffer);
29 29
30 public: 30 public:
31 /// Reads a file's TLS directory. 31 /// Reads a file's TLS directory.
32 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize); // EXPORT 32 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize); // EXPORT
33 int read(unsigned char* buffer, unsigned int buffersize); // EXPORT 33 int read(unsigned char* buffer, unsigned int buffersize); // EXPORT
34 /// Rebuilds the TLS directory. 34 /// Rebuilds the TLS directory.
35 void rebuild(std::vector<byte>& vBuffer) const; // EXPORT 35 void rebuild(std::vector<byte>& vBuffer) const; // EXPORT
36 /// Returns the size of the TLS Directory. 36 /// Returns the size of the TLS Directory.
37 unsigned int size() const; // EXPORT 37 unsigned int size() const; // EXPORT
38 /// Writes the TLS directory to a file. 38 /// Writes the TLS directory to a file.
39 int write(const std::string& strFilename, unsigned int dwOffset) const; // EXPORT 39 int write(const std::string& strFilename, unsigned int dwOffset) const; // EXPORT
40 40
41 /// Returns the StartAddressOfRawData value of the TLS header. 41 /// Returns the StartAddressOfRawData value of the TLS header.
42 dword getStartAddressOfRawData() const; // EXPORT 42 dword getStartAddressOfRawData() const; // EXPORT
43 /// Returns the EndAddressOfRawData value of the TLS header. 43 /// Returns the EndAddressOfRawData value of the TLS header.
44 dword getEndAddressOfRawData() const; // EXPORT 44 dword getEndAddressOfRawData() const; // EXPORT
45 /// Returns the AddressOfIndex value of the TLS header. 45 /// Returns the AddressOfIndex value of the TLS header.
46 dword getAddressOfIndex() const; // EXPORT 46 dword getAddressOfIndex() const; // EXPORT
47 /// Returns the AddressOfCallBacks value of the TLS header. 47 /// Returns the AddressOfCallBacks value of the TLS header.
48 dword getAddressOfCallBacks() const; // EXPORT 48 dword getAddressOfCallBacks() const; // EXPORT
49 /// Returns the SizeOfZeroFill value of the TLS header. 49 /// Returns the SizeOfZeroFill value of the TLS header.
50 dword getSizeOfZeroFill() const; // EXPORT 50 dword getSizeOfZeroFill() const; // EXPORT
51 /// Returns the Characteristics value of the TLS header. 51 /// Returns the Characteristics value of the TLS header.
52 dword getCharacteristics() const; // EXPORT 52 dword getCharacteristics() const; // EXPORT
53 53
54 /// Sets the StartAddressOfRawData value of the TLS header. 54 /// Sets the StartAddressOfRawData value of the TLS header.
55 void setStartAddressOfRawData(dword dwValue); // EXPORT 55 void setStartAddressOfRawData(dword dwValue); // EXPORT
56 /// Sets the EndAddressOfRawData value of the TLS header. 56 /// Sets the EndAddressOfRawData value of the TLS header.
57 void setEndAddressOfRawData(dword dwValue); // EXPORT 57 void setEndAddressOfRawData(dword dwValue); // EXPORT
58 /// Sets the AddressOfIndex value of the TLS header. 58 /// Sets the AddressOfIndex value of the TLS header.
59 void setAddressOfIndex(dword dwValue); // EXPORT 59 void setAddressOfIndex(dword dwValue); // EXPORT
60 /// Sets the AddressOfCallBacks value of the TLS header. 60 /// Sets the AddressOfCallBacks value of the TLS header.
61 void setAddressOfCallBacks(dword dwValue); // EXPORT 61 void setAddressOfCallBacks(dword dwValue); // EXPORT
62 /// Sets the SizeOfZeroFill value of the TLS header. 62 /// Sets the SizeOfZeroFill value of the TLS header.
63 void setSizeOfZeroFill(dword dwValue); // EXPORT 63 void setSizeOfZeroFill(dword dwValue); // EXPORT
64 /// Sets the Characteristics value of the TLS header. 64 /// Sets the Characteristics value of the TLS header.
65 void setCharacteristics(dword dwValue); // EXPORT 65 void setCharacteristics(dword dwValue); // EXPORT
66 }; 66 };
67 67
68 template<int bits> 68 template<int bits>
69 void TlsDirectory<bits>::read(InputBuffer& inputBuffer) 69 void TlsDirectory<bits>::read(InputBuffer& inputBuffer)
70 { 70 {
71 PELIB_IMAGE_TLS_DIRECTORY<bits> itdCurr; 71 PELIB_IMAGE_TLS_DIRECTORY<bits> itdCurr;
72 72
73 inputBuffer >> itdCurr.StartAddressOfRawData; 73 inputBuffer >> itdCurr.StartAddressOfRawData;
74 inputBuffer >> itdCurr.EndAddressOfRawData; 74 inputBuffer >> itdCurr.EndAddressOfRawData;
75 inputBuffer >> itdCurr.AddressOfIndex; 75 inputBuffer >> itdCurr.AddressOfIndex;
76 inputBuffer >> itdCurr.AddressOfCallBacks; 76 inputBuffer >> itdCurr.AddressOfCallBacks;
77 inputBuffer >> itdCurr.SizeOfZeroFill; 77 inputBuffer >> itdCurr.SizeOfZeroFill;
78 inputBuffer >> itdCurr.Characteristics; 78 inputBuffer >> itdCurr.Characteristics;
79 79
80 std::swap(itdCurr, m_tls); 80 std::swap(itdCurr, m_tls);
81 } 81 }
82 82
83 template<int bits> 83 template<int bits>
84 int TlsDirectory<bits>::read(unsigned char* buffer, unsigned int buffersize) 84 int TlsDirectory<bits>::read(unsigned char* buffer, unsigned int buffersize)
85 { 85 {
86 if (buffersize < PELIB_IMAGE_TLS_DIRECTORY<bits>::size()) 86 if (buffersize < PELIB_IMAGE_TLS_DIRECTORY<bits>::size())
87 { 87 {
88 return ERROR_INVALID_FILE; 88 return ERROR_INVALID_FILE;
89 } 89 }
90 90
91 std::vector<byte> vTlsDirectory(buffer, buffer + buffersize); 91 std::vector<byte> vTlsDirectory(buffer, buffer + buffersize);
92 92
93 InputBuffer ibBuffer(vTlsDirectory); 93 InputBuffer ibBuffer(vTlsDirectory);
94 read(ibBuffer); 94 read(ibBuffer);
95 return NO_ERROR; 95 return NO_ERROR;
96 } 96 }
97 97
98 /** 98 /**
99 * Reads a file's TLS directory. 99 * Reads a file's TLS directory.
100 * @param strFilename Name of the file. 100 * @param strFilename Name of the file.
101 * @param uiOffset File offset of the TLS directory. 101 * @param uiOffset File offset of the TLS directory.
102 * @param uiSize Size of the TLS directory. 102 * @param uiSize Size of the TLS directory.
103 **/ 103 **/
104 template<int bits> 104 template<int bits>
105 int TlsDirectory<bits>::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize) 105 int TlsDirectory<bits>::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize)
106 { 106 {
107 std::ifstream ifFile(strFilename.c_str(), std::ios::binary); 107 std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
108 unsigned int ulFileSize = fileSize(ifFile); 108 unsigned int ulFileSize = fileSize(ifFile);
109 109
110 if (!ifFile) 110 if (!ifFile)
111 { 111 {
112 return ERROR_OPENING_FILE; 112 return ERROR_OPENING_FILE;
113 } 113 }
114 114
115 if (ulFileSize < uiOffset + uiSize) 115 if (ulFileSize < uiOffset + uiSize)
116 { 116 {
117 return ERROR_INVALID_FILE; 117 return ERROR_INVALID_FILE;
118 } 118 }
119 119
120 ifFile.seekg(uiOffset, std::ios::beg); 120 ifFile.seekg(uiOffset, std::ios::beg);
121 121
122 std::vector<byte> vTlsDirectory(uiSize); 122 std::vector<byte> vTlsDirectory(uiSize);
123 ifFile.read(reinterpret_cast<char*>(&vTlsDirectory[0]), uiSize); 123 ifFile.read(reinterpret_cast<char*>(&vTlsDirectory[0]), uiSize);
124 124
125 InputBuffer ibBuffer(vTlsDirectory); 125 InputBuffer ibBuffer(vTlsDirectory);
126 read(ibBuffer); 126 read(ibBuffer);
127 return NO_ERROR; 127 return NO_ERROR;
128 } 128 }
129 129
130 /** 130 /**
131 * Rebuilds the current TLS Directory. 131 * Rebuilds the current TLS Directory.
132 * @param vBuffer Buffer where the TLS directory will be written to. 132 * @param vBuffer Buffer where the TLS directory will be written to.
133 **/ 133 **/
134 template<int bits> 134 template<int bits>
135 void TlsDirectory<bits>::rebuild(std::vector<byte>& vBuffer) const 135 void TlsDirectory<bits>::rebuild(std::vector<byte>& vBuffer) const
136 { 136 {
137 OutputBuffer obBuffer(vBuffer); 137 OutputBuffer obBuffer(vBuffer);
138 138
139 obBuffer << m_tls.StartAddressOfRawData; 139 obBuffer << m_tls.StartAddressOfRawData;
140 obBuffer << m_tls.EndAddressOfRawData; 140 obBuffer << m_tls.EndAddressOfRawData;
141 obBuffer << m_tls.AddressOfIndex; 141 obBuffer << m_tls.AddressOfIndex;
142 obBuffer << m_tls.AddressOfCallBacks; 142 obBuffer << m_tls.AddressOfCallBacks;
143 obBuffer << m_tls.SizeOfZeroFill; 143 obBuffer << m_tls.SizeOfZeroFill;
144 obBuffer << m_tls.Characteristics; 144 obBuffer << m_tls.Characteristics;
145 } 145 }
146 146
147 /** 147 /**
148 * Returns the size of the TLS directory. Due to the static nature of this structure the return value 148 * Returns the size of the TLS directory. Due to the static nature of this structure the return value
149 * will always be 24. 149 * will always be 24.
150 * @return Size in bytes. 150 * @return Size in bytes.
151 **/ 151 **/
152 template<int bits> 152 template<int bits>
153 unsigned int TlsDirectory<bits>::size() const 153 unsigned int TlsDirectory<bits>::size() const
154 { 154 {
155 return PELIB_IMAGE_TLS_DIRECTORY<bits>::size(); 155 return PELIB_IMAGE_TLS_DIRECTORY<bits>::size();
156 } 156 }
157 157
158 /** 158 /**
159 * @param strFilename Name of the file. 159 * @param strFilename Name of the file.
160 * @param dwOffset File offset the TLS Directory will be written to. 160 * @param dwOffset File offset the TLS Directory will be written to.
161 **/ 161 **/
162 template<int bits> 162 template<int bits>
163 int TlsDirectory<bits>::write(const std::string& strFilename, unsigned int dwOffset) const 163 int TlsDirectory<bits>::write(const std::string& strFilename, unsigned int dwOffset) const
164 { 164 {
165 std::fstream ofFile(strFilename.c_str(), std::ios_base::in); 165 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
166 166
167 if (!ofFile) 167 if (!ofFile)
168 { 168 {
169 ofFile.clear(); 169 ofFile.clear();
170 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary); 170 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
171 } 171 }
172 else 172 else
173 { 173 {
174 ofFile.close(); 174 ofFile.close();
175 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary); 175 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
176 } 176 }
177 177
178 if (!ofFile) 178 if (!ofFile)
179 { 179 {
180 return ERROR_OPENING_FILE; 180 return ERROR_OPENING_FILE;
181 } 181 }
182 182
183 ofFile.seekp(dwOffset, std::ios::beg); 183 ofFile.seekp(dwOffset, std::ios::beg);
184 184
185 std::vector<unsigned char> vBuffer; 185 std::vector<unsigned char> vBuffer;
186 rebuild(vBuffer); 186 rebuild(vBuffer);
187 187
188 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), vBuffer.size()); 188 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), vBuffer.size());
189 189
190 ofFile.close(); 190 ofFile.close();
191 191
192 return NO_ERROR; 192 return NO_ERROR;
193 } 193 }
194 194
195 /** 195 /**
196 * @return The StartAddressOfRawData value of the TLS directory. 196 * @return The StartAddressOfRawData value of the TLS directory.
197 **/ 197 **/
198 template<int bits> 198 template<int bits>
199 dword TlsDirectory<bits>::getStartAddressOfRawData() const 199 dword TlsDirectory<bits>::getStartAddressOfRawData() const
200 { 200 {
201 return m_tls.StartAddressOfRawData; 201 return m_tls.StartAddressOfRawData;
202 } 202 }
203 203
204 /** 204 /**
205 * @return The EndAddressOfRawData value of the TLS directory. 205 * @return The EndAddressOfRawData value of the TLS directory.
206 **/ 206 **/
207 template<int bits> 207 template<int bits>
208 dword TlsDirectory<bits>::getEndAddressOfRawData() const 208 dword TlsDirectory<bits>::getEndAddressOfRawData() const
209 { 209 {
210 return m_tls.EndAddressOfRawData; 210 return m_tls.EndAddressOfRawData;
211 } 211 }
212 212
213 /** 213 /**
214 * @return The AddressOfIndex value of the TLS directory. 214 * @return The AddressOfIndex value of the TLS directory.
215 **/ 215 **/
216 template<int bits> 216 template<int bits>
217 dword TlsDirectory<bits>::getAddressOfIndex() const 217 dword TlsDirectory<bits>::getAddressOfIndex() const
218 { 218 {
219 return m_tls.AddressOfIndex; 219 return m_tls.AddressOfIndex;
220 } 220 }
221 221
222 /** 222 /**
223 * @return The AddressOfCallBacks value of the TLS directory. 223 * @return The AddressOfCallBacks value of the TLS directory.
224 **/ 224 **/
225 template<int bits> 225 template<int bits>
226 dword TlsDirectory<bits>::getAddressOfCallBacks() const 226 dword TlsDirectory<bits>::getAddressOfCallBacks() const
227 { 227 {
228 return m_tls.AddressOfCallBacks; 228 return m_tls.AddressOfCallBacks;
229 } 229 }
230 230
231 /** 231 /**
232 * @return The SizeOfZeroFill value of the TLS directory. 232 * @return The SizeOfZeroFill value of the TLS directory.
233 **/ 233 **/
234 template<int bits> 234 template<int bits>
235 dword TlsDirectory<bits>::getSizeOfZeroFill() const 235 dword TlsDirectory<bits>::getSizeOfZeroFill() const
236 { 236 {
237 return m_tls.SizeOfZeroFill; 237 return m_tls.SizeOfZeroFill;
238 } 238 }
239 239
240 /** 240 /**
241 * @return The Characteristics value of the TLS directory. 241 * @return The Characteristics value of the TLS directory.
242 **/ 242 **/
243 template<int bits> 243 template<int bits>
244 dword TlsDirectory<bits>::getCharacteristics() const 244 dword TlsDirectory<bits>::getCharacteristics() const
245 { 245 {
246 return m_tls.Characteristics; 246 return m_tls.Characteristics;
247 } 247 }
248 248
249 /** 249 /**
250 * @param dwValue The new StartAddressOfRawData value of the TLS directory. 250 * @param dwValue The new StartAddressOfRawData value of the TLS directory.
251 **/ 251 **/
252 template<int bits> 252 template<int bits>
253 void TlsDirectory<bits>::setStartAddressOfRawData(dword dwValue) 253 void TlsDirectory<bits>::setStartAddressOfRawData(dword dwValue)
254 { 254 {
255 m_tls.StartAddressOfRawData = dwValue; 255 m_tls.StartAddressOfRawData = dwValue;
256 } 256 }
257 257
258 /** 258 /**
259 * @param dwValue The new EndAddressOfRawData value of the TLS directory. 259 * @param dwValue The new EndAddressOfRawData value of the TLS directory.
260 **/ 260 **/
261 template<int bits> 261 template<int bits>
262 void TlsDirectory<bits>::setEndAddressOfRawData(dword dwValue) 262 void TlsDirectory<bits>::setEndAddressOfRawData(dword dwValue)
263 { 263 {
264 m_tls.EndAddressOfRawData = dwValue; 264 m_tls.EndAddressOfRawData = dwValue;
265 } 265 }
266 266
267 /** 267 /**
268 * @param dwValue The new AddressOfIndex value of the TLS directory. 268 * @param dwValue The new AddressOfIndex value of the TLS directory.
269 **/ 269 **/
270 template<int bits> 270 template<int bits>
271 void TlsDirectory<bits>::setAddressOfIndex(dword dwValue) 271 void TlsDirectory<bits>::setAddressOfIndex(dword dwValue)
272 { 272 {
273 m_tls.AddressOfIndex = dwValue; 273 m_tls.AddressOfIndex = dwValue;
274 } 274 }
275 275
276 /** 276 /**
277 * @param dwValue The new AddressOfCallBacks value of the TLS directory. 277 * @param dwValue The new AddressOfCallBacks value of the TLS directory.
278 **/ 278 **/
279 template<int bits> 279 template<int bits>
280 void TlsDirectory<bits>::setAddressOfCallBacks(dword dwValue) 280 void TlsDirectory<bits>::setAddressOfCallBacks(dword dwValue)
281 { 281 {
282 m_tls.AddressOfCallBacks = dwValue; 282 m_tls.AddressOfCallBacks = dwValue;
283 } 283 }
284 284
285 /** 285 /**
286 * @param dwValue The new SizeOfZeroFill value of the TLS directory. 286 * @param dwValue The new SizeOfZeroFill value of the TLS directory.
287 **/ 287 **/
288 template<int bits> 288 template<int bits>
289 void TlsDirectory<bits>::setSizeOfZeroFill(dword dwValue) 289 void TlsDirectory<bits>::setSizeOfZeroFill(dword dwValue)
290 { 290 {
291 m_tls.SizeOfZeroFill = dwValue; 291 m_tls.SizeOfZeroFill = dwValue;
292 } 292 }
293 293
294 /** 294 /**
295 * @param dwValue The new Characteristics value of the TLS directory. 295 * @param dwValue The new Characteristics value of the TLS directory.
296 **/ 296 **/
297 template<int bits> 297 template<int bits>
298 void TlsDirectory<bits>::setCharacteristics(dword dwValue) 298 void TlsDirectory<bits>::setCharacteristics(dword dwValue)
299 { 299 {
300 m_tls.Characteristics = dwValue; 300 m_tls.Characteristics = dwValue;
301 } 301 }
302 302
303} 303}
304#endif 304#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/buffer/InputBuffer.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/buffer/InputBuffer.cpp
index ae2584edb1..579b152659 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/buffer/InputBuffer.cpp
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/buffer/InputBuffer.cpp
@@ -1,58 +1,58 @@
1/* 1/*
2* InputBuffer.cpp - Part of the PeLib library. 2* InputBuffer.cpp - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#include "InputBuffer.h" 13#include "InputBuffer.h"
14 14
15namespace PeLib 15namespace PeLib
16{ 16{
17 unsigned long InputBuffer::get() 17 unsigned long InputBuffer::get()
18 { 18 {
19 return ulIndex; 19 return ulIndex;
20 } 20 }
21 21
22 InputBuffer::InputBuffer(std::vector<unsigned char>& vBuffer) : m_vBuffer(vBuffer), ulIndex(0) 22 InputBuffer::InputBuffer(std::vector<unsigned char>& vBuffer) : m_vBuffer(vBuffer), ulIndex(0)
23 { 23 {
24 } 24 }
25 25
26 const unsigned char* InputBuffer::data() const 26 const unsigned char* InputBuffer::data() const
27 { 27 {
28 return &m_vBuffer[0]; 28 return &m_vBuffer[0];
29 } 29 }
30 30
31 unsigned long InputBuffer::size() 31 unsigned long InputBuffer::size()
32 { 32 {
33 return static_cast<unsigned long>(m_vBuffer.size()); 33 return static_cast<unsigned long>(m_vBuffer.size());
34 } 34 }
35 35
36 void InputBuffer::read(char* lpBuffer, unsigned long ulSize) 36 void InputBuffer::read(char* lpBuffer, unsigned long ulSize)
37 { 37 {
38 std::copy(&m_vBuffer[ulIndex], &m_vBuffer[ulIndex + ulSize], lpBuffer); 38 std::copy(&m_vBuffer[ulIndex], &m_vBuffer[ulIndex + ulSize], lpBuffer);
39 ulIndex += ulSize; 39 ulIndex += ulSize;
40 } 40 }
41 41
42 void InputBuffer::reset() 42 void InputBuffer::reset()
43 { 43 {
44 m_vBuffer.clear(); 44 m_vBuffer.clear();
45 } 45 }
46 46
47 void InputBuffer::set(unsigned long ulIndex) 47 void InputBuffer::set(unsigned long ulIndex)
48 { 48 {
49 this->ulIndex = ulIndex; 49 this->ulIndex = ulIndex;
50 } 50 }
51 51
52 void InputBuffer::setBuffer(std::vector<unsigned char>& vBuffer) 52 void InputBuffer::setBuffer(std::vector<unsigned char>& vBuffer)
53 { 53 {
54 m_vBuffer = vBuffer; 54 m_vBuffer = vBuffer;
55 ulIndex = 0; 55 ulIndex = 0;
56 } 56 }
57} 57}
58 58
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/buffer/InputBuffer.h b/utils/zenutils/libraries/pelib-0.9/pelib/buffer/InputBuffer.h
index fc5a14e357..18a7b1b7bc 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/buffer/InputBuffer.h
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/buffer/InputBuffer.h
@@ -1,52 +1,52 @@
1/* 1/*
2* InputBuffer.h - Part of the PeLib library. 2* InputBuffer.h - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#ifndef INPUTBUFFER_H 13#ifndef INPUTBUFFER_H
14#define INPUTBUFFER_H 14#define INPUTBUFFER_H
15 15
16#include <vector> 16#include <vector>
17#include <iterator> 17#include <iterator>
18#include <cassert> 18#include <cassert>
19 19
20namespace PeLib 20namespace PeLib
21{ 21{
22 class InputBuffer 22 class InputBuffer
23 { 23 {
24 private: 24 private:
25 std::vector<unsigned char>& m_vBuffer; 25 std::vector<unsigned char>& m_vBuffer;
26 unsigned long ulIndex; 26 unsigned long ulIndex;
27 27
28 public: 28 public:
29 InputBuffer(std::vector<unsigned char>& vBuffer); 29 InputBuffer(std::vector<unsigned char>& vBuffer);
30 30
31 const unsigned char* data() const; 31 const unsigned char* data() const;
32 unsigned long size(); 32 unsigned long size();
33 33
34 template<typename T> 34 template<typename T>
35 InputBuffer& operator>>(T& value) 35 InputBuffer& operator>>(T& value)
36 { 36 {
37 assert(ulIndex + sizeof(value) <= m_vBuffer.size()); 37 assert(ulIndex + sizeof(value) <= m_vBuffer.size());
38 value = *(T*)(&m_vBuffer[ulIndex]);//reinterpret_cast<T*>(&m_vBuffer[ulIndex]); 38 value = *(T*)(&m_vBuffer[ulIndex]);//reinterpret_cast<T*>(&m_vBuffer[ulIndex]);
39 ulIndex += sizeof(T); 39 ulIndex += sizeof(T);
40 return *this; 40 return *this;
41 } 41 }
42 42
43 void read(char* lpBuffer, unsigned long ulSize); 43 void read(char* lpBuffer, unsigned long ulSize);
44 void reset(); 44 void reset();
45 void set(unsigned long ulIndex); 45 void set(unsigned long ulIndex);
46 unsigned long get(); 46 unsigned long get();
47 void setBuffer(std::vector<unsigned char>& vBuffer); 47 void setBuffer(std::vector<unsigned char>& vBuffer);
48// void updateData(unsigned long ulIndex, 48// void updateData(unsigned long ulIndex,
49 }; 49 };
50} 50}
51 51
52#endif 52#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/buffer/OutputBuffer.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/buffer/OutputBuffer.cpp
index b47fbb6ff8..4ad8471d83 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/buffer/OutputBuffer.cpp
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/buffer/OutputBuffer.cpp
@@ -1,41 +1,41 @@
1/* 1/*
2* OutputBuffer.cpp - Part of the PeLib library. 2* OutputBuffer.cpp - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#include "OutputBuffer.h" 13#include "OutputBuffer.h"
14 14
15namespace PeLib 15namespace PeLib
16{ 16{
17 OutputBuffer::OutputBuffer(std::vector<unsigned char>& vBuffer) : m_vBuffer(vBuffer) 17 OutputBuffer::OutputBuffer(std::vector<unsigned char>& vBuffer) : m_vBuffer(vBuffer)
18 { 18 {
19 m_vBuffer.clear(); 19 m_vBuffer.clear();
20 } 20 }
21 21
22 const unsigned char* OutputBuffer::data() const 22 const unsigned char* OutputBuffer::data() const
23 { 23 {
24 return &m_vBuffer[0]; 24 return &m_vBuffer[0];
25 } 25 }
26 26
27 unsigned long OutputBuffer::size() 27 unsigned long OutputBuffer::size()
28 { 28 {
29 return static_cast<unsigned long>(m_vBuffer.size()); 29 return static_cast<unsigned long>(m_vBuffer.size());
30 } 30 }
31 31
32 void OutputBuffer::add(const char* lpBuffer, unsigned long ulSize) 32 void OutputBuffer::add(const char* lpBuffer, unsigned long ulSize)
33 { 33 {
34 std::copy(lpBuffer, lpBuffer + ulSize, std::back_inserter(m_vBuffer)); 34 std::copy(lpBuffer, lpBuffer + ulSize, std::back_inserter(m_vBuffer));
35 } 35 }
36 36
37 void OutputBuffer::reset() 37 void OutputBuffer::reset()
38 { 38 {
39 m_vBuffer.clear(); 39 m_vBuffer.clear();
40 } 40 }
41} 41}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/buffer/OutputBuffer.h b/utils/zenutils/libraries/pelib-0.9/pelib/buffer/OutputBuffer.h
index f1ab99039b..06049ddd9d 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/buffer/OutputBuffer.h
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/buffer/OutputBuffer.h
@@ -1,51 +1,51 @@
1/* 1/*
2* OutputBuffer.h - Part of the PeLib library. 2* OutputBuffer.h - Part of the PeLib library.
3* 3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com) 4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved. 5* All rights reserved.
6* 6*
7* This software is licensed under the zlib/libpng License. 7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php 8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory 9* or the license information file (license.htm) in the root directory
10* of PeLib. 10* of PeLib.
11*/ 11*/
12 12
13#ifndef OUTPUTBUFFER_H 13#ifndef OUTPUTBUFFER_H
14#define OUTPUTBUFFER_H 14#define OUTPUTBUFFER_H
15 15
16#include <vector> 16#include <vector>
17#include <iterator> 17#include <iterator>
18 18
19namespace PeLib 19namespace PeLib
20{ 20{
21 class OutputBuffer 21 class OutputBuffer
22 { 22 {
23 private: 23 private:
24 std::vector<unsigned char>& m_vBuffer; 24 std::vector<unsigned char>& m_vBuffer;
25 25
26 public: 26 public:
27 OutputBuffer(std::vector<unsigned char>& vBuffer); 27 OutputBuffer(std::vector<unsigned char>& vBuffer);
28 const unsigned char* data() const; 28 const unsigned char* data() const;
29 unsigned long size(); 29 unsigned long size();
30 30
31 template<typename T> 31 template<typename T>
32 OutputBuffer& operator<<(const T& value) 32 OutputBuffer& operator<<(const T& value)
33 { 33 {
34 const unsigned char* p = reinterpret_cast<const unsigned char*>(&value); 34 const unsigned char* p = reinterpret_cast<const unsigned char*>(&value);
35 std::copy(p, p + sizeof(value), std::back_inserter(m_vBuffer)); 35 std::copy(p, p + sizeof(value), std::back_inserter(m_vBuffer));
36 return *this; 36 return *this;
37 } 37 }
38 void add(const char* lpBuffer, unsigned long ulSize); 38 void add(const char* lpBuffer, unsigned long ulSize);
39 void reset(); 39 void reset();
40 void resize(unsigned int uiSize); 40 void resize(unsigned int uiSize);
41 void set(unsigned int uiPosition); 41 void set(unsigned int uiPosition);
42 42
43 template<typename T> 43 template<typename T>
44 void update(unsigned long ulIndex, const T& value) 44 void update(unsigned long ulIndex, const T& value)
45 { 45 {
46 *(T*)(&m_vBuffer[ulIndex]) = value; 46 *(T*)(&m_vBuffer[ulIndex]) = value;
47 } 47 }
48 }; 48 };
49} 49}
50 50
51#endif 51#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/changelog.txt b/utils/zenutils/libraries/pelib-0.9/pelib/changelog.txt
index 37a7c36229..8099edf3db 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/changelog.txt
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/changelog.txt
@@ -1,321 +1,321 @@
1PeLib 0.09 alpha (February 09, 2005) 1PeLib 0.09 alpha (February 09, 2005)
2 2
3Added: 3Added:
4- Added PeHeaderT<x>::setIddBaseRelocRva(dword value) 4- Added PeHeaderT<x>::setIddBaseRelocRva(dword value)
5- Added PeHeaderT<x>::setIddBaseRelocSize(dword value) 5- Added PeHeaderT<x>::setIddBaseRelocSize(dword value)
6- Added PeHeaderT<x>::setIddArchitectureRva(dword value) 6- Added PeHeaderT<x>::setIddArchitectureRva(dword value)
7- Added PeHeaderT<x>::setIddArchitectureSize(dword value) 7- Added PeHeaderT<x>::setIddArchitectureSize(dword value)
8- Added PeHeaderT<x>::setIddComHeaderRva(dword value) 8- Added PeHeaderT<x>::setIddComHeaderRva(dword value)
9- Added PeHeaderT<x>::setIddComHeaderSize(dword value) 9- Added PeHeaderT<x>::setIddComHeaderSize(dword value)
10- Added void PeHeaderT<x>::setImageDataDirectoryRva(dword dwDirectory, dword value) 10- Added void PeHeaderT<x>::setImageDataDirectoryRva(dword dwDirectory, dword value)
11- Added void PeHeaderT<x>::setImageDataDirectorySize(dword dwDirectory, dword value) 11- Added void PeHeaderT<x>::setImageDataDirectorySize(dword dwDirectory, dword value)
12- Added bool PeHeaderT<x>::isValid() const 12- Added bool PeHeaderT<x>::isValid() const
13- Added int PeHeaderT<x>::read(const unsigned char* pcBuffer, unsigned int uiSize, unsigned int uiOffset); 13- Added int PeHeaderT<x>::read(const unsigned char* pcBuffer, unsigned int uiSize, unsigned int uiOffset);
14- Added int BoundImportDirectory::read(unsigned char* pcBuffer, unsigned int uiSize); 14- Added int BoundImportDirectory::read(unsigned char* pcBuffer, unsigned int uiSize);
15- Added int BoundImportDirectory::read(InputBuffer& inpBuffer, unsigned char* data, unsigned int dwSize); 15- Added int BoundImportDirectory::read(InputBuffer& inpBuffer, unsigned char* data, unsigned int dwSize);
16- Added unsigned int BoundImportDirectory::totalModules() 16- Added unsigned int BoundImportDirectory::totalModules()
17- Added DebugDirectory::setData to set the debug data of individual entries in the DebugDirectory. 17- Added DebugDirectory::setData to set the debug data of individual entries in the DebugDirectory.
18- Added DebugDirectory::getData to get the debug data of individual entries in the DebugDirectory. 18- Added DebugDirectory::getData to get the debug data of individual entries in the DebugDirectory.
19- Added int IatDirectory::read(unsigned char* buffer, unsigned int buffersize) 19- Added int IatDirectory::read(unsigned char* buffer, unsigned int buffersize)
20- Optimized the size and rebuild methods to avoid duplicate strings for files that appear 20- Optimized the size and rebuild methods to avoid duplicate strings for files that appear
21 more than once in the BoundImport Directory. 21 more than once in the BoundImport Directory.
22- Added two read functions to TlsDirectory and updated the return values of the old read function. 22- Added two read functions to TlsDirectory and updated the return values of the old read function.
23- Added two read functions to ComHeaderDirectory and updated the return values of the old read function. 23- Added two read functions to ComHeaderDirectory and updated the return values of the old read function.
24- Added two read functions to RelocationsDirectory and updated the return values of the old read function. 24- Added two read functions to RelocationsDirectory and updated the return values of the old read function.
25- Added void RelocationsDirectory::addRelocation() 25- Added void RelocationsDirectory::addRelocation()
26- Added void RelocationsDirectory::removeRelocation(unsigned int index) 26- Added void RelocationsDirectory::removeRelocation(unsigned int index)
27- Added void DebugDirectory::clear() 27- Added void DebugDirectory::clear()
28- Added void ExportDirectory::removeFunction(unsigned int index) 28- Added void ExportDirectory::removeFunction(unsigned int index)
29- Added void ExportDirectory::clear() 29- Added void ExportDirectory::clear()
30- Added unsigned int ExportDirectory::calcNumberOfFunctions() 30- Added unsigned int ExportDirectory::calcNumberOfFunctions()
31- Added void ExportDirectory::setAddressOfNameOrdinals(dword value) 31- Added void ExportDirectory::setAddressOfNameOrdinals(dword value)
32 32
33Bugfixes: 33Bugfixes:
34- Fixed a bug in TlsDirectory<bits>::size() 34- Fixed a bug in TlsDirectory<bits>::size()
35- Fixed a bug in PeHeaderT<64>::isValid(dword) 35- Fixed a bug in PeHeaderT<64>::isValid(dword)
36- Fixed a bug in PeHeaderT<bits>::removeDataDirectory(dword) 36- Fixed a bug in PeHeaderT<bits>::removeDataDirectory(dword)
37- Fixed a bug in BoundImportDirectory::rebuild() 37- Fixed a bug in BoundImportDirectory::rebuild()
38- Fixed a bug in BoundImportDirectory::read() (Potential buffer overflow) 38- Fixed a bug in BoundImportDirectory::read() (Potential buffer overflow)
39- Fixed a bug in BoundImportDirectory::read() (Bug caused incorrect results when reading the directory more than once) 39- Fixed a bug in BoundImportDirectory::read() (Bug caused incorrect results when reading the directory more than once)
40- Fixed a bug when reading the debug data of individual DebugDirectory entries. 40- Fixed a bug when reading the debug data of individual DebugDirectory entries.
41- Fixed a bug that caused non-existing data directories to be read (PeFile). 41- Fixed a bug that caused non-existing data directories to be read (PeFile).
42- Fixed a bug that caused problems when reading import directories that were located close to the end of the file (ImportDirectory). 42- Fixed a bug that caused problems when reading import directories that were located close to the end of the file (ImportDirectory).
43- Fixed a minor bug in PeHeader::calcSizeOfImage 43- Fixed a minor bug in PeHeader::calcSizeOfImage
44- Fixed some return values and removed all exception handling blocks. 44- Fixed some return values and removed all exception handling blocks.
45 45
46Changes: 46Changes:
47- Changed return values of PeHeader::addSection 47- Changed return values of PeHeader::addSection
48- Changed return values of PeHeader::read 48- Changed return values of PeHeader::read
49- Changed behaviour: PeHeader::m_uiOffset is initialized to 0 in default constructors. 49- Changed behaviour: PeHeader::m_uiOffset is initialized to 0 in default constructors.
50- Changed return value of BoundImportDirectory::getNumberOfModules() from int to unsigned int 50- Changed return value of BoundImportDirectory::getNumberOfModules() from int to unsigned int
51- Changed name of BoundImportDirectory::getNumberOfModules to calcNumberOfModules 51- Changed name of BoundImportDirectory::getNumberOfModules to calcNumberOfModules
52- Changed the return values of the PeFile::read* functions. 52- Changed the return values of the PeFile::read* functions.
53- Renamed IatDirectory::removeAll to IatDirectory::clear 53- Renamed IatDirectory::removeAll to IatDirectory::clear
54- Renamed IatDirectory::numberOfAddresses to IatDirectory::calcNumberOfAddresses 54- Renamed IatDirectory::numberOfAddresses to IatDirectory::calcNumberOfAddresses
55- Changed the parameter types of IatDirectory::getAddress from dword to unsigned int 55- Changed the parameter types of IatDirectory::getAddress from dword to unsigned int
56- Changed the parameter types of IatDirectory::removeAddress from dword to unsigned int 56- Changed the parameter types of IatDirectory::removeAddress from dword to unsigned int
57- All constants taken from windows.h that were redefined in PeLibAux.h now have the prefix PELIB_ to avoid 57- All constants taken from windows.h that were redefined in PeLibAux.h now have the prefix PELIB_ to avoid
58 conflicts with windows.h if both files are included to a project. 58 conflicts with windows.h if both files are included to a project.
59- Changed PELIB_IMAGE_TLS_DIRECTORY<bits>::size from an enum to a function. 59- Changed PELIB_IMAGE_TLS_DIRECTORY<bits>::size from an enum to a function.
60- Changed the name of RelocationsDirectory::getNumberOfRelocationData to calcNumberOfRelocationData 60- Changed the name of RelocationsDirectory::getNumberOfRelocationData to calcNumberOfRelocationData
61- Changed void RelocationsDirectory::removeRelocationData(unsigned int ulRelocation, word wValue) 61- Changed void RelocationsDirectory::removeRelocationData(unsigned int ulRelocation, word wValue)
62 to void RelocationsDirectory::removeRelocationData(unsigned int relocindex, unsigned int dataindex) 62 to void RelocationsDirectory::removeRelocationData(unsigned int relocindex, unsigned int dataindex)
63- Removed dword ExportDirectory::getNumberOfNameOrdinals() 63- Removed dword ExportDirectory::getNumberOfNameOrdinals()
64- Removed dword ExportDirectory::getNumberOfAddressOfFunctionNames() 64- Removed dword ExportDirectory::getNumberOfAddressOfFunctionNames()
65- Removed dword ExportDirectory::getNumberOfAddressOfFunctions() 65- Removed dword ExportDirectory::getNumberOfAddressOfFunctions()
66- Changed the parameters of some functions in ExportDirectory from dword to unsigned int. 66- Changed the parameters of some functions in ExportDirectory from dword to unsigned int.
67 67
68 68
69January 16, 2005 PeLib 0.08 alpha 69January 16, 2005 PeLib 0.08 alpha
70 70
71Added: 71Added:
72- Added std::string ExportDirectory::getNameString() 72- Added std::string ExportDirectory::getNameString()
73- Added resource type RT_MANIFEST to PeLibAux.h 73- Added resource type RT_MANIFEST to PeLibAux.h
74- Added the following functions of PeHeaderT<int x>: setIddDebugRva, setIddDebugSize, 74- Added the following functions of PeHeaderT<int x>: setIddDebugRva, setIddDebugSize,
75 setIddDelayImportRva, setIddDelayImportSize, setIddExceptionRva, setIddExceptionSize, setIddGlobalPtrRva, 75 setIddDelayImportRva, setIddDelayImportSize, setIddExceptionRva, setIddExceptionSize, setIddGlobalPtrRva,
76 setIddGlobalPtrSize, setIddIatRva, setIddIatSize, setIddLoadConfigRva, setIddLoadConfigSize, 76 setIddGlobalPtrSize, setIddIatRva, setIddIatSize, setIddLoadConfigRva, setIddLoadConfigSize,
77 setIddResourceRva, setIddResourceSize, setIddResourceRva, setIddResourceSize, setIddSecurityRva, 77 setIddResourceRva, setIddResourceSize, setIddResourceRva, setIddResourceSize, setIddSecurityRva,
78 setIddSecuritySize, setIddTlsRva, setIddTlsSize 78 setIddSecuritySize, setIddTlsRva, setIddTlsSize
79- ImportDirectory32 and ImportDirectory64 are now available. 79- ImportDirectory32 and ImportDirectory64 are now available.
80- Added ImportDirectory<bits>::setFileName(dword, currdir, const std::string&) 80- Added ImportDirectory<bits>::setFileName(dword, currdir, const std::string&)
81- Added ImportDirectory<bits>::setFirstThunk(dword, currdir, dword) 81- Added ImportDirectory<bits>::setFirstThunk(dword, currdir, dword)
82- Added ImportDirectory<bits>::setForwarderChain(dword, currdir, dword) 82- Added ImportDirectory<bits>::setForwarderChain(dword, currdir, dword)
83- Added ImportDirectory<bits>::setRvaOfName(dword, currdir, dword) 83- Added ImportDirectory<bits>::setRvaOfName(dword, currdir, dword)
84- Added ImportDirectory<bits>::setOriginalFirstThunk(dword, currdir, dword) 84- Added ImportDirectory<bits>::setOriginalFirstThunk(dword, currdir, dword)
85- Added ImportDirectory<bits>::setTimeDateStamp(dword, currdir, dword) 85- Added ImportDirectory<bits>::setTimeDateStamp(dword, currdir, dword)
86- Added ImportDirectory<bits>::setOriginalFirstThunk(dword, dword, currdir, dword) 86- Added ImportDirectory<bits>::setOriginalFirstThunk(dword, dword, currdir, dword)
87- Added ImportDirectory<bits>::setFirstThunk(dword, dword, currdir, dword) 87- Added ImportDirectory<bits>::setFirstThunk(dword, dword, currdir, dword)
88- Added ImportDirectory<bits>::setFunctionHint(dword, dword, currdir, word) 88- Added ImportDirectory<bits>::setFunctionHint(dword, dword, currdir, word)
89- Added ImportDirectory<bits>::setFunctionName(dword, dword, currdir, const std::string&) 89- Added ImportDirectory<bits>::setFunctionName(dword, dword, currdir, const std::string&)
90- Added dword BoundImportDirectory::getTimeDateStamp(dword dwBidnr, dword forwardedModule) const 90- Added dword BoundImportDirectory::getTimeDateStamp(dword dwBidnr, dword forwardedModule) const
91- Added word BoundImportDirectory::getOffsetModuleName(dword dwBidnr, dword forwardedModule) const 91- Added word BoundImportDirectory::getOffsetModuleName(dword dwBidnr, dword forwardedModule) const
92- Added word BoundImportDirectory::getNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule) const 92- Added word BoundImportDirectory::getNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule) const
93- Added std::string BoundImportDirectory::getModuleName(dword dwBidnr, dword forwardedModule) const 93- Added std::string BoundImportDirectory::getModuleName(dword dwBidnr, dword forwardedModule) const
94- Added void BoundImportDirectory::setTimeDateStamp(dword dwBidnr, dword forwardedModule, dword dwTds) 94- Added void BoundImportDirectory::setTimeDateStamp(dword dwBidnr, dword forwardedModule, dword dwTds)
95- Added void BoundImportDirectory::setOffsetModuleName(dword dwBidnr, dword forwardedModule, word wOmn) 95- Added void BoundImportDirectory::setOffsetModuleName(dword dwBidnr, dword forwardedModule, word wOmn)
96- Added void BoundImportDirectory::setNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule, word wMfr) 96- Added void BoundImportDirectory::setNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule, word wMfr)
97- Added void BoundImportDirectory::setModuleName(dword dwBidnr, dword forwardedModule, const std::string& strModuleName) 97- Added void BoundImportDirectory::setModuleName(dword dwBidnr, dword forwardedModule, const std::string& strModuleName)
98- Added word calcNumberOfModuleForwarderRefs(dword dwBidnr) const 98- Added word calcNumberOfModuleForwarderRefs(dword dwBidnr) const
99- Added void addForwardedModule(dword dwBidnr, const std::string& name, dword timeStamp = 0, word offsetModuleName = 0, word forwardedModules = 0) 99- Added void addForwardedModule(dword dwBidnr, const std::string& name, dword timeStamp = 0, word offsetModuleName = 0, word forwardedModules = 0)
100- Added void removeForwardedModule(dword dwBidnr, word forwardedModule) 100- Added void removeForwardedModule(dword dwBidnr, word forwardedModule)
101- Added PeHeaderT<x>::addDataDirectory() 101- Added PeHeaderT<x>::addDataDirectory()
102- Added PeHeaderT<x>::removeDataDirectory(dword) 102- Added PeHeaderT<x>::removeDataDirectory(dword)
103 103
104Bugfixes: 104Bugfixes:
105- Fixed a bug in MzHeader::isValid 105- Fixed a bug in MzHeader::isValid
106- Fixed a bug in PeHeaderT<x>::size() 106- Fixed a bug in PeHeaderT<x>::size()
107- Fixed a bug in PeHeaderT<x>::calcRva() 107- Fixed a bug in PeHeaderT<x>::calcRva()
108- Fixed a bug in PeHeaderT<x>::calcSizeOfImage() 108- Fixed a bug in PeHeaderT<x>::calcSizeOfImage()
109- Fixed a bug in PeHeaderT<x>::getSectionName(dword) 109- Fixed a bug in PeHeaderT<x>::getSectionName(dword)
110- Fixed a bug in PeHeaderT<x>::calcStartOfCode() 110- Fixed a bug in PeHeaderT<x>::calcStartOfCode()
111- Fixed a bug in PELIB_THUNK_DATA<bits>::bool equalHint(word wHint) const 111- Fixed a bug in PELIB_THUNK_DATA<bits>::bool equalHint(word wHint) const
112- Fixed a bug in PELIB_IMAGE_THUNK_DATA<bits>::bool equalHint(word wHint) const 112- Fixed a bug in PELIB_IMAGE_THUNK_DATA<bits>::bool equalHint(word wHint) const
113- Fixed a bug in int ImportDirectory<bits>::removeFunction(const std::string& strFilename, word wHint) 113- Fixed a bug in int ImportDirectory<bits>::removeFunction(const std::string& strFilename, word wHint)
114- Fixed a bug in int ImportDirectory<bits>::removeFile(const std::string& strFilename) 114- Fixed a bug in int ImportDirectory<bits>::removeFile(const std::string& strFilename)
115- Function hints are now properly added when rebuilding import directories. 115- Function hints are now properly added when rebuilding import directories.
116- Reading and rebuilding bound import directories now works with forwarded modules. 116- Reading and rebuilding bound import directories now works with forwarded modules.
117 117
118Changes: 118Changes:
119- Changed behaviour: Removed all exceptions from the MzHeader class. The functions work with return values now. 119- Changed behaviour: Removed all exceptions from the MzHeader class. The functions work with return values now.
120- Changed behaviour: The MzHeader::read() functions stopped checking if the MzHeader begins with "MZ". 120- Changed behaviour: The MzHeader::read() functions stopped checking if the MzHeader begins with "MZ".
121- Changed behaviour: PeHeaderT<int x>::addSection(std::string, dword) doesn't use exceptions anymore. 121- Changed behaviour: PeHeaderT<int x>::addSection(std::string, dword) doesn't use exceptions anymore.
122 Return values now indicate if the function succeeded or failed. 122 Return values now indicate if the function succeeded or failed.
123- Changed behaviour: PeHeaderT<int x>::getSectionWithOffset(dword) doesn't use exceptions anymore. 123- Changed behaviour: PeHeaderT<int x>::getSectionWithOffset(dword) doesn't use exceptions anymore.
124 Return values now indicate if the function succeeded or failed. 124 Return values now indicate if the function succeeded or failed.
125- Changed behaviour: PeHeaderT<int x>::getSectionWithRva(dword) doesn't use exceptions anymore. 125- Changed behaviour: PeHeaderT<int x>::getSectionWithRva(dword) doesn't use exceptions anymore.
126 Return values now indicate if the function succeeded or failed. 126 Return values now indicate if the function succeeded or failed.
127- Changed behaviour: PeHeaderT<int x>::rvaToOffset(dword) doesn't use exceptions anymore. 127- Changed behaviour: PeHeaderT<int x>::rvaToOffset(dword) doesn't use exceptions anymore.
128 Return values now indicate if the function succeeded or failed. 128 Return values now indicate if the function succeeded or failed.
129- Changed behaviour: PeHeaderT<int x>::write(std::string, unsigned int) doesn't use exceptions anymore. 129- Changed behaviour: PeHeaderT<int x>::write(std::string, unsigned int) doesn't use exceptions anymore.
130 Return values now indicate if the function succeeded or failed. 130 Return values now indicate if the function succeeded or failed.
131- Changed behaviour: PeHeaderT<int x>::writeSectionData(const std::string& strFilename, word wSecnr, 131- Changed behaviour: PeHeaderT<int x>::writeSectionData(const std::string& strFilename, word wSecnr,
132 const std::vector<byte>& vBuffer) doesn't use exceptions anymore. 132 const std::vector<byte>& vBuffer) doesn't use exceptions anymore.
133 Return values now indicate if the function succeeded or failed. 133 Return values now indicate if the function succeeded or failed.
134- Changed behaviour: PeHeaderT<int x>::writeSections(std::string) doesn't use exceptions anymore. 134- Changed behaviour: PeHeaderT<int x>::writeSections(std::string) doesn't use exceptions anymore.
135 Return values now indicate if the function succeeded or failed. 135 Return values now indicate if the function succeeded or failed.
136- Changed behaviour: Return value of PeHeaderT<x>::calcSpaceAfterHeader() changed from unsigned long 136- Changed behaviour: Return value of PeHeaderT<x>::calcSpaceAfterHeader() changed from unsigned long
137 to unsigned int. 137 to unsigned int.
138- Changed behaviour: Return value of PeHeaderT<x>::calcStartOfCode() changed from unsigned long 138- Changed behaviour: Return value of PeHeaderT<x>::calcStartOfCode() changed from unsigned long
139 to unsigned int. 139 to unsigned int.
140- Changed behaviour: Return value of PeHeaderT<x>::calcOffset() changed from unsigned long 140- Changed behaviour: Return value of PeHeaderT<x>::calcOffset() changed from unsigned long
141 to unsigned int. 141 to unsigned int.
142- Changed behaviour: Return value of PeHeaderT<x>::offsetToRva(dword) changed from unsigned long 142- Changed behaviour: Return value of PeHeaderT<x>::offsetToRva(dword) changed from unsigned long
143 to unsigned int. 143 to unsigned int.
144- Changed behaviour: Return value of PeHeaderT<x>::offsetToVa(dword) changed from unsigned long 144- Changed behaviour: Return value of PeHeaderT<x>::offsetToVa(dword) changed from unsigned long
145 to unsigned int. 145 to unsigned int.
146- Renamed ExportDirectory::setName(std::string) to ExportDirectory::setNameString(std::string) 146- Renamed ExportDirectory::setName(std::string) to ExportDirectory::setNameString(std::string)
147- Renamed the PeHeaderT::getId* functions to PeHeaderT::getIdd* 147- Renamed the PeHeaderT::getId* functions to PeHeaderT::getIdd*
148- Renamed PeHeaderT::getImageDirectoryRva to PeHeaderT::getImageDataDirectoryRva 148- Renamed PeHeaderT::getImageDirectoryRva to PeHeaderT::getImageDataDirectoryRva
149- Renamed PeHeaderT::getImageDirectorySize to PeHeaderT::getImageDataDirectorySize 149- Renamed PeHeaderT::getImageDirectorySize to PeHeaderT::getImageDataDirectorySize
150- Renamed void PeHeaderT<x>::setWinVersionValue(dword dwValue) to void PeHeaderT<x>::setWin32VersionValue(dword dwValue) 150- Renamed void PeHeaderT<x>::setWinVersionValue(dword dwValue) to void PeHeaderT<x>::setWin32VersionValue(dword dwValue)
151- Renamed the following functions of PeHeaderT<int x>: setIdImportRva to setIddImportRva, 151- Renamed the following functions of PeHeaderT<int x>: setIdImportRva to setIddImportRva,
152 setIdImportSize to setIddImportSize, setIdExportRva to setIddExportRva, setIdExportSize to setIddExportSize 152 setIdImportSize to setIddImportSize, setIdExportRva to setIddExportRva, setIdExportSize to setIddExportSize
153- Renamed dword ImportDirectory<bits>::getName to dword ImportDirectory<bits>::getRvaOfName 153- Renamed dword ImportDirectory<bits>::getName to dword ImportDirectory<bits>::getRvaOfName
154- Changed behaviour: All removeFunction and removeFile functions from ImportDirectory.h return int instead 154- Changed behaviour: All removeFunction and removeFile functions from ImportDirectory.h return int instead
155 of void now. 155 of void now.
156- Changed behavior: ResourceDirectory::resourceTypeNameToIndex returns int instead of unsigned int. 156- Changed behavior: ResourceDirectory::resourceTypeNameToIndex returns int instead of unsigned int.
157 157
158------------------------------------------------------------------------------------------------------------- 158-------------------------------------------------------------------------------------------------------------
159 159
160July 18, 2004 PeLib 0.07 alpha 160July 18, 2004 PeLib 0.07 alpha
161 161
162Added: 162Added:
163- Full support of the PE+ format. 163- Full support of the PE+ format.
164- ImportDirectory::getName(string, currdir) 164- ImportDirectory::getName(string, currdir)
165- ImportDirectory::getFirstThunk(dword, currdir) 165- ImportDirectory::getFirstThunk(dword, currdir)
166- ImportDirectory::getOriginalFirstThunk(dword, currdir) 166- ImportDirectory::getOriginalFirstThunk(dword, currdir)
167- ImportDirectory::getForwarderChain(dword, currdir) 167- ImportDirectory::getForwarderChain(dword, currdir)
168- ImportDirectory::getName(dword, currdir) 168- ImportDirectory::getName(dword, currdir)
169- ImportDirectory::getTimeDateStamp(dword, currdir) 169- ImportDirectory::getTimeDateStamp(dword, currdir)
170- PeLib::getFileType(string) 170- PeLib::getFileType(string)
171- PeLib::openPeFile(string) 171- PeLib::openPeFile(string)
172- Added class PeFileVisitor 172- Added class PeFileVisitor
173- Added PeFile::visit(PeFileVisitor&) 173- Added PeFile::visit(PeFileVisitor&)
174 174
175Bugfixes: 175Bugfixes:
176- Fixed a bug in PeHeader::rvaToOffset 176- Fixed a bug in PeHeader::rvaToOffset
177 177
178Changes: 178Changes:
179- Renamed ImportDirectory::OLD to PeLib::OLDDIR and ImportDirectory::NEW to PeLib::NEWDIR 179- Renamed ImportDirectory::OLD to PeLib::OLDDIR and ImportDirectory::NEW to PeLib::NEWDIR
180- Renamed Relocations to RelocationsDirectory 180- Renamed Relocations to RelocationsDirectory
181- Renamed ImportAddressTable to IatDirectory 181- Renamed ImportAddressTable to IatDirectory
182- Renamed ComDescriptor to ComHeader 182- Renamed ComDescriptor to ComHeader
183- Renamed PeFile::comDescDir to PeFile::comDir 183- Renamed PeFile::comDescDir to PeFile::comDir
184- Changed unsigned long ExportDirectory::getFunctionIndex to unsigned int ExportDirectory::getFunctionIndex 184- Changed unsigned long ExportDirectory::getFunctionIndex to unsigned int ExportDirectory::getFunctionIndex
185 185
186------------------------------------------------------------------------------------------------------------- 186-------------------------------------------------------------------------------------------------------------
187 187
188July 4, 2004 PeLib 0.06 alpha 188July 4, 2004 PeLib 0.06 alpha
189 189
190Added: 190Added:
191- TlsDirectory class 191- TlsDirectory class
192 192
193Changes: 193Changes:
194- ResourceElement::read and ResourceElement::rebuild are now protected. 194- ResourceElement::read and ResourceElement::rebuild are now protected.
195 195
196Bugfixes: 196Bugfixes:
197- Fixed a bug in PeHeader::rvaToOffset 197- Fixed a bug in PeHeader::rvaToOffset
198 198
199------------------------------------------------------------------------------------------------------------- 199-------------------------------------------------------------------------------------------------------------
200 200
201June 26, 2004 PeLib 0.05 alpha 201June 26, 2004 PeLib 0.05 alpha
202 202
203Added: 203Added:
204- Constructor, Copy constructor, assignment operator and destructor for ResourceChild. 204- Constructor, Copy constructor, assignment operator and destructor for ResourceChild.
205- ResourceDirectory::getRoot() 205- ResourceDirectory::getRoot()
206- ResourceElement::isLeaf() 206- ResourceElement::isLeaf()
207- ResourceElement::getElementRva 207- ResourceElement::getElementRva
208- 10 new functions in ResourceLeaf. 208- 10 new functions in ResourceLeaf.
209- 22 new functions in ResourceNode. 209- 22 new functions in ResourceNode.
210- Added the RT_* constants which identify resource types to PeLibAux.h 210- Added the RT_* constants which identify resource types to PeLibAux.h
211- Added a new example (examples/ResourceTree) which shows how to use low level ResourceDirectory functions. 211- Added a new example (examples/ResourceTree) which shows how to use low level ResourceDirectory functions.
212- Added PELIB_IMAGE_DEBUG_DIRECTORY and PELIB_IMG_DEBUG_DIRECTORY 212- Added PELIB_IMAGE_DEBUG_DIRECTORY and PELIB_IMG_DEBUG_DIRECTORY
213- Added the new class DebugDirectory which handles the debug directory of PE files. 213- Added the new class DebugDirectory which handles the debug directory of PE files.
214- Added readDebugDirectory() and debugDir() to PeFile. 214- Added readDebugDirectory() and debugDir() to PeFile.
215 215
216Removed: 216Removed:
217- ~ResourceNode() 217- ~ResourceNode()
218 218
219------------------------------------------------------------------------------------------------------------- 219-------------------------------------------------------------------------------------------------------------
220 220
221June 12, 2004 PeLib 0.04 alpha 221June 12, 2004 PeLib 0.04 alpha
222 222
223New: 223New:
224- Finally implemented the class ResourceDirectory. That means lots of new functions I won't explicitly list here. 224- Finally implemented the class ResourceDirectory. That means lots of new functions I won't explicitly list here.
225 Check the documentation. 225 Check the documentation.
226 226
227Removed: 227Removed:
228- The files buffer/ResTree.cpp and buffer/ResTree.h are obsolete and were removed. 228- The files buffer/ResTree.cpp and buffer/ResTree.h are obsolete and were removed.
229 229
230Bugfixes: 230Bugfixes:
231- Fixed PeHeader::calcStartOfCode 231- Fixed PeHeader::calcStartOfCode
232- Fixed PeHeader::getSectionWithRva 232- Fixed PeHeader::getSectionWithRva
233 233
234Changes: 234Changes:
235- Changed PeHeader::read to throw an exception if the NT signature is not 'PE'\0\0 235- Changed PeHeader::read to throw an exception if the NT signature is not 'PE'\0\0
236- Changed the 2nd parameter of void MzHeader::read(unsigned char*, unsigned long) from unsigned long to unsigned int. 236- Changed the 2nd parameter of void MzHeader::read(unsigned char*, unsigned long) from unsigned long to unsigned int.
237- Changed the return value of MzHeader::size from long to int. 237- Changed the return value of MzHeader::size from long to int.
238- Changed parameters of MzHeader::getReservedWords1, MzHeader::getReservedWords2, MzHeader::setReservedWords1 and 238- Changed parameters of MzHeader::getReservedWords1, MzHeader::getReservedWords2, MzHeader::setReservedWords1 and
239 MzHeader::setReservedWords2 from long to int. 239 MzHeader::setReservedWords2 from long to int.
240- Changed MzHeader::read(std::string) to MzHeader::read(const std::string&) 240- Changed MzHeader::read(std::string) to MzHeader::read(const std::string&)
241- Changed return value of BoundImportDirectory::getModuleIndex from long to int. 241- Changed return value of BoundImportDirectory::getModuleIndex from long to int.
242- Changed return value of BoundImportDirectory::size from long to int. 242- Changed return value of BoundImportDirectory::size from long to int.
243- Changed return value of ComDescriptor::size from long to int. 243- Changed return value of ComDescriptor::size from long to int.
244- Changed return value of ImportAddressTable::size from long to int. 244- Changed return value of ImportAddressTable::size from long to int.
245- Changed return value of Relocations::getNumberOfRelocations from long to int. 245- Changed return value of Relocations::getNumberOfRelocations from long to int.
246- Changed return value of Relocations::getNumberOfRelocationData from long to int. 246- Changed return value of Relocations::getNumberOfRelocationData from long to int.
247- Changed return value of Relocations::size from long to int. 247- Changed return value of Relocations::size from long to int.
248- Changed parameter of Relocations::getVirtualAddress from long to int. 248- Changed parameter of Relocations::getVirtualAddress from long to int.
249- Changed parameter of Relocations::getSizeOfBlock from long to int. 249- Changed parameter of Relocations::getSizeOfBlock from long to int.
250- Changed parameter of Relocations::getRelocationData from long to int. 250- Changed parameter of Relocations::getRelocationData from long to int.
251- Changed parameters of Relocations::setRelocationData from long to int. 251- Changed parameters of Relocations::setRelocationData from long to int.
252- Changed parameters of Relocations::setVirtualAddress from long to int. 252- Changed parameters of Relocations::setVirtualAddress from long to int.
253- Changed parameters of Relocations::setSizeOfBlock from long to int. 253- Changed parameters of Relocations::setSizeOfBlock from long to int.
254- Changed parameters of Relocations::addRelocationData from long to int. 254- Changed parameters of Relocations::addRelocationData from long to int.
255- Changed parameters of Relocations::removeRelocationData from long to int. 255- Changed parameters of Relocations::removeRelocationData from long to int.
256- Changed return value of ExportDirectory::getFunctionIndex(const std::string&) const from unsigned int to int. 256- Changed return value of ExportDirectory::getFunctionIndex(const std::string&) const from unsigned int to int.
257 257
258------------------------------------------------------------------------------------------------------------- 258-------------------------------------------------------------------------------------------------------------
259 259
260May 31, 2004: PeLib 0.03 alpha 260May 31, 2004: PeLib 0.03 alpha
261 261
262Bugfixes: 262Bugfixes:
263- Fixed some bugs in FileDump.cpp 263- Fixed some bugs in FileDump.cpp
264 264
265Changes: 265Changes:
266- Modified PeLibAux.cpp to make PeLib VC++ 7.1 compatible. 266- Modified PeLibAux.cpp to make PeLib VC++ 7.1 compatible.
267- Changed vector access from .at to operator[] all over the project. 267- Changed vector access from .at to operator[] all over the project.
268 Real undefined behaviour is probably better than spontaniously terminating applications. 268 Real undefined behaviour is probably better than spontaniously terminating applications.
269 269
270New: 270New:
271- Added makefiles for Borland C++ commandline tools (tested on version 5.6.4) 271- Added makefiles for Borland C++ commandline tools (tested on version 5.6.4)
272- Added makefiles for Digital Mars Compiler (tested on version 8.38n) 272- Added makefiles for Digital Mars Compiler (tested on version 8.38n)
273 Note that support for DMC is not yet complete. PeLib compiles though, the examples don't yet but the 273 Note that support for DMC is not yet complete. PeLib compiles though, the examples don't yet but the
274 reason for this is that I am unable to correctly specifiy the PeLib object files when compiling. 274 reason for this is that I am unable to correctly specifiy the PeLib object files when compiling.
275- Added makefiles for Visual C++ 7.1 (tested on compiler Version 13.10.3052) 275- Added makefiles for Visual C++ 7.1 (tested on compiler Version 13.10.3052)
276 276
277------------------------------------------------------------------------------------------------------------- 277-------------------------------------------------------------------------------------------------------------
278 278
279Mai 1, 2004: PeLib 0.02 alpha 279Mai 1, 2004: PeLib 0.02 alpha
280 280
281Bugfixes: 281Bugfixes:
282- Fixed a bug in FileDump's and OON2's makefile.g++ 282- Fixed a bug in FileDump's and OON2's makefile.g++
283- Fixed ImportDirectory::size 283- Fixed ImportDirectory::size
284- Changed parameter of PELIB_THUNK_DATA::equalHint from dword to word 284- Changed parameter of PELIB_THUNK_DATA::equalHint from dword to word
285- Fixed a bug in PeHeader::read (PeLib always assumed 0x10 data directories in version 0.01 alpha) 285- Fixed a bug in PeHeader::read (PeLib always assumed 0x10 data directories in version 0.01 alpha)
286 286
287Changes: 287Changes:
288- Slightly changed ImportDirectory::removeFile (Changed function's signature) 288- Slightly changed ImportDirectory::removeFile (Changed function's signature)
289- Moved the definitions of byte, word and dword into the PeLib namespace. 289- Moved the definitions of byte, word and dword into the PeLib namespace.
290- Renamed PELIB_THUNK_DATA::equalName to PELIB_THUNK_DATA::equalFunctionName 290- Renamed PELIB_THUNK_DATA::equalName to PELIB_THUNK_DATA::equalFunctionName
291- Started to add size() functions to structs defined in PeLibAux.h 291- Started to add size() functions to structs defined in PeLibAux.h
292- Moved PeFile::writeSectionData to PeHeader::writeSectionData 292- Moved PeFile::writeSectionData to PeHeader::writeSectionData
293- Moved PeFile::writeSections to PeHeader::writeSections 293- Moved PeFile::writeSections to PeHeader::writeSections
294 294
295New: 295New:
296- Added ImportDirectory::hasFunction 296- Added ImportDirectory::hasFunction
297- Wrote BoundImportDirectory::size 297- Wrote BoundImportDirectory::size
298- Added accumulate function to PeLibAux.h 298- Added accumulate function to PeLibAux.h
299- Added PELIB_IMAGE_SECTION_HEADER::biggerFileOffset 299- Added PELIB_IMAGE_SECTION_HEADER::biggerFileOffset
300- Added PELIB_IMAGE_SECTION_HEADER::biggerVirtualAddress 300- Added PELIB_IMAGE_SECTION_HEADER::biggerVirtualAddress
301- Added PeHeader::calcSizeOfImage 301- Added PeHeader::calcSizeOfImage
302- Added PeHeader::enlargeLastSection 302- Added PeHeader::enlargeLastSection
303 303
304Removed: 304Removed:
305- Removed PeFile::write 305- Removed PeFile::write
306- Removed PeFile::writeImportDirectory 306- Removed PeFile::writeImportDirectory
307 307
308Other changes: 308Other changes:
309- Rewrote parts of ImportDirectory::read 309- Rewrote parts of ImportDirectory::read
310- Rewrote ImportDirectory::removeFunction (both version). 310- Rewrote ImportDirectory::removeFunction (both version).
311- Changed std::ios:: to std::ios_base:: in ImportDirectory 311- Changed std::ios:: to std::ios_base:: in ImportDirectory
312- Changed ImportDirectory::addFunction (both versions) 312- Changed ImportDirectory::addFunction (both versions)
313- Changed ExportDirectory::rebuild 313- Changed ExportDirectory::rebuild
314- Changed ExportDirectory::size 314- Changed ExportDirectory::size
315- Rewrote ImportDirectory::size 315- Rewrote ImportDirectory::size
316- Rewrote PeHeader::size 316- Rewrote PeHeader::size
317- Rewrote ComDescriptor::size 317- Rewrote ComDescriptor::size
318 318
319------------------------------------------------------------------------------------------------------------- 319-------------------------------------------------------------------------------------------------------------
320 320
321April 9, 2004: PeLib 0.01 alpha Initial release \ No newline at end of file 321April 9, 2004: PeLib 0.01 alpha Initial release \ No newline at end of file
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/license.htm b/utils/zenutils/libraries/pelib-0.9/pelib/license.htm
index 2978aa7920..74f3b5a83c 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/license.htm
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/license.htm
@@ -1,35 +1,35 @@
1<html> 1<html>
2<body> 2<body>
3<h1>The zlib/libpng License</h1> 3<h1>The zlib/libpng License</h1>
4 4
5<tt> 5<tt>
6 6
7<p>Copyright (c) 2004 - Sebastian Porst</p> 7<p>Copyright (c) 2004 - Sebastian Porst</p>
8 8
9 <p>This software is provided 'as-is', without any express or implied 9 <p>This software is provided 'as-is', without any express or implied
10 warranty. In no event will the authors be held liable for any damages 10 warranty. In no event will the authors be held liable for any damages
11 arising from the use of this software.</p> 11 arising from the use of this software.</p>
12 12
13 <p>Permission is granted to anyone to use this software for any purpose, 13 <p>Permission is granted to anyone to use this software for any purpose,
14 including commercial applications, and to alter it and redistribute it 14 including commercial applications, and to alter it and redistribute it
15 freely, subject to the following restrictions:</p> 15 freely, subject to the following restrictions:</p>
16 16
17<blockquote> 17<blockquote>
18 18
19 <p>1. The origin of this software must not be misrepresented; you must not 19 <p>1. The origin of this software must not be misrepresented; you must not
20 claim that you wrote the original software. If you use this software 20 claim that you wrote the original software. If you use this software
21 in a product, an acknowledgment in the product documentation would be 21 in a product, an acknowledgment in the product documentation would be
22 appreciated but is not required.</p> 22 appreciated but is not required.</p>
23 23
24 <p>2. Altered source versions must be plainly marked as such, and must not be 24 <p>2. Altered source versions must be plainly marked as such, and must not be
25 misrepresented as being the original software.</p> 25 misrepresented as being the original software.</p>
26 26
27 <p>3. This notice may not be removed or altered from any source 27 <p>3. This notice may not be removed or altered from any source
28 distribution.</p> 28 distribution.</p>
29 29
30</blockquote> 30</blockquote>
31 31
32</tt> 32</tt>
33 33
34</body> 34</body>
35</html> \ No newline at end of file 35</html> \ No newline at end of file
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/readme.txt b/utils/zenutils/libraries/pelib-0.9/pelib/readme.txt
index b26a3e5287..65f289a8fe 100755..100644
--- a/utils/zenutils/libraries/pelib-0.9/pelib/readme.txt
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/readme.txt
@@ -1,44 +1,44 @@
1PeLib - Version 0.09 (alpha release) 1PeLib - Version 0.09 (alpha release)
2========================================= 2=========================================
3 3
4Copyright 2004 by Sebastian Porst 4Copyright 2004 by Sebastian Porst
5WWW: http://www.pelib.com 5WWW: http://www.pelib.com
6E-Mail: webmaster@the-interweb.com 6E-Mail: webmaster@the-interweb.com
7 7
8========================================= 8=========================================
9 9
101. What is PeLib? 101. What is PeLib?
112. Where can I find a documentation of PeLib DLL? 112. Where can I find a documentation of PeLib DLL?
123. Which license is used for PeLib? 123. Which license is used for PeLib?
134. Which compilers are being supported? 134. Which compilers are being supported?
145. How do I compile PeLib? 145. How do I compile PeLib?
15 15
161. What is PeLib DLL? 161. What is PeLib DLL?
17 PeLib is an open-source C++ library to modify 17 PeLib is an open-source C++ library to modify
18 PE files. See http://www.pelib.com for more details. 18 PE files. See http://www.pelib.com for more details.
19 19
202. Where can I find a documentation of PeLib DLL? 202. Where can I find a documentation of PeLib DLL?
21 http://www.pelib.com 21 http://www.pelib.com
22 22
233. All parts of PeLib are distributed under the zlib/libpng license. 233. All parts of PeLib are distributed under the zlib/libpng license.
24 See license.htm for details. 24 See license.htm for details.
25 25
264. The following compilers have been tested: 264. The following compilers have been tested:
27 MingW with g++ 3.2.3 27 MingW with g++ 3.2.3
28 Visual C++ 7.1 / Compiler version 13.10.3052 28 Visual C++ 7.1 / Compiler version 13.10.3052
29 Borland C++ 5.6.4 (currently not supported) 29 Borland C++ 5.6.4 (currently not supported)
30 Digital Mars Compiler 8.38n (currently not supported) 30 Digital Mars Compiler 8.38n (currently not supported)
31 31
325. Go into the PeLib/source directory and enter the following lines 325. Go into the PeLib/source directory and enter the following lines
33 depending on which compiler you use. 33 depending on which compiler you use.
34 34
35 g++: make -f makefile.g++ 35 g++: make -f makefile.g++
36 Borland C++: make -f makefile.bcc (currently not supported) 36 Borland C++: make -f makefile.bcc (currently not supported)
37 Visual C++ 7.1: nmake makefile.vc7 37 Visual C++ 7.1: nmake makefile.vc7
38 Digital Mars: make makefile.dmc (currently not supported) 38 Digital Mars: make makefile.dmc (currently not supported)
39 39
40 If the compilation is succesful there should be some *.o/*.obj files 40 If the compilation is succesful there should be some *.o/*.obj files
41 and (if you used g++) a PeLib.a file in the lib directory. 41 and (if you used g++) a PeLib.a file in the lib directory.
42 Then go to the examples directory and pick one example (I 42 Then go to the examples directory and pick one example (I
43 suggest FileDump) and try to build it with the same make 43 suggest FileDump) and try to build it with the same make
44 command as above. \ No newline at end of file 44 command as above. \ No newline at end of file
diff --git a/utils/zenutils/libraries/zlib123/CMakeLists.txt b/utils/zenutils/libraries/zlib123/CMakeLists.txt
index 05e949567d..32c1fa667b 100755..100644
--- a/utils/zenutils/libraries/zlib123/CMakeLists.txt
+++ b/utils/zenutils/libraries/zlib123/CMakeLists.txt
@@ -1,19 +1,19 @@
1PROJECT(zlib) 1PROJECT(zlib)
2 2
3# source files for zlib 3# source files for zlib
4SET(zlib_src 4SET(zlib_src
5 zlib/adler32.c 5 zlib/adler32.c
6 zlib/compress.c 6 zlib/compress.c
7 zlib/crc32.c 7 zlib/crc32.c
8 zlib/deflate.c 8 zlib/deflate.c
9 zlib/gzio.c 9 zlib/gzio.c
10 zlib/infback.c 10 zlib/infback.c
11 zlib/inffast.c 11 zlib/inffast.c
12 zlib/inflate.c 12 zlib/inflate.c
13 zlib/inftrees.c 13 zlib/inftrees.c
14 zlib/trees.c 14 zlib/trees.c
15 zlib/uncompr.c 15 zlib/uncompr.c
16 zlib/zutil.c 16 zlib/zutil.c
17) 17)
18 18
19ADD_LIBRARY(zlib ${zlib_src}) 19ADD_LIBRARY(zlib ${zlib_src})
diff --git a/utils/zenutils/libraries/zlib123/zlib/ChangeLog b/utils/zenutils/libraries/zlib123/zlib/ChangeLog
index 1ac946309b..7f6869d323 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/ChangeLog
+++ b/utils/zenutils/libraries/zlib123/zlib/ChangeLog
@@ -1,855 +1,855 @@
1 1
2 ChangeLog file for zlib 2 ChangeLog file for zlib
3 3
4Changes in 1.2.3 (18 July 2005) 4Changes in 1.2.3 (18 July 2005)
5- Apply security vulnerability fixes to contrib/infback9 as well 5- Apply security vulnerability fixes to contrib/infback9 as well
6- Clean up some text files (carriage returns, trailing space) 6- Clean up some text files (carriage returns, trailing space)
7- Update testzlib, vstudio, masmx64, and masmx86 in contrib [Vollant] 7- Update testzlib, vstudio, masmx64, and masmx86 in contrib [Vollant]
8 8
9Changes in 1.2.2.4 (11 July 2005) 9Changes in 1.2.2.4 (11 July 2005)
10- Add inflatePrime() function for starting inflation at bit boundary 10- Add inflatePrime() function for starting inflation at bit boundary
11- Avoid some Visual C warnings in deflate.c 11- Avoid some Visual C warnings in deflate.c
12- Avoid more silly Visual C warnings in inflate.c and inftrees.c for 64-bit 12- Avoid more silly Visual C warnings in inflate.c and inftrees.c for 64-bit
13 compile 13 compile
14- Fix some spelling errors in comments [Betts] 14- Fix some spelling errors in comments [Betts]
15- Correct inflateInit2() error return documentation in zlib.h 15- Correct inflateInit2() error return documentation in zlib.h
16- Added zran.c example of compressed data random access to examples 16- Added zran.c example of compressed data random access to examples
17 directory, shows use of inflatePrime() 17 directory, shows use of inflatePrime()
18- Fix cast for assignments to strm->state in inflate.c and infback.c 18- Fix cast for assignments to strm->state in inflate.c and infback.c
19- Fix zlibCompileFlags() in zutil.c to use 1L for long shifts [Oberhumer] 19- Fix zlibCompileFlags() in zutil.c to use 1L for long shifts [Oberhumer]
20- Move declarations of gf2 functions to right place in crc32.c [Oberhumer] 20- Move declarations of gf2 functions to right place in crc32.c [Oberhumer]
21- Add cast in trees.c t avoid a warning [Oberhumer] 21- Add cast in trees.c t avoid a warning [Oberhumer]
22- Avoid some warnings in fitblk.c, gun.c, gzjoin.c in examples [Oberhumer] 22- Avoid some warnings in fitblk.c, gun.c, gzjoin.c in examples [Oberhumer]
23- Update make_vms.com [Zinser] 23- Update make_vms.com [Zinser]
24- Initialize state->write in inflateReset() since copied in inflate_fast() 24- Initialize state->write in inflateReset() since copied in inflate_fast()
25- Be more strict on incomplete code sets in inflate_table() and increase 25- Be more strict on incomplete code sets in inflate_table() and increase
26 ENOUGH and MAXD -- this repairs a possible security vulnerability for 26 ENOUGH and MAXD -- this repairs a possible security vulnerability for
27 invalid inflate input. Thanks to Tavis Ormandy and Markus Oberhumer for 27 invalid inflate input. Thanks to Tavis Ormandy and Markus Oberhumer for
28 discovering the vulnerability and providing test cases. 28 discovering the vulnerability and providing test cases.
29- Add ia64 support to configure for HP-UX [Smith] 29- Add ia64 support to configure for HP-UX [Smith]
30- Add error return to gzread() for format or i/o error [Levin] 30- Add error return to gzread() for format or i/o error [Levin]
31- Use malloc.h for OS/2 [Necasek] 31- Use malloc.h for OS/2 [Necasek]
32 32
33Changes in 1.2.2.3 (27 May 2005) 33Changes in 1.2.2.3 (27 May 2005)
34- Replace 1U constants in inflate.c and inftrees.c for 64-bit compile 34- Replace 1U constants in inflate.c and inftrees.c for 64-bit compile
35- Typecast fread() return values in gzio.c [Vollant] 35- Typecast fread() return values in gzio.c [Vollant]
36- Remove trailing space in minigzip.c outmode (VC++ can't deal with it) 36- Remove trailing space in minigzip.c outmode (VC++ can't deal with it)
37- Fix crc check bug in gzread() after gzungetc() [Heiner] 37- Fix crc check bug in gzread() after gzungetc() [Heiner]
38- Add the deflateTune() function to adjust internal compression parameters 38- Add the deflateTune() function to adjust internal compression parameters
39- Add a fast gzip decompressor, gun.c, to examples (use of inflateBack) 39- Add a fast gzip decompressor, gun.c, to examples (use of inflateBack)
40- Remove an incorrect assertion in examples/zpipe.c 40- Remove an incorrect assertion in examples/zpipe.c
41- Add C++ wrapper in infback9.h [Donais] 41- Add C++ wrapper in infback9.h [Donais]
42- Fix bug in inflateCopy() when decoding fixed codes 42- Fix bug in inflateCopy() when decoding fixed codes
43- Note in zlib.h how much deflateSetDictionary() actually uses 43- Note in zlib.h how much deflateSetDictionary() actually uses
44- Remove USE_DICT_HEAD in deflate.c (would mess up inflate if used) 44- Remove USE_DICT_HEAD in deflate.c (would mess up inflate if used)
45- Add _WIN32_WCE to define WIN32 in zconf.in.h [Spencer] 45- Add _WIN32_WCE to define WIN32 in zconf.in.h [Spencer]
46- Don't include stderr.h or errno.h for _WIN32_WCE in zutil.h [Spencer] 46- Don't include stderr.h or errno.h for _WIN32_WCE in zutil.h [Spencer]
47- Add gzdirect() function to indicate transparent reads 47- Add gzdirect() function to indicate transparent reads
48- Update contrib/minizip [Vollant] 48- Update contrib/minizip [Vollant]
49- Fix compilation of deflate.c when both ASMV and FASTEST [Oberhumer] 49- Fix compilation of deflate.c when both ASMV and FASTEST [Oberhumer]
50- Add casts in crc32.c to avoid warnings [Oberhumer] 50- Add casts in crc32.c to avoid warnings [Oberhumer]
51- Add contrib/masmx64 [Vollant] 51- Add contrib/masmx64 [Vollant]
52- Update contrib/asm586, asm686, masmx86, testzlib, vstudio [Vollant] 52- Update contrib/asm586, asm686, masmx86, testzlib, vstudio [Vollant]
53 53
54Changes in 1.2.2.2 (30 December 2004) 54Changes in 1.2.2.2 (30 December 2004)
55- Replace structure assignments in deflate.c and inflate.c with zmemcpy to 55- Replace structure assignments in deflate.c and inflate.c with zmemcpy to
56 avoid implicit memcpy calls (portability for no-library compilation) 56 avoid implicit memcpy calls (portability for no-library compilation)
57- Increase sprintf() buffer size in gzdopen() to allow for large numbers 57- Increase sprintf() buffer size in gzdopen() to allow for large numbers
58- Add INFLATE_STRICT to check distances against zlib header 58- Add INFLATE_STRICT to check distances against zlib header
59- Improve WinCE errno handling and comments [Chang] 59- Improve WinCE errno handling and comments [Chang]
60- Remove comment about no gzip header processing in FAQ 60- Remove comment about no gzip header processing in FAQ
61- Add Z_FIXED strategy option to deflateInit2() to force fixed trees 61- Add Z_FIXED strategy option to deflateInit2() to force fixed trees
62- Add updated make_vms.com [Coghlan], update README 62- Add updated make_vms.com [Coghlan], update README
63- Create a new "examples" directory, move gzappend.c there, add zpipe.c, 63- Create a new "examples" directory, move gzappend.c there, add zpipe.c,
64 fitblk.c, gzlog.[ch], gzjoin.c, and zlib_how.html. 64 fitblk.c, gzlog.[ch], gzjoin.c, and zlib_how.html.
65- Add FAQ entry and comments in deflate.c on uninitialized memory access 65- Add FAQ entry and comments in deflate.c on uninitialized memory access
66- Add Solaris 9 make options in configure [Gilbert] 66- Add Solaris 9 make options in configure [Gilbert]
67- Allow strerror() usage in gzio.c for STDC 67- Allow strerror() usage in gzio.c for STDC
68- Fix DecompressBuf in contrib/delphi/ZLib.pas [ManChesTer] 68- Fix DecompressBuf in contrib/delphi/ZLib.pas [ManChesTer]
69- Update contrib/masmx86/inffas32.asm and gvmat32.asm [Vollant] 69- Update contrib/masmx86/inffas32.asm and gvmat32.asm [Vollant]
70- Use z_off_t for adler32_combine() and crc32_combine() lengths 70- Use z_off_t for adler32_combine() and crc32_combine() lengths
71- Make adler32() much faster for small len 71- Make adler32() much faster for small len
72- Use OS_CODE in deflate() default gzip header 72- Use OS_CODE in deflate() default gzip header
73 73
74Changes in 1.2.2.1 (31 October 2004) 74Changes in 1.2.2.1 (31 October 2004)
75- Allow inflateSetDictionary() call for raw inflate 75- Allow inflateSetDictionary() call for raw inflate
76- Fix inflate header crc check bug for file names and comments 76- Fix inflate header crc check bug for file names and comments
77- Add deflateSetHeader() and gz_header structure for custom gzip headers 77- Add deflateSetHeader() and gz_header structure for custom gzip headers
78- Add inflateGetheader() to retrieve gzip headers 78- Add inflateGetheader() to retrieve gzip headers
79- Add crc32_combine() and adler32_combine() functions 79- Add crc32_combine() and adler32_combine() functions
80- Add alloc_func, free_func, in_func, out_func to Z_PREFIX list 80- Add alloc_func, free_func, in_func, out_func to Z_PREFIX list
81- Use zstreamp consistently in zlib.h (inflate_back functions) 81- Use zstreamp consistently in zlib.h (inflate_back functions)
82- Remove GUNZIP condition from definition of inflate_mode in inflate.h 82- Remove GUNZIP condition from definition of inflate_mode in inflate.h
83 and in contrib/inflate86/inffast.S [Truta, Anderson] 83 and in contrib/inflate86/inffast.S [Truta, Anderson]
84- Add support for AMD64 in contrib/inflate86/inffas86.c [Anderson] 84- Add support for AMD64 in contrib/inflate86/inffas86.c [Anderson]
85- Update projects/README.projects and projects/visualc6 [Truta] 85- Update projects/README.projects and projects/visualc6 [Truta]
86- Update win32/DLL_FAQ.txt [Truta] 86- Update win32/DLL_FAQ.txt [Truta]
87- Avoid warning under NO_GZCOMPRESS in gzio.c; fix typo [Truta] 87- Avoid warning under NO_GZCOMPRESS in gzio.c; fix typo [Truta]
88- Deprecate Z_ASCII; use Z_TEXT instead [Truta] 88- Deprecate Z_ASCII; use Z_TEXT instead [Truta]
89- Use a new algorithm for setting strm->data_type in trees.c [Truta] 89- Use a new algorithm for setting strm->data_type in trees.c [Truta]
90- Do not define an exit() prototype in zutil.c unless DEBUG defined 90- Do not define an exit() prototype in zutil.c unless DEBUG defined
91- Remove prototype of exit() from zutil.c, example.c, minigzip.c [Truta] 91- Remove prototype of exit() from zutil.c, example.c, minigzip.c [Truta]
92- Add comment in zlib.h for Z_NO_FLUSH parameter to deflate() 92- Add comment in zlib.h for Z_NO_FLUSH parameter to deflate()
93- Fix Darwin build version identification [Peterson] 93- Fix Darwin build version identification [Peterson]
94 94
95Changes in 1.2.2 (3 October 2004) 95Changes in 1.2.2 (3 October 2004)
96- Update zlib.h comments on gzip in-memory processing 96- Update zlib.h comments on gzip in-memory processing
97- Set adler to 1 in inflateReset() to support Java test suite [Walles] 97- Set adler to 1 in inflateReset() to support Java test suite [Walles]
98- Add contrib/dotzlib [Ravn] 98- Add contrib/dotzlib [Ravn]
99- Update win32/DLL_FAQ.txt [Truta] 99- Update win32/DLL_FAQ.txt [Truta]
100- Update contrib/minizip [Vollant] 100- Update contrib/minizip [Vollant]
101- Move contrib/visual-basic.txt to old/ [Truta] 101- Move contrib/visual-basic.txt to old/ [Truta]
102- Fix assembler builds in projects/visualc6/ [Truta] 102- Fix assembler builds in projects/visualc6/ [Truta]
103 103
104Changes in 1.2.1.2 (9 September 2004) 104Changes in 1.2.1.2 (9 September 2004)
105- Update INDEX file 105- Update INDEX file
106- Fix trees.c to update strm->data_type (no one ever noticed!) 106- Fix trees.c to update strm->data_type (no one ever noticed!)
107- Fix bug in error case in inflate.c, infback.c, and infback9.c [Brown] 107- Fix bug in error case in inflate.c, infback.c, and infback9.c [Brown]
108- Add "volatile" to crc table flag declaration (for DYNAMIC_CRC_TABLE) 108- Add "volatile" to crc table flag declaration (for DYNAMIC_CRC_TABLE)
109- Add limited multitasking protection to DYNAMIC_CRC_TABLE 109- Add limited multitasking protection to DYNAMIC_CRC_TABLE
110- Add NO_vsnprintf for VMS in zutil.h [Mozilla] 110- Add NO_vsnprintf for VMS in zutil.h [Mozilla]
111- Don't declare strerror() under VMS [Mozilla] 111- Don't declare strerror() under VMS [Mozilla]
112- Add comment to DYNAMIC_CRC_TABLE to use get_crc_table() to initialize 112- Add comment to DYNAMIC_CRC_TABLE to use get_crc_table() to initialize
113- Update contrib/ada [Anisimkov] 113- Update contrib/ada [Anisimkov]
114- Update contrib/minizip [Vollant] 114- Update contrib/minizip [Vollant]
115- Fix configure to not hardcode directories for Darwin [Peterson] 115- Fix configure to not hardcode directories for Darwin [Peterson]
116- Fix gzio.c to not return error on empty files [Brown] 116- Fix gzio.c to not return error on empty files [Brown]
117- Fix indentation; update version in contrib/delphi/ZLib.pas and 117- Fix indentation; update version in contrib/delphi/ZLib.pas and
118 contrib/pascal/zlibpas.pas [Truta] 118 contrib/pascal/zlibpas.pas [Truta]
119- Update mkasm.bat in contrib/masmx86 [Truta] 119- Update mkasm.bat in contrib/masmx86 [Truta]
120- Update contrib/untgz [Truta] 120- Update contrib/untgz [Truta]
121- Add projects/README.projects [Truta] 121- Add projects/README.projects [Truta]
122- Add project for MS Visual C++ 6.0 in projects/visualc6 [Cadieux, Truta] 122- Add project for MS Visual C++ 6.0 in projects/visualc6 [Cadieux, Truta]
123- Update win32/DLL_FAQ.txt [Truta] 123- Update win32/DLL_FAQ.txt [Truta]
124- Update list of Z_PREFIX symbols in zconf.h [Randers-Pehrson, Truta] 124- Update list of Z_PREFIX symbols in zconf.h [Randers-Pehrson, Truta]
125- Remove an unnecessary assignment to curr in inftrees.c [Truta] 125- Remove an unnecessary assignment to curr in inftrees.c [Truta]
126- Add OS/2 to exe builds in configure [Poltorak] 126- Add OS/2 to exe builds in configure [Poltorak]
127- Remove err dummy parameter in zlib.h [Kientzle] 127- Remove err dummy parameter in zlib.h [Kientzle]
128 128
129Changes in 1.2.1.1 (9 January 2004) 129Changes in 1.2.1.1 (9 January 2004)
130- Update email address in README 130- Update email address in README
131- Several FAQ updates 131- Several FAQ updates
132- Fix a big fat bug in inftrees.c that prevented decoding valid 132- Fix a big fat bug in inftrees.c that prevented decoding valid
133 dynamic blocks with only literals and no distance codes -- 133 dynamic blocks with only literals and no distance codes --
134 Thanks to "Hot Emu" for the bug report and sample file 134 Thanks to "Hot Emu" for the bug report and sample file
135- Add a note to puff.c on no distance codes case. 135- Add a note to puff.c on no distance codes case.
136 136
137Changes in 1.2.1 (17 November 2003) 137Changes in 1.2.1 (17 November 2003)
138- Remove a tab in contrib/gzappend/gzappend.c 138- Remove a tab in contrib/gzappend/gzappend.c
139- Update some interfaces in contrib for new zlib functions 139- Update some interfaces in contrib for new zlib functions
140- Update zlib version number in some contrib entries 140- Update zlib version number in some contrib entries
141- Add Windows CE definition for ptrdiff_t in zutil.h [Mai, Truta] 141- Add Windows CE definition for ptrdiff_t in zutil.h [Mai, Truta]
142- Support shared libraries on Hurd and KFreeBSD [Brown] 142- Support shared libraries on Hurd and KFreeBSD [Brown]
143- Fix error in NO_DIVIDE option of adler32.c 143- Fix error in NO_DIVIDE option of adler32.c
144 144
145Changes in 1.2.0.8 (4 November 2003) 145Changes in 1.2.0.8 (4 November 2003)
146- Update version in contrib/delphi/ZLib.pas and contrib/pascal/zlibpas.pas 146- Update version in contrib/delphi/ZLib.pas and contrib/pascal/zlibpas.pas
147- Add experimental NO_DIVIDE #define in adler32.c 147- Add experimental NO_DIVIDE #define in adler32.c
148 - Possibly faster on some processors (let me know if it is) 148 - Possibly faster on some processors (let me know if it is)
149- Correct Z_BLOCK to not return on first inflate call if no wrap 149- Correct Z_BLOCK to not return on first inflate call if no wrap
150- Fix strm->data_type on inflate() return to correctly indicate EOB 150- Fix strm->data_type on inflate() return to correctly indicate EOB
151- Add deflatePrime() function for appending in the middle of a byte 151- Add deflatePrime() function for appending in the middle of a byte
152- Add contrib/gzappend for an example of appending to a stream 152- Add contrib/gzappend for an example of appending to a stream
153- Update win32/DLL_FAQ.txt [Truta] 153- Update win32/DLL_FAQ.txt [Truta]
154- Delete Turbo C comment in README [Truta] 154- Delete Turbo C comment in README [Truta]
155- Improve some indentation in zconf.h [Truta] 155- Improve some indentation in zconf.h [Truta]
156- Fix infinite loop on bad input in configure script [Church] 156- Fix infinite loop on bad input in configure script [Church]
157- Fix gzeof() for concatenated gzip files [Johnson] 157- Fix gzeof() for concatenated gzip files [Johnson]
158- Add example to contrib/visual-basic.txt [Michael B.] 158- Add example to contrib/visual-basic.txt [Michael B.]
159- Add -p to mkdir's in Makefile.in [vda] 159- Add -p to mkdir's in Makefile.in [vda]
160- Fix configure to properly detect presence or lack of printf functions 160- Fix configure to properly detect presence or lack of printf functions
161- Add AS400 support [Monnerat] 161- Add AS400 support [Monnerat]
162- Add a little Cygwin support [Wilson] 162- Add a little Cygwin support [Wilson]
163 163
164Changes in 1.2.0.7 (21 September 2003) 164Changes in 1.2.0.7 (21 September 2003)
165- Correct some debug formats in contrib/infback9 165- Correct some debug formats in contrib/infback9
166- Cast a type in a debug statement in trees.c 166- Cast a type in a debug statement in trees.c
167- Change search and replace delimiter in configure from % to # [Beebe] 167- Change search and replace delimiter in configure from % to # [Beebe]
168- Update contrib/untgz to 0.2 with various fixes [Truta] 168- Update contrib/untgz to 0.2 with various fixes [Truta]
169- Add build support for Amiga [Nikl] 169- Add build support for Amiga [Nikl]
170- Remove some directories in old that have been updated to 1.2 170- Remove some directories in old that have been updated to 1.2
171- Add dylib building for Mac OS X in configure and Makefile.in 171- Add dylib building for Mac OS X in configure and Makefile.in
172- Remove old distribution stuff from Makefile 172- Remove old distribution stuff from Makefile
173- Update README to point to DLL_FAQ.txt, and add comment on Mac OS X 173- Update README to point to DLL_FAQ.txt, and add comment on Mac OS X
174- Update links in README 174- Update links in README
175 175
176Changes in 1.2.0.6 (13 September 2003) 176Changes in 1.2.0.6 (13 September 2003)
177- Minor FAQ updates 177- Minor FAQ updates
178- Update contrib/minizip to 1.00 [Vollant] 178- Update contrib/minizip to 1.00 [Vollant]
179- Remove test of gz functions in example.c when GZ_COMPRESS defined [Truta] 179- Remove test of gz functions in example.c when GZ_COMPRESS defined [Truta]
180- Update POSTINC comment for 68060 [Nikl] 180- Update POSTINC comment for 68060 [Nikl]
181- Add contrib/infback9 with deflate64 decoding (unsupported) 181- Add contrib/infback9 with deflate64 decoding (unsupported)
182- For MVS define NO_vsnprintf and undefine FAR [van Burik] 182- For MVS define NO_vsnprintf and undefine FAR [van Burik]
183- Add pragma for fdopen on MVS [van Burik] 183- Add pragma for fdopen on MVS [van Burik]
184 184
185Changes in 1.2.0.5 (8 September 2003) 185Changes in 1.2.0.5 (8 September 2003)
186- Add OF to inflateBackEnd() declaration in zlib.h 186- Add OF to inflateBackEnd() declaration in zlib.h
187- Remember start when using gzdopen in the middle of a file 187- Remember start when using gzdopen in the middle of a file
188- Use internal off_t counters in gz* functions to properly handle seeks 188- Use internal off_t counters in gz* functions to properly handle seeks
189- Perform more rigorous check for distance-too-far in inffast.c 189- Perform more rigorous check for distance-too-far in inffast.c
190- Add Z_BLOCK flush option to return from inflate at block boundary 190- Add Z_BLOCK flush option to return from inflate at block boundary
191- Set strm->data_type on return from inflate 191- Set strm->data_type on return from inflate
192 - Indicate bits unused, if at block boundary, and if in last block 192 - Indicate bits unused, if at block boundary, and if in last block
193- Replace size_t with ptrdiff_t in crc32.c, and check for correct size 193- Replace size_t with ptrdiff_t in crc32.c, and check for correct size
194- Add condition so old NO_DEFLATE define still works for compatibility 194- Add condition so old NO_DEFLATE define still works for compatibility
195- FAQ update regarding the Windows DLL [Truta] 195- FAQ update regarding the Windows DLL [Truta]
196- INDEX update: add qnx entry, remove aix entry [Truta] 196- INDEX update: add qnx entry, remove aix entry [Truta]
197- Install zlib.3 into mandir [Wilson] 197- Install zlib.3 into mandir [Wilson]
198- Move contrib/zlib_dll_FAQ.txt to win32/DLL_FAQ.txt; update [Truta] 198- Move contrib/zlib_dll_FAQ.txt to win32/DLL_FAQ.txt; update [Truta]
199- Adapt the zlib interface to the new DLL convention guidelines [Truta] 199- Adapt the zlib interface to the new DLL convention guidelines [Truta]
200- Introduce ZLIB_WINAPI macro to allow the export of functions using 200- Introduce ZLIB_WINAPI macro to allow the export of functions using
201 the WINAPI calling convention, for Visual Basic [Vollant, Truta] 201 the WINAPI calling convention, for Visual Basic [Vollant, Truta]
202- Update msdos and win32 scripts and makefiles [Truta] 202- Update msdos and win32 scripts and makefiles [Truta]
203- Export symbols by name, not by ordinal, in win32/zlib.def [Truta] 203- Export symbols by name, not by ordinal, in win32/zlib.def [Truta]
204- Add contrib/ada [Anisimkov] 204- Add contrib/ada [Anisimkov]
205- Move asm files from contrib/vstudio/vc70_32 to contrib/asm386 [Truta] 205- Move asm files from contrib/vstudio/vc70_32 to contrib/asm386 [Truta]
206- Rename contrib/asm386 to contrib/masmx86 [Truta, Vollant] 206- Rename contrib/asm386 to contrib/masmx86 [Truta, Vollant]
207- Add contrib/masm686 [Truta] 207- Add contrib/masm686 [Truta]
208- Fix offsets in contrib/inflate86 and contrib/masmx86/inffas32.asm 208- Fix offsets in contrib/inflate86 and contrib/masmx86/inffas32.asm
209 [Truta, Vollant] 209 [Truta, Vollant]
210- Update contrib/delphi; rename to contrib/pascal; add example [Truta] 210- Update contrib/delphi; rename to contrib/pascal; add example [Truta]
211- Remove contrib/delphi2; add a new contrib/delphi [Truta] 211- Remove contrib/delphi2; add a new contrib/delphi [Truta]
212- Avoid inclusion of the nonstandard <memory.h> in contrib/iostream, 212- Avoid inclusion of the nonstandard <memory.h> in contrib/iostream,
213 and fix some method prototypes [Truta] 213 and fix some method prototypes [Truta]
214- Fix the ZCR_SEED2 constant to avoid warnings in contrib/minizip 214- Fix the ZCR_SEED2 constant to avoid warnings in contrib/minizip
215 [Truta] 215 [Truta]
216- Avoid the use of backslash (\) in contrib/minizip [Vollant] 216- Avoid the use of backslash (\) in contrib/minizip [Vollant]
217- Fix file time handling in contrib/untgz; update makefiles [Truta] 217- Fix file time handling in contrib/untgz; update makefiles [Truta]
218- Update contrib/vstudio/vc70_32 to comply with the new DLL guidelines 218- Update contrib/vstudio/vc70_32 to comply with the new DLL guidelines
219 [Vollant] 219 [Vollant]
220- Remove contrib/vstudio/vc15_16 [Vollant] 220- Remove contrib/vstudio/vc15_16 [Vollant]
221- Rename contrib/vstudio/vc70_32 to contrib/vstudio/vc7 [Truta] 221- Rename contrib/vstudio/vc70_32 to contrib/vstudio/vc7 [Truta]
222- Update README.contrib [Truta] 222- Update README.contrib [Truta]
223- Invert the assignment order of match_head and s->prev[...] in 223- Invert the assignment order of match_head and s->prev[...] in
224 INSERT_STRING [Truta] 224 INSERT_STRING [Truta]
225- Compare TOO_FAR with 32767 instead of 32768, to avoid 16-bit warnings 225- Compare TOO_FAR with 32767 instead of 32768, to avoid 16-bit warnings
226 [Truta] 226 [Truta]
227- Compare function pointers with 0, not with NULL or Z_NULL [Truta] 227- Compare function pointers with 0, not with NULL or Z_NULL [Truta]
228- Fix prototype of syncsearch in inflate.c [Truta] 228- Fix prototype of syncsearch in inflate.c [Truta]
229- Introduce ASMINF macro to be enabled when using an ASM implementation 229- Introduce ASMINF macro to be enabled when using an ASM implementation
230 of inflate_fast [Truta] 230 of inflate_fast [Truta]
231- Change NO_DEFLATE to NO_GZCOMPRESS [Truta] 231- Change NO_DEFLATE to NO_GZCOMPRESS [Truta]
232- Modify test_gzio in example.c to take a single file name as a 232- Modify test_gzio in example.c to take a single file name as a
233 parameter [Truta] 233 parameter [Truta]
234- Exit the example.c program if gzopen fails [Truta] 234- Exit the example.c program if gzopen fails [Truta]
235- Add type casts around strlen in example.c [Truta] 235- Add type casts around strlen in example.c [Truta]
236- Remove casting to sizeof in minigzip.c; give a proper type 236- Remove casting to sizeof in minigzip.c; give a proper type
237 to the variable compared with SUFFIX_LEN [Truta] 237 to the variable compared with SUFFIX_LEN [Truta]
238- Update definitions of STDC and STDC99 in zconf.h [Truta] 238- Update definitions of STDC and STDC99 in zconf.h [Truta]
239- Synchronize zconf.h with the new Windows DLL interface [Truta] 239- Synchronize zconf.h with the new Windows DLL interface [Truta]
240- Use SYS16BIT instead of __32BIT__ to distinguish between 240- Use SYS16BIT instead of __32BIT__ to distinguish between
241 16- and 32-bit platforms [Truta] 241 16- and 32-bit platforms [Truta]
242- Use far memory allocators in small 16-bit memory models for 242- Use far memory allocators in small 16-bit memory models for
243 Turbo C [Truta] 243 Turbo C [Truta]
244- Add info about the use of ASMV, ASMINF and ZLIB_WINAPI in 244- Add info about the use of ASMV, ASMINF and ZLIB_WINAPI in
245 zlibCompileFlags [Truta] 245 zlibCompileFlags [Truta]
246- Cygwin has vsnprintf [Wilson] 246- Cygwin has vsnprintf [Wilson]
247- In Windows16, OS_CODE is 0, as in MSDOS [Truta] 247- In Windows16, OS_CODE is 0, as in MSDOS [Truta]
248- In Cygwin, OS_CODE is 3 (Unix), not 11 (Windows32) [Wilson] 248- In Cygwin, OS_CODE is 3 (Unix), not 11 (Windows32) [Wilson]
249 249
250Changes in 1.2.0.4 (10 August 2003) 250Changes in 1.2.0.4 (10 August 2003)
251- Minor FAQ updates 251- Minor FAQ updates
252- Be more strict when checking inflateInit2's windowBits parameter 252- Be more strict when checking inflateInit2's windowBits parameter
253- Change NO_GUNZIP compile option to NO_GZIP to cover deflate as well 253- Change NO_GUNZIP compile option to NO_GZIP to cover deflate as well
254- Add gzip wrapper option to deflateInit2 using windowBits 254- Add gzip wrapper option to deflateInit2 using windowBits
255- Add updated QNX rule in configure and qnx directory [Bonnefoy] 255- Add updated QNX rule in configure and qnx directory [Bonnefoy]
256- Make inflate distance-too-far checks more rigorous 256- Make inflate distance-too-far checks more rigorous
257- Clean up FAR usage in inflate 257- Clean up FAR usage in inflate
258- Add casting to sizeof() in gzio.c and minigzip.c 258- Add casting to sizeof() in gzio.c and minigzip.c
259 259
260Changes in 1.2.0.3 (19 July 2003) 260Changes in 1.2.0.3 (19 July 2003)
261- Fix silly error in gzungetc() implementation [Vollant] 261- Fix silly error in gzungetc() implementation [Vollant]
262- Update contrib/minizip and contrib/vstudio [Vollant] 262- Update contrib/minizip and contrib/vstudio [Vollant]
263- Fix printf format in example.c 263- Fix printf format in example.c
264- Correct cdecl support in zconf.in.h [Anisimkov] 264- Correct cdecl support in zconf.in.h [Anisimkov]
265- Minor FAQ updates 265- Minor FAQ updates
266 266
267Changes in 1.2.0.2 (13 July 2003) 267Changes in 1.2.0.2 (13 July 2003)
268- Add ZLIB_VERNUM in zlib.h for numerical preprocessor comparisons 268- Add ZLIB_VERNUM in zlib.h for numerical preprocessor comparisons
269- Attempt to avoid warnings in crc32.c for pointer-int conversion 269- Attempt to avoid warnings in crc32.c for pointer-int conversion
270- Add AIX to configure, remove aix directory [Bakker] 270- Add AIX to configure, remove aix directory [Bakker]
271- Add some casts to minigzip.c 271- Add some casts to minigzip.c
272- Improve checking after insecure sprintf() or vsprintf() calls 272- Improve checking after insecure sprintf() or vsprintf() calls
273- Remove #elif's from crc32.c 273- Remove #elif's from crc32.c
274- Change leave label to inf_leave in inflate.c and infback.c to avoid 274- Change leave label to inf_leave in inflate.c and infback.c to avoid
275 library conflicts 275 library conflicts
276- Remove inflate gzip decoding by default--only enable gzip decoding by 276- Remove inflate gzip decoding by default--only enable gzip decoding by
277 special request for stricter backward compatibility 277 special request for stricter backward compatibility
278- Add zlibCompileFlags() function to return compilation information 278- Add zlibCompileFlags() function to return compilation information
279- More typecasting in deflate.c to avoid warnings 279- More typecasting in deflate.c to avoid warnings
280- Remove leading underscore from _Capital #defines [Truta] 280- Remove leading underscore from _Capital #defines [Truta]
281- Fix configure to link shared library when testing 281- Fix configure to link shared library when testing
282- Add some Windows CE target adjustments [Mai] 282- Add some Windows CE target adjustments [Mai]
283- Remove #define ZLIB_DLL in zconf.h [Vollant] 283- Remove #define ZLIB_DLL in zconf.h [Vollant]
284- Add zlib.3 [Rodgers] 284- Add zlib.3 [Rodgers]
285- Update RFC URL in deflate.c and algorithm.txt [Mai] 285- Update RFC URL in deflate.c and algorithm.txt [Mai]
286- Add zlib_dll_FAQ.txt to contrib [Truta] 286- Add zlib_dll_FAQ.txt to contrib [Truta]
287- Add UL to some constants [Truta] 287- Add UL to some constants [Truta]
288- Update minizip and vstudio [Vollant] 288- Update minizip and vstudio [Vollant]
289- Remove vestigial NEED_DUMMY_RETURN from zconf.in.h 289- Remove vestigial NEED_DUMMY_RETURN from zconf.in.h
290- Expand use of NO_DUMMY_DECL to avoid all dummy structures 290- Expand use of NO_DUMMY_DECL to avoid all dummy structures
291- Added iostream3 to contrib [Schwardt] 291- Added iostream3 to contrib [Schwardt]
292- Replace rewind() with fseek() for WinCE [Truta] 292- Replace rewind() with fseek() for WinCE [Truta]
293- Improve setting of zlib format compression level flags 293- Improve setting of zlib format compression level flags
294 - Report 0 for huffman and rle strategies and for level == 0 or 1 294 - Report 0 for huffman and rle strategies and for level == 0 or 1
295 - Report 2 only for level == 6 295 - Report 2 only for level == 6
296- Only deal with 64K limit when necessary at compile time [Truta] 296- Only deal with 64K limit when necessary at compile time [Truta]
297- Allow TOO_FAR check to be turned off at compile time [Truta] 297- Allow TOO_FAR check to be turned off at compile time [Truta]
298- Add gzclearerr() function [Souza] 298- Add gzclearerr() function [Souza]
299- Add gzungetc() function 299- Add gzungetc() function
300 300
301Changes in 1.2.0.1 (17 March 2003) 301Changes in 1.2.0.1 (17 March 2003)
302- Add Z_RLE strategy for run-length encoding [Truta] 302- Add Z_RLE strategy for run-length encoding [Truta]
303 - When Z_RLE requested, restrict matches to distance one 303 - When Z_RLE requested, restrict matches to distance one
304 - Update zlib.h, minigzip.c, gzopen(), gzdopen() for Z_RLE 304 - Update zlib.h, minigzip.c, gzopen(), gzdopen() for Z_RLE
305- Correct FASTEST compilation to allow level == 0 305- Correct FASTEST compilation to allow level == 0
306- Clean up what gets compiled for FASTEST 306- Clean up what gets compiled for FASTEST
307- Incorporate changes to zconf.in.h [Vollant] 307- Incorporate changes to zconf.in.h [Vollant]
308 - Refine detection of Turbo C need for dummy returns 308 - Refine detection of Turbo C need for dummy returns
309 - Refine ZLIB_DLL compilation 309 - Refine ZLIB_DLL compilation
310 - Include additional header file on VMS for off_t typedef 310 - Include additional header file on VMS for off_t typedef
311- Try to use _vsnprintf where it supplants vsprintf [Vollant] 311- Try to use _vsnprintf where it supplants vsprintf [Vollant]
312- Add some casts in inffast.c 312- Add some casts in inffast.c
313- Enchance comments in zlib.h on what happens if gzprintf() tries to 313- Enchance comments in zlib.h on what happens if gzprintf() tries to
314 write more than 4095 bytes before compression 314 write more than 4095 bytes before compression
315- Remove unused state from inflateBackEnd() 315- Remove unused state from inflateBackEnd()
316- Remove exit(0) from minigzip.c, example.c 316- Remove exit(0) from minigzip.c, example.c
317- Get rid of all those darn tabs 317- Get rid of all those darn tabs
318- Add "check" target to Makefile.in that does the same thing as "test" 318- Add "check" target to Makefile.in that does the same thing as "test"
319- Add "mostlyclean" and "maintainer-clean" targets to Makefile.in 319- Add "mostlyclean" and "maintainer-clean" targets to Makefile.in
320- Update contrib/inflate86 [Anderson] 320- Update contrib/inflate86 [Anderson]
321- Update contrib/testzlib, contrib/vstudio, contrib/minizip [Vollant] 321- Update contrib/testzlib, contrib/vstudio, contrib/minizip [Vollant]
322- Add msdos and win32 directories with makefiles [Truta] 322- Add msdos and win32 directories with makefiles [Truta]
323- More additions and improvements to the FAQ 323- More additions and improvements to the FAQ
324 324
325Changes in 1.2.0 (9 March 2003) 325Changes in 1.2.0 (9 March 2003)
326- New and improved inflate code 326- New and improved inflate code
327 - About 20% faster 327 - About 20% faster
328 - Does not allocate 32K window unless and until needed 328 - Does not allocate 32K window unless and until needed
329 - Automatically detects and decompresses gzip streams 329 - Automatically detects and decompresses gzip streams
330 - Raw inflate no longer needs an extra dummy byte at end 330 - Raw inflate no longer needs an extra dummy byte at end
331 - Added inflateBack functions using a callback interface--even faster 331 - Added inflateBack functions using a callback interface--even faster
332 than inflate, useful for file utilities (gzip, zip) 332 than inflate, useful for file utilities (gzip, zip)
333 - Added inflateCopy() function to record state for random access on 333 - Added inflateCopy() function to record state for random access on
334 externally generated deflate streams (e.g. in gzip files) 334 externally generated deflate streams (e.g. in gzip files)
335 - More readable code (I hope) 335 - More readable code (I hope)
336- New and improved crc32() 336- New and improved crc32()
337 - About 50% faster, thanks to suggestions from Rodney Brown 337 - About 50% faster, thanks to suggestions from Rodney Brown
338- Add deflateBound() and compressBound() functions 338- Add deflateBound() and compressBound() functions
339- Fix memory leak in deflateInit2() 339- Fix memory leak in deflateInit2()
340- Permit setting dictionary for raw deflate (for parallel deflate) 340- Permit setting dictionary for raw deflate (for parallel deflate)
341- Fix const declaration for gzwrite() 341- Fix const declaration for gzwrite()
342- Check for some malloc() failures in gzio.c 342- Check for some malloc() failures in gzio.c
343- Fix bug in gzopen() on single-byte file 0x1f 343- Fix bug in gzopen() on single-byte file 0x1f
344- Fix bug in gzread() on concatenated file with 0x1f at end of buffer 344- Fix bug in gzread() on concatenated file with 0x1f at end of buffer
345 and next buffer doesn't start with 0x8b 345 and next buffer doesn't start with 0x8b
346- Fix uncompress() to return Z_DATA_ERROR on truncated input 346- Fix uncompress() to return Z_DATA_ERROR on truncated input
347- Free memory at end of example.c 347- Free memory at end of example.c
348- Remove MAX #define in trees.c (conflicted with some libraries) 348- Remove MAX #define in trees.c (conflicted with some libraries)
349- Fix static const's in deflate.c, gzio.c, and zutil.[ch] 349- Fix static const's in deflate.c, gzio.c, and zutil.[ch]
350- Declare malloc() and free() in gzio.c if STDC not defined 350- Declare malloc() and free() in gzio.c if STDC not defined
351- Use malloc() instead of calloc() in zutil.c if int big enough 351- Use malloc() instead of calloc() in zutil.c if int big enough
352- Define STDC for AIX 352- Define STDC for AIX
353- Add aix/ with approach for compiling shared library on AIX 353- Add aix/ with approach for compiling shared library on AIX
354- Add HP-UX support for shared libraries in configure 354- Add HP-UX support for shared libraries in configure
355- Add OpenUNIX support for shared libraries in configure 355- Add OpenUNIX support for shared libraries in configure
356- Use $cc instead of gcc to build shared library 356- Use $cc instead of gcc to build shared library
357- Make prefix directory if needed when installing 357- Make prefix directory if needed when installing
358- Correct Macintosh avoidance of typedef Byte in zconf.h 358- Correct Macintosh avoidance of typedef Byte in zconf.h
359- Correct Turbo C memory allocation when under Linux 359- Correct Turbo C memory allocation when under Linux
360- Use libz.a instead of -lz in Makefile (assure use of compiled library) 360- Use libz.a instead of -lz in Makefile (assure use of compiled library)
361- Update configure to check for snprintf or vsnprintf functions and their 361- Update configure to check for snprintf or vsnprintf functions and their
362 return value, warn during make if using an insecure function 362 return value, warn during make if using an insecure function
363- Fix configure problem with compile-time knowledge of HAVE_UNISTD_H that 363- Fix configure problem with compile-time knowledge of HAVE_UNISTD_H that
364 is lost when library is used--resolution is to build new zconf.h 364 is lost when library is used--resolution is to build new zconf.h
365- Documentation improvements (in zlib.h): 365- Documentation improvements (in zlib.h):
366 - Document raw deflate and inflate 366 - Document raw deflate and inflate
367 - Update RFCs URL 367 - Update RFCs URL
368 - Point out that zlib and gzip formats are different 368 - Point out that zlib and gzip formats are different
369 - Note that Z_BUF_ERROR is not fatal 369 - Note that Z_BUF_ERROR is not fatal
370 - Document string limit for gzprintf() and possible buffer overflow 370 - Document string limit for gzprintf() and possible buffer overflow
371 - Note requirement on avail_out when flushing 371 - Note requirement on avail_out when flushing
372 - Note permitted values of flush parameter of inflate() 372 - Note permitted values of flush parameter of inflate()
373- Add some FAQs (and even answers) to the FAQ 373- Add some FAQs (and even answers) to the FAQ
374- Add contrib/inflate86/ for x86 faster inflate 374- Add contrib/inflate86/ for x86 faster inflate
375- Add contrib/blast/ for PKWare Data Compression Library decompression 375- Add contrib/blast/ for PKWare Data Compression Library decompression
376- Add contrib/puff/ simple inflate for deflate format description 376- Add contrib/puff/ simple inflate for deflate format description
377 377
378Changes in 1.1.4 (11 March 2002) 378Changes in 1.1.4 (11 March 2002)
379- ZFREE was repeated on same allocation on some error conditions. 379- ZFREE was repeated on same allocation on some error conditions.
380 This creates a security problem described in 380 This creates a security problem described in
381 http://www.zlib.org/advisory-2002-03-11.txt 381 http://www.zlib.org/advisory-2002-03-11.txt
382- Returned incorrect error (Z_MEM_ERROR) on some invalid data 382- Returned incorrect error (Z_MEM_ERROR) on some invalid data
383- Avoid accesses before window for invalid distances with inflate window 383- Avoid accesses before window for invalid distances with inflate window
384 less than 32K. 384 less than 32K.
385- force windowBits > 8 to avoid a bug in the encoder for a window size 385- force windowBits > 8 to avoid a bug in the encoder for a window size
386 of 256 bytes. (A complete fix will be available in 1.1.5). 386 of 256 bytes. (A complete fix will be available in 1.1.5).
387 387
388Changes in 1.1.3 (9 July 1998) 388Changes in 1.1.3 (9 July 1998)
389- fix "an inflate input buffer bug that shows up on rare but persistent 389- fix "an inflate input buffer bug that shows up on rare but persistent
390 occasions" (Mark) 390 occasions" (Mark)
391- fix gzread and gztell for concatenated .gz files (Didier Le Botlan) 391- fix gzread and gztell for concatenated .gz files (Didier Le Botlan)
392- fix gzseek(..., SEEK_SET) in write mode 392- fix gzseek(..., SEEK_SET) in write mode
393- fix crc check after a gzeek (Frank Faubert) 393- fix crc check after a gzeek (Frank Faubert)
394- fix miniunzip when the last entry in a zip file is itself a zip file 394- fix miniunzip when the last entry in a zip file is itself a zip file
395 (J Lillge) 395 (J Lillge)
396- add contrib/asm586 and contrib/asm686 (Brian Raiter) 396- add contrib/asm586 and contrib/asm686 (Brian Raiter)
397 See http://www.muppetlabs.com/~breadbox/software/assembly.html 397 See http://www.muppetlabs.com/~breadbox/software/assembly.html
398- add support for Delphi 3 in contrib/delphi (Bob Dellaca) 398- add support for Delphi 3 in contrib/delphi (Bob Dellaca)
399- add support for C++Builder 3 and Delphi 3 in contrib/delphi2 (Davide Moretti) 399- add support for C++Builder 3 and Delphi 3 in contrib/delphi2 (Davide Moretti)
400- do not exit prematurely in untgz if 0 at start of block (Magnus Holmgren) 400- do not exit prematurely in untgz if 0 at start of block (Magnus Holmgren)
401- use macro EXTERN instead of extern to support DLL for BeOS (Sander Stoks) 401- use macro EXTERN instead of extern to support DLL for BeOS (Sander Stoks)
402- added a FAQ file 402- added a FAQ file
403 403
404- Support gzdopen on Mac with Metrowerks (Jason Linhart) 404- Support gzdopen on Mac with Metrowerks (Jason Linhart)
405- Do not redefine Byte on Mac (Brad Pettit & Jason Linhart) 405- Do not redefine Byte on Mac (Brad Pettit & Jason Linhart)
406- define SEEK_END too if SEEK_SET is not defined (Albert Chin-A-Young) 406- define SEEK_END too if SEEK_SET is not defined (Albert Chin-A-Young)
407- avoid some warnings with Borland C (Tom Tanner) 407- avoid some warnings with Borland C (Tom Tanner)
408- fix a problem in contrib/minizip/zip.c for 16-bit MSDOS (Gilles Vollant) 408- fix a problem in contrib/minizip/zip.c for 16-bit MSDOS (Gilles Vollant)
409- emulate utime() for WIN32 in contrib/untgz (Gilles Vollant) 409- emulate utime() for WIN32 in contrib/untgz (Gilles Vollant)
410- allow several arguments to configure (Tim Mooney, Frodo Looijaard) 410- allow several arguments to configure (Tim Mooney, Frodo Looijaard)
411- use libdir and includedir in Makefile.in (Tim Mooney) 411- use libdir and includedir in Makefile.in (Tim Mooney)
412- support shared libraries on OSF1 V4 (Tim Mooney) 412- support shared libraries on OSF1 V4 (Tim Mooney)
413- remove so_locations in "make clean" (Tim Mooney) 413- remove so_locations in "make clean" (Tim Mooney)
414- fix maketree.c compilation error (Glenn, Mark) 414- fix maketree.c compilation error (Glenn, Mark)
415- Python interface to zlib now in Python 1.5 (Jeremy Hylton) 415- Python interface to zlib now in Python 1.5 (Jeremy Hylton)
416- new Makefile.riscos (Rich Walker) 416- new Makefile.riscos (Rich Walker)
417- initialize static descriptors in trees.c for embedded targets (Nick Smith) 417- initialize static descriptors in trees.c for embedded targets (Nick Smith)
418- use "foo-gz" in example.c for RISCOS and VMS (Nick Smith) 418- use "foo-gz" in example.c for RISCOS and VMS (Nick Smith)
419- add the OS/2 files in Makefile.in too (Andrew Zabolotny) 419- add the OS/2 files in Makefile.in too (Andrew Zabolotny)
420- fix fdopen and halloc macros for Microsoft C 6.0 (Tom Lane) 420- fix fdopen and halloc macros for Microsoft C 6.0 (Tom Lane)
421- fix maketree.c to allow clean compilation of inffixed.h (Mark) 421- fix maketree.c to allow clean compilation of inffixed.h (Mark)
422- fix parameter check in deflateCopy (Gunther Nikl) 422- fix parameter check in deflateCopy (Gunther Nikl)
423- cleanup trees.c, use compressed_len only in debug mode (Christian Spieler) 423- cleanup trees.c, use compressed_len only in debug mode (Christian Spieler)
424- Many portability patches by Christian Spieler: 424- Many portability patches by Christian Spieler:
425 . zutil.c, zutil.h: added "const" for zmem* 425 . zutil.c, zutil.h: added "const" for zmem*
426 . Make_vms.com: fixed some typos 426 . Make_vms.com: fixed some typos
427 . Make_vms.com: msdos/Makefile.*: removed zutil.h from some dependency lists 427 . Make_vms.com: msdos/Makefile.*: removed zutil.h from some dependency lists
428 . msdos/Makefile.msc: remove "default rtl link library" info from obj files 428 . msdos/Makefile.msc: remove "default rtl link library" info from obj files
429 . msdos/Makefile.*: use model-dependent name for the built zlib library 429 . msdos/Makefile.*: use model-dependent name for the built zlib library
430 . msdos/Makefile.emx, nt/Makefile.emx, nt/Makefile.gcc: 430 . msdos/Makefile.emx, nt/Makefile.emx, nt/Makefile.gcc:
431 new makefiles, for emx (DOS/OS2), emx&rsxnt and mingw32 (Windows 9x / NT) 431 new makefiles, for emx (DOS/OS2), emx&rsxnt and mingw32 (Windows 9x / NT)
432- use define instead of typedef for Bytef also for MSC small/medium (Tom Lane) 432- use define instead of typedef for Bytef also for MSC small/medium (Tom Lane)
433- replace __far with _far for better portability (Christian Spieler, Tom Lane) 433- replace __far with _far for better portability (Christian Spieler, Tom Lane)
434- fix test for errno.h in configure (Tim Newsham) 434- fix test for errno.h in configure (Tim Newsham)
435 435
436Changes in 1.1.2 (19 March 98) 436Changes in 1.1.2 (19 March 98)
437- added contrib/minzip, mini zip and unzip based on zlib (Gilles Vollant) 437- added contrib/minzip, mini zip and unzip based on zlib (Gilles Vollant)
438 See http://www.winimage.com/zLibDll/unzip.html 438 See http://www.winimage.com/zLibDll/unzip.html
439- preinitialize the inflate tables for fixed codes, to make the code 439- preinitialize the inflate tables for fixed codes, to make the code
440 completely thread safe (Mark) 440 completely thread safe (Mark)
441- some simplifications and slight speed-up to the inflate code (Mark) 441- some simplifications and slight speed-up to the inflate code (Mark)
442- fix gzeof on non-compressed files (Allan Schrum) 442- fix gzeof on non-compressed files (Allan Schrum)
443- add -std1 option in configure for OSF1 to fix gzprintf (Martin Mokrejs) 443- add -std1 option in configure for OSF1 to fix gzprintf (Martin Mokrejs)
444- use default value of 4K for Z_BUFSIZE for 16-bit MSDOS (Tim Wegner + Glenn) 444- use default value of 4K for Z_BUFSIZE for 16-bit MSDOS (Tim Wegner + Glenn)
445- added os2/Makefile.def and os2/zlib.def (Andrew Zabolotny) 445- added os2/Makefile.def and os2/zlib.def (Andrew Zabolotny)
446- add shared lib support for UNIX_SV4.2MP (MATSUURA Takanori) 446- add shared lib support for UNIX_SV4.2MP (MATSUURA Takanori)
447- do not wrap extern "C" around system includes (Tom Lane) 447- do not wrap extern "C" around system includes (Tom Lane)
448- mention zlib binding for TCL in README (Andreas Kupries) 448- mention zlib binding for TCL in README (Andreas Kupries)
449- added amiga/Makefile.pup for Amiga powerUP SAS/C PPC (Andreas Kleinert) 449- added amiga/Makefile.pup for Amiga powerUP SAS/C PPC (Andreas Kleinert)
450- allow "make install prefix=..." even after configure (Glenn Randers-Pehrson) 450- allow "make install prefix=..." even after configure (Glenn Randers-Pehrson)
451- allow "configure --prefix $HOME" (Tim Mooney) 451- allow "configure --prefix $HOME" (Tim Mooney)
452- remove warnings in example.c and gzio.c (Glenn Randers-Pehrson) 452- remove warnings in example.c and gzio.c (Glenn Randers-Pehrson)
453- move Makefile.sas to amiga/Makefile.sas 453- move Makefile.sas to amiga/Makefile.sas
454 454
455Changes in 1.1.1 (27 Feb 98) 455Changes in 1.1.1 (27 Feb 98)
456- fix macros _tr_tally_* in deflate.h for debug mode (Glenn Randers-Pehrson) 456- fix macros _tr_tally_* in deflate.h for debug mode (Glenn Randers-Pehrson)
457- remove block truncation heuristic which had very marginal effect for zlib 457- remove block truncation heuristic which had very marginal effect for zlib
458 (smaller lit_bufsize than in gzip 1.2.4) and degraded a little the 458 (smaller lit_bufsize than in gzip 1.2.4) and degraded a little the
459 compression ratio on some files. This also allows inlining _tr_tally for 459 compression ratio on some files. This also allows inlining _tr_tally for
460 matches in deflate_slow. 460 matches in deflate_slow.
461- added msdos/Makefile.w32 for WIN32 Microsoft Visual C++ (Bob Frazier) 461- added msdos/Makefile.w32 for WIN32 Microsoft Visual C++ (Bob Frazier)
462 462
463Changes in 1.1.0 (24 Feb 98) 463Changes in 1.1.0 (24 Feb 98)
464- do not return STREAM_END prematurely in inflate (John Bowler) 464- do not return STREAM_END prematurely in inflate (John Bowler)
465- revert to the zlib 1.0.8 inflate to avoid the gcc 2.8.0 bug (Jeremy Buhler) 465- revert to the zlib 1.0.8 inflate to avoid the gcc 2.8.0 bug (Jeremy Buhler)
466- compile with -DFASTEST to get compression code optimized for speed only 466- compile with -DFASTEST to get compression code optimized for speed only
467- in minigzip, try mmap'ing the input file first (Miguel Albrecht) 467- in minigzip, try mmap'ing the input file first (Miguel Albrecht)
468- increase size of I/O buffers in minigzip.c and gzio.c (not a big gain 468- increase size of I/O buffers in minigzip.c and gzio.c (not a big gain
469 on Sun but significant on HP) 469 on Sun but significant on HP)
470 470
471- add a pointer to experimental unzip library in README (Gilles Vollant) 471- add a pointer to experimental unzip library in README (Gilles Vollant)
472- initialize variable gcc in configure (Chris Herborth) 472- initialize variable gcc in configure (Chris Herborth)
473 473
474Changes in 1.0.9 (17 Feb 1998) 474Changes in 1.0.9 (17 Feb 1998)
475- added gzputs and gzgets functions 475- added gzputs and gzgets functions
476- do not clear eof flag in gzseek (Mark Diekhans) 476- do not clear eof flag in gzseek (Mark Diekhans)
477- fix gzseek for files in transparent mode (Mark Diekhans) 477- fix gzseek for files in transparent mode (Mark Diekhans)
478- do not assume that vsprintf returns the number of bytes written (Jens Krinke) 478- do not assume that vsprintf returns the number of bytes written (Jens Krinke)
479- replace EXPORT with ZEXPORT to avoid conflict with other programs 479- replace EXPORT with ZEXPORT to avoid conflict with other programs
480- added compress2 in zconf.h, zlib.def, zlib.dnt 480- added compress2 in zconf.h, zlib.def, zlib.dnt
481- new asm code from Gilles Vollant in contrib/asm386 481- new asm code from Gilles Vollant in contrib/asm386
482- simplify the inflate code (Mark): 482- simplify the inflate code (Mark):
483 . Replace ZALLOC's in huft_build() with single ZALLOC in inflate_blocks_new() 483 . Replace ZALLOC's in huft_build() with single ZALLOC in inflate_blocks_new()
484 . ZALLOC the length list in inflate_trees_fixed() instead of using stack 484 . ZALLOC the length list in inflate_trees_fixed() instead of using stack
485 . ZALLOC the value area for huft_build() instead of using stack 485 . ZALLOC the value area for huft_build() instead of using stack
486 . Simplify Z_FINISH check in inflate() 486 . Simplify Z_FINISH check in inflate()
487 487
488- Avoid gcc 2.8.0 comparison bug a little differently than zlib 1.0.8 488- Avoid gcc 2.8.0 comparison bug a little differently than zlib 1.0.8
489- in inftrees.c, avoid cc -O bug on HP (Farshid Elahi) 489- in inftrees.c, avoid cc -O bug on HP (Farshid Elahi)
490- in zconf.h move the ZLIB_DLL stuff earlier to avoid problems with 490- in zconf.h move the ZLIB_DLL stuff earlier to avoid problems with
491 the declaration of FAR (Gilles VOllant) 491 the declaration of FAR (Gilles VOllant)
492- install libz.so* with mode 755 (executable) instead of 644 (Marc Lehmann) 492- install libz.so* with mode 755 (executable) instead of 644 (Marc Lehmann)
493- read_buf buf parameter of type Bytef* instead of charf* 493- read_buf buf parameter of type Bytef* instead of charf*
494- zmemcpy parameters are of type Bytef*, not charf* (Joseph Strout) 494- zmemcpy parameters are of type Bytef*, not charf* (Joseph Strout)
495- do not redeclare unlink in minigzip.c for WIN32 (John Bowler) 495- do not redeclare unlink in minigzip.c for WIN32 (John Bowler)
496- fix check for presence of directories in "make install" (Ian Willis) 496- fix check for presence of directories in "make install" (Ian Willis)
497 497
498Changes in 1.0.8 (27 Jan 1998) 498Changes in 1.0.8 (27 Jan 1998)
499- fixed offsets in contrib/asm386/gvmat32.asm (Gilles Vollant) 499- fixed offsets in contrib/asm386/gvmat32.asm (Gilles Vollant)
500- fix gzgetc and gzputc for big endian systems (Markus Oberhumer) 500- fix gzgetc and gzputc for big endian systems (Markus Oberhumer)
501- added compress2() to allow setting the compression level 501- added compress2() to allow setting the compression level
502- include sys/types.h to get off_t on some systems (Marc Lehmann & QingLong) 502- include sys/types.h to get off_t on some systems (Marc Lehmann & QingLong)
503- use constant arrays for the static trees in trees.c instead of computing 503- use constant arrays for the static trees in trees.c instead of computing
504 them at run time (thanks to Ken Raeburn for this suggestion). To create 504 them at run time (thanks to Ken Raeburn for this suggestion). To create
505 trees.h, compile with GEN_TREES_H and run "make test". 505 trees.h, compile with GEN_TREES_H and run "make test".
506- check return code of example in "make test" and display result 506- check return code of example in "make test" and display result
507- pass minigzip command line options to file_compress 507- pass minigzip command line options to file_compress
508- simplifying code of inflateSync to avoid gcc 2.8 bug 508- simplifying code of inflateSync to avoid gcc 2.8 bug
509 509
510- support CC="gcc -Wall" in configure -s (QingLong) 510- support CC="gcc -Wall" in configure -s (QingLong)
511- avoid a flush caused by ftell in gzopen for write mode (Ken Raeburn) 511- avoid a flush caused by ftell in gzopen for write mode (Ken Raeburn)
512- fix test for shared library support to avoid compiler warnings 512- fix test for shared library support to avoid compiler warnings
513- zlib.lib -> zlib.dll in msdos/zlib.rc (Gilles Vollant) 513- zlib.lib -> zlib.dll in msdos/zlib.rc (Gilles Vollant)
514- check for TARGET_OS_MAC in addition to MACOS (Brad Pettit) 514- check for TARGET_OS_MAC in addition to MACOS (Brad Pettit)
515- do not use fdopen for Metrowerks on Mac (Brad Pettit)) 515- do not use fdopen for Metrowerks on Mac (Brad Pettit))
516- add checks for gzputc and gzputc in example.c 516- add checks for gzputc and gzputc in example.c
517- avoid warnings in gzio.c and deflate.c (Andreas Kleinert) 517- avoid warnings in gzio.c and deflate.c (Andreas Kleinert)
518- use const for the CRC table (Ken Raeburn) 518- use const for the CRC table (Ken Raeburn)
519- fixed "make uninstall" for shared libraries 519- fixed "make uninstall" for shared libraries
520- use Tracev instead of Trace in infblock.c 520- use Tracev instead of Trace in infblock.c
521- in example.c use correct compressed length for test_sync 521- in example.c use correct compressed length for test_sync
522- suppress +vnocompatwarnings in configure for HPUX (not always supported) 522- suppress +vnocompatwarnings in configure for HPUX (not always supported)
523 523
524Changes in 1.0.7 (20 Jan 1998) 524Changes in 1.0.7 (20 Jan 1998)
525- fix gzseek which was broken in write mode 525- fix gzseek which was broken in write mode
526- return error for gzseek to negative absolute position 526- return error for gzseek to negative absolute position
527- fix configure for Linux (Chun-Chung Chen) 527- fix configure for Linux (Chun-Chung Chen)
528- increase stack space for MSC (Tim Wegner) 528- increase stack space for MSC (Tim Wegner)
529- get_crc_table and inflateSyncPoint are EXPORTed (Gilles Vollant) 529- get_crc_table and inflateSyncPoint are EXPORTed (Gilles Vollant)
530- define EXPORTVA for gzprintf (Gilles Vollant) 530- define EXPORTVA for gzprintf (Gilles Vollant)
531- added man page zlib.3 (Rick Rodgers) 531- added man page zlib.3 (Rick Rodgers)
532- for contrib/untgz, fix makedir() and improve Makefile 532- for contrib/untgz, fix makedir() and improve Makefile
533 533
534- check gzseek in write mode in example.c 534- check gzseek in write mode in example.c
535- allocate extra buffer for seeks only if gzseek is actually called 535- allocate extra buffer for seeks only if gzseek is actually called
536- avoid signed/unsigned comparisons (Tim Wegner, Gilles Vollant) 536- avoid signed/unsigned comparisons (Tim Wegner, Gilles Vollant)
537- add inflateSyncPoint in zconf.h 537- add inflateSyncPoint in zconf.h
538- fix list of exported functions in nt/zlib.dnt and mdsos/zlib.def 538- fix list of exported functions in nt/zlib.dnt and mdsos/zlib.def
539 539
540Changes in 1.0.6 (19 Jan 1998) 540Changes in 1.0.6 (19 Jan 1998)
541- add functions gzprintf, gzputc, gzgetc, gztell, gzeof, gzseek, gzrewind and 541- add functions gzprintf, gzputc, gzgetc, gztell, gzeof, gzseek, gzrewind and
542 gzsetparams (thanks to Roland Giersig and Kevin Ruland for some of this code) 542 gzsetparams (thanks to Roland Giersig and Kevin Ruland for some of this code)
543- Fix a deflate bug occurring only with compression level 0 (thanks to 543- Fix a deflate bug occurring only with compression level 0 (thanks to
544 Andy Buckler for finding this one). 544 Andy Buckler for finding this one).
545- In minigzip, pass transparently also the first byte for .Z files. 545- In minigzip, pass transparently also the first byte for .Z files.
546- return Z_BUF_ERROR instead of Z_OK if output buffer full in uncompress() 546- return Z_BUF_ERROR instead of Z_OK if output buffer full in uncompress()
547- check Z_FINISH in inflate (thanks to Marc Schluper) 547- check Z_FINISH in inflate (thanks to Marc Schluper)
548- Implement deflateCopy (thanks to Adam Costello) 548- Implement deflateCopy (thanks to Adam Costello)
549- make static libraries by default in configure, add --shared option. 549- make static libraries by default in configure, add --shared option.
550- move MSDOS or Windows specific files to directory msdos 550- move MSDOS or Windows specific files to directory msdos
551- suppress the notion of partial flush to simplify the interface 551- suppress the notion of partial flush to simplify the interface
552 (but the symbol Z_PARTIAL_FLUSH is kept for compatibility with 1.0.4) 552 (but the symbol Z_PARTIAL_FLUSH is kept for compatibility with 1.0.4)
553- suppress history buffer provided by application to simplify the interface 553- suppress history buffer provided by application to simplify the interface
554 (this feature was not implemented anyway in 1.0.4) 554 (this feature was not implemented anyway in 1.0.4)
555- next_in and avail_in must be initialized before calling inflateInit or 555- next_in and avail_in must be initialized before calling inflateInit or
556 inflateInit2 556 inflateInit2
557- add EXPORT in all exported functions (for Windows DLL) 557- add EXPORT in all exported functions (for Windows DLL)
558- added Makefile.nt (thanks to Stephen Williams) 558- added Makefile.nt (thanks to Stephen Williams)
559- added the unsupported "contrib" directory: 559- added the unsupported "contrib" directory:
560 contrib/asm386/ by Gilles Vollant <info@winimage.com> 560 contrib/asm386/ by Gilles Vollant <info@winimage.com>
561 386 asm code replacing longest_match(). 561 386 asm code replacing longest_match().
562 contrib/iostream/ by Kevin Ruland <kevin@rodin.wustl.edu> 562 contrib/iostream/ by Kevin Ruland <kevin@rodin.wustl.edu>
563 A C++ I/O streams interface to the zlib gz* functions 563 A C++ I/O streams interface to the zlib gz* functions
564 contrib/iostream2/ by Tyge Løvset <Tyge.Lovset@cmr.no> 564 contrib/iostream2/ by Tyge Løvset <Tyge.Lovset@cmr.no>
565 Another C++ I/O streams interface 565 Another C++ I/O streams interface
566 contrib/untgz/ by "Pedro A. Aranda Guti\irrez" <paag@tid.es> 566 contrib/untgz/ by "Pedro A. Aranda Guti\irrez" <paag@tid.es>
567 A very simple tar.gz file extractor using zlib 567 A very simple tar.gz file extractor using zlib
568 contrib/visual-basic.txt by Carlos Rios <c_rios@sonda.cl> 568 contrib/visual-basic.txt by Carlos Rios <c_rios@sonda.cl>
569 How to use compress(), uncompress() and the gz* functions from VB. 569 How to use compress(), uncompress() and the gz* functions from VB.
570- pass params -f (filtered data), -h (huffman only), -1 to -9 (compression 570- pass params -f (filtered data), -h (huffman only), -1 to -9 (compression
571 level) in minigzip (thanks to Tom Lane) 571 level) in minigzip (thanks to Tom Lane)
572 572
573- use const for rommable constants in deflate 573- use const for rommable constants in deflate
574- added test for gzseek and gztell in example.c 574- added test for gzseek and gztell in example.c
575- add undocumented function inflateSyncPoint() (hack for Paul Mackerras) 575- add undocumented function inflateSyncPoint() (hack for Paul Mackerras)
576- add undocumented function zError to convert error code to string 576- add undocumented function zError to convert error code to string
577 (for Tim Smithers) 577 (for Tim Smithers)
578- Allow compilation of gzio with -DNO_DEFLATE to avoid the compression code. 578- Allow compilation of gzio with -DNO_DEFLATE to avoid the compression code.
579- Use default memcpy for Symantec MSDOS compiler. 579- Use default memcpy for Symantec MSDOS compiler.
580- Add EXPORT keyword for check_func (needed for Windows DLL) 580- Add EXPORT keyword for check_func (needed for Windows DLL)
581- add current directory to LD_LIBRARY_PATH for "make test" 581- add current directory to LD_LIBRARY_PATH for "make test"
582- create also a link for libz.so.1 582- create also a link for libz.so.1
583- added support for FUJITSU UXP/DS (thanks to Toshiaki Nomura) 583- added support for FUJITSU UXP/DS (thanks to Toshiaki Nomura)
584- use $(SHAREDLIB) instead of libz.so in Makefile.in (for HPUX) 584- use $(SHAREDLIB) instead of libz.so in Makefile.in (for HPUX)
585- added -soname for Linux in configure (Chun-Chung Chen, 585- added -soname for Linux in configure (Chun-Chung Chen,
586- assign numbers to the exported functions in zlib.def (for Windows DLL) 586- assign numbers to the exported functions in zlib.def (for Windows DLL)
587- add advice in zlib.h for best usage of deflateSetDictionary 587- add advice in zlib.h for best usage of deflateSetDictionary
588- work around compiler bug on Atari (cast Z_NULL in call of s->checkfn) 588- work around compiler bug on Atari (cast Z_NULL in call of s->checkfn)
589- allow compilation with ANSI keywords only enabled for TurboC in large model 589- allow compilation with ANSI keywords only enabled for TurboC in large model
590- avoid "versionString"[0] (Borland bug) 590- avoid "versionString"[0] (Borland bug)
591- add NEED_DUMMY_RETURN for Borland 591- add NEED_DUMMY_RETURN for Borland
592- use variable z_verbose for tracing in debug mode (L. Peter Deutsch). 592- use variable z_verbose for tracing in debug mode (L. Peter Deutsch).
593- allow compilation with CC 593- allow compilation with CC
594- defined STDC for OS/2 (David Charlap) 594- defined STDC for OS/2 (David Charlap)
595- limit external names to 8 chars for MVS (Thomas Lund) 595- limit external names to 8 chars for MVS (Thomas Lund)
596- in minigzip.c, use static buffers only for 16-bit systems 596- in minigzip.c, use static buffers only for 16-bit systems
597- fix suffix check for "minigzip -d foo.gz" 597- fix suffix check for "minigzip -d foo.gz"
598- do not return an error for the 2nd of two consecutive gzflush() (Felix Lee) 598- do not return an error for the 2nd of two consecutive gzflush() (Felix Lee)
599- use _fdopen instead of fdopen for MSC >= 6.0 (Thomas Fanslau) 599- use _fdopen instead of fdopen for MSC >= 6.0 (Thomas Fanslau)
600- added makelcc.bat for lcc-win32 (Tom St Denis) 600- added makelcc.bat for lcc-win32 (Tom St Denis)
601- in Makefile.dj2, use copy and del instead of install and rm (Frank Donahoe) 601- in Makefile.dj2, use copy and del instead of install and rm (Frank Donahoe)
602- Avoid expanded $Id$. Use "rcs -kb" or "cvs admin -kb" to avoid Id expansion. 602- Avoid expanded $Id$. Use "rcs -kb" or "cvs admin -kb" to avoid Id expansion.
603- check for unistd.h in configure (for off_t) 603- check for unistd.h in configure (for off_t)
604- remove useless check parameter in inflate_blocks_free 604- remove useless check parameter in inflate_blocks_free
605- avoid useless assignment of s->check to itself in inflate_blocks_new 605- avoid useless assignment of s->check to itself in inflate_blocks_new
606- do not flush twice in gzclose (thanks to Ken Raeburn) 606- do not flush twice in gzclose (thanks to Ken Raeburn)
607- rename FOPEN as F_OPEN to avoid clash with /usr/include/sys/file.h 607- rename FOPEN as F_OPEN to avoid clash with /usr/include/sys/file.h
608- use NO_ERRNO_H instead of enumeration of operating systems with errno.h 608- use NO_ERRNO_H instead of enumeration of operating systems with errno.h
609- work around buggy fclose on pipes for HP/UX 609- work around buggy fclose on pipes for HP/UX
610- support zlib DLL with BORLAND C++ 5.0 (thanks to Glenn Randers-Pehrson) 610- support zlib DLL with BORLAND C++ 5.0 (thanks to Glenn Randers-Pehrson)
611- fix configure if CC is already equal to gcc 611- fix configure if CC is already equal to gcc
612 612
613Changes in 1.0.5 (3 Jan 98) 613Changes in 1.0.5 (3 Jan 98)
614- Fix inflate to terminate gracefully when fed corrupted or invalid data 614- Fix inflate to terminate gracefully when fed corrupted or invalid data
615- Use const for rommable constants in inflate 615- Use const for rommable constants in inflate
616- Eliminate memory leaks on error conditions in inflate 616- Eliminate memory leaks on error conditions in inflate
617- Removed some vestigial code in inflate 617- Removed some vestigial code in inflate
618- Update web address in README 618- Update web address in README
619 619
620Changes in 1.0.4 (24 Jul 96) 620Changes in 1.0.4 (24 Jul 96)
621- In very rare conditions, deflate(s, Z_FINISH) could fail to produce an EOF 621- In very rare conditions, deflate(s, Z_FINISH) could fail to produce an EOF
622 bit, so the decompressor could decompress all the correct data but went 622 bit, so the decompressor could decompress all the correct data but went
623 on to attempt decompressing extra garbage data. This affected minigzip too. 623 on to attempt decompressing extra garbage data. This affected minigzip too.
624- zlibVersion and gzerror return const char* (needed for DLL) 624- zlibVersion and gzerror return const char* (needed for DLL)
625- port to RISCOS (no fdopen, no multiple dots, no unlink, no fileno) 625- port to RISCOS (no fdopen, no multiple dots, no unlink, no fileno)
626- use z_error only for DEBUG (avoid problem with DLLs) 626- use z_error only for DEBUG (avoid problem with DLLs)
627 627
628Changes in 1.0.3 (2 Jul 96) 628Changes in 1.0.3 (2 Jul 96)
629- use z_streamp instead of z_stream *, which is now a far pointer in MSDOS 629- use z_streamp instead of z_stream *, which is now a far pointer in MSDOS
630 small and medium models; this makes the library incompatible with previous 630 small and medium models; this makes the library incompatible with previous
631 versions for these models. (No effect in large model or on other systems.) 631 versions for these models. (No effect in large model or on other systems.)
632- return OK instead of BUF_ERROR if previous deflate call returned with 632- return OK instead of BUF_ERROR if previous deflate call returned with
633 avail_out as zero but there is nothing to do 633 avail_out as zero but there is nothing to do
634- added memcmp for non STDC compilers 634- added memcmp for non STDC compilers
635- define NO_DUMMY_DECL for more Mac compilers (.h files merged incorrectly) 635- define NO_DUMMY_DECL for more Mac compilers (.h files merged incorrectly)
636- define __32BIT__ if __386__ or i386 is defined (pb. with Watcom and SCO) 636- define __32BIT__ if __386__ or i386 is defined (pb. with Watcom and SCO)
637- better check for 16-bit mode MSC (avoids problem with Symantec) 637- better check for 16-bit mode MSC (avoids problem with Symantec)
638 638
639Changes in 1.0.2 (23 May 96) 639Changes in 1.0.2 (23 May 96)
640- added Windows DLL support 640- added Windows DLL support
641- added a function zlibVersion (for the DLL support) 641- added a function zlibVersion (for the DLL support)
642- fixed declarations using Bytef in infutil.c (pb with MSDOS medium model) 642- fixed declarations using Bytef in infutil.c (pb with MSDOS medium model)
643- Bytef is define's instead of typedef'd only for Borland C 643- Bytef is define's instead of typedef'd only for Borland C
644- avoid reading uninitialized memory in example.c 644- avoid reading uninitialized memory in example.c
645- mention in README that the zlib format is now RFC1950 645- mention in README that the zlib format is now RFC1950
646- updated Makefile.dj2 646- updated Makefile.dj2
647- added algorithm.doc 647- added algorithm.doc
648 648
649Changes in 1.0.1 (20 May 96) [1.0 skipped to avoid confusion] 649Changes in 1.0.1 (20 May 96) [1.0 skipped to avoid confusion]
650- fix array overlay in deflate.c which sometimes caused bad compressed data 650- fix array overlay in deflate.c which sometimes caused bad compressed data
651- fix inflate bug with empty stored block 651- fix inflate bug with empty stored block
652- fix MSDOS medium model which was broken in 0.99 652- fix MSDOS medium model which was broken in 0.99
653- fix deflateParams() which could generated bad compressed data. 653- fix deflateParams() which could generated bad compressed data.
654- Bytef is define'd instead of typedef'ed (work around Borland bug) 654- Bytef is define'd instead of typedef'ed (work around Borland bug)
655- added an INDEX file 655- added an INDEX file
656- new makefiles for DJGPP (Makefile.dj2), 32-bit Borland (Makefile.b32), 656- new makefiles for DJGPP (Makefile.dj2), 32-bit Borland (Makefile.b32),
657 Watcom (Makefile.wat), Amiga SAS/C (Makefile.sas) 657 Watcom (Makefile.wat), Amiga SAS/C (Makefile.sas)
658- speed up adler32 for modern machines without auto-increment 658- speed up adler32 for modern machines without auto-increment
659- added -ansi for IRIX in configure 659- added -ansi for IRIX in configure
660- static_init_done in trees.c is an int 660- static_init_done in trees.c is an int
661- define unlink as delete for VMS 661- define unlink as delete for VMS
662- fix configure for QNX 662- fix configure for QNX
663- add configure branch for SCO and HPUX 663- add configure branch for SCO and HPUX
664- avoid many warnings (unused variables, dead assignments, etc...) 664- avoid many warnings (unused variables, dead assignments, etc...)
665- no fdopen for BeOS 665- no fdopen for BeOS
666- fix the Watcom fix for 32 bit mode (define FAR as empty) 666- fix the Watcom fix for 32 bit mode (define FAR as empty)
667- removed redefinition of Byte for MKWERKS 667- removed redefinition of Byte for MKWERKS
668- work around an MWKERKS bug (incorrect merge of all .h files) 668- work around an MWKERKS bug (incorrect merge of all .h files)
669 669
670Changes in 0.99 (27 Jan 96) 670Changes in 0.99 (27 Jan 96)
671- allow preset dictionary shared between compressor and decompressor 671- allow preset dictionary shared between compressor and decompressor
672- allow compression level 0 (no compression) 672- allow compression level 0 (no compression)
673- add deflateParams in zlib.h: allow dynamic change of compression level 673- add deflateParams in zlib.h: allow dynamic change of compression level
674 and compression strategy. 674 and compression strategy.
675- test large buffers and deflateParams in example.c 675- test large buffers and deflateParams in example.c
676- add optional "configure" to build zlib as a shared library 676- add optional "configure" to build zlib as a shared library
677- suppress Makefile.qnx, use configure instead 677- suppress Makefile.qnx, use configure instead
678- fixed deflate for 64-bit systems (detected on Cray) 678- fixed deflate for 64-bit systems (detected on Cray)
679- fixed inflate_blocks for 64-bit systems (detected on Alpha) 679- fixed inflate_blocks for 64-bit systems (detected on Alpha)
680- declare Z_DEFLATED in zlib.h (possible parameter for deflateInit2) 680- declare Z_DEFLATED in zlib.h (possible parameter for deflateInit2)
681- always return Z_BUF_ERROR when deflate() has nothing to do 681- always return Z_BUF_ERROR when deflate() has nothing to do
682- deflateInit and inflateInit are now macros to allow version checking 682- deflateInit and inflateInit are now macros to allow version checking
683- prefix all global functions and types with z_ with -DZ_PREFIX 683- prefix all global functions and types with z_ with -DZ_PREFIX
684- make falloc completely reentrant (inftrees.c) 684- make falloc completely reentrant (inftrees.c)
685- fixed very unlikely race condition in ct_static_init 685- fixed very unlikely race condition in ct_static_init
686- free in reverse order of allocation to help memory manager 686- free in reverse order of allocation to help memory manager
687- use zlib-1.0/* instead of zlib/* inside the tar.gz 687- use zlib-1.0/* instead of zlib/* inside the tar.gz
688- make zlib warning-free with "gcc -O3 -Wall -Wwrite-strings -Wpointer-arith 688- make zlib warning-free with "gcc -O3 -Wall -Wwrite-strings -Wpointer-arith
689 -Wconversion -Wstrict-prototypes -Wmissing-prototypes" 689 -Wconversion -Wstrict-prototypes -Wmissing-prototypes"
690- allow gzread on concatenated .gz files 690- allow gzread on concatenated .gz files
691- deflateEnd now returns Z_DATA_ERROR if it was premature 691- deflateEnd now returns Z_DATA_ERROR if it was premature
692- deflate is finally (?) fully deterministic (no matches beyond end of input) 692- deflate is finally (?) fully deterministic (no matches beyond end of input)
693- Document Z_SYNC_FLUSH 693- Document Z_SYNC_FLUSH
694- add uninstall in Makefile 694- add uninstall in Makefile
695- Check for __cpluplus in zlib.h 695- Check for __cpluplus in zlib.h
696- Better test in ct_align for partial flush 696- Better test in ct_align for partial flush
697- avoid harmless warnings for Borland C++ 697- avoid harmless warnings for Borland C++
698- initialize hash_head in deflate.c 698- initialize hash_head in deflate.c
699- avoid warning on fdopen (gzio.c) for HP cc -Aa 699- avoid warning on fdopen (gzio.c) for HP cc -Aa
700- include stdlib.h for STDC compilers 700- include stdlib.h for STDC compilers
701- include errno.h for Cray 701- include errno.h for Cray
702- ignore error if ranlib doesn't exist 702- ignore error if ranlib doesn't exist
703- call ranlib twice for NeXTSTEP 703- call ranlib twice for NeXTSTEP
704- use exec_prefix instead of prefix for libz.a 704- use exec_prefix instead of prefix for libz.a
705- renamed ct_* as _tr_* to avoid conflict with applications 705- renamed ct_* as _tr_* to avoid conflict with applications
706- clear z->msg in inflateInit2 before any error return 706- clear z->msg in inflateInit2 before any error return
707- initialize opaque in example.c, gzio.c, deflate.c and inflate.c 707- initialize opaque in example.c, gzio.c, deflate.c and inflate.c
708- fixed typo in zconf.h (_GNUC__ => __GNUC__) 708- fixed typo in zconf.h (_GNUC__ => __GNUC__)
709- check for WIN32 in zconf.h and zutil.c (avoid farmalloc in 32-bit mode) 709- check for WIN32 in zconf.h and zutil.c (avoid farmalloc in 32-bit mode)
710- fix typo in Make_vms.com (f$trnlnm -> f$getsyi) 710- fix typo in Make_vms.com (f$trnlnm -> f$getsyi)
711- in fcalloc, normalize pointer if size > 65520 bytes 711- in fcalloc, normalize pointer if size > 65520 bytes
712- don't use special fcalloc for 32 bit Borland C++ 712- don't use special fcalloc for 32 bit Borland C++
713- use STDC instead of __GO32__ to avoid redeclaring exit, calloc, etc... 713- use STDC instead of __GO32__ to avoid redeclaring exit, calloc, etc...
714- use Z_BINARY instead of BINARY 714- use Z_BINARY instead of BINARY
715- document that gzclose after gzdopen will close the file 715- document that gzclose after gzdopen will close the file
716- allow "a" as mode in gzopen. 716- allow "a" as mode in gzopen.
717- fix error checking in gzread 717- fix error checking in gzread
718- allow skipping .gz extra-field on pipes 718- allow skipping .gz extra-field on pipes
719- added reference to Perl interface in README 719- added reference to Perl interface in README
720- put the crc table in FAR data (I dislike more and more the medium model :) 720- put the crc table in FAR data (I dislike more and more the medium model :)
721- added get_crc_table 721- added get_crc_table
722- added a dimension to all arrays (Borland C can't count). 722- added a dimension to all arrays (Borland C can't count).
723- workaround Borland C bug in declaration of inflate_codes_new & inflate_fast 723- workaround Borland C bug in declaration of inflate_codes_new & inflate_fast
724- guard against multiple inclusion of *.h (for precompiled header on Mac) 724- guard against multiple inclusion of *.h (for precompiled header on Mac)
725- Watcom C pretends to be Microsoft C small model even in 32 bit mode. 725- Watcom C pretends to be Microsoft C small model even in 32 bit mode.
726- don't use unsized arrays to avoid silly warnings by Visual C++: 726- don't use unsized arrays to avoid silly warnings by Visual C++:
727 warning C4746: 'inflate_mask' : unsized array treated as '__far' 727 warning C4746: 'inflate_mask' : unsized array treated as '__far'
728 (what's wrong with far data in far model?). 728 (what's wrong with far data in far model?).
729- define enum out of inflate_blocks_state to allow compilation with C++ 729- define enum out of inflate_blocks_state to allow compilation with C++
730 730
731Changes in 0.95 (16 Aug 95) 731Changes in 0.95 (16 Aug 95)
732- fix MSDOS small and medium model (now easier to adapt to any compiler) 732- fix MSDOS small and medium model (now easier to adapt to any compiler)
733- inlined send_bits 733- inlined send_bits
734- fix the final (:-) bug for deflate with flush (output was correct but 734- fix the final (:-) bug for deflate with flush (output was correct but
735 not completely flushed in rare occasions). 735 not completely flushed in rare occasions).
736- default window size is same for compression and decompression 736- default window size is same for compression and decompression
737 (it's now sufficient to set MAX_WBITS in zconf.h). 737 (it's now sufficient to set MAX_WBITS in zconf.h).
738- voidp -> voidpf and voidnp -> voidp (for consistency with other 738- voidp -> voidpf and voidnp -> voidp (for consistency with other
739 typedefs and because voidnp was not near in large model). 739 typedefs and because voidnp was not near in large model).
740 740
741Changes in 0.94 (13 Aug 95) 741Changes in 0.94 (13 Aug 95)
742- support MSDOS medium model 742- support MSDOS medium model
743- fix deflate with flush (could sometimes generate bad output) 743- fix deflate with flush (could sometimes generate bad output)
744- fix deflateReset (zlib header was incorrectly suppressed) 744- fix deflateReset (zlib header was incorrectly suppressed)
745- added support for VMS 745- added support for VMS
746- allow a compression level in gzopen() 746- allow a compression level in gzopen()
747- gzflush now calls fflush 747- gzflush now calls fflush
748- For deflate with flush, flush even if no more input is provided. 748- For deflate with flush, flush even if no more input is provided.
749- rename libgz.a as libz.a 749- rename libgz.a as libz.a
750- avoid complex expression in infcodes.c triggering Turbo C bug 750- avoid complex expression in infcodes.c triggering Turbo C bug
751- work around a problem with gcc on Alpha (in INSERT_STRING) 751- work around a problem with gcc on Alpha (in INSERT_STRING)
752- don't use inline functions (problem with some gcc versions) 752- don't use inline functions (problem with some gcc versions)
753- allow renaming of Byte, uInt, etc... with #define. 753- allow renaming of Byte, uInt, etc... with #define.
754- avoid warning about (unused) pointer before start of array in deflate.c 754- avoid warning about (unused) pointer before start of array in deflate.c
755- avoid various warnings in gzio.c, example.c, infblock.c, adler32.c, zutil.c 755- avoid various warnings in gzio.c, example.c, infblock.c, adler32.c, zutil.c
756- avoid reserved word 'new' in trees.c 756- avoid reserved word 'new' in trees.c
757 757
758Changes in 0.93 (25 June 95) 758Changes in 0.93 (25 June 95)
759- temporarily disable inline functions 759- temporarily disable inline functions
760- make deflate deterministic 760- make deflate deterministic
761- give enough lookahead for PARTIAL_FLUSH 761- give enough lookahead for PARTIAL_FLUSH
762- Set binary mode for stdin/stdout in minigzip.c for OS/2 762- Set binary mode for stdin/stdout in minigzip.c for OS/2
763- don't even use signed char in inflate (not portable enough) 763- don't even use signed char in inflate (not portable enough)
764- fix inflate memory leak for segmented architectures 764- fix inflate memory leak for segmented architectures
765 765
766Changes in 0.92 (3 May 95) 766Changes in 0.92 (3 May 95)
767- don't assume that char is signed (problem on SGI) 767- don't assume that char is signed (problem on SGI)
768- Clear bit buffer when starting a stored block 768- Clear bit buffer when starting a stored block
769- no memcpy on Pyramid 769- no memcpy on Pyramid
770- suppressed inftest.c 770- suppressed inftest.c
771- optimized fill_window, put longest_match inline for gcc 771- optimized fill_window, put longest_match inline for gcc
772- optimized inflate on stored blocks. 772- optimized inflate on stored blocks.
773- untabify all sources to simplify patches 773- untabify all sources to simplify patches
774 774
775Changes in 0.91 (2 May 95) 775Changes in 0.91 (2 May 95)
776- Default MEM_LEVEL is 8 (not 9 for Unix) as documented in zlib.h 776- Default MEM_LEVEL is 8 (not 9 for Unix) as documented in zlib.h
777- Document the memory requirements in zconf.h 777- Document the memory requirements in zconf.h
778- added "make install" 778- added "make install"
779- fix sync search logic in inflateSync 779- fix sync search logic in inflateSync
780- deflate(Z_FULL_FLUSH) now works even if output buffer too short 780- deflate(Z_FULL_FLUSH) now works even if output buffer too short
781- after inflateSync, don't scare people with just "lo world" 781- after inflateSync, don't scare people with just "lo world"
782- added support for DJGPP 782- added support for DJGPP
783 783
784Changes in 0.9 (1 May 95) 784Changes in 0.9 (1 May 95)
785- don't assume that zalloc clears the allocated memory (the TurboC bug 785- don't assume that zalloc clears the allocated memory (the TurboC bug
786 was Mark's bug after all :) 786 was Mark's bug after all :)
787- let again gzread copy uncompressed data unchanged (was working in 0.71) 787- let again gzread copy uncompressed data unchanged (was working in 0.71)
788- deflate(Z_FULL_FLUSH), inflateReset and inflateSync are now fully implemented 788- deflate(Z_FULL_FLUSH), inflateReset and inflateSync are now fully implemented
789- added a test of inflateSync in example.c 789- added a test of inflateSync in example.c
790- moved MAX_WBITS to zconf.h because users might want to change that. 790- moved MAX_WBITS to zconf.h because users might want to change that.
791- document explicitly that zalloc(64K) on MSDOS must return a normalized 791- document explicitly that zalloc(64K) on MSDOS must return a normalized
792 pointer (zero offset) 792 pointer (zero offset)
793- added Makefiles for Microsoft C, Turbo C, Borland C++ 793- added Makefiles for Microsoft C, Turbo C, Borland C++
794- faster crc32() 794- faster crc32()
795 795
796Changes in 0.8 (29 April 95) 796Changes in 0.8 (29 April 95)
797- added fast inflate (inffast.c) 797- added fast inflate (inffast.c)
798- deflate(Z_FINISH) now returns Z_STREAM_END when done. Warning: this 798- deflate(Z_FINISH) now returns Z_STREAM_END when done. Warning: this
799 is incompatible with previous versions of zlib which returned Z_OK. 799 is incompatible with previous versions of zlib which returned Z_OK.
800- work around a TurboC compiler bug (bad code for b << 0, see infutil.h) 800- work around a TurboC compiler bug (bad code for b << 0, see infutil.h)
801 (actually that was not a compiler bug, see 0.81 above) 801 (actually that was not a compiler bug, see 0.81 above)
802- gzread no longer reads one extra byte in certain cases 802- gzread no longer reads one extra byte in certain cases
803- In gzio destroy(), don't reference a freed structure 803- In gzio destroy(), don't reference a freed structure
804- avoid many warnings for MSDOS 804- avoid many warnings for MSDOS
805- avoid the ERROR symbol which is used by MS Windows 805- avoid the ERROR symbol which is used by MS Windows
806 806
807Changes in 0.71 (14 April 95) 807Changes in 0.71 (14 April 95)
808- Fixed more MSDOS compilation problems :( There is still a bug with 808- Fixed more MSDOS compilation problems :( There is still a bug with
809 TurboC large model. 809 TurboC large model.
810 810
811Changes in 0.7 (14 April 95) 811Changes in 0.7 (14 April 95)
812- Added full inflate support. 812- Added full inflate support.
813- Simplified the crc32() interface. The pre- and post-conditioning 813- Simplified the crc32() interface. The pre- and post-conditioning
814 (one's complement) is now done inside crc32(). WARNING: this is 814 (one's complement) is now done inside crc32(). WARNING: this is
815 incompatible with previous versions; see zlib.h for the new usage. 815 incompatible with previous versions; see zlib.h for the new usage.
816 816
817Changes in 0.61 (12 April 95) 817Changes in 0.61 (12 April 95)
818- workaround for a bug in TurboC. example and minigzip now work on MSDOS. 818- workaround for a bug in TurboC. example and minigzip now work on MSDOS.
819 819
820Changes in 0.6 (11 April 95) 820Changes in 0.6 (11 April 95)
821- added minigzip.c 821- added minigzip.c
822- added gzdopen to reopen a file descriptor as gzFile 822- added gzdopen to reopen a file descriptor as gzFile
823- added transparent reading of non-gziped files in gzread. 823- added transparent reading of non-gziped files in gzread.
824- fixed bug in gzread (don't read crc as data) 824- fixed bug in gzread (don't read crc as data)
825- fixed bug in destroy (gzio.c) (don't return Z_STREAM_END for gzclose). 825- fixed bug in destroy (gzio.c) (don't return Z_STREAM_END for gzclose).
826- don't allocate big arrays in the stack (for MSDOS) 826- don't allocate big arrays in the stack (for MSDOS)
827- fix some MSDOS compilation problems 827- fix some MSDOS compilation problems
828 828
829Changes in 0.5: 829Changes in 0.5:
830- do real compression in deflate.c. Z_PARTIAL_FLUSH is supported but 830- do real compression in deflate.c. Z_PARTIAL_FLUSH is supported but
831 not yet Z_FULL_FLUSH. 831 not yet Z_FULL_FLUSH.
832- support decompression but only in a single step (forced Z_FINISH) 832- support decompression but only in a single step (forced Z_FINISH)
833- added opaque object for zalloc and zfree. 833- added opaque object for zalloc and zfree.
834- added deflateReset and inflateReset 834- added deflateReset and inflateReset
835- added a variable zlib_version for consistency checking. 835- added a variable zlib_version for consistency checking.
836- renamed the 'filter' parameter of deflateInit2 as 'strategy'. 836- renamed the 'filter' parameter of deflateInit2 as 'strategy'.
837 Added Z_FILTERED and Z_HUFFMAN_ONLY constants. 837 Added Z_FILTERED and Z_HUFFMAN_ONLY constants.
838 838
839Changes in 0.4: 839Changes in 0.4:
840- avoid "zip" everywhere, use zlib instead of ziplib. 840- avoid "zip" everywhere, use zlib instead of ziplib.
841- suppress Z_BLOCK_FLUSH, interpret Z_PARTIAL_FLUSH as block flush 841- suppress Z_BLOCK_FLUSH, interpret Z_PARTIAL_FLUSH as block flush
842 if compression method == 8. 842 if compression method == 8.
843- added adler32 and crc32 843- added adler32 and crc32
844- renamed deflateOptions as deflateInit2, call one or the other but not both 844- renamed deflateOptions as deflateInit2, call one or the other but not both
845- added the method parameter for deflateInit2. 845- added the method parameter for deflateInit2.
846- added inflateInit2 846- added inflateInit2
847- simplied considerably deflateInit and inflateInit by not supporting 847- simplied considerably deflateInit and inflateInit by not supporting
848 user-provided history buffer. This is supported only in deflateInit2 848 user-provided history buffer. This is supported only in deflateInit2
849 and inflateInit2. 849 and inflateInit2.
850 850
851Changes in 0.3: 851Changes in 0.3:
852- prefix all macro names with Z_ 852- prefix all macro names with Z_
853- use Z_FINISH instead of deflateEnd to finish compression. 853- use Z_FINISH instead of deflateEnd to finish compression.
854- added Z_HUFFMAN_ONLY 854- added Z_HUFFMAN_ONLY
855- added gzerror() 855- added gzerror()
diff --git a/utils/zenutils/libraries/zlib123/zlib/FAQ b/utils/zenutils/libraries/zlib123/zlib/FAQ
index 15d043615e..441d910daa 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/FAQ
+++ b/utils/zenutils/libraries/zlib123/zlib/FAQ
@@ -1,339 +1,339 @@
1 1
2 Frequently Asked Questions about zlib 2 Frequently Asked Questions about zlib
3 3
4 4
5If your question is not there, please check the zlib home page 5If your question is not there, please check the zlib home page
6http://www.zlib.org which may have more recent information. 6http://www.zlib.org which may have more recent information.
7The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html 7The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html
8 8
9 9
10 1. Is zlib Y2K-compliant? 10 1. Is zlib Y2K-compliant?
11 11
12 Yes. zlib doesn't handle dates. 12 Yes. zlib doesn't handle dates.
13 13
14 2. Where can I get a Windows DLL version? 14 2. Where can I get a Windows DLL version?
15 15
16 The zlib sources can be compiled without change to produce a DLL. 16 The zlib sources can be compiled without change to produce a DLL.
17 See the file win32/DLL_FAQ.txt in the zlib distribution. 17 See the file win32/DLL_FAQ.txt in the zlib distribution.
18 Pointers to the precompiled DLL are found in the zlib web site at 18 Pointers to the precompiled DLL are found in the zlib web site at
19 http://www.zlib.org. 19 http://www.zlib.org.
20 20
21 3. Where can I get a Visual Basic interface to zlib? 21 3. Where can I get a Visual Basic interface to zlib?
22 22
23 See 23 See
24 * http://www.dogma.net/markn/articles/zlibtool/zlibtool.htm 24 * http://www.dogma.net/markn/articles/zlibtool/zlibtool.htm
25 * contrib/visual-basic.txt in the zlib distribution 25 * contrib/visual-basic.txt in the zlib distribution
26 * win32/DLL_FAQ.txt in the zlib distribution 26 * win32/DLL_FAQ.txt in the zlib distribution
27 27
28 4. compress() returns Z_BUF_ERROR. 28 4. compress() returns Z_BUF_ERROR.
29 29
30 Make sure that before the call of compress, the length of the compressed 30 Make sure that before the call of compress, the length of the compressed
31 buffer is equal to the total size of the compressed buffer and not 31 buffer is equal to the total size of the compressed buffer and not
32 zero. For Visual Basic, check that this parameter is passed by reference 32 zero. For Visual Basic, check that this parameter is passed by reference
33 ("as any"), not by value ("as long"). 33 ("as any"), not by value ("as long").
34 34
35 5. deflate() or inflate() returns Z_BUF_ERROR. 35 5. deflate() or inflate() returns Z_BUF_ERROR.
36 36
37 Before making the call, make sure that avail_in and avail_out are not 37 Before making the call, make sure that avail_in and avail_out are not
38 zero. When setting the parameter flush equal to Z_FINISH, also make sure 38 zero. When setting the parameter flush equal to Z_FINISH, also make sure
39 that avail_out is big enough to allow processing all pending input. 39 that avail_out is big enough to allow processing all pending input.
40 Note that a Z_BUF_ERROR is not fatal--another call to deflate() or 40 Note that a Z_BUF_ERROR is not fatal--another call to deflate() or
41 inflate() can be made with more input or output space. A Z_BUF_ERROR 41 inflate() can be made with more input or output space. A Z_BUF_ERROR
42 may in fact be unavoidable depending on how the functions are used, since 42 may in fact be unavoidable depending on how the functions are used, since
43 it is not possible to tell whether or not there is more output pending 43 it is not possible to tell whether or not there is more output pending
44 when strm.avail_out returns with zero. 44 when strm.avail_out returns with zero.
45 45
46 6. Where's the zlib documentation (man pages, etc.)? 46 6. Where's the zlib documentation (man pages, etc.)?
47 47
48 It's in zlib.h for the moment, and Francis S. Lin has converted it to a 48 It's in zlib.h for the moment, and Francis S. Lin has converted it to a
49 web page zlib.html. Volunteers to transform this to Unix-style man pages, 49 web page zlib.html. Volunteers to transform this to Unix-style man pages,
50 please contact us (zlib@gzip.org). Examples of zlib usage are in the files 50 please contact us (zlib@gzip.org). Examples of zlib usage are in the files
51 example.c and minigzip.c. 51 example.c and minigzip.c.
52 52
53 7. Why don't you use GNU autoconf or libtool or ...? 53 7. Why don't you use GNU autoconf or libtool or ...?
54 54
55 Because we would like to keep zlib as a very small and simple 55 Because we would like to keep zlib as a very small and simple
56 package. zlib is rather portable and doesn't need much configuration. 56 package. zlib is rather portable and doesn't need much configuration.
57 57
58 8. I found a bug in zlib. 58 8. I found a bug in zlib.
59 59
60 Most of the time, such problems are due to an incorrect usage of 60 Most of the time, such problems are due to an incorrect usage of
61 zlib. Please try to reproduce the problem with a small program and send 61 zlib. Please try to reproduce the problem with a small program and send
62 the corresponding source to us at zlib@gzip.org . Do not send 62 the corresponding source to us at zlib@gzip.org . Do not send
63 multi-megabyte data files without prior agreement. 63 multi-megabyte data files without prior agreement.
64 64
65 9. Why do I get "undefined reference to gzputc"? 65 9. Why do I get "undefined reference to gzputc"?
66 66
67 If "make test" produces something like 67 If "make test" produces something like
68 68
69 example.o(.text+0x154): undefined reference to `gzputc' 69 example.o(.text+0x154): undefined reference to `gzputc'
70 70
71 check that you don't have old files libz.* in /usr/lib, /usr/local/lib or 71 check that you don't have old files libz.* in /usr/lib, /usr/local/lib or
72 /usr/X11R6/lib. Remove any old versions, then do "make install". 72 /usr/X11R6/lib. Remove any old versions, then do "make install".
73 73
7410. I need a Delphi interface to zlib. 7410. I need a Delphi interface to zlib.
75 75
76 See the contrib/delphi directory in the zlib distribution. 76 See the contrib/delphi directory in the zlib distribution.
77 77
7811. Can zlib handle .zip archives? 7811. Can zlib handle .zip archives?
79 79
80 Not by itself, no. See the directory contrib/minizip in the zlib 80 Not by itself, no. See the directory contrib/minizip in the zlib
81 distribution. 81 distribution.
82 82
8312. Can zlib handle .Z files? 8312. Can zlib handle .Z files?
84 84
85 No, sorry. You have to spawn an uncompress or gunzip subprocess, or adapt 85 No, sorry. You have to spawn an uncompress or gunzip subprocess, or adapt
86 the code of uncompress on your own. 86 the code of uncompress on your own.
87 87
8813. How can I make a Unix shared library? 8813. How can I make a Unix shared library?
89 89
90 make clean 90 make clean
91 ./configure -s 91 ./configure -s
92 make 92 make
93 93
9414. How do I install a shared zlib library on Unix? 9414. How do I install a shared zlib library on Unix?
95 95
96 After the above, then: 96 After the above, then:
97 97
98 make install 98 make install
99 99
100 However, many flavors of Unix come with a shared zlib already installed. 100 However, many flavors of Unix come with a shared zlib already installed.
101 Before going to the trouble of compiling a shared version of zlib and 101 Before going to the trouble of compiling a shared version of zlib and
102 trying to install it, you may want to check if it's already there! If you 102 trying to install it, you may want to check if it's already there! If you
103 can #include <zlib.h>, it's there. The -lz option will probably link to it. 103 can #include <zlib.h>, it's there. The -lz option will probably link to it.
104 104
10515. I have a question about OttoPDF. 10515. I have a question about OttoPDF.
106 106
107 We are not the authors of OttoPDF. The real author is on the OttoPDF web 107 We are not the authors of OttoPDF. The real author is on the OttoPDF web
108 site: Joel Hainley, jhainley@myndkryme.com. 108 site: Joel Hainley, jhainley@myndkryme.com.
109 109
11016. Can zlib decode Flate data in an Adobe PDF file? 11016. Can zlib decode Flate data in an Adobe PDF file?
111 111
112 Yes. See http://www.fastio.com/ (ClibPDF), or http://www.pdflib.com/ . 112 Yes. See http://www.fastio.com/ (ClibPDF), or http://www.pdflib.com/ .
113 To modify PDF forms, see http://sourceforge.net/projects/acroformtool/ . 113 To modify PDF forms, see http://sourceforge.net/projects/acroformtool/ .
114 114
11517. Why am I getting this "register_frame_info not found" error on Solaris? 11517. Why am I getting this "register_frame_info not found" error on Solaris?
116 116
117 After installing zlib 1.1.4 on Solaris 2.6, running applications using zlib 117 After installing zlib 1.1.4 on Solaris 2.6, running applications using zlib
118 generates an error such as: 118 generates an error such as:
119 119
120 ld.so.1: rpm: fatal: relocation error: file /usr/local/lib/libz.so: 120 ld.so.1: rpm: fatal: relocation error: file /usr/local/lib/libz.so:
121 symbol __register_frame_info: referenced symbol not found 121 symbol __register_frame_info: referenced symbol not found
122 122
123 The symbol __register_frame_info is not part of zlib, it is generated by 123 The symbol __register_frame_info is not part of zlib, it is generated by
124 the C compiler (cc or gcc). You must recompile applications using zlib 124 the C compiler (cc or gcc). You must recompile applications using zlib
125 which have this problem. This problem is specific to Solaris. See 125 which have this problem. This problem is specific to Solaris. See
126 http://www.sunfreeware.com for Solaris versions of zlib and applications 126 http://www.sunfreeware.com for Solaris versions of zlib and applications
127 using zlib. 127 using zlib.
128 128
12918. Why does gzip give an error on a file I make with compress/deflate? 12918. Why does gzip give an error on a file I make with compress/deflate?
130 130
131 The compress and deflate functions produce data in the zlib format, which 131 The compress and deflate functions produce data in the zlib format, which
132 is different and incompatible with the gzip format. The gz* functions in 132 is different and incompatible with the gzip format. The gz* functions in
133 zlib on the other hand use the gzip format. Both the zlib and gzip 133 zlib on the other hand use the gzip format. Both the zlib and gzip
134 formats use the same compressed data format internally, but have different 134 formats use the same compressed data format internally, but have different
135 headers and trailers around the compressed data. 135 headers and trailers around the compressed data.
136 136
13719. Ok, so why are there two different formats? 13719. Ok, so why are there two different formats?
138 138
139 The gzip format was designed to retain the directory information about 139 The gzip format was designed to retain the directory information about
140 a single file, such as the name and last modification date. The zlib 140 a single file, such as the name and last modification date. The zlib
141 format on the other hand was designed for in-memory and communication 141 format on the other hand was designed for in-memory and communication
142 channel applications, and has a much more compact header and trailer and 142 channel applications, and has a much more compact header and trailer and
143 uses a faster integrity check than gzip. 143 uses a faster integrity check than gzip.
144 144
14520. Well that's nice, but how do I make a gzip file in memory? 14520. Well that's nice, but how do I make a gzip file in memory?
146 146
147 You can request that deflate write the gzip format instead of the zlib 147 You can request that deflate write the gzip format instead of the zlib
148 format using deflateInit2(). You can also request that inflate decode 148 format using deflateInit2(). You can also request that inflate decode
149 the gzip format using inflateInit2(). Read zlib.h for more details. 149 the gzip format using inflateInit2(). Read zlib.h for more details.
150 150
15121. Is zlib thread-safe? 15121. Is zlib thread-safe?
152 152
153 Yes. However any library routines that zlib uses and any application- 153 Yes. However any library routines that zlib uses and any application-
154 provided memory allocation routines must also be thread-safe. zlib's gz* 154 provided memory allocation routines must also be thread-safe. zlib's gz*
155 functions use stdio library routines, and most of zlib's functions use the 155 functions use stdio library routines, and most of zlib's functions use the
156 library memory allocation routines by default. zlib's Init functions allow 156 library memory allocation routines by default. zlib's Init functions allow
157 for the application to provide custom memory allocation routines. 157 for the application to provide custom memory allocation routines.
158 158
159 Of course, you should only operate on any given zlib or gzip stream from a 159 Of course, you should only operate on any given zlib or gzip stream from a
160 single thread at a time. 160 single thread at a time.
161 161
16222. Can I use zlib in my commercial application? 16222. Can I use zlib in my commercial application?
163 163
164 Yes. Please read the license in zlib.h. 164 Yes. Please read the license in zlib.h.
165 165
16623. Is zlib under the GNU license? 16623. Is zlib under the GNU license?
167 167
168 No. Please read the license in zlib.h. 168 No. Please read the license in zlib.h.
169 169
17024. The license says that altered source versions must be "plainly marked". So 17024. The license says that altered source versions must be "plainly marked". So
171 what exactly do I need to do to meet that requirement? 171 what exactly do I need to do to meet that requirement?
172 172
173 You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h. In 173 You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h. In
174 particular, the final version number needs to be changed to "f", and an 174 particular, the final version number needs to be changed to "f", and an
175 identification string should be appended to ZLIB_VERSION. Version numbers 175 identification string should be appended to ZLIB_VERSION. Version numbers
176 x.x.x.f are reserved for modifications to zlib by others than the zlib 176 x.x.x.f are reserved for modifications to zlib by others than the zlib
177 maintainers. For example, if the version of the base zlib you are altering 177 maintainers. For example, if the version of the base zlib you are altering
178 is "1.2.3.4", then in zlib.h you should change ZLIB_VERNUM to 0x123f, and 178 is "1.2.3.4", then in zlib.h you should change ZLIB_VERNUM to 0x123f, and
179 ZLIB_VERSION to something like "1.2.3.f-zachary-mods-v3". You can also 179 ZLIB_VERSION to something like "1.2.3.f-zachary-mods-v3". You can also
180 update the version strings in deflate.c and inftrees.c. 180 update the version strings in deflate.c and inftrees.c.
181 181
182 For altered source distributions, you should also note the origin and 182 For altered source distributions, you should also note the origin and
183 nature of the changes in zlib.h, as well as in ChangeLog and README, along 183 nature of the changes in zlib.h, as well as in ChangeLog and README, along
184 with the dates of the alterations. The origin should include at least your 184 with the dates of the alterations. The origin should include at least your
185 name (or your company's name), and an email address to contact for help or 185 name (or your company's name), and an email address to contact for help or
186 issues with the library. 186 issues with the library.
187 187
188 Note that distributing a compiled zlib library along with zlib.h and 188 Note that distributing a compiled zlib library along with zlib.h and
189 zconf.h is also a source distribution, and so you should change 189 zconf.h is also a source distribution, and so you should change
190 ZLIB_VERSION and ZLIB_VERNUM and note the origin and nature of the changes 190 ZLIB_VERSION and ZLIB_VERNUM and note the origin and nature of the changes
191 in zlib.h as you would for a full source distribution. 191 in zlib.h as you would for a full source distribution.
192 192
19325. Will zlib work on a big-endian or little-endian architecture, and can I 19325. Will zlib work on a big-endian or little-endian architecture, and can I
194 exchange compressed data between them? 194 exchange compressed data between them?
195 195
196 Yes and yes. 196 Yes and yes.
197 197
19826. Will zlib work on a 64-bit machine? 19826. Will zlib work on a 64-bit machine?
199 199
200 It should. It has been tested on 64-bit machines, and has no dependence 200 It should. It has been tested on 64-bit machines, and has no dependence
201 on any data types being limited to 32-bits in length. If you have any 201 on any data types being limited to 32-bits in length. If you have any
202 difficulties, please provide a complete problem report to zlib@gzip.org 202 difficulties, please provide a complete problem report to zlib@gzip.org
203 203
20427. Will zlib decompress data from the PKWare Data Compression Library? 20427. Will zlib decompress data from the PKWare Data Compression Library?
205 205
206 No. The PKWare DCL uses a completely different compressed data format 206 No. The PKWare DCL uses a completely different compressed data format
207 than does PKZIP and zlib. However, you can look in zlib's contrib/blast 207 than does PKZIP and zlib. However, you can look in zlib's contrib/blast
208 directory for a possible solution to your problem. 208 directory for a possible solution to your problem.
209 209
21028. Can I access data randomly in a compressed stream? 21028. Can I access data randomly in a compressed stream?
211 211
212 No, not without some preparation. If when compressing you periodically 212 No, not without some preparation. If when compressing you periodically
213 use Z_FULL_FLUSH, carefully write all the pending data at those points, 213 use Z_FULL_FLUSH, carefully write all the pending data at those points,
214 and keep an index of those locations, then you can start decompression 214 and keep an index of those locations, then you can start decompression
215 at those points. You have to be careful to not use Z_FULL_FLUSH too 215 at those points. You have to be careful to not use Z_FULL_FLUSH too
216 often, since it can significantly degrade compression. 216 often, since it can significantly degrade compression.
217 217
21829. Does zlib work on MVS, OS/390, CICS, etc.? 21829. Does zlib work on MVS, OS/390, CICS, etc.?
219 219
220 We don't know for sure. We have heard occasional reports of success on 220 We don't know for sure. We have heard occasional reports of success on
221 these systems. If you do use it on one of these, please provide us with 221 these systems. If you do use it on one of these, please provide us with
222 a report, instructions, and patches that we can reference when we get 222 a report, instructions, and patches that we can reference when we get
223 these questions. Thanks. 223 these questions. Thanks.
224 224
22530. Is there some simpler, easier to read version of inflate I can look at 22530. Is there some simpler, easier to read version of inflate I can look at
226 to understand the deflate format? 226 to understand the deflate format?
227 227
228 First off, you should read RFC 1951. Second, yes. Look in zlib's 228 First off, you should read RFC 1951. Second, yes. Look in zlib's
229 contrib/puff directory. 229 contrib/puff directory.
230 230
23131. Does zlib infringe on any patents? 23131. Does zlib infringe on any patents?
232 232
233 As far as we know, no. In fact, that was originally the whole point behind 233 As far as we know, no. In fact, that was originally the whole point behind
234 zlib. Look here for some more information: 234 zlib. Look here for some more information:
235 235
236 http://www.gzip.org/#faq11 236 http://www.gzip.org/#faq11
237 237
23832. Can zlib work with greater than 4 GB of data? 23832. Can zlib work with greater than 4 GB of data?
239 239
240 Yes. inflate() and deflate() will process any amount of data correctly. 240 Yes. inflate() and deflate() will process any amount of data correctly.
241 Each call of inflate() or deflate() is limited to input and output chunks 241 Each call of inflate() or deflate() is limited to input and output chunks
242 of the maximum value that can be stored in the compiler's "unsigned int" 242 of the maximum value that can be stored in the compiler's "unsigned int"
243 type, but there is no limit to the number of chunks. Note however that the 243 type, but there is no limit to the number of chunks. Note however that the
244 strm.total_in and strm_total_out counters may be limited to 4 GB. These 244 strm.total_in and strm_total_out counters may be limited to 4 GB. These
245 counters are provided as a convenience and are not used internally by 245 counters are provided as a convenience and are not used internally by
246 inflate() or deflate(). The application can easily set up its own counters 246 inflate() or deflate(). The application can easily set up its own counters
247 updated after each call of inflate() or deflate() to count beyond 4 GB. 247 updated after each call of inflate() or deflate() to count beyond 4 GB.
248 compress() and uncompress() may be limited to 4 GB, since they operate in a 248 compress() and uncompress() may be limited to 4 GB, since they operate in a
249 single call. gzseek() and gztell() may be limited to 4 GB depending on how 249 single call. gzseek() and gztell() may be limited to 4 GB depending on how
250 zlib is compiled. See the zlibCompileFlags() function in zlib.h. 250 zlib is compiled. See the zlibCompileFlags() function in zlib.h.
251 251
252 The word "may" appears several times above since there is a 4 GB limit 252 The word "may" appears several times above since there is a 4 GB limit
253 only if the compiler's "long" type is 32 bits. If the compiler's "long" 253 only if the compiler's "long" type is 32 bits. If the compiler's "long"
254 type is 64 bits, then the limit is 16 exabytes. 254 type is 64 bits, then the limit is 16 exabytes.
255 255
25633. Does zlib have any security vulnerabilities? 25633. Does zlib have any security vulnerabilities?
257 257
258 The only one that we are aware of is potentially in gzprintf(). If zlib 258 The only one that we are aware of is potentially in gzprintf(). If zlib
259 is compiled to use sprintf() or vsprintf(), then there is no protection 259 is compiled to use sprintf() or vsprintf(), then there is no protection
260 against a buffer overflow of a 4K string space, other than the caller of 260 against a buffer overflow of a 4K string space, other than the caller of
261 gzprintf() assuring that the output will not exceed 4K. On the other 261 gzprintf() assuring that the output will not exceed 4K. On the other
262 hand, if zlib is compiled to use snprintf() or vsnprintf(), which should 262 hand, if zlib is compiled to use snprintf() or vsnprintf(), which should
263 normally be the case, then there is no vulnerability. The ./configure 263 normally be the case, then there is no vulnerability. The ./configure
264 script will display warnings if an insecure variation of sprintf() will 264 script will display warnings if an insecure variation of sprintf() will
265 be used by gzprintf(). Also the zlibCompileFlags() function will return 265 be used by gzprintf(). Also the zlibCompileFlags() function will return
266 information on what variant of sprintf() is used by gzprintf(). 266 information on what variant of sprintf() is used by gzprintf().
267 267
268 If you don't have snprintf() or vsnprintf() and would like one, you can 268 If you don't have snprintf() or vsnprintf() and would like one, you can
269 find a portable implementation here: 269 find a portable implementation here:
270 270
271 http://www.ijs.si/software/snprintf/ 271 http://www.ijs.si/software/snprintf/
272 272
273 Note that you should be using the most recent version of zlib. Versions 273 Note that you should be using the most recent version of zlib. Versions
274 1.1.3 and before were subject to a double-free vulnerability. 274 1.1.3 and before were subject to a double-free vulnerability.
275 275
27634. Is there a Java version of zlib? 27634. Is there a Java version of zlib?
277 277
278 Probably what you want is to use zlib in Java. zlib is already included 278 Probably what you want is to use zlib in Java. zlib is already included
279 as part of the Java SDK in the java.util.zip package. If you really want 279 as part of the Java SDK in the java.util.zip package. If you really want
280 a version of zlib written in the Java language, look on the zlib home 280 a version of zlib written in the Java language, look on the zlib home
281 page for links: http://www.zlib.org/ 281 page for links: http://www.zlib.org/
282 282
28335. I get this or that compiler or source-code scanner warning when I crank it 28335. I get this or that compiler or source-code scanner warning when I crank it
284 up to maximally-pedantic. Can't you guys write proper code? 284 up to maximally-pedantic. Can't you guys write proper code?
285 285
286 Many years ago, we gave up attempting to avoid warnings on every compiler 286 Many years ago, we gave up attempting to avoid warnings on every compiler
287 in the universe. It just got to be a waste of time, and some compilers 287 in the universe. It just got to be a waste of time, and some compilers
288 were downright silly. So now, we simply make sure that the code always 288 were downright silly. So now, we simply make sure that the code always
289 works. 289 works.
290 290
29136. Valgrind (or some similar memory access checker) says that deflate is 29136. Valgrind (or some similar memory access checker) says that deflate is
292 performing a conditional jump that depends on an uninitialized value. 292 performing a conditional jump that depends on an uninitialized value.
293 Isn't that a bug? 293 Isn't that a bug?
294 294
295 No. That is intentional for performance reasons, and the output of 295 No. That is intentional for performance reasons, and the output of
296 deflate is not affected. This only started showing up recently since 296 deflate is not affected. This only started showing up recently since
297 zlib 1.2.x uses malloc() by default for allocations, whereas earlier 297 zlib 1.2.x uses malloc() by default for allocations, whereas earlier
298 versions used calloc(), which zeros out the allocated memory. 298 versions used calloc(), which zeros out the allocated memory.
299 299
30037. Will zlib read the (insert any ancient or arcane format here) compressed 30037. Will zlib read the (insert any ancient or arcane format here) compressed
301 data format? 301 data format?
302 302
303 Probably not. Look in the comp.compression FAQ for pointers to various 303 Probably not. Look in the comp.compression FAQ for pointers to various
304 formats and associated software. 304 formats and associated software.
305 305
30638. How can I encrypt/decrypt zip files with zlib? 30638. How can I encrypt/decrypt zip files with zlib?
307 307
308 zlib doesn't support encryption. The original PKZIP encryption is very weak 308 zlib doesn't support encryption. The original PKZIP encryption is very weak
309 and can be broken with freely available programs. To get strong encryption, 309 and can be broken with freely available programs. To get strong encryption,
310 use GnuPG, http://www.gnupg.org/ , which already includes zlib compression. 310 use GnuPG, http://www.gnupg.org/ , which already includes zlib compression.
311 For PKZIP compatible "encryption", look at http://www.info-zip.org/ 311 For PKZIP compatible "encryption", look at http://www.info-zip.org/
312 312
31339. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings? 31339. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings?
314 314
315 "gzip" is the gzip format, and "deflate" is the zlib format. They should 315 "gzip" is the gzip format, and "deflate" is the zlib format. They should
316 probably have called the second one "zlib" instead to avoid confusion 316 probably have called the second one "zlib" instead to avoid confusion
317 with the raw deflate compressed data format. While the HTTP 1.1 RFC 2616 317 with the raw deflate compressed data format. While the HTTP 1.1 RFC 2616
318 correctly points to the zlib specification in RFC 1950 for the "deflate" 318 correctly points to the zlib specification in RFC 1950 for the "deflate"
319 transfer encoding, there have been reports of servers and browsers that 319 transfer encoding, there have been reports of servers and browsers that
320 incorrectly produce or expect raw deflate data per the deflate 320 incorrectly produce or expect raw deflate data per the deflate
321 specficiation in RFC 1951, most notably Microsoft. So even though the 321 specficiation in RFC 1951, most notably Microsoft. So even though the
322 "deflate" transfer encoding using the zlib format would be the more 322 "deflate" transfer encoding using the zlib format would be the more
323 efficient approach (and in fact exactly what the zlib format was designed 323 efficient approach (and in fact exactly what the zlib format was designed
324 for), using the "gzip" transfer encoding is probably more reliable due to 324 for), using the "gzip" transfer encoding is probably more reliable due to
325 an unfortunate choice of name on the part of the HTTP 1.1 authors. 325 an unfortunate choice of name on the part of the HTTP 1.1 authors.
326 326
327 Bottom line: use the gzip format for HTTP 1.1 encoding. 327 Bottom line: use the gzip format for HTTP 1.1 encoding.
328 328
32940. Does zlib support the new "Deflate64" format introduced by PKWare? 32940. Does zlib support the new "Deflate64" format introduced by PKWare?
330 330
331 No. PKWare has apparently decided to keep that format proprietary, since 331 No. PKWare has apparently decided to keep that format proprietary, since
332 they have not documented it as they have previous compression formats. 332 they have not documented it as they have previous compression formats.
333 In any case, the compression improvements are so modest compared to other 333 In any case, the compression improvements are so modest compared to other
334 more modern approaches, that it's not worth the effort to implement. 334 more modern approaches, that it's not worth the effort to implement.
335 335
33641. Can you please sign these lengthy legal documents and fax them back to us 33641. Can you please sign these lengthy legal documents and fax them back to us
337 so that we can use your software in our product? 337 so that we can use your software in our product?
338 338
339 No. Go away. Shoo. 339 No. Go away. Shoo.
diff --git a/utils/zenutils/libraries/zlib123/zlib/INDEX b/utils/zenutils/libraries/zlib123/zlib/INDEX
index 4d7eac44bc..0587e5902b 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/INDEX
+++ b/utils/zenutils/libraries/zlib123/zlib/INDEX
@@ -1,51 +1,51 @@
1ChangeLog history of changes 1ChangeLog history of changes
2FAQ Frequently Asked Questions about zlib 2FAQ Frequently Asked Questions about zlib
3INDEX this file 3INDEX this file
4Makefile makefile for Unix (generated by configure) 4Makefile makefile for Unix (generated by configure)
5Makefile.in makefile for Unix (template for configure) 5Makefile.in makefile for Unix (template for configure)
6README guess what 6README guess what
7algorithm.txt description of the (de)compression algorithm 7algorithm.txt description of the (de)compression algorithm
8configure configure script for Unix 8configure configure script for Unix
9zconf.in.h template for zconf.h (used by configure) 9zconf.in.h template for zconf.h (used by configure)
10 10
11amiga/ makefiles for Amiga SAS C 11amiga/ makefiles for Amiga SAS C
12as400/ makefiles for IBM AS/400 12as400/ makefiles for IBM AS/400
13msdos/ makefiles for MSDOS 13msdos/ makefiles for MSDOS
14old/ makefiles for various architectures and zlib documentation 14old/ makefiles for various architectures and zlib documentation
15 files that have not yet been updated for zlib 1.2.x 15 files that have not yet been updated for zlib 1.2.x
16projects/ projects for various Integrated Development Environments 16projects/ projects for various Integrated Development Environments
17qnx/ makefiles for QNX 17qnx/ makefiles for QNX
18win32/ makefiles for Windows 18win32/ makefiles for Windows
19 19
20 zlib public header files (must be kept): 20 zlib public header files (must be kept):
21zconf.h 21zconf.h
22zlib.h 22zlib.h
23 23
24 private source files used to build the zlib library: 24 private source files used to build the zlib library:
25adler32.c 25adler32.c
26compress.c 26compress.c
27crc32.c 27crc32.c
28crc32.h 28crc32.h
29deflate.c 29deflate.c
30deflate.h 30deflate.h
31gzio.c 31gzio.c
32infback.c 32infback.c
33inffast.c 33inffast.c
34inffast.h 34inffast.h
35inffixed.h 35inffixed.h
36inflate.c 36inflate.c
37inflate.h 37inflate.h
38inftrees.c 38inftrees.c
39inftrees.h 39inftrees.h
40trees.c 40trees.c
41trees.h 41trees.h
42uncompr.c 42uncompr.c
43zutil.c 43zutil.c
44zutil.h 44zutil.h
45 45
46 source files for sample programs: 46 source files for sample programs:
47example.c 47example.c
48minigzip.c 48minigzip.c
49 49
50 unsupported contribution by third parties 50 unsupported contribution by third parties
51See contrib/README.contrib 51See contrib/README.contrib
diff --git a/utils/zenutils/libraries/zlib123/zlib/Makefile b/utils/zenutils/libraries/zlib123/zlib/Makefile
index a4954c8f97..2fd6e45c48 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/Makefile
+++ b/utils/zenutils/libraries/zlib123/zlib/Makefile
@@ -1,154 +1,154 @@
1# Makefile for zlib 1# Makefile for zlib
2# Copyright (C) 1995-2005 Jean-loup Gailly. 2# Copyright (C) 1995-2005 Jean-loup Gailly.
3# For conditions of distribution and use, see copyright notice in zlib.h 3# For conditions of distribution and use, see copyright notice in zlib.h
4 4
5# To compile and test, type: 5# To compile and test, type:
6# ./configure; make test 6# ./configure; make test
7# The call of configure is optional if you don't have special requirements 7# The call of configure is optional if you don't have special requirements
8# If you wish to build zlib as a shared library, use: ./configure -s 8# If you wish to build zlib as a shared library, use: ./configure -s
9 9
10# To use the asm code, type: 10# To use the asm code, type:
11# cp contrib/asm?86/match.S ./match.S 11# cp contrib/asm?86/match.S ./match.S
12# make LOC=-DASMV OBJA=match.o 12# make LOC=-DASMV OBJA=match.o
13 13
14# To install /usr/local/lib/libz.* and /usr/local/include/zlib.h, type: 14# To install /usr/local/lib/libz.* and /usr/local/include/zlib.h, type:
15# make install 15# make install
16# To install in $HOME instead of /usr/local, use: 16# To install in $HOME instead of /usr/local, use:
17# make install prefix=$HOME 17# make install prefix=$HOME
18 18
19CC=cc 19CC=cc
20 20
21CFLAGS=-O 21CFLAGS=-O
22#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7 22#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7
23#CFLAGS=-g -DDEBUG 23#CFLAGS=-g -DDEBUG
24#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \ 24#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \
25# -Wstrict-prototypes -Wmissing-prototypes 25# -Wstrict-prototypes -Wmissing-prototypes
26 26
27LDFLAGS=libz.a 27LDFLAGS=libz.a
28LDSHARED=$(CC) 28LDSHARED=$(CC)
29CPP=$(CC) -E 29CPP=$(CC) -E
30 30
31LIBS=libz.a 31LIBS=libz.a
32SHAREDLIB=libz.so 32SHAREDLIB=libz.so
33SHAREDLIBV=libz.so.1.2.3 33SHAREDLIBV=libz.so.1.2.3
34SHAREDLIBM=libz.so.1 34SHAREDLIBM=libz.so.1
35 35
36AR=ar rc 36AR=ar rc
37RANLIB=ranlib 37RANLIB=ranlib
38TAR=tar 38TAR=tar
39SHELL=/bin/sh 39SHELL=/bin/sh
40EXE= 40EXE=
41 41
42prefix = /usr/local 42prefix = /usr/local
43exec_prefix = ${prefix} 43exec_prefix = ${prefix}
44libdir = ${exec_prefix}/lib 44libdir = ${exec_prefix}/lib
45includedir = ${prefix}/include 45includedir = ${prefix}/include
46mandir = ${prefix}/share/man 46mandir = ${prefix}/share/man
47man3dir = ${mandir}/man3 47man3dir = ${mandir}/man3
48 48
49OBJS = adler32.o compress.o crc32.o gzio.o uncompr.o deflate.o trees.o \ 49OBJS = adler32.o compress.o crc32.o gzio.o uncompr.o deflate.o trees.o \
50 zutil.o inflate.o infback.o inftrees.o inffast.o 50 zutil.o inflate.o infback.o inftrees.o inffast.o
51 51
52OBJA = 52OBJA =
53# to use the asm code: make OBJA=match.o 53# to use the asm code: make OBJA=match.o
54 54
55TEST_OBJS = example.o minigzip.o 55TEST_OBJS = example.o minigzip.o
56 56
57all: example$(EXE) minigzip$(EXE) 57all: example$(EXE) minigzip$(EXE)
58 58
59check: test 59check: test
60test: all 60test: all
61 @LD_LIBRARY_PATH=.:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \ 61 @LD_LIBRARY_PATH=.:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \
62 echo hello world | ./minigzip | ./minigzip -d || \ 62 echo hello world | ./minigzip | ./minigzip -d || \
63 echo ' *** minigzip test FAILED ***' ; \ 63 echo ' *** minigzip test FAILED ***' ; \
64 if ./example; then \ 64 if ./example; then \
65 echo ' *** zlib test OK ***'; \ 65 echo ' *** zlib test OK ***'; \
66 else \ 66 else \
67 echo ' *** zlib test FAILED ***'; \ 67 echo ' *** zlib test FAILED ***'; \
68 fi 68 fi
69 69
70libz.a: $(OBJS) $(OBJA) 70libz.a: $(OBJS) $(OBJA)
71 $(AR) $@ $(OBJS) $(OBJA) 71 $(AR) $@ $(OBJS) $(OBJA)
72 -@ ($(RANLIB) $@ || true) >/dev/null 2>&1 72 -@ ($(RANLIB) $@ || true) >/dev/null 2>&1
73 73
74match.o: match.S 74match.o: match.S
75 $(CPP) match.S > _match.s 75 $(CPP) match.S > _match.s
76 $(CC) -c _match.s 76 $(CC) -c _match.s
77 mv _match.o match.o 77 mv _match.o match.o
78 rm -f _match.s 78 rm -f _match.s
79 79
80$(SHAREDLIBV): $(OBJS) 80$(SHAREDLIBV): $(OBJS)
81 $(LDSHARED) -o $@ $(OBJS) 81 $(LDSHARED) -o $@ $(OBJS)
82 rm -f $(SHAREDLIB) $(SHAREDLIBM) 82 rm -f $(SHAREDLIB) $(SHAREDLIBM)
83 ln -s $@ $(SHAREDLIB) 83 ln -s $@ $(SHAREDLIB)
84 ln -s $@ $(SHAREDLIBM) 84 ln -s $@ $(SHAREDLIBM)
85 85
86example$(EXE): example.o $(LIBS) 86example$(EXE): example.o $(LIBS)
87 $(CC) $(CFLAGS) -o $@ example.o $(LDFLAGS) 87 $(CC) $(CFLAGS) -o $@ example.o $(LDFLAGS)
88 88
89minigzip$(EXE): minigzip.o $(LIBS) 89minigzip$(EXE): minigzip.o $(LIBS)
90 $(CC) $(CFLAGS) -o $@ minigzip.o $(LDFLAGS) 90 $(CC) $(CFLAGS) -o $@ minigzip.o $(LDFLAGS)
91 91
92install: $(LIBS) 92install: $(LIBS)
93 -@if [ ! -d $(exec_prefix) ]; then mkdir -p $(exec_prefix); fi 93 -@if [ ! -d $(exec_prefix) ]; then mkdir -p $(exec_prefix); fi
94 -@if [ ! -d $(includedir) ]; then mkdir -p $(includedir); fi 94 -@if [ ! -d $(includedir) ]; then mkdir -p $(includedir); fi
95 -@if [ ! -d $(libdir) ]; then mkdir -p $(libdir); fi 95 -@if [ ! -d $(libdir) ]; then mkdir -p $(libdir); fi
96 -@if [ ! -d $(man3dir) ]; then mkdir -p $(man3dir); fi 96 -@if [ ! -d $(man3dir) ]; then mkdir -p $(man3dir); fi
97 cp zlib.h zconf.h $(includedir) 97 cp zlib.h zconf.h $(includedir)
98 chmod 644 $(includedir)/zlib.h $(includedir)/zconf.h 98 chmod 644 $(includedir)/zlib.h $(includedir)/zconf.h
99 cp $(LIBS) $(libdir) 99 cp $(LIBS) $(libdir)
100 cd $(libdir); chmod 755 $(LIBS) 100 cd $(libdir); chmod 755 $(LIBS)
101 -@(cd $(libdir); $(RANLIB) libz.a || true) >/dev/null 2>&1 101 -@(cd $(libdir); $(RANLIB) libz.a || true) >/dev/null 2>&1
102 cd $(libdir); if test -f $(SHAREDLIBV); then \ 102 cd $(libdir); if test -f $(SHAREDLIBV); then \
103 rm -f $(SHAREDLIB) $(SHAREDLIBM); \ 103 rm -f $(SHAREDLIB) $(SHAREDLIBM); \
104 ln -s $(SHAREDLIBV) $(SHAREDLIB); \ 104 ln -s $(SHAREDLIBV) $(SHAREDLIB); \
105 ln -s $(SHAREDLIBV) $(SHAREDLIBM); \ 105 ln -s $(SHAREDLIBV) $(SHAREDLIBM); \
106 (ldconfig || true) >/dev/null 2>&1; \ 106 (ldconfig || true) >/dev/null 2>&1; \
107 fi 107 fi
108 cp zlib.3 $(man3dir) 108 cp zlib.3 $(man3dir)
109 chmod 644 $(man3dir)/zlib.3 109 chmod 644 $(man3dir)/zlib.3
110# The ranlib in install is needed on NeXTSTEP which checks file times 110# The ranlib in install is needed on NeXTSTEP which checks file times
111# ldconfig is for Linux 111# ldconfig is for Linux
112 112
113uninstall: 113uninstall:
114 cd $(includedir); \ 114 cd $(includedir); \
115 cd $(libdir); rm -f libz.a; \ 115 cd $(libdir); rm -f libz.a; \
116 if test -f $(SHAREDLIBV); then \ 116 if test -f $(SHAREDLIBV); then \
117 rm -f $(SHAREDLIBV) $(SHAREDLIB) $(SHAREDLIBM); \ 117 rm -f $(SHAREDLIBV) $(SHAREDLIB) $(SHAREDLIBM); \
118 fi 118 fi
119 cd $(man3dir); rm -f zlib.3 119 cd $(man3dir); rm -f zlib.3
120 120
121mostlyclean: clean 121mostlyclean: clean
122clean: 122clean:
123 rm -f *.o *~ example$(EXE) minigzip$(EXE) \ 123 rm -f *.o *~ example$(EXE) minigzip$(EXE) \
124 libz.* foo.gz so_locations \ 124 libz.* foo.gz so_locations \
125 _match.s maketree contrib/infback9/*.o 125 _match.s maketree contrib/infback9/*.o
126 126
127maintainer-clean: distclean 127maintainer-clean: distclean
128distclean: clean 128distclean: clean
129 cp -p Makefile.in Makefile 129 cp -p Makefile.in Makefile
130 cp -p zconf.in.h zconf.h 130 cp -p zconf.in.h zconf.h
131 rm -f .DS_Store 131 rm -f .DS_Store
132 132
133tags: 133tags:
134 etags *.[ch] 134 etags *.[ch]
135 135
136depend: 136depend:
137 makedepend -- $(CFLAGS) -- *.[ch] 137 makedepend -- $(CFLAGS) -- *.[ch]
138 138
139# DO NOT DELETE THIS LINE -- make depend depends on it. 139# DO NOT DELETE THIS LINE -- make depend depends on it.
140 140
141adler32.o: zlib.h zconf.h 141adler32.o: zlib.h zconf.h
142compress.o: zlib.h zconf.h 142compress.o: zlib.h zconf.h
143crc32.o: crc32.h zlib.h zconf.h 143crc32.o: crc32.h zlib.h zconf.h
144deflate.o: deflate.h zutil.h zlib.h zconf.h 144deflate.o: deflate.h zutil.h zlib.h zconf.h
145example.o: zlib.h zconf.h 145example.o: zlib.h zconf.h
146gzio.o: zutil.h zlib.h zconf.h 146gzio.o: zutil.h zlib.h zconf.h
147inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h 147inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
148inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h 148inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
149infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h 149infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
150inftrees.o: zutil.h zlib.h zconf.h inftrees.h 150inftrees.o: zutil.h zlib.h zconf.h inftrees.h
151minigzip.o: zlib.h zconf.h 151minigzip.o: zlib.h zconf.h
152trees.o: deflate.h zutil.h zlib.h zconf.h trees.h 152trees.o: deflate.h zutil.h zlib.h zconf.h trees.h
153uncompr.o: zlib.h zconf.h 153uncompr.o: zlib.h zconf.h
154zutil.o: zutil.h zlib.h zconf.h 154zutil.o: zutil.h zlib.h zconf.h
diff --git a/utils/zenutils/libraries/zlib123/zlib/Makefile.in b/utils/zenutils/libraries/zlib123/zlib/Makefile.in
index a4954c8f97..2fd6e45c48 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/Makefile.in
+++ b/utils/zenutils/libraries/zlib123/zlib/Makefile.in
@@ -1,154 +1,154 @@
1# Makefile for zlib 1# Makefile for zlib
2# Copyright (C) 1995-2005 Jean-loup Gailly. 2# Copyright (C) 1995-2005 Jean-loup Gailly.
3# For conditions of distribution and use, see copyright notice in zlib.h 3# For conditions of distribution and use, see copyright notice in zlib.h
4 4
5# To compile and test, type: 5# To compile and test, type:
6# ./configure; make test 6# ./configure; make test
7# The call of configure is optional if you don't have special requirements 7# The call of configure is optional if you don't have special requirements
8# If you wish to build zlib as a shared library, use: ./configure -s 8# If you wish to build zlib as a shared library, use: ./configure -s
9 9
10# To use the asm code, type: 10# To use the asm code, type:
11# cp contrib/asm?86/match.S ./match.S 11# cp contrib/asm?86/match.S ./match.S
12# make LOC=-DASMV OBJA=match.o 12# make LOC=-DASMV OBJA=match.o
13 13
14# To install /usr/local/lib/libz.* and /usr/local/include/zlib.h, type: 14# To install /usr/local/lib/libz.* and /usr/local/include/zlib.h, type:
15# make install 15# make install
16# To install in $HOME instead of /usr/local, use: 16# To install in $HOME instead of /usr/local, use:
17# make install prefix=$HOME 17# make install prefix=$HOME
18 18
19CC=cc 19CC=cc
20 20
21CFLAGS=-O 21CFLAGS=-O
22#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7 22#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7
23#CFLAGS=-g -DDEBUG 23#CFLAGS=-g -DDEBUG
24#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \ 24#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \
25# -Wstrict-prototypes -Wmissing-prototypes 25# -Wstrict-prototypes -Wmissing-prototypes
26 26
27LDFLAGS=libz.a 27LDFLAGS=libz.a
28LDSHARED=$(CC) 28LDSHARED=$(CC)
29CPP=$(CC) -E 29CPP=$(CC) -E
30 30
31LIBS=libz.a 31LIBS=libz.a
32SHAREDLIB=libz.so 32SHAREDLIB=libz.so
33SHAREDLIBV=libz.so.1.2.3 33SHAREDLIBV=libz.so.1.2.3
34SHAREDLIBM=libz.so.1 34SHAREDLIBM=libz.so.1
35 35
36AR=ar rc 36AR=ar rc
37RANLIB=ranlib 37RANLIB=ranlib
38TAR=tar 38TAR=tar
39SHELL=/bin/sh 39SHELL=/bin/sh
40EXE= 40EXE=
41 41
42prefix = /usr/local 42prefix = /usr/local
43exec_prefix = ${prefix} 43exec_prefix = ${prefix}
44libdir = ${exec_prefix}/lib 44libdir = ${exec_prefix}/lib
45includedir = ${prefix}/include 45includedir = ${prefix}/include
46mandir = ${prefix}/share/man 46mandir = ${prefix}/share/man
47man3dir = ${mandir}/man3 47man3dir = ${mandir}/man3
48 48
49OBJS = adler32.o compress.o crc32.o gzio.o uncompr.o deflate.o trees.o \ 49OBJS = adler32.o compress.o crc32.o gzio.o uncompr.o deflate.o trees.o \
50 zutil.o inflate.o infback.o inftrees.o inffast.o 50 zutil.o inflate.o infback.o inftrees.o inffast.o
51 51
52OBJA = 52OBJA =
53# to use the asm code: make OBJA=match.o 53# to use the asm code: make OBJA=match.o
54 54
55TEST_OBJS = example.o minigzip.o 55TEST_OBJS = example.o minigzip.o
56 56
57all: example$(EXE) minigzip$(EXE) 57all: example$(EXE) minigzip$(EXE)
58 58
59check: test 59check: test
60test: all 60test: all
61 @LD_LIBRARY_PATH=.:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \ 61 @LD_LIBRARY_PATH=.:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \
62 echo hello world | ./minigzip | ./minigzip -d || \ 62 echo hello world | ./minigzip | ./minigzip -d || \
63 echo ' *** minigzip test FAILED ***' ; \ 63 echo ' *** minigzip test FAILED ***' ; \
64 if ./example; then \ 64 if ./example; then \
65 echo ' *** zlib test OK ***'; \ 65 echo ' *** zlib test OK ***'; \
66 else \ 66 else \
67 echo ' *** zlib test FAILED ***'; \ 67 echo ' *** zlib test FAILED ***'; \
68 fi 68 fi
69 69
70libz.a: $(OBJS) $(OBJA) 70libz.a: $(OBJS) $(OBJA)
71 $(AR) $@ $(OBJS) $(OBJA) 71 $(AR) $@ $(OBJS) $(OBJA)
72 -@ ($(RANLIB) $@ || true) >/dev/null 2>&1 72 -@ ($(RANLIB) $@ || true) >/dev/null 2>&1
73 73
74match.o: match.S 74match.o: match.S
75 $(CPP) match.S > _match.s 75 $(CPP) match.S > _match.s
76 $(CC) -c _match.s 76 $(CC) -c _match.s
77 mv _match.o match.o 77 mv _match.o match.o
78 rm -f _match.s 78 rm -f _match.s
79 79
80$(SHAREDLIBV): $(OBJS) 80$(SHAREDLIBV): $(OBJS)
81 $(LDSHARED) -o $@ $(OBJS) 81 $(LDSHARED) -o $@ $(OBJS)
82 rm -f $(SHAREDLIB) $(SHAREDLIBM) 82 rm -f $(SHAREDLIB) $(SHAREDLIBM)
83 ln -s $@ $(SHAREDLIB) 83 ln -s $@ $(SHAREDLIB)
84 ln -s $@ $(SHAREDLIBM) 84 ln -s $@ $(SHAREDLIBM)
85 85
86example$(EXE): example.o $(LIBS) 86example$(EXE): example.o $(LIBS)
87 $(CC) $(CFLAGS) -o $@ example.o $(LDFLAGS) 87 $(CC) $(CFLAGS) -o $@ example.o $(LDFLAGS)
88 88
89minigzip$(EXE): minigzip.o $(LIBS) 89minigzip$(EXE): minigzip.o $(LIBS)
90 $(CC) $(CFLAGS) -o $@ minigzip.o $(LDFLAGS) 90 $(CC) $(CFLAGS) -o $@ minigzip.o $(LDFLAGS)
91 91
92install: $(LIBS) 92install: $(LIBS)
93 -@if [ ! -d $(exec_prefix) ]; then mkdir -p $(exec_prefix); fi 93 -@if [ ! -d $(exec_prefix) ]; then mkdir -p $(exec_prefix); fi
94 -@if [ ! -d $(includedir) ]; then mkdir -p $(includedir); fi 94 -@if [ ! -d $(includedir) ]; then mkdir -p $(includedir); fi
95 -@if [ ! -d $(libdir) ]; then mkdir -p $(libdir); fi 95 -@if [ ! -d $(libdir) ]; then mkdir -p $(libdir); fi
96 -@if [ ! -d $(man3dir) ]; then mkdir -p $(man3dir); fi 96 -@if [ ! -d $(man3dir) ]; then mkdir -p $(man3dir); fi
97 cp zlib.h zconf.h $(includedir) 97 cp zlib.h zconf.h $(includedir)
98 chmod 644 $(includedir)/zlib.h $(includedir)/zconf.h 98 chmod 644 $(includedir)/zlib.h $(includedir)/zconf.h
99 cp $(LIBS) $(libdir) 99 cp $(LIBS) $(libdir)
100 cd $(libdir); chmod 755 $(LIBS) 100 cd $(libdir); chmod 755 $(LIBS)
101 -@(cd $(libdir); $(RANLIB) libz.a || true) >/dev/null 2>&1 101 -@(cd $(libdir); $(RANLIB) libz.a || true) >/dev/null 2>&1
102 cd $(libdir); if test -f $(SHAREDLIBV); then \ 102 cd $(libdir); if test -f $(SHAREDLIBV); then \
103 rm -f $(SHAREDLIB) $(SHAREDLIBM); \ 103 rm -f $(SHAREDLIB) $(SHAREDLIBM); \
104 ln -s $(SHAREDLIBV) $(SHAREDLIB); \ 104 ln -s $(SHAREDLIBV) $(SHAREDLIB); \
105 ln -s $(SHAREDLIBV) $(SHAREDLIBM); \ 105 ln -s $(SHAREDLIBV) $(SHAREDLIBM); \
106 (ldconfig || true) >/dev/null 2>&1; \ 106 (ldconfig || true) >/dev/null 2>&1; \
107 fi 107 fi
108 cp zlib.3 $(man3dir) 108 cp zlib.3 $(man3dir)
109 chmod 644 $(man3dir)/zlib.3 109 chmod 644 $(man3dir)/zlib.3
110# The ranlib in install is needed on NeXTSTEP which checks file times 110# The ranlib in install is needed on NeXTSTEP which checks file times
111# ldconfig is for Linux 111# ldconfig is for Linux
112 112
113uninstall: 113uninstall:
114 cd $(includedir); \ 114 cd $(includedir); \
115 cd $(libdir); rm -f libz.a; \ 115 cd $(libdir); rm -f libz.a; \
116 if test -f $(SHAREDLIBV); then \ 116 if test -f $(SHAREDLIBV); then \
117 rm -f $(SHAREDLIBV) $(SHAREDLIB) $(SHAREDLIBM); \ 117 rm -f $(SHAREDLIBV) $(SHAREDLIB) $(SHAREDLIBM); \
118 fi 118 fi
119 cd $(man3dir); rm -f zlib.3 119 cd $(man3dir); rm -f zlib.3
120 120
121mostlyclean: clean 121mostlyclean: clean
122clean: 122clean:
123 rm -f *.o *~ example$(EXE) minigzip$(EXE) \ 123 rm -f *.o *~ example$(EXE) minigzip$(EXE) \
124 libz.* foo.gz so_locations \ 124 libz.* foo.gz so_locations \
125 _match.s maketree contrib/infback9/*.o 125 _match.s maketree contrib/infback9/*.o
126 126
127maintainer-clean: distclean 127maintainer-clean: distclean
128distclean: clean 128distclean: clean
129 cp -p Makefile.in Makefile 129 cp -p Makefile.in Makefile
130 cp -p zconf.in.h zconf.h 130 cp -p zconf.in.h zconf.h
131 rm -f .DS_Store 131 rm -f .DS_Store
132 132
133tags: 133tags:
134 etags *.[ch] 134 etags *.[ch]
135 135
136depend: 136depend:
137 makedepend -- $(CFLAGS) -- *.[ch] 137 makedepend -- $(CFLAGS) -- *.[ch]
138 138
139# DO NOT DELETE THIS LINE -- make depend depends on it. 139# DO NOT DELETE THIS LINE -- make depend depends on it.
140 140
141adler32.o: zlib.h zconf.h 141adler32.o: zlib.h zconf.h
142compress.o: zlib.h zconf.h 142compress.o: zlib.h zconf.h
143crc32.o: crc32.h zlib.h zconf.h 143crc32.o: crc32.h zlib.h zconf.h
144deflate.o: deflate.h zutil.h zlib.h zconf.h 144deflate.o: deflate.h zutil.h zlib.h zconf.h
145example.o: zlib.h zconf.h 145example.o: zlib.h zconf.h
146gzio.o: zutil.h zlib.h zconf.h 146gzio.o: zutil.h zlib.h zconf.h
147inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h 147inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
148inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h 148inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
149infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h 149infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
150inftrees.o: zutil.h zlib.h zconf.h inftrees.h 150inftrees.o: zutil.h zlib.h zconf.h inftrees.h
151minigzip.o: zlib.h zconf.h 151minigzip.o: zlib.h zconf.h
152trees.o: deflate.h zutil.h zlib.h zconf.h trees.h 152trees.o: deflate.h zutil.h zlib.h zconf.h trees.h
153uncompr.o: zlib.h zconf.h 153uncompr.o: zlib.h zconf.h
154zutil.o: zutil.h zlib.h zconf.h 154zutil.o: zutil.h zlib.h zconf.h
diff --git a/utils/zenutils/libraries/zlib123/zlib/README b/utils/zenutils/libraries/zlib123/zlib/README
index 80f71ae856..758cc50020 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/README
+++ b/utils/zenutils/libraries/zlib123/zlib/README
@@ -1,125 +1,125 @@
1ZLIB DATA COMPRESSION LIBRARY 1ZLIB DATA COMPRESSION LIBRARY
2 2
3zlib 1.2.3 is a general purpose data compression library. All the code is 3zlib 1.2.3 is a general purpose data compression library. All the code is
4thread safe. The data format used by the zlib library is described by RFCs 4thread safe. The data format used by the zlib library is described by RFCs
5(Request for Comments) 1950 to 1952 in the files 5(Request for Comments) 1950 to 1952 in the files
6http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format) 6http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format)
7and rfc1952.txt (gzip format). These documents are also available in other 7and rfc1952.txt (gzip format). These documents are also available in other
8formats from ftp://ftp.uu.net/graphics/png/documents/zlib/zdoc-index.html 8formats from ftp://ftp.uu.net/graphics/png/documents/zlib/zdoc-index.html
9 9
10All functions of the compression library are documented in the file zlib.h 10All functions of the compression library are documented in the file zlib.h
11(volunteer to write man pages welcome, contact zlib@gzip.org). A usage example 11(volunteer to write man pages welcome, contact zlib@gzip.org). A usage example
12of the library is given in the file example.c which also tests that the library 12of the library is given in the file example.c which also tests that the library
13is working correctly. Another example is given in the file minigzip.c. The 13is working correctly. Another example is given in the file minigzip.c. The
14compression library itself is composed of all source files except example.c and 14compression library itself is composed of all source files except example.c and
15minigzip.c. 15minigzip.c.
16 16
17To compile all files and run the test program, follow the instructions given at 17To compile all files and run the test program, follow the instructions given at
18the top of Makefile. In short "make test; make install" should work for most 18the top of Makefile. In short "make test; make install" should work for most
19machines. For Unix: "./configure; make test; make install". For MSDOS, use one 19machines. For Unix: "./configure; make test; make install". For MSDOS, use one
20of the special makefiles such as Makefile.msc. For VMS, use make_vms.com. 20of the special makefiles such as Makefile.msc. For VMS, use make_vms.com.
21 21
22Questions about zlib should be sent to <zlib@gzip.org>, or to Gilles Vollant 22Questions about zlib should be sent to <zlib@gzip.org>, or to Gilles Vollant
23<info@winimage.com> for the Windows DLL version. The zlib home page is 23<info@winimage.com> for the Windows DLL version. The zlib home page is
24http://www.zlib.org or http://www.gzip.org/zlib/ Before reporting a problem, 24http://www.zlib.org or http://www.gzip.org/zlib/ Before reporting a problem,
25please check this site to verify that you have the latest version of zlib; 25please check this site to verify that you have the latest version of zlib;
26otherwise get the latest version and check whether the problem still exists or 26otherwise get the latest version and check whether the problem still exists or
27not. 27not.
28 28
29PLEASE read the zlib FAQ http://www.gzip.org/zlib/zlib_faq.html before asking 29PLEASE read the zlib FAQ http://www.gzip.org/zlib/zlib_faq.html before asking
30for help. 30for help.
31 31
32Mark Nelson <markn@ieee.org> wrote an article about zlib for the Jan. 1997 32Mark Nelson <markn@ieee.org> wrote an article about zlib for the Jan. 1997
33issue of Dr. Dobb's Journal; a copy of the article is available in 33issue of Dr. Dobb's Journal; a copy of the article is available in
34http://dogma.net/markn/articles/zlibtool/zlibtool.htm 34http://dogma.net/markn/articles/zlibtool/zlibtool.htm
35 35
36The changes made in version 1.2.3 are documented in the file ChangeLog. 36The changes made in version 1.2.3 are documented in the file ChangeLog.
37 37
38Unsupported third party contributions are provided in directory "contrib". 38Unsupported third party contributions are provided in directory "contrib".
39 39
40A Java implementation of zlib is available in the Java Development Kit 40A Java implementation of zlib is available in the Java Development Kit
41http://java.sun.com/j2se/1.4.2/docs/api/java/util/zip/package-summary.html 41http://java.sun.com/j2se/1.4.2/docs/api/java/util/zip/package-summary.html
42See the zlib home page http://www.zlib.org for details. 42See the zlib home page http://www.zlib.org for details.
43 43
44A Perl interface to zlib written by Paul Marquess <pmqs@cpan.org> is in the 44A Perl interface to zlib written by Paul Marquess <pmqs@cpan.org> is in the
45CPAN (Comprehensive Perl Archive Network) sites 45CPAN (Comprehensive Perl Archive Network) sites
46http://www.cpan.org/modules/by-module/Compress/ 46http://www.cpan.org/modules/by-module/Compress/
47 47
48A Python interface to zlib written by A.M. Kuchling <amk@amk.ca> is 48A Python interface to zlib written by A.M. Kuchling <amk@amk.ca> is
49available in Python 1.5 and later versions, see 49available in Python 1.5 and later versions, see
50http://www.python.org/doc/lib/module-zlib.html 50http://www.python.org/doc/lib/module-zlib.html
51 51
52A zlib binding for TCL written by Andreas Kupries <a.kupries@westend.com> is 52A zlib binding for TCL written by Andreas Kupries <a.kupries@westend.com> is
53availlable at http://www.oche.de/~akupries/soft/trf/trf_zip.html 53availlable at http://www.oche.de/~akupries/soft/trf/trf_zip.html
54 54
55An experimental package to read and write files in .zip format, written on top 55An experimental package to read and write files in .zip format, written on top
56of zlib by Gilles Vollant <info@winimage.com>, is available in the 56of zlib by Gilles Vollant <info@winimage.com>, is available in the
57contrib/minizip directory of zlib. 57contrib/minizip directory of zlib.
58 58
59 59
60Notes for some targets: 60Notes for some targets:
61 61
62- For Windows DLL versions, please see win32/DLL_FAQ.txt 62- For Windows DLL versions, please see win32/DLL_FAQ.txt
63 63
64- For 64-bit Irix, deflate.c must be compiled without any optimization. With 64- For 64-bit Irix, deflate.c must be compiled without any optimization. With
65 -O, one libpng test fails. The test works in 32 bit mode (with the -n32 65 -O, one libpng test fails. The test works in 32 bit mode (with the -n32
66 compiler flag). The compiler bug has been reported to SGI. 66 compiler flag). The compiler bug has been reported to SGI.
67 67
68- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works 68- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works
69 when compiled with cc. 69 when compiled with cc.
70 70
71- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is 71- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is
72 necessary to get gzprintf working correctly. This is done by configure. 72 necessary to get gzprintf working correctly. This is done by configure.
73 73
74- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with 74- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with
75 other compilers. Use "make test" to check your compiler. 75 other compilers. Use "make test" to check your compiler.
76 76
77- gzdopen is not supported on RISCOS, BEOS and by some Mac compilers. 77- gzdopen is not supported on RISCOS, BEOS and by some Mac compilers.
78 78
79- For PalmOs, see http://palmzlib.sourceforge.net/ 79- For PalmOs, see http://palmzlib.sourceforge.net/
80 80
81- When building a shared, i.e. dynamic library on Mac OS X, the library must be 81- When building a shared, i.e. dynamic library on Mac OS X, the library must be
82 installed before testing (do "make install" before "make test"), since the 82 installed before testing (do "make install" before "make test"), since the
83 library location is specified in the library. 83 library location is specified in the library.
84 84
85 85
86Acknowledgments: 86Acknowledgments:
87 87
88 The deflate format used by zlib was defined by Phil Katz. The deflate 88 The deflate format used by zlib was defined by Phil Katz. The deflate
89 and zlib specifications were written by L. Peter Deutsch. Thanks to all the 89 and zlib specifications were written by L. Peter Deutsch. Thanks to all the
90 people who reported problems and suggested various improvements in zlib; 90 people who reported problems and suggested various improvements in zlib;
91 they are too numerous to cite here. 91 they are too numerous to cite here.
92 92
93Copyright notice: 93Copyright notice:
94 94
95 (C) 1995-2004 Jean-loup Gailly and Mark Adler 95 (C) 1995-2004 Jean-loup Gailly and Mark Adler
96 96
97 This software is provided 'as-is', without any express or implied 97 This software is provided 'as-is', without any express or implied
98 warranty. In no event will the authors be held liable for any damages 98 warranty. In no event will the authors be held liable for any damages
99 arising from the use of this software. 99 arising from the use of this software.
100 100
101 Permission is granted to anyone to use this software for any purpose, 101 Permission is granted to anyone to use this software for any purpose,
102 including commercial applications, and to alter it and redistribute it 102 including commercial applications, and to alter it and redistribute it
103 freely, subject to the following restrictions: 103 freely, subject to the following restrictions:
104 104
105 1. The origin of this software must not be misrepresented; you must not 105 1. The origin of this software must not be misrepresented; you must not
106 claim that you wrote the original software. If you use this software 106 claim that you wrote the original software. If you use this software
107 in a product, an acknowledgment in the product documentation would be 107 in a product, an acknowledgment in the product documentation would be
108 appreciated but is not required. 108 appreciated but is not required.
109 2. Altered source versions must be plainly marked as such, and must not be 109 2. Altered source versions must be plainly marked as such, and must not be
110 misrepresented as being the original software. 110 misrepresented as being the original software.
111 3. This notice may not be removed or altered from any source distribution. 111 3. This notice may not be removed or altered from any source distribution.
112 112
113 Jean-loup Gailly Mark Adler 113 Jean-loup Gailly Mark Adler
114 jloup@gzip.org madler@alumni.caltech.edu 114 jloup@gzip.org madler@alumni.caltech.edu
115 115
116If you use the zlib library in a product, we would appreciate *not* 116If you use the zlib library in a product, we would appreciate *not*
117receiving lengthy legal documents to sign. The sources are provided 117receiving lengthy legal documents to sign. The sources are provided
118for free but without warranty of any kind. The library has been 118for free but without warranty of any kind. The library has been
119entirely written by Jean-loup Gailly and Mark Adler; it does not 119entirely written by Jean-loup Gailly and Mark Adler; it does not
120include third-party code. 120include third-party code.
121 121
122If you redistribute modified sources, we would appreciate that you include 122If you redistribute modified sources, we would appreciate that you include
123in the file ChangeLog history information documenting your changes. Please 123in the file ChangeLog history information documenting your changes. Please
124read the FAQ for more information on the distribution of modified source 124read the FAQ for more information on the distribution of modified source
125versions. 125versions.
diff --git a/utils/zenutils/libraries/zlib123/zlib/adler32.c b/utils/zenutils/libraries/zlib123/zlib/adler32.c
index f201d6701e..007ba26277 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/adler32.c
+++ b/utils/zenutils/libraries/zlib123/zlib/adler32.c
@@ -1,149 +1,149 @@
1/* adler32.c -- compute the Adler-32 checksum of a data stream 1/* adler32.c -- compute the Adler-32 checksum of a data stream
2 * Copyright (C) 1995-2004 Mark Adler 2 * Copyright (C) 1995-2004 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6/* @(#) $Id$ */ 6/* @(#) $Id$ */
7 7
8#define ZLIB_INTERNAL 8#define ZLIB_INTERNAL
9#include "zlib.h" 9#include "zlib.h"
10 10
11#define BASE 65521UL /* largest prime smaller than 65536 */ 11#define BASE 65521UL /* largest prime smaller than 65536 */
12#define NMAX 5552 12#define NMAX 5552
13/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ 13/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
14 14
15#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} 15#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
16#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); 16#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
17#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); 17#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
18#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); 18#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
19#define DO16(buf) DO8(buf,0); DO8(buf,8); 19#define DO16(buf) DO8(buf,0); DO8(buf,8);
20 20
21/* use NO_DIVIDE if your processor does not do division in hardware */ 21/* use NO_DIVIDE if your processor does not do division in hardware */
22#ifdef NO_DIVIDE 22#ifdef NO_DIVIDE
23# define MOD(a) \ 23# define MOD(a) \
24 do { \ 24 do { \
25 if (a >= (BASE << 16)) a -= (BASE << 16); \ 25 if (a >= (BASE << 16)) a -= (BASE << 16); \
26 if (a >= (BASE << 15)) a -= (BASE << 15); \ 26 if (a >= (BASE << 15)) a -= (BASE << 15); \
27 if (a >= (BASE << 14)) a -= (BASE << 14); \ 27 if (a >= (BASE << 14)) a -= (BASE << 14); \
28 if (a >= (BASE << 13)) a -= (BASE << 13); \ 28 if (a >= (BASE << 13)) a -= (BASE << 13); \
29 if (a >= (BASE << 12)) a -= (BASE << 12); \ 29 if (a >= (BASE << 12)) a -= (BASE << 12); \
30 if (a >= (BASE << 11)) a -= (BASE << 11); \ 30 if (a >= (BASE << 11)) a -= (BASE << 11); \
31 if (a >= (BASE << 10)) a -= (BASE << 10); \ 31 if (a >= (BASE << 10)) a -= (BASE << 10); \
32 if (a >= (BASE << 9)) a -= (BASE << 9); \ 32 if (a >= (BASE << 9)) a -= (BASE << 9); \
33 if (a >= (BASE << 8)) a -= (BASE << 8); \ 33 if (a >= (BASE << 8)) a -= (BASE << 8); \
34 if (a >= (BASE << 7)) a -= (BASE << 7); \ 34 if (a >= (BASE << 7)) a -= (BASE << 7); \
35 if (a >= (BASE << 6)) a -= (BASE << 6); \ 35 if (a >= (BASE << 6)) a -= (BASE << 6); \
36 if (a >= (BASE << 5)) a -= (BASE << 5); \ 36 if (a >= (BASE << 5)) a -= (BASE << 5); \
37 if (a >= (BASE << 4)) a -= (BASE << 4); \ 37 if (a >= (BASE << 4)) a -= (BASE << 4); \
38 if (a >= (BASE << 3)) a -= (BASE << 3); \ 38 if (a >= (BASE << 3)) a -= (BASE << 3); \
39 if (a >= (BASE << 2)) a -= (BASE << 2); \ 39 if (a >= (BASE << 2)) a -= (BASE << 2); \
40 if (a >= (BASE << 1)) a -= (BASE << 1); \ 40 if (a >= (BASE << 1)) a -= (BASE << 1); \
41 if (a >= BASE) a -= BASE; \ 41 if (a >= BASE) a -= BASE; \
42 } while (0) 42 } while (0)
43# define MOD4(a) \ 43# define MOD4(a) \
44 do { \ 44 do { \
45 if (a >= (BASE << 4)) a -= (BASE << 4); \ 45 if (a >= (BASE << 4)) a -= (BASE << 4); \
46 if (a >= (BASE << 3)) a -= (BASE << 3); \ 46 if (a >= (BASE << 3)) a -= (BASE << 3); \
47 if (a >= (BASE << 2)) a -= (BASE << 2); \ 47 if (a >= (BASE << 2)) a -= (BASE << 2); \
48 if (a >= (BASE << 1)) a -= (BASE << 1); \ 48 if (a >= (BASE << 1)) a -= (BASE << 1); \
49 if (a >= BASE) a -= BASE; \ 49 if (a >= BASE) a -= BASE; \
50 } while (0) 50 } while (0)
51#else 51#else
52# define MOD(a) a %= BASE 52# define MOD(a) a %= BASE
53# define MOD4(a) a %= BASE 53# define MOD4(a) a %= BASE
54#endif 54#endif
55 55
56/* ========================================================================= */ 56/* ========================================================================= */
57uLong ZEXPORT adler32(adler, buf, len) 57uLong ZEXPORT adler32(adler, buf, len)
58 uLong adler; 58 uLong adler;
59 const Bytef *buf; 59 const Bytef *buf;
60 uInt len; 60 uInt len;
61{ 61{
62 unsigned long sum2; 62 unsigned long sum2;
63 unsigned n; 63 unsigned n;
64 64
65 /* split Adler-32 into component sums */ 65 /* split Adler-32 into component sums */
66 sum2 = (adler >> 16) & 0xffff; 66 sum2 = (adler >> 16) & 0xffff;
67 adler &= 0xffff; 67 adler &= 0xffff;
68 68
69 /* in case user likes doing a byte at a time, keep it fast */ 69 /* in case user likes doing a byte at a time, keep it fast */
70 if (len == 1) { 70 if (len == 1) {
71 adler += buf[0]; 71 adler += buf[0];
72 if (adler >= BASE) 72 if (adler >= BASE)
73 adler -= BASE; 73 adler -= BASE;
74 sum2 += adler; 74 sum2 += adler;
75 if (sum2 >= BASE) 75 if (sum2 >= BASE)
76 sum2 -= BASE; 76 sum2 -= BASE;
77 return adler | (sum2 << 16); 77 return adler | (sum2 << 16);
78 } 78 }
79 79
80 /* initial Adler-32 value (deferred check for len == 1 speed) */ 80 /* initial Adler-32 value (deferred check for len == 1 speed) */
81 if (buf == Z_NULL) 81 if (buf == Z_NULL)
82 return 1L; 82 return 1L;
83 83
84 /* in case short lengths are provided, keep it somewhat fast */ 84 /* in case short lengths are provided, keep it somewhat fast */
85 if (len < 16) { 85 if (len < 16) {
86 while (len--) { 86 while (len--) {
87 adler += *buf++; 87 adler += *buf++;
88 sum2 += adler; 88 sum2 += adler;
89 } 89 }
90 if (adler >= BASE) 90 if (adler >= BASE)
91 adler -= BASE; 91 adler -= BASE;
92 MOD4(sum2); /* only added so many BASE's */ 92 MOD4(sum2); /* only added so many BASE's */
93 return adler | (sum2 << 16); 93 return adler | (sum2 << 16);
94 } 94 }
95 95
96 /* do length NMAX blocks -- requires just one modulo operation */ 96 /* do length NMAX blocks -- requires just one modulo operation */
97 while (len >= NMAX) { 97 while (len >= NMAX) {
98 len -= NMAX; 98 len -= NMAX;
99 n = NMAX / 16; /* NMAX is divisible by 16 */ 99 n = NMAX / 16; /* NMAX is divisible by 16 */
100 do { 100 do {
101 DO16(buf); /* 16 sums unrolled */ 101 DO16(buf); /* 16 sums unrolled */
102 buf += 16; 102 buf += 16;
103 } while (--n); 103 } while (--n);
104 MOD(adler); 104 MOD(adler);
105 MOD(sum2); 105 MOD(sum2);
106 } 106 }
107 107
108 /* do remaining bytes (less than NMAX, still just one modulo) */ 108 /* do remaining bytes (less than NMAX, still just one modulo) */
109 if (len) { /* avoid modulos if none remaining */ 109 if (len) { /* avoid modulos if none remaining */
110 while (len >= 16) { 110 while (len >= 16) {
111 len -= 16; 111 len -= 16;
112 DO16(buf); 112 DO16(buf);
113 buf += 16; 113 buf += 16;
114 } 114 }
115 while (len--) { 115 while (len--) {
116 adler += *buf++; 116 adler += *buf++;
117 sum2 += adler; 117 sum2 += adler;
118 } 118 }
119 MOD(adler); 119 MOD(adler);
120 MOD(sum2); 120 MOD(sum2);
121 } 121 }
122 122
123 /* return recombined sums */ 123 /* return recombined sums */
124 return adler | (sum2 << 16); 124 return adler | (sum2 << 16);
125} 125}
126 126
127/* ========================================================================= */ 127/* ========================================================================= */
128uLong ZEXPORT adler32_combine(adler1, adler2, len2) 128uLong ZEXPORT adler32_combine(adler1, adler2, len2)
129 uLong adler1; 129 uLong adler1;
130 uLong adler2; 130 uLong adler2;
131 z_off_t len2; 131 z_off_t len2;
132{ 132{
133 unsigned long sum1; 133 unsigned long sum1;
134 unsigned long sum2; 134 unsigned long sum2;
135 unsigned rem; 135 unsigned rem;
136 136
137 /* the derivation of this formula is left as an exercise for the reader */ 137 /* the derivation of this formula is left as an exercise for the reader */
138 rem = (unsigned)(len2 % BASE); 138 rem = (unsigned)(len2 % BASE);
139 sum1 = adler1 & 0xffff; 139 sum1 = adler1 & 0xffff;
140 sum2 = rem * sum1; 140 sum2 = rem * sum1;
141 MOD(sum2); 141 MOD(sum2);
142 sum1 += (adler2 & 0xffff) + BASE - 1; 142 sum1 += (adler2 & 0xffff) + BASE - 1;
143 sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; 143 sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
144 if (sum1 > BASE) sum1 -= BASE; 144 if (sum1 > BASE) sum1 -= BASE;
145 if (sum1 > BASE) sum1 -= BASE; 145 if (sum1 > BASE) sum1 -= BASE;
146 if (sum2 > (BASE << 1)) sum2 -= (BASE << 1); 146 if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
147 if (sum2 > BASE) sum2 -= BASE; 147 if (sum2 > BASE) sum2 -= BASE;
148 return sum1 | (sum2 << 16); 148 return sum1 | (sum2 << 16);
149} 149}
diff --git a/utils/zenutils/libraries/zlib123/zlib/algorithm.txt b/utils/zenutils/libraries/zlib123/zlib/algorithm.txt
index 9f6b06808c..b022dde312 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/algorithm.txt
+++ b/utils/zenutils/libraries/zlib123/zlib/algorithm.txt
@@ -1,209 +1,209 @@
11. Compression algorithm (deflate) 11. Compression algorithm (deflate)
2 2
3The deflation algorithm used by gzip (also zip and zlib) is a variation of 3The deflation algorithm used by gzip (also zip and zlib) is a variation of
4LZ77 (Lempel-Ziv 1977, see reference below). It finds duplicated strings in 4LZ77 (Lempel-Ziv 1977, see reference below). It finds duplicated strings in
5the input data. The second occurrence of a string is replaced by a 5the input data. The second occurrence of a string is replaced by a
6pointer to the previous string, in the form of a pair (distance, 6pointer to the previous string, in the form of a pair (distance,
7length). Distances are limited to 32K bytes, and lengths are limited 7length). Distances are limited to 32K bytes, and lengths are limited
8to 258 bytes. When a string does not occur anywhere in the previous 8to 258 bytes. When a string does not occur anywhere in the previous
932K bytes, it is emitted as a sequence of literal bytes. (In this 932K bytes, it is emitted as a sequence of literal bytes. (In this
10description, `string' must be taken as an arbitrary sequence of bytes, 10description, `string' must be taken as an arbitrary sequence of bytes,
11and is not restricted to printable characters.) 11and is not restricted to printable characters.)
12 12
13Literals or match lengths are compressed with one Huffman tree, and 13Literals or match lengths are compressed with one Huffman tree, and
14match distances are compressed with another tree. The trees are stored 14match distances are compressed with another tree. The trees are stored
15in a compact form at the start of each block. The blocks can have any 15in a compact form at the start of each block. The blocks can have any
16size (except that the compressed data for one block must fit in 16size (except that the compressed data for one block must fit in
17available memory). A block is terminated when deflate() determines that 17available memory). A block is terminated when deflate() determines that
18it would be useful to start another block with fresh trees. (This is 18it would be useful to start another block with fresh trees. (This is
19somewhat similar to the behavior of LZW-based _compress_.) 19somewhat similar to the behavior of LZW-based _compress_.)
20 20
21Duplicated strings are found using a hash table. All input strings of 21Duplicated strings are found using a hash table. All input strings of
22length 3 are inserted in the hash table. A hash index is computed for 22length 3 are inserted in the hash table. A hash index is computed for
23the next 3 bytes. If the hash chain for this index is not empty, all 23the next 3 bytes. If the hash chain for this index is not empty, all
24strings in the chain are compared with the current input string, and 24strings in the chain are compared with the current input string, and
25the longest match is selected. 25the longest match is selected.
26 26
27The hash chains are searched starting with the most recent strings, to 27The hash chains are searched starting with the most recent strings, to
28favor small distances and thus take advantage of the Huffman encoding. 28favor small distances and thus take advantage of the Huffman encoding.
29The hash chains are singly linked. There are no deletions from the 29The hash chains are singly linked. There are no deletions from the
30hash chains, the algorithm simply discards matches that are too old. 30hash chains, the algorithm simply discards matches that are too old.
31 31
32To avoid a worst-case situation, very long hash chains are arbitrarily 32To avoid a worst-case situation, very long hash chains are arbitrarily
33truncated at a certain length, determined by a runtime option (level 33truncated at a certain length, determined by a runtime option (level
34parameter of deflateInit). So deflate() does not always find the longest 34parameter of deflateInit). So deflate() does not always find the longest
35possible match but generally finds a match which is long enough. 35possible match but generally finds a match which is long enough.
36 36
37deflate() also defers the selection of matches with a lazy evaluation 37deflate() also defers the selection of matches with a lazy evaluation
38mechanism. After a match of length N has been found, deflate() searches for 38mechanism. After a match of length N has been found, deflate() searches for
39a longer match at the next input byte. If a longer match is found, the 39a longer match at the next input byte. If a longer match is found, the
40previous match is truncated to a length of one (thus producing a single 40previous match is truncated to a length of one (thus producing a single
41literal byte) and the process of lazy evaluation begins again. Otherwise, 41literal byte) and the process of lazy evaluation begins again. Otherwise,
42the original match is kept, and the next match search is attempted only N 42the original match is kept, and the next match search is attempted only N
43steps later. 43steps later.
44 44
45The lazy match evaluation is also subject to a runtime parameter. If 45The lazy match evaluation is also subject to a runtime parameter. If
46the current match is long enough, deflate() reduces the search for a longer 46the current match is long enough, deflate() reduces the search for a longer
47match, thus speeding up the whole process. If compression ratio is more 47match, thus speeding up the whole process. If compression ratio is more
48important than speed, deflate() attempts a complete second search even if 48important than speed, deflate() attempts a complete second search even if
49the first match is already long enough. 49the first match is already long enough.
50 50
51The lazy match evaluation is not performed for the fastest compression 51The lazy match evaluation is not performed for the fastest compression
52modes (level parameter 1 to 3). For these fast modes, new strings 52modes (level parameter 1 to 3). For these fast modes, new strings
53are inserted in the hash table only when no match was found, or 53are inserted in the hash table only when no match was found, or
54when the match is not too long. This degrades the compression ratio 54when the match is not too long. This degrades the compression ratio
55but saves time since there are both fewer insertions and fewer searches. 55but saves time since there are both fewer insertions and fewer searches.
56 56
57 57
582. Decompression algorithm (inflate) 582. Decompression algorithm (inflate)
59 59
602.1 Introduction 602.1 Introduction
61 61
62The key question is how to represent a Huffman code (or any prefix code) so 62The key question is how to represent a Huffman code (or any prefix code) so
63that you can decode fast. The most important characteristic is that shorter 63that you can decode fast. The most important characteristic is that shorter
64codes are much more common than longer codes, so pay attention to decoding the 64codes are much more common than longer codes, so pay attention to decoding the
65short codes fast, and let the long codes take longer to decode. 65short codes fast, and let the long codes take longer to decode.
66 66
67inflate() sets up a first level table that covers some number of bits of 67inflate() sets up a first level table that covers some number of bits of
68input less than the length of longest code. It gets that many bits from the 68input less than the length of longest code. It gets that many bits from the
69stream, and looks it up in the table. The table will tell if the next 69stream, and looks it up in the table. The table will tell if the next
70code is that many bits or less and how many, and if it is, it will tell 70code is that many bits or less and how many, and if it is, it will tell
71the value, else it will point to the next level table for which inflate() 71the value, else it will point to the next level table for which inflate()
72grabs more bits and tries to decode a longer code. 72grabs more bits and tries to decode a longer code.
73 73
74How many bits to make the first lookup is a tradeoff between the time it 74How many bits to make the first lookup is a tradeoff between the time it
75takes to decode and the time it takes to build the table. If building the 75takes to decode and the time it takes to build the table. If building the
76table took no time (and if you had infinite memory), then there would only 76table took no time (and if you had infinite memory), then there would only
77be a first level table to cover all the way to the longest code. However, 77be a first level table to cover all the way to the longest code. However,
78building the table ends up taking a lot longer for more bits since short 78building the table ends up taking a lot longer for more bits since short
79codes are replicated many times in such a table. What inflate() does is 79codes are replicated many times in such a table. What inflate() does is
80simply to make the number of bits in the first table a variable, and then 80simply to make the number of bits in the first table a variable, and then
81to set that variable for the maximum speed. 81to set that variable for the maximum speed.
82 82
83For inflate, which has 286 possible codes for the literal/length tree, the size 83For inflate, which has 286 possible codes for the literal/length tree, the size
84of the first table is nine bits. Also the distance trees have 30 possible 84of the first table is nine bits. Also the distance trees have 30 possible
85values, and the size of the first table is six bits. Note that for each of 85values, and the size of the first table is six bits. Note that for each of
86those cases, the table ended up one bit longer than the ``average'' code 86those cases, the table ended up one bit longer than the ``average'' code
87length, i.e. the code length of an approximately flat code which would be a 87length, i.e. the code length of an approximately flat code which would be a
88little more than eight bits for 286 symbols and a little less than five bits 88little more than eight bits for 286 symbols and a little less than five bits
89for 30 symbols. 89for 30 symbols.
90 90
91 91
922.2 More details on the inflate table lookup 922.2 More details on the inflate table lookup
93 93
94Ok, you want to know what this cleverly obfuscated inflate tree actually 94Ok, you want to know what this cleverly obfuscated inflate tree actually
95looks like. You are correct that it's not a Huffman tree. It is simply a 95looks like. You are correct that it's not a Huffman tree. It is simply a
96lookup table for the first, let's say, nine bits of a Huffman symbol. The 96lookup table for the first, let's say, nine bits of a Huffman symbol. The
97symbol could be as short as one bit or as long as 15 bits. If a particular 97symbol could be as short as one bit or as long as 15 bits. If a particular
98symbol is shorter than nine bits, then that symbol's translation is duplicated 98symbol is shorter than nine bits, then that symbol's translation is duplicated
99in all those entries that start with that symbol's bits. For example, if the 99in all those entries that start with that symbol's bits. For example, if the
100symbol is four bits, then it's duplicated 32 times in a nine-bit table. If a 100symbol is four bits, then it's duplicated 32 times in a nine-bit table. If a
101symbol is nine bits long, it appears in the table once. 101symbol is nine bits long, it appears in the table once.
102 102
103If the symbol is longer than nine bits, then that entry in the table points 103If the symbol is longer than nine bits, then that entry in the table points
104to another similar table for the remaining bits. Again, there are duplicated 104to another similar table for the remaining bits. Again, there are duplicated
105entries as needed. The idea is that most of the time the symbol will be short 105entries as needed. The idea is that most of the time the symbol will be short
106and there will only be one table look up. (That's whole idea behind data 106and there will only be one table look up. (That's whole idea behind data
107compression in the first place.) For the less frequent long symbols, there 107compression in the first place.) For the less frequent long symbols, there
108will be two lookups. If you had a compression method with really long 108will be two lookups. If you had a compression method with really long
109symbols, you could have as many levels of lookups as is efficient. For 109symbols, you could have as many levels of lookups as is efficient. For
110inflate, two is enough. 110inflate, two is enough.
111 111
112So a table entry either points to another table (in which case nine bits in 112So a table entry either points to another table (in which case nine bits in
113the above example are gobbled), or it contains the translation for the symbol 113the above example are gobbled), or it contains the translation for the symbol
114and the number of bits to gobble. Then you start again with the next 114and the number of bits to gobble. Then you start again with the next
115ungobbled bit. 115ungobbled bit.
116 116
117You may wonder: why not just have one lookup table for how ever many bits the 117You may wonder: why not just have one lookup table for how ever many bits the
118longest symbol is? The reason is that if you do that, you end up spending 118longest symbol is? The reason is that if you do that, you end up spending
119more time filling in duplicate symbol entries than you do actually decoding. 119more time filling in duplicate symbol entries than you do actually decoding.
120At least for deflate's output that generates new trees every several 10's of 120At least for deflate's output that generates new trees every several 10's of
121kbytes. You can imagine that filling in a 2^15 entry table for a 15-bit code 121kbytes. You can imagine that filling in a 2^15 entry table for a 15-bit code
122would take too long if you're only decoding several thousand symbols. At the 122would take too long if you're only decoding several thousand symbols. At the
123other extreme, you could make a new table for every bit in the code. In fact, 123other extreme, you could make a new table for every bit in the code. In fact,
124that's essentially a Huffman tree. But then you spend two much time 124that's essentially a Huffman tree. But then you spend two much time
125traversing the tree while decoding, even for short symbols. 125traversing the tree while decoding, even for short symbols.
126 126
127So the number of bits for the first lookup table is a trade of the time to 127So the number of bits for the first lookup table is a trade of the time to
128fill out the table vs. the time spent looking at the second level and above of 128fill out the table vs. the time spent looking at the second level and above of
129the table. 129the table.
130 130
131Here is an example, scaled down: 131Here is an example, scaled down:
132 132
133The code being decoded, with 10 symbols, from 1 to 6 bits long: 133The code being decoded, with 10 symbols, from 1 to 6 bits long:
134 134
135A: 0 135A: 0
136B: 10 136B: 10
137C: 1100 137C: 1100
138D: 11010 138D: 11010
139E: 11011 139E: 11011
140F: 11100 140F: 11100
141G: 11101 141G: 11101
142H: 11110 142H: 11110
143I: 111110 143I: 111110
144J: 111111 144J: 111111
145 145
146Let's make the first table three bits long (eight entries): 146Let's make the first table three bits long (eight entries):
147 147
148000: A,1 148000: A,1
149001: A,1 149001: A,1
150010: A,1 150010: A,1
151011: A,1 151011: A,1
152100: B,2 152100: B,2
153101: B,2 153101: B,2
154110: -> table X (gobble 3 bits) 154110: -> table X (gobble 3 bits)
155111: -> table Y (gobble 3 bits) 155111: -> table Y (gobble 3 bits)
156 156
157Each entry is what the bits decode as and how many bits that is, i.e. how 157Each entry is what the bits decode as and how many bits that is, i.e. how
158many bits to gobble. Or the entry points to another table, with the number of 158many bits to gobble. Or the entry points to another table, with the number of
159bits to gobble implicit in the size of the table. 159bits to gobble implicit in the size of the table.
160 160
161Table X is two bits long since the longest code starting with 110 is five bits 161Table X is two bits long since the longest code starting with 110 is five bits
162long: 162long:
163 163
16400: C,1 16400: C,1
16501: C,1 16501: C,1
16610: D,2 16610: D,2
16711: E,2 16711: E,2
168 168
169Table Y is three bits long since the longest code starting with 111 is six 169Table Y is three bits long since the longest code starting with 111 is six
170bits long: 170bits long:
171 171
172000: F,2 172000: F,2
173001: F,2 173001: F,2
174010: G,2 174010: G,2
175011: G,2 175011: G,2
176100: H,2 176100: H,2
177101: H,2 177101: H,2
178110: I,3 178110: I,3
179111: J,3 179111: J,3
180 180
181So what we have here are three tables with a total of 20 entries that had to 181So what we have here are three tables with a total of 20 entries that had to
182be constructed. That's compared to 64 entries for a single table. Or 182be constructed. That's compared to 64 entries for a single table. Or
183compared to 16 entries for a Huffman tree (six two entry tables and one four 183compared to 16 entries for a Huffman tree (six two entry tables and one four
184entry table). Assuming that the code ideally represents the probability of 184entry table). Assuming that the code ideally represents the probability of
185the symbols, it takes on the average 1.25 lookups per symbol. That's compared 185the symbols, it takes on the average 1.25 lookups per symbol. That's compared
186to one lookup for the single table, or 1.66 lookups per symbol for the 186to one lookup for the single table, or 1.66 lookups per symbol for the
187Huffman tree. 187Huffman tree.
188 188
189There, I think that gives you a picture of what's going on. For inflate, the 189There, I think that gives you a picture of what's going on. For inflate, the
190meaning of a particular symbol is often more than just a letter. It can be a 190meaning of a particular symbol is often more than just a letter. It can be a
191byte (a "literal"), or it can be either a length or a distance which 191byte (a "literal"), or it can be either a length or a distance which
192indicates a base value and a number of bits to fetch after the code that is 192indicates a base value and a number of bits to fetch after the code that is
193added to the base value. Or it might be the special end-of-block code. The 193added to the base value. Or it might be the special end-of-block code. The
194data structures created in inftrees.c try to encode all that information 194data structures created in inftrees.c try to encode all that information
195compactly in the tables. 195compactly in the tables.
196 196
197 197
198Jean-loup Gailly Mark Adler 198Jean-loup Gailly Mark Adler
199jloup@gzip.org madler@alumni.caltech.edu 199jloup@gzip.org madler@alumni.caltech.edu
200 200
201 201
202References: 202References:
203 203
204[LZ77] Ziv J., Lempel A., ``A Universal Algorithm for Sequential Data 204[LZ77] Ziv J., Lempel A., ``A Universal Algorithm for Sequential Data
205Compression,'' IEEE Transactions on Information Theory, Vol. 23, No. 3, 205Compression,'' IEEE Transactions on Information Theory, Vol. 23, No. 3,
206pp. 337-343. 206pp. 337-343.
207 207
208``DEFLATE Compressed Data Format Specification'' available in 208``DEFLATE Compressed Data Format Specification'' available in
209http://www.ietf.org/rfc/rfc1951.txt 209http://www.ietf.org/rfc/rfc1951.txt
diff --git a/utils/zenutils/libraries/zlib123/zlib/compress.c b/utils/zenutils/libraries/zlib123/zlib/compress.c
index d37e84f5e3..df04f0148e 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/compress.c
+++ b/utils/zenutils/libraries/zlib123/zlib/compress.c
@@ -1,79 +1,79 @@
1/* compress.c -- compress a memory buffer 1/* compress.c -- compress a memory buffer
2 * Copyright (C) 1995-2003 Jean-loup Gailly. 2 * Copyright (C) 1995-2003 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6/* @(#) $Id$ */ 6/* @(#) $Id$ */
7 7
8#define ZLIB_INTERNAL 8#define ZLIB_INTERNAL
9#include "zlib.h" 9#include "zlib.h"
10 10
11/* =========================================================================== 11/* ===========================================================================
12 Compresses the source buffer into the destination buffer. The level 12 Compresses the source buffer into the destination buffer. The level
13 parameter has the same meaning as in deflateInit. sourceLen is the byte 13 parameter has the same meaning as in deflateInit. sourceLen is the byte
14 length of the source buffer. Upon entry, destLen is the total size of the 14 length of the source buffer. Upon entry, destLen is the total size of the
15 destination buffer, which must be at least 0.1% larger than sourceLen plus 15 destination buffer, which must be at least 0.1% larger than sourceLen plus
16 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. 16 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
17 17
18 compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough 18 compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
19 memory, Z_BUF_ERROR if there was not enough room in the output buffer, 19 memory, Z_BUF_ERROR if there was not enough room in the output buffer,
20 Z_STREAM_ERROR if the level parameter is invalid. 20 Z_STREAM_ERROR if the level parameter is invalid.
21*/ 21*/
22int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) 22int ZEXPORT compress2 (dest, destLen, source, sourceLen, level)
23 Bytef *dest; 23 Bytef *dest;
24 uLongf *destLen; 24 uLongf *destLen;
25 const Bytef *source; 25 const Bytef *source;
26 uLong sourceLen; 26 uLong sourceLen;
27 int level; 27 int level;
28{ 28{
29 z_stream stream; 29 z_stream stream;
30 int err; 30 int err;
31 31
32 stream.next_in = (Bytef*)source; 32 stream.next_in = (Bytef*)source;
33 stream.avail_in = (uInt)sourceLen; 33 stream.avail_in = (uInt)sourceLen;
34#ifdef MAXSEG_64K 34#ifdef MAXSEG_64K
35 /* Check for source > 64K on 16-bit machine: */ 35 /* Check for source > 64K on 16-bit machine: */
36 if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; 36 if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
37#endif 37#endif
38 stream.next_out = dest; 38 stream.next_out = dest;
39 stream.avail_out = (uInt)*destLen; 39 stream.avail_out = (uInt)*destLen;
40 if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; 40 if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
41 41
42 stream.zalloc = (alloc_func)0; 42 stream.zalloc = (alloc_func)0;
43 stream.zfree = (free_func)0; 43 stream.zfree = (free_func)0;
44 stream.opaque = (voidpf)0; 44 stream.opaque = (voidpf)0;
45 45
46 err = deflateInit(&stream, level); 46 err = deflateInit(&stream, level);
47 if (err != Z_OK) return err; 47 if (err != Z_OK) return err;
48 48
49 err = deflate(&stream, Z_FINISH); 49 err = deflate(&stream, Z_FINISH);
50 if (err != Z_STREAM_END) { 50 if (err != Z_STREAM_END) {
51 deflateEnd(&stream); 51 deflateEnd(&stream);
52 return err == Z_OK ? Z_BUF_ERROR : err; 52 return err == Z_OK ? Z_BUF_ERROR : err;
53 } 53 }
54 *destLen = stream.total_out; 54 *destLen = stream.total_out;
55 55
56 err = deflateEnd(&stream); 56 err = deflateEnd(&stream);
57 return err; 57 return err;
58} 58}
59 59
60/* =========================================================================== 60/* ===========================================================================
61 */ 61 */
62int ZEXPORT compress (dest, destLen, source, sourceLen) 62int ZEXPORT compress (dest, destLen, source, sourceLen)
63 Bytef *dest; 63 Bytef *dest;
64 uLongf *destLen; 64 uLongf *destLen;
65 const Bytef *source; 65 const Bytef *source;
66 uLong sourceLen; 66 uLong sourceLen;
67{ 67{
68 return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); 68 return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
69} 69}
70 70
71/* =========================================================================== 71/* ===========================================================================
72 If the default memLevel or windowBits for deflateInit() is changed, then 72 If the default memLevel or windowBits for deflateInit() is changed, then
73 this function needs to be updated. 73 this function needs to be updated.
74 */ 74 */
75uLong ZEXPORT compressBound (sourceLen) 75uLong ZEXPORT compressBound (sourceLen)
76 uLong sourceLen; 76 uLong sourceLen;
77{ 77{
78 return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11; 78 return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
79} 79}
diff --git a/utils/zenutils/libraries/zlib123/zlib/configure b/utils/zenutils/libraries/zlib123/zlib/configure
index 212e92ed27..d7ffdc3458 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/configure
+++ b/utils/zenutils/libraries/zlib123/zlib/configure
@@ -1,459 +1,459 @@
1#!/bin/sh 1#!/bin/sh
2# configure script for zlib. This script is needed only if 2# configure script for zlib. This script is needed only if
3# you wish to build a shared library and your system supports them, 3# you wish to build a shared library and your system supports them,
4# of if you need special compiler, flags or install directory. 4# of if you need special compiler, flags or install directory.
5# Otherwise, you can just use directly "make test; make install" 5# Otherwise, you can just use directly "make test; make install"
6# 6#
7# To create a shared library, use "configure --shared"; by default a static 7# To create a shared library, use "configure --shared"; by default a static
8# library is created. If the primitive shared library support provided here 8# library is created. If the primitive shared library support provided here
9# does not work, use ftp://prep.ai.mit.edu/pub/gnu/libtool-*.tar.gz 9# does not work, use ftp://prep.ai.mit.edu/pub/gnu/libtool-*.tar.gz
10# 10#
11# To impose specific compiler or flags or install directory, use for example: 11# To impose specific compiler or flags or install directory, use for example:
12# prefix=$HOME CC=cc CFLAGS="-O4" ./configure 12# prefix=$HOME CC=cc CFLAGS="-O4" ./configure
13# or for csh/tcsh users: 13# or for csh/tcsh users:
14# (setenv prefix $HOME; setenv CC cc; setenv CFLAGS "-O4"; ./configure) 14# (setenv prefix $HOME; setenv CC cc; setenv CFLAGS "-O4"; ./configure)
15# LDSHARED is the command to be used to create a shared library 15# LDSHARED is the command to be used to create a shared library
16 16
17# Incorrect settings of CC or CFLAGS may prevent creating a shared library. 17# Incorrect settings of CC or CFLAGS may prevent creating a shared library.
18# If you have problems, try without defining CC and CFLAGS before reporting 18# If you have problems, try without defining CC and CFLAGS before reporting
19# an error. 19# an error.
20 20
21LIBS=libz.a 21LIBS=libz.a
22LDFLAGS="-L. ${LIBS}" 22LDFLAGS="-L. ${LIBS}"
23VER=`sed -n -e '/VERSION "/s/.*"\(.*\)".*/\1/p' < zlib.h` 23VER=`sed -n -e '/VERSION "/s/.*"\(.*\)".*/\1/p' < zlib.h`
24VER2=`sed -n -e '/VERSION "/s/.*"\([0-9]*\\.[0-9]*\)\\..*/\1/p' < zlib.h` 24VER2=`sed -n -e '/VERSION "/s/.*"\([0-9]*\\.[0-9]*\)\\..*/\1/p' < zlib.h`
25VER1=`sed -n -e '/VERSION "/s/.*"\([0-9]*\)\\..*/\1/p' < zlib.h` 25VER1=`sed -n -e '/VERSION "/s/.*"\([0-9]*\)\\..*/\1/p' < zlib.h`
26AR=${AR-"ar rc"} 26AR=${AR-"ar rc"}
27RANLIB=${RANLIB-"ranlib"} 27RANLIB=${RANLIB-"ranlib"}
28prefix=${prefix-/usr/local} 28prefix=${prefix-/usr/local}
29exec_prefix=${exec_prefix-'${prefix}'} 29exec_prefix=${exec_prefix-'${prefix}'}
30libdir=${libdir-'${exec_prefix}/lib'} 30libdir=${libdir-'${exec_prefix}/lib'}
31includedir=${includedir-'${prefix}/include'} 31includedir=${includedir-'${prefix}/include'}
32mandir=${mandir-'${prefix}/share/man'} 32mandir=${mandir-'${prefix}/share/man'}
33shared_ext='.so' 33shared_ext='.so'
34shared=0 34shared=0
35gcc=0 35gcc=0
36old_cc="$CC" 36old_cc="$CC"
37old_cflags="$CFLAGS" 37old_cflags="$CFLAGS"
38 38
39while test $# -ge 1 39while test $# -ge 1
40do 40do
41case "$1" in 41case "$1" in
42 -h* | --h*) 42 -h* | --h*)
43 echo 'usage:' 43 echo 'usage:'
44 echo ' configure [--shared] [--prefix=PREFIX] [--exec_prefix=EXPREFIX]' 44 echo ' configure [--shared] [--prefix=PREFIX] [--exec_prefix=EXPREFIX]'
45 echo ' [--libdir=LIBDIR] [--includedir=INCLUDEDIR]' 45 echo ' [--libdir=LIBDIR] [--includedir=INCLUDEDIR]'
46 exit 0;; 46 exit 0;;
47 -p*=* | --p*=*) prefix=`echo $1 | sed 's/[-a-z_]*=//'`; shift;; 47 -p*=* | --p*=*) prefix=`echo $1 | sed 's/[-a-z_]*=//'`; shift;;
48 -e*=* | --e*=*) exec_prefix=`echo $1 | sed 's/[-a-z_]*=//'`; shift;; 48 -e*=* | --e*=*) exec_prefix=`echo $1 | sed 's/[-a-z_]*=//'`; shift;;
49 -l*=* | --libdir=*) libdir=`echo $1 | sed 's/[-a-z_]*=//'`; shift;; 49 -l*=* | --libdir=*) libdir=`echo $1 | sed 's/[-a-z_]*=//'`; shift;;
50 -i*=* | --includedir=*) includedir=`echo $1 | sed 's/[-a-z_]*=//'`;shift;; 50 -i*=* | --includedir=*) includedir=`echo $1 | sed 's/[-a-z_]*=//'`;shift;;
51 -p* | --p*) prefix="$2"; shift; shift;; 51 -p* | --p*) prefix="$2"; shift; shift;;
52 -e* | --e*) exec_prefix="$2"; shift; shift;; 52 -e* | --e*) exec_prefix="$2"; shift; shift;;
53 -l* | --l*) libdir="$2"; shift; shift;; 53 -l* | --l*) libdir="$2"; shift; shift;;
54 -i* | --i*) includedir="$2"; shift; shift;; 54 -i* | --i*) includedir="$2"; shift; shift;;
55 -s* | --s*) shared=1; shift;; 55 -s* | --s*) shared=1; shift;;
56 *) echo "unknown option: $1"; echo "$0 --help for help"; exit 1;; 56 *) echo "unknown option: $1"; echo "$0 --help for help"; exit 1;;
57 esac 57 esac
58done 58done
59 59
60test=ztest$$ 60test=ztest$$
61cat > $test.c <<EOF 61cat > $test.c <<EOF
62extern int getchar(); 62extern int getchar();
63int hello() {return getchar();} 63int hello() {return getchar();}
64EOF 64EOF
65 65
66test -z "$CC" && echo Checking for gcc... 66test -z "$CC" && echo Checking for gcc...
67cc=${CC-gcc} 67cc=${CC-gcc}
68cflags=${CFLAGS-"-O3"} 68cflags=${CFLAGS-"-O3"}
69# to force the asm version use: CFLAGS="-O3 -DASMV" ./configure 69# to force the asm version use: CFLAGS="-O3 -DASMV" ./configure
70case "$cc" in 70case "$cc" in
71 *gcc*) gcc=1;; 71 *gcc*) gcc=1;;
72esac 72esac
73 73
74if test "$gcc" -eq 1 && ($cc -c $cflags $test.c) 2>/dev/null; then 74if test "$gcc" -eq 1 && ($cc -c $cflags $test.c) 2>/dev/null; then
75 CC="$cc" 75 CC="$cc"
76 SFLAGS=${CFLAGS-"-fPIC -O3"} 76 SFLAGS=${CFLAGS-"-fPIC -O3"}
77 CFLAGS="$cflags" 77 CFLAGS="$cflags"
78 case `(uname -s || echo unknown) 2>/dev/null` in 78 case `(uname -s || echo unknown) 2>/dev/null` in
79 Linux | linux | GNU | GNU/*) LDSHARED=${LDSHARED-"$cc -shared -Wl,-soname,libz.so.1"};; 79 Linux | linux | GNU | GNU/*) LDSHARED=${LDSHARED-"$cc -shared -Wl,-soname,libz.so.1"};;
80 CYGWIN* | Cygwin* | cygwin* | OS/2* ) 80 CYGWIN* | Cygwin* | cygwin* | OS/2* )
81 EXE='.exe';; 81 EXE='.exe';;
82 QNX*) # This is for QNX6. I suppose that the QNX rule below is for QNX2,QNX4 82 QNX*) # This is for QNX6. I suppose that the QNX rule below is for QNX2,QNX4
83 # (alain.bonnefoy@icbt.com) 83 # (alain.bonnefoy@icbt.com)
84 LDSHARED=${LDSHARED-"$cc -shared -Wl,-hlibz.so.1"};; 84 LDSHARED=${LDSHARED-"$cc -shared -Wl,-hlibz.so.1"};;
85 HP-UX*) 85 HP-UX*)
86 LDSHARED=${LDSHARED-"$cc -shared $SFLAGS"} 86 LDSHARED=${LDSHARED-"$cc -shared $SFLAGS"}
87 case `(uname -m || echo unknown) 2>/dev/null` in 87 case `(uname -m || echo unknown) 2>/dev/null` in
88 ia64) 88 ia64)
89 shared_ext='.so' 89 shared_ext='.so'
90 SHAREDLIB='libz.so';; 90 SHAREDLIB='libz.so';;
91 *) 91 *)
92 shared_ext='.sl' 92 shared_ext='.sl'
93 SHAREDLIB='libz.sl';; 93 SHAREDLIB='libz.sl';;
94 esac;; 94 esac;;
95 Darwin*) shared_ext='.dylib' 95 Darwin*) shared_ext='.dylib'
96 SHAREDLIB=libz$shared_ext 96 SHAREDLIB=libz$shared_ext
97 SHAREDLIBV=libz.$VER$shared_ext 97 SHAREDLIBV=libz.$VER$shared_ext
98 SHAREDLIBM=libz.$VER1$shared_ext 98 SHAREDLIBM=libz.$VER1$shared_ext
99 LDSHARED=${LDSHARED-"$cc -dynamiclib -install_name $libdir/$SHAREDLIBM -compatibility_version $VER1 -current_version $VER"};; 99 LDSHARED=${LDSHARED-"$cc -dynamiclib -install_name $libdir/$SHAREDLIBM -compatibility_version $VER1 -current_version $VER"};;
100 *) LDSHARED=${LDSHARED-"$cc -shared"};; 100 *) LDSHARED=${LDSHARED-"$cc -shared"};;
101 esac 101 esac
102else 102else
103 # find system name and corresponding cc options 103 # find system name and corresponding cc options
104 CC=${CC-cc} 104 CC=${CC-cc}
105 case `(uname -sr || echo unknown) 2>/dev/null` in 105 case `(uname -sr || echo unknown) 2>/dev/null` in
106 HP-UX*) SFLAGS=${CFLAGS-"-O +z"} 106 HP-UX*) SFLAGS=${CFLAGS-"-O +z"}
107 CFLAGS=${CFLAGS-"-O"} 107 CFLAGS=${CFLAGS-"-O"}
108# LDSHARED=${LDSHARED-"ld -b +vnocompatwarnings"} 108# LDSHARED=${LDSHARED-"ld -b +vnocompatwarnings"}
109 LDSHARED=${LDSHARED-"ld -b"} 109 LDSHARED=${LDSHARED-"ld -b"}
110 case `(uname -m || echo unknown) 2>/dev/null` in 110 case `(uname -m || echo unknown) 2>/dev/null` in
111 ia64) 111 ia64)
112 shared_ext='.so' 112 shared_ext='.so'
113 SHAREDLIB='libz.so';; 113 SHAREDLIB='libz.so';;
114 *) 114 *)
115 shared_ext='.sl' 115 shared_ext='.sl'
116 SHAREDLIB='libz.sl';; 116 SHAREDLIB='libz.sl';;
117 esac;; 117 esac;;
118 IRIX*) SFLAGS=${CFLAGS-"-ansi -O2 -rpath ."} 118 IRIX*) SFLAGS=${CFLAGS-"-ansi -O2 -rpath ."}
119 CFLAGS=${CFLAGS-"-ansi -O2"} 119 CFLAGS=${CFLAGS-"-ansi -O2"}
120 LDSHARED=${LDSHARED-"cc -shared"};; 120 LDSHARED=${LDSHARED-"cc -shared"};;
121 OSF1\ V4*) SFLAGS=${CFLAGS-"-O -std1"} 121 OSF1\ V4*) SFLAGS=${CFLAGS-"-O -std1"}
122 CFLAGS=${CFLAGS-"-O -std1"} 122 CFLAGS=${CFLAGS-"-O -std1"}
123 LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so -Wl,-msym -Wl,-rpath,$(libdir) -Wl,-set_version,${VER}:1.0"};; 123 LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so -Wl,-msym -Wl,-rpath,$(libdir) -Wl,-set_version,${VER}:1.0"};;
124 OSF1*) SFLAGS=${CFLAGS-"-O -std1"} 124 OSF1*) SFLAGS=${CFLAGS-"-O -std1"}
125 CFLAGS=${CFLAGS-"-O -std1"} 125 CFLAGS=${CFLAGS-"-O -std1"}
126 LDSHARED=${LDSHARED-"cc -shared"};; 126 LDSHARED=${LDSHARED-"cc -shared"};;
127 QNX*) SFLAGS=${CFLAGS-"-4 -O"} 127 QNX*) SFLAGS=${CFLAGS-"-4 -O"}
128 CFLAGS=${CFLAGS-"-4 -O"} 128 CFLAGS=${CFLAGS-"-4 -O"}
129 LDSHARED=${LDSHARED-"cc"} 129 LDSHARED=${LDSHARED-"cc"}
130 RANLIB=${RANLIB-"true"} 130 RANLIB=${RANLIB-"true"}
131 AR="cc -A";; 131 AR="cc -A";;
132 SCO_SV\ 3.2*) SFLAGS=${CFLAGS-"-O3 -dy -KPIC "} 132 SCO_SV\ 3.2*) SFLAGS=${CFLAGS-"-O3 -dy -KPIC "}
133 CFLAGS=${CFLAGS-"-O3"} 133 CFLAGS=${CFLAGS-"-O3"}
134 LDSHARED=${LDSHARED-"cc -dy -KPIC -G"};; 134 LDSHARED=${LDSHARED-"cc -dy -KPIC -G"};;
135 SunOS\ 5*) SFLAGS=${CFLAGS-"-fast -xcg89 -KPIC -R."} 135 SunOS\ 5*) SFLAGS=${CFLAGS-"-fast -xcg89 -KPIC -R."}
136 CFLAGS=${CFLAGS-"-fast -xcg89"} 136 CFLAGS=${CFLAGS-"-fast -xcg89"}
137 LDSHARED=${LDSHARED-"cc -G"};; 137 LDSHARED=${LDSHARED-"cc -G"};;
138 SunOS\ 4*) SFLAGS=${CFLAGS-"-O2 -PIC"} 138 SunOS\ 4*) SFLAGS=${CFLAGS-"-O2 -PIC"}
139 CFLAGS=${CFLAGS-"-O2"} 139 CFLAGS=${CFLAGS-"-O2"}
140 LDSHARED=${LDSHARED-"ld"};; 140 LDSHARED=${LDSHARED-"ld"};;
141 SunStudio\ 9*) SFLAGS=${CFLAGS-"-DUSE_MMAP -fast -xcode=pic32 -xtarget=ultra3 -xarch=v9b"} 141 SunStudio\ 9*) SFLAGS=${CFLAGS-"-DUSE_MMAP -fast -xcode=pic32 -xtarget=ultra3 -xarch=v9b"}
142 CFLAGS=${CFLAGS-"-DUSE_MMAP -fast -xtarget=ultra3 -xarch=v9b"} 142 CFLAGS=${CFLAGS-"-DUSE_MMAP -fast -xtarget=ultra3 -xarch=v9b"}
143 LDSHARED=${LDSHARED-"cc -xarch=v9b"};; 143 LDSHARED=${LDSHARED-"cc -xarch=v9b"};;
144 UNIX_System_V\ 4.2.0) 144 UNIX_System_V\ 4.2.0)
145 SFLAGS=${CFLAGS-"-KPIC -O"} 145 SFLAGS=${CFLAGS-"-KPIC -O"}
146 CFLAGS=${CFLAGS-"-O"} 146 CFLAGS=${CFLAGS-"-O"}
147 LDSHARED=${LDSHARED-"cc -G"};; 147 LDSHARED=${LDSHARED-"cc -G"};;
148 UNIX_SV\ 4.2MP) 148 UNIX_SV\ 4.2MP)
149 SFLAGS=${CFLAGS-"-Kconform_pic -O"} 149 SFLAGS=${CFLAGS-"-Kconform_pic -O"}
150 CFLAGS=${CFLAGS-"-O"} 150 CFLAGS=${CFLAGS-"-O"}
151 LDSHARED=${LDSHARED-"cc -G"};; 151 LDSHARED=${LDSHARED-"cc -G"};;
152 OpenUNIX\ 5) 152 OpenUNIX\ 5)
153 SFLAGS=${CFLAGS-"-KPIC -O"} 153 SFLAGS=${CFLAGS-"-KPIC -O"}
154 CFLAGS=${CFLAGS-"-O"} 154 CFLAGS=${CFLAGS-"-O"}
155 LDSHARED=${LDSHARED-"cc -G"};; 155 LDSHARED=${LDSHARED-"cc -G"};;
156 AIX*) # Courtesy of dbakker@arrayasolutions.com 156 AIX*) # Courtesy of dbakker@arrayasolutions.com
157 SFLAGS=${CFLAGS-"-O -qmaxmem=8192"} 157 SFLAGS=${CFLAGS-"-O -qmaxmem=8192"}
158 CFLAGS=${CFLAGS-"-O -qmaxmem=8192"} 158 CFLAGS=${CFLAGS-"-O -qmaxmem=8192"}
159 LDSHARED=${LDSHARED-"xlc -G"};; 159 LDSHARED=${LDSHARED-"xlc -G"};;
160 # send working options for other systems to support@gzip.org 160 # send working options for other systems to support@gzip.org
161 *) SFLAGS=${CFLAGS-"-O"} 161 *) SFLAGS=${CFLAGS-"-O"}
162 CFLAGS=${CFLAGS-"-O"} 162 CFLAGS=${CFLAGS-"-O"}
163 LDSHARED=${LDSHARED-"cc -shared"};; 163 LDSHARED=${LDSHARED-"cc -shared"};;
164 esac 164 esac
165fi 165fi
166 166
167SHAREDLIB=${SHAREDLIB-"libz$shared_ext"} 167SHAREDLIB=${SHAREDLIB-"libz$shared_ext"}
168SHAREDLIBV=${SHAREDLIBV-"libz$shared_ext.$VER"} 168SHAREDLIBV=${SHAREDLIBV-"libz$shared_ext.$VER"}
169SHAREDLIBM=${SHAREDLIBM-"libz$shared_ext.$VER1"} 169SHAREDLIBM=${SHAREDLIBM-"libz$shared_ext.$VER1"}
170 170
171if test $shared -eq 1; then 171if test $shared -eq 1; then
172 echo Checking for shared library support... 172 echo Checking for shared library support...
173 # we must test in two steps (cc then ld), required at least on SunOS 4.x 173 # we must test in two steps (cc then ld), required at least on SunOS 4.x
174 if test "`($CC -c $SFLAGS $test.c) 2>&1`" = "" && 174 if test "`($CC -c $SFLAGS $test.c) 2>&1`" = "" &&
175 test "`($LDSHARED -o $test$shared_ext $test.o) 2>&1`" = ""; then 175 test "`($LDSHARED -o $test$shared_ext $test.o) 2>&1`" = ""; then
176 CFLAGS="$SFLAGS" 176 CFLAGS="$SFLAGS"
177 LIBS="$SHAREDLIBV" 177 LIBS="$SHAREDLIBV"
178 echo Building shared library $SHAREDLIBV with $CC. 178 echo Building shared library $SHAREDLIBV with $CC.
179 elif test -z "$old_cc" -a -z "$old_cflags"; then 179 elif test -z "$old_cc" -a -z "$old_cflags"; then
180 echo No shared library support. 180 echo No shared library support.
181 shared=0; 181 shared=0;
182 else 182 else
183 echo 'No shared library support; try without defining CC and CFLAGS' 183 echo 'No shared library support; try without defining CC and CFLAGS'
184 shared=0; 184 shared=0;
185 fi 185 fi
186fi 186fi
187if test $shared -eq 0; then 187if test $shared -eq 0; then
188 LDSHARED="$CC" 188 LDSHARED="$CC"
189 echo Building static library $LIBS version $VER with $CC. 189 echo Building static library $LIBS version $VER with $CC.
190else 190else
191 LDFLAGS="-L. ${SHAREDLIBV}" 191 LDFLAGS="-L. ${SHAREDLIBV}"
192fi 192fi
193 193
194cat > $test.c <<EOF 194cat > $test.c <<EOF
195#include <unistd.h> 195#include <unistd.h>
196int main() { return 0; } 196int main() { return 0; }
197EOF 197EOF
198if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then 198if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
199 sed < zconf.in.h "/HAVE_UNISTD_H/s%0%1%" > zconf.h 199 sed < zconf.in.h "/HAVE_UNISTD_H/s%0%1%" > zconf.h
200 echo "Checking for unistd.h... Yes." 200 echo "Checking for unistd.h... Yes."
201else 201else
202 cp -p zconf.in.h zconf.h 202 cp -p zconf.in.h zconf.h
203 echo "Checking for unistd.h... No." 203 echo "Checking for unistd.h... No."
204fi 204fi
205 205
206cat > $test.c <<EOF 206cat > $test.c <<EOF
207#include <stdio.h> 207#include <stdio.h>
208#include <stdarg.h> 208#include <stdarg.h>
209#include "zconf.h" 209#include "zconf.h"
210 210
211int main() 211int main()
212{ 212{
213#ifndef STDC 213#ifndef STDC
214 choke me 214 choke me
215#endif 215#endif
216 216
217 return 0; 217 return 0;
218} 218}
219EOF 219EOF
220 220
221if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then 221if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
222 echo "Checking whether to use vs[n]printf() or s[n]printf()... using vs[n]printf()" 222 echo "Checking whether to use vs[n]printf() or s[n]printf()... using vs[n]printf()"
223 223
224 cat > $test.c <<EOF 224 cat > $test.c <<EOF
225#include <stdio.h> 225#include <stdio.h>
226#include <stdarg.h> 226#include <stdarg.h>
227 227
228int mytest(char *fmt, ...) 228int mytest(char *fmt, ...)
229{ 229{
230 char buf[20]; 230 char buf[20];
231 va_list ap; 231 va_list ap;
232 232
233 va_start(ap, fmt); 233 va_start(ap, fmt);
234 vsnprintf(buf, sizeof(buf), fmt, ap); 234 vsnprintf(buf, sizeof(buf), fmt, ap);
235 va_end(ap); 235 va_end(ap);
236 return 0; 236 return 0;
237} 237}
238 238
239int main() 239int main()
240{ 240{
241 return (mytest("Hello%d\n", 1)); 241 return (mytest("Hello%d\n", 1));
242} 242}
243EOF 243EOF
244 244
245 if test "`($CC $CFLAGS -o $test $test.c) 2>&1`" = ""; then 245 if test "`($CC $CFLAGS -o $test $test.c) 2>&1`" = ""; then
246 echo "Checking for vsnprintf() in stdio.h... Yes." 246 echo "Checking for vsnprintf() in stdio.h... Yes."
247 247
248 cat >$test.c <<EOF 248 cat >$test.c <<EOF
249#include <stdio.h> 249#include <stdio.h>
250#include <stdarg.h> 250#include <stdarg.h>
251 251
252int mytest(char *fmt, ...) 252int mytest(char *fmt, ...)
253{ 253{
254 int n; 254 int n;
255 char buf[20]; 255 char buf[20];
256 va_list ap; 256 va_list ap;
257 257
258 va_start(ap, fmt); 258 va_start(ap, fmt);
259 n = vsnprintf(buf, sizeof(buf), fmt, ap); 259 n = vsnprintf(buf, sizeof(buf), fmt, ap);
260 va_end(ap); 260 va_end(ap);
261 return n; 261 return n;
262} 262}
263 263
264int main() 264int main()
265{ 265{
266 return (mytest("Hello%d\n", 1)); 266 return (mytest("Hello%d\n", 1));
267} 267}
268EOF 268EOF
269 269
270 if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then 270 if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
271 echo "Checking for return value of vsnprintf()... Yes." 271 echo "Checking for return value of vsnprintf()... Yes."
272 else 272 else
273 CFLAGS="$CFLAGS -DHAS_vsnprintf_void" 273 CFLAGS="$CFLAGS -DHAS_vsnprintf_void"
274 echo "Checking for return value of vsnprintf()... No." 274 echo "Checking for return value of vsnprintf()... No."
275 echo " WARNING: apparently vsnprintf() does not return a value. zlib" 275 echo " WARNING: apparently vsnprintf() does not return a value. zlib"
276 echo " can build but will be open to possible string-format security" 276 echo " can build but will be open to possible string-format security"
277 echo " vulnerabilities." 277 echo " vulnerabilities."
278 fi 278 fi
279 else 279 else
280 CFLAGS="$CFLAGS -DNO_vsnprintf" 280 CFLAGS="$CFLAGS -DNO_vsnprintf"
281 echo "Checking for vsnprintf() in stdio.h... No." 281 echo "Checking for vsnprintf() in stdio.h... No."
282 echo " WARNING: vsnprintf() not found, falling back to vsprintf(). zlib" 282 echo " WARNING: vsnprintf() not found, falling back to vsprintf(). zlib"
283 echo " can build but will be open to possible buffer-overflow security" 283 echo " can build but will be open to possible buffer-overflow security"
284 echo " vulnerabilities." 284 echo " vulnerabilities."
285 285
286 cat >$test.c <<EOF 286 cat >$test.c <<EOF
287#include <stdio.h> 287#include <stdio.h>
288#include <stdarg.h> 288#include <stdarg.h>
289 289
290int mytest(char *fmt, ...) 290int mytest(char *fmt, ...)
291{ 291{
292 int n; 292 int n;
293 char buf[20]; 293 char buf[20];
294 va_list ap; 294 va_list ap;
295 295
296 va_start(ap, fmt); 296 va_start(ap, fmt);
297 n = vsprintf(buf, fmt, ap); 297 n = vsprintf(buf, fmt, ap);
298 va_end(ap); 298 va_end(ap);
299 return n; 299 return n;
300} 300}
301 301
302int main() 302int main()
303{ 303{
304 return (mytest("Hello%d\n", 1)); 304 return (mytest("Hello%d\n", 1));
305} 305}
306EOF 306EOF
307 307
308 if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then 308 if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
309 echo "Checking for return value of vsprintf()... Yes." 309 echo "Checking for return value of vsprintf()... Yes."
310 else 310 else
311 CFLAGS="$CFLAGS -DHAS_vsprintf_void" 311 CFLAGS="$CFLAGS -DHAS_vsprintf_void"
312 echo "Checking for return value of vsprintf()... No." 312 echo "Checking for return value of vsprintf()... No."
313 echo " WARNING: apparently vsprintf() does not return a value. zlib" 313 echo " WARNING: apparently vsprintf() does not return a value. zlib"
314 echo " can build but will be open to possible string-format security" 314 echo " can build but will be open to possible string-format security"
315 echo " vulnerabilities." 315 echo " vulnerabilities."
316 fi 316 fi
317 fi 317 fi
318else 318else
319 echo "Checking whether to use vs[n]printf() or s[n]printf()... using s[n]printf()" 319 echo "Checking whether to use vs[n]printf() or s[n]printf()... using s[n]printf()"
320 320
321 cat >$test.c <<EOF 321 cat >$test.c <<EOF
322#include <stdio.h> 322#include <stdio.h>
323 323
324int mytest() 324int mytest()
325{ 325{
326 char buf[20]; 326 char buf[20];
327 327
328 snprintf(buf, sizeof(buf), "%s", "foo"); 328 snprintf(buf, sizeof(buf), "%s", "foo");
329 return 0; 329 return 0;
330} 330}
331 331
332int main() 332int main()
333{ 333{
334 return (mytest()); 334 return (mytest());
335} 335}
336EOF 336EOF
337 337
338 if test "`($CC $CFLAGS -o $test $test.c) 2>&1`" = ""; then 338 if test "`($CC $CFLAGS -o $test $test.c) 2>&1`" = ""; then
339 echo "Checking for snprintf() in stdio.h... Yes." 339 echo "Checking for snprintf() in stdio.h... Yes."
340 340
341 cat >$test.c <<EOF 341 cat >$test.c <<EOF
342#include <stdio.h> 342#include <stdio.h>
343 343
344int mytest() 344int mytest()
345{ 345{
346 char buf[20]; 346 char buf[20];
347 347
348 return snprintf(buf, sizeof(buf), "%s", "foo"); 348 return snprintf(buf, sizeof(buf), "%s", "foo");
349} 349}
350 350
351int main() 351int main()
352{ 352{
353 return (mytest()); 353 return (mytest());
354} 354}
355EOF 355EOF
356 356
357 if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then 357 if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
358 echo "Checking for return value of snprintf()... Yes." 358 echo "Checking for return value of snprintf()... Yes."
359 else 359 else
360 CFLAGS="$CFLAGS -DHAS_snprintf_void" 360 CFLAGS="$CFLAGS -DHAS_snprintf_void"
361 echo "Checking for return value of snprintf()... No." 361 echo "Checking for return value of snprintf()... No."
362 echo " WARNING: apparently snprintf() does not return a value. zlib" 362 echo " WARNING: apparently snprintf() does not return a value. zlib"
363 echo " can build but will be open to possible string-format security" 363 echo " can build but will be open to possible string-format security"
364 echo " vulnerabilities." 364 echo " vulnerabilities."
365 fi 365 fi
366 else 366 else
367 CFLAGS="$CFLAGS -DNO_snprintf" 367 CFLAGS="$CFLAGS -DNO_snprintf"
368 echo "Checking for snprintf() in stdio.h... No." 368 echo "Checking for snprintf() in stdio.h... No."
369 echo " WARNING: snprintf() not found, falling back to sprintf(). zlib" 369 echo " WARNING: snprintf() not found, falling back to sprintf(). zlib"
370 echo " can build but will be open to possible buffer-overflow security" 370 echo " can build but will be open to possible buffer-overflow security"
371 echo " vulnerabilities." 371 echo " vulnerabilities."
372 372
373 cat >$test.c <<EOF 373 cat >$test.c <<EOF
374#include <stdio.h> 374#include <stdio.h>
375 375
376int mytest() 376int mytest()
377{ 377{
378 char buf[20]; 378 char buf[20];
379 379
380 return sprintf(buf, "%s", "foo"); 380 return sprintf(buf, "%s", "foo");
381} 381}
382 382
383int main() 383int main()
384{ 384{
385 return (mytest()); 385 return (mytest());
386} 386}
387EOF 387EOF
388 388
389 if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then 389 if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
390 echo "Checking for return value of sprintf()... Yes." 390 echo "Checking for return value of sprintf()... Yes."
391 else 391 else
392 CFLAGS="$CFLAGS -DHAS_sprintf_void" 392 CFLAGS="$CFLAGS -DHAS_sprintf_void"
393 echo "Checking for return value of sprintf()... No." 393 echo "Checking for return value of sprintf()... No."
394 echo " WARNING: apparently sprintf() does not return a value. zlib" 394 echo " WARNING: apparently sprintf() does not return a value. zlib"
395 echo " can build but will be open to possible string-format security" 395 echo " can build but will be open to possible string-format security"
396 echo " vulnerabilities." 396 echo " vulnerabilities."
397 fi 397 fi
398 fi 398 fi
399fi 399fi
400 400
401cat >$test.c <<EOF 401cat >$test.c <<EOF
402#include <errno.h> 402#include <errno.h>
403int main() { return 0; } 403int main() { return 0; }
404EOF 404EOF
405if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then 405if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
406 echo "Checking for errno.h... Yes." 406 echo "Checking for errno.h... Yes."
407else 407else
408 echo "Checking for errno.h... No." 408 echo "Checking for errno.h... No."
409 CFLAGS="$CFLAGS -DNO_ERRNO_H" 409 CFLAGS="$CFLAGS -DNO_ERRNO_H"
410fi 410fi
411 411
412cat > $test.c <<EOF 412cat > $test.c <<EOF
413#include <sys/types.h> 413#include <sys/types.h>
414#include <sys/mman.h> 414#include <sys/mman.h>
415#include <sys/stat.h> 415#include <sys/stat.h>
416caddr_t hello() { 416caddr_t hello() {
417 return mmap((caddr_t)0, (off_t)0, PROT_READ, MAP_SHARED, 0, (off_t)0); 417 return mmap((caddr_t)0, (off_t)0, PROT_READ, MAP_SHARED, 0, (off_t)0);
418} 418}
419EOF 419EOF
420if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then 420if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
421 CFLAGS="$CFLAGS -DUSE_MMAP" 421 CFLAGS="$CFLAGS -DUSE_MMAP"
422 echo Checking for mmap support... Yes. 422 echo Checking for mmap support... Yes.
423else 423else
424 echo Checking for mmap support... No. 424 echo Checking for mmap support... No.
425fi 425fi
426 426
427CPP=${CPP-"$CC -E"} 427CPP=${CPP-"$CC -E"}
428case $CFLAGS in 428case $CFLAGS in
429 *ASMV*) 429 *ASMV*)
430 if test "`nm $test.o | grep _hello`" = ""; then 430 if test "`nm $test.o | grep _hello`" = ""; then
431 CPP="$CPP -DNO_UNDERLINE" 431 CPP="$CPP -DNO_UNDERLINE"
432 echo Checking for underline in external names... No. 432 echo Checking for underline in external names... No.
433 else 433 else
434 echo Checking for underline in external names... Yes. 434 echo Checking for underline in external names... Yes.
435 fi;; 435 fi;;
436esac 436esac
437 437
438rm -f $test.[co] $test $test$shared_ext 438rm -f $test.[co] $test $test$shared_ext
439 439
440# udpate Makefile 440# udpate Makefile
441sed < Makefile.in " 441sed < Makefile.in "
442/^CC *=/s#=.*#=$CC# 442/^CC *=/s#=.*#=$CC#
443/^CFLAGS *=/s#=.*#=$CFLAGS# 443/^CFLAGS *=/s#=.*#=$CFLAGS#
444/^CPP *=/s#=.*#=$CPP# 444/^CPP *=/s#=.*#=$CPP#
445/^LDSHARED *=/s#=.*#=$LDSHARED# 445/^LDSHARED *=/s#=.*#=$LDSHARED#
446/^LIBS *=/s#=.*#=$LIBS# 446/^LIBS *=/s#=.*#=$LIBS#
447/^SHAREDLIB *=/s#=.*#=$SHAREDLIB# 447/^SHAREDLIB *=/s#=.*#=$SHAREDLIB#
448/^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV# 448/^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV#
449/^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM# 449/^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM#
450/^AR *=/s#=.*#=$AR# 450/^AR *=/s#=.*#=$AR#
451/^RANLIB *=/s#=.*#=$RANLIB# 451/^RANLIB *=/s#=.*#=$RANLIB#
452/^EXE *=/s#=.*#=$EXE# 452/^EXE *=/s#=.*#=$EXE#
453/^prefix *=/s#=.*#=$prefix# 453/^prefix *=/s#=.*#=$prefix#
454/^exec_prefix *=/s#=.*#=$exec_prefix# 454/^exec_prefix *=/s#=.*#=$exec_prefix#
455/^libdir *=/s#=.*#=$libdir# 455/^libdir *=/s#=.*#=$libdir#
456/^includedir *=/s#=.*#=$includedir# 456/^includedir *=/s#=.*#=$includedir#
457/^mandir *=/s#=.*#=$mandir# 457/^mandir *=/s#=.*#=$mandir#
458/^LDFLAGS *=/s#=.*#=$LDFLAGS# 458/^LDFLAGS *=/s#=.*#=$LDFLAGS#
459" > Makefile 459" > Makefile
diff --git a/utils/zenutils/libraries/zlib123/zlib/crc32.c b/utils/zenutils/libraries/zlib123/zlib/crc32.c
index 32814c20c8..f658a9ef55 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/crc32.c
+++ b/utils/zenutils/libraries/zlib123/zlib/crc32.c
@@ -1,423 +1,423 @@
1/* crc32.c -- compute the CRC-32 of a data stream 1/* crc32.c -- compute the CRC-32 of a data stream
2 * Copyright (C) 1995-2005 Mark Adler 2 * Copyright (C) 1995-2005 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 * 4 *
5 * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster 5 * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster
6 * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing 6 * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing
7 * tables for updating the shift register in one step with three exclusive-ors 7 * tables for updating the shift register in one step with three exclusive-ors
8 * instead of four steps with four exclusive-ors. This results in about a 8 * instead of four steps with four exclusive-ors. This results in about a
9 * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. 9 * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3.
10 */ 10 */
11 11
12/* @(#) $Id$ */ 12/* @(#) $Id$ */
13 13
14/* 14/*
15 Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore 15 Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
16 protection on the static variables used to control the first-use generation 16 protection on the static variables used to control the first-use generation
17 of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should 17 of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
18 first call get_crc_table() to initialize the tables before allowing more than 18 first call get_crc_table() to initialize the tables before allowing more than
19 one thread to use crc32(). 19 one thread to use crc32().
20 */ 20 */
21 21
22#ifdef MAKECRCH 22#ifdef MAKECRCH
23# include <stdio.h> 23# include <stdio.h>
24# ifndef DYNAMIC_CRC_TABLE 24# ifndef DYNAMIC_CRC_TABLE
25# define DYNAMIC_CRC_TABLE 25# define DYNAMIC_CRC_TABLE
26# endif /* !DYNAMIC_CRC_TABLE */ 26# endif /* !DYNAMIC_CRC_TABLE */
27#endif /* MAKECRCH */ 27#endif /* MAKECRCH */
28 28
29#include "zutil.h" /* for STDC and FAR definitions */ 29#include "zutil.h" /* for STDC and FAR definitions */
30 30
31#define local static 31#define local static
32 32
33/* Find a four-byte integer type for crc32_little() and crc32_big(). */ 33/* Find a four-byte integer type for crc32_little() and crc32_big(). */
34#ifndef NOBYFOUR 34#ifndef NOBYFOUR
35# ifdef STDC /* need ANSI C limits.h to determine sizes */ 35# ifdef STDC /* need ANSI C limits.h to determine sizes */
36# include <limits.h> 36# include <limits.h>
37# define BYFOUR 37# define BYFOUR
38# if (UINT_MAX == 0xffffffffUL) 38# if (UINT_MAX == 0xffffffffUL)
39 typedef unsigned int u4; 39 typedef unsigned int u4;
40# else 40# else
41# if (ULONG_MAX == 0xffffffffUL) 41# if (ULONG_MAX == 0xffffffffUL)
42 typedef unsigned long u4; 42 typedef unsigned long u4;
43# else 43# else
44# if (USHRT_MAX == 0xffffffffUL) 44# if (USHRT_MAX == 0xffffffffUL)
45 typedef unsigned short u4; 45 typedef unsigned short u4;
46# else 46# else
47# undef BYFOUR /* can't find a four-byte integer type! */ 47# undef BYFOUR /* can't find a four-byte integer type! */
48# endif 48# endif
49# endif 49# endif
50# endif 50# endif
51# endif /* STDC */ 51# endif /* STDC */
52#endif /* !NOBYFOUR */ 52#endif /* !NOBYFOUR */
53 53
54/* Definitions for doing the crc four data bytes at a time. */ 54/* Definitions for doing the crc four data bytes at a time. */
55#ifdef BYFOUR 55#ifdef BYFOUR
56# define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \ 56# define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
57 (((w)&0xff00)<<8)+(((w)&0xff)<<24)) 57 (((w)&0xff00)<<8)+(((w)&0xff)<<24))
58 local unsigned long crc32_little OF((unsigned long, 58 local unsigned long crc32_little OF((unsigned long,
59 const unsigned char FAR *, unsigned)); 59 const unsigned char FAR *, unsigned));
60 local unsigned long crc32_big OF((unsigned long, 60 local unsigned long crc32_big OF((unsigned long,
61 const unsigned char FAR *, unsigned)); 61 const unsigned char FAR *, unsigned));
62# define TBLS 8 62# define TBLS 8
63#else 63#else
64# define TBLS 1 64# define TBLS 1
65#endif /* BYFOUR */ 65#endif /* BYFOUR */
66 66
67/* Local functions for crc concatenation */ 67/* Local functions for crc concatenation */
68local unsigned long gf2_matrix_times OF((unsigned long *mat, 68local unsigned long gf2_matrix_times OF((unsigned long *mat,
69 unsigned long vec)); 69 unsigned long vec));
70local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); 70local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
71 71
72#ifdef DYNAMIC_CRC_TABLE 72#ifdef DYNAMIC_CRC_TABLE
73 73
74local volatile int crc_table_empty = 1; 74local volatile int crc_table_empty = 1;
75local unsigned long FAR crc_table[TBLS][256]; 75local unsigned long FAR crc_table[TBLS][256];
76local void make_crc_table OF((void)); 76local void make_crc_table OF((void));
77#ifdef MAKECRCH 77#ifdef MAKECRCH
78 local void write_table OF((FILE *, const unsigned long FAR *)); 78 local void write_table OF((FILE *, const unsigned long FAR *));
79#endif /* MAKECRCH */ 79#endif /* MAKECRCH */
80/* 80/*
81 Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: 81 Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
82 x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. 82 x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
83 83
84 Polynomials over GF(2) are represented in binary, one bit per coefficient, 84 Polynomials over GF(2) are represented in binary, one bit per coefficient,
85 with the lowest powers in the most significant bit. Then adding polynomials 85 with the lowest powers in the most significant bit. Then adding polynomials
86 is just exclusive-or, and multiplying a polynomial by x is a right shift by 86 is just exclusive-or, and multiplying a polynomial by x is a right shift by
87 one. If we call the above polynomial p, and represent a byte as the 87 one. If we call the above polynomial p, and represent a byte as the
88 polynomial q, also with the lowest power in the most significant bit (so the 88 polynomial q, also with the lowest power in the most significant bit (so the
89 byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, 89 byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
90 where a mod b means the remainder after dividing a by b. 90 where a mod b means the remainder after dividing a by b.
91 91
92 This calculation is done using the shift-register method of multiplying and 92 This calculation is done using the shift-register method of multiplying and
93 taking the remainder. The register is initialized to zero, and for each 93 taking the remainder. The register is initialized to zero, and for each
94 incoming bit, x^32 is added mod p to the register if the bit is a one (where 94 incoming bit, x^32 is added mod p to the register if the bit is a one (where
95 x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by 95 x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
96 x (which is shifting right by one and adding x^32 mod p if the bit shifted 96 x (which is shifting right by one and adding x^32 mod p if the bit shifted
97 out is a one). We start with the highest power (least significant bit) of 97 out is a one). We start with the highest power (least significant bit) of
98 q and repeat for all eight bits of q. 98 q and repeat for all eight bits of q.
99 99
100 The first table is simply the CRC of all possible eight bit values. This is 100 The first table is simply the CRC of all possible eight bit values. This is
101 all the information needed to generate CRCs on data a byte at a time for all 101 all the information needed to generate CRCs on data a byte at a time for all
102 combinations of CRC register values and incoming bytes. The remaining tables 102 combinations of CRC register values and incoming bytes. The remaining tables
103 allow for word-at-a-time CRC calculation for both big-endian and little- 103 allow for word-at-a-time CRC calculation for both big-endian and little-
104 endian machines, where a word is four bytes. 104 endian machines, where a word is four bytes.
105*/ 105*/
106local void make_crc_table() 106local void make_crc_table()
107{ 107{
108 unsigned long c; 108 unsigned long c;
109 int n, k; 109 int n, k;
110 unsigned long poly; /* polynomial exclusive-or pattern */ 110 unsigned long poly; /* polynomial exclusive-or pattern */
111 /* terms of polynomial defining this crc (except x^32): */ 111 /* terms of polynomial defining this crc (except x^32): */
112 static volatile int first = 1; /* flag to limit concurrent making */ 112 static volatile int first = 1; /* flag to limit concurrent making */
113 static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; 113 static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
114 114
115 /* See if another task is already doing this (not thread-safe, but better 115 /* See if another task is already doing this (not thread-safe, but better
116 than nothing -- significantly reduces duration of vulnerability in 116 than nothing -- significantly reduces duration of vulnerability in
117 case the advice about DYNAMIC_CRC_TABLE is ignored) */ 117 case the advice about DYNAMIC_CRC_TABLE is ignored) */
118 if (first) { 118 if (first) {
119 first = 0; 119 first = 0;
120 120
121 /* make exclusive-or pattern from polynomial (0xedb88320UL) */ 121 /* make exclusive-or pattern from polynomial (0xedb88320UL) */
122 poly = 0UL; 122 poly = 0UL;
123 for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++) 123 for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
124 poly |= 1UL << (31 - p[n]); 124 poly |= 1UL << (31 - p[n]);
125 125
126 /* generate a crc for every 8-bit value */ 126 /* generate a crc for every 8-bit value */
127 for (n = 0; n < 256; n++) { 127 for (n = 0; n < 256; n++) {
128 c = (unsigned long)n; 128 c = (unsigned long)n;
129 for (k = 0; k < 8; k++) 129 for (k = 0; k < 8; k++)
130 c = c & 1 ? poly ^ (c >> 1) : c >> 1; 130 c = c & 1 ? poly ^ (c >> 1) : c >> 1;
131 crc_table[0][n] = c; 131 crc_table[0][n] = c;
132 } 132 }
133 133
134#ifdef BYFOUR 134#ifdef BYFOUR
135 /* generate crc for each value followed by one, two, and three zeros, 135 /* generate crc for each value followed by one, two, and three zeros,
136 and then the byte reversal of those as well as the first table */ 136 and then the byte reversal of those as well as the first table */
137 for (n = 0; n < 256; n++) { 137 for (n = 0; n < 256; n++) {
138 c = crc_table[0][n]; 138 c = crc_table[0][n];
139 crc_table[4][n] = REV(c); 139 crc_table[4][n] = REV(c);
140 for (k = 1; k < 4; k++) { 140 for (k = 1; k < 4; k++) {
141 c = crc_table[0][c & 0xff] ^ (c >> 8); 141 c = crc_table[0][c & 0xff] ^ (c >> 8);
142 crc_table[k][n] = c; 142 crc_table[k][n] = c;
143 crc_table[k + 4][n] = REV(c); 143 crc_table[k + 4][n] = REV(c);
144 } 144 }
145 } 145 }
146#endif /* BYFOUR */ 146#endif /* BYFOUR */
147 147
148 crc_table_empty = 0; 148 crc_table_empty = 0;
149 } 149 }
150 else { /* not first */ 150 else { /* not first */
151 /* wait for the other guy to finish (not efficient, but rare) */ 151 /* wait for the other guy to finish (not efficient, but rare) */
152 while (crc_table_empty) 152 while (crc_table_empty)
153 ; 153 ;
154 } 154 }
155 155
156#ifdef MAKECRCH 156#ifdef MAKECRCH
157 /* write out CRC tables to crc32.h */ 157 /* write out CRC tables to crc32.h */
158 { 158 {
159 FILE *out; 159 FILE *out;
160 160
161 out = fopen("crc32.h", "w"); 161 out = fopen("crc32.h", "w");
162 if (out == NULL) return; 162 if (out == NULL) return;
163 fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); 163 fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
164 fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); 164 fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
165 fprintf(out, "local const unsigned long FAR "); 165 fprintf(out, "local const unsigned long FAR ");
166 fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); 166 fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
167 write_table(out, crc_table[0]); 167 write_table(out, crc_table[0]);
168# ifdef BYFOUR 168# ifdef BYFOUR
169 fprintf(out, "#ifdef BYFOUR\n"); 169 fprintf(out, "#ifdef BYFOUR\n");
170 for (k = 1; k < 8; k++) { 170 for (k = 1; k < 8; k++) {
171 fprintf(out, " },\n {\n"); 171 fprintf(out, " },\n {\n");
172 write_table(out, crc_table[k]); 172 write_table(out, crc_table[k]);
173 } 173 }
174 fprintf(out, "#endif\n"); 174 fprintf(out, "#endif\n");
175# endif /* BYFOUR */ 175# endif /* BYFOUR */
176 fprintf(out, " }\n};\n"); 176 fprintf(out, " }\n};\n");
177 fclose(out); 177 fclose(out);
178 } 178 }
179#endif /* MAKECRCH */ 179#endif /* MAKECRCH */
180} 180}
181 181
182#ifdef MAKECRCH 182#ifdef MAKECRCH
183local void write_table(out, table) 183local void write_table(out, table)
184 FILE *out; 184 FILE *out;
185 const unsigned long FAR *table; 185 const unsigned long FAR *table;
186{ 186{
187 int n; 187 int n;
188 188
189 for (n = 0; n < 256; n++) 189 for (n = 0; n < 256; n++)
190 fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n], 190 fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
191 n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); 191 n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
192} 192}
193#endif /* MAKECRCH */ 193#endif /* MAKECRCH */
194 194
195#else /* !DYNAMIC_CRC_TABLE */ 195#else /* !DYNAMIC_CRC_TABLE */
196/* ======================================================================== 196/* ========================================================================
197 * Tables of CRC-32s of all single-byte values, made by make_crc_table(). 197 * Tables of CRC-32s of all single-byte values, made by make_crc_table().
198 */ 198 */
199#include "crc32.h" 199#include "crc32.h"
200#endif /* DYNAMIC_CRC_TABLE */ 200#endif /* DYNAMIC_CRC_TABLE */
201 201
202/* ========================================================================= 202/* =========================================================================
203 * This function can be used by asm versions of crc32() 203 * This function can be used by asm versions of crc32()
204 */ 204 */
205const unsigned long FAR * ZEXPORT get_crc_table() 205const unsigned long FAR * ZEXPORT get_crc_table()
206{ 206{
207#ifdef DYNAMIC_CRC_TABLE 207#ifdef DYNAMIC_CRC_TABLE
208 if (crc_table_empty) 208 if (crc_table_empty)
209 make_crc_table(); 209 make_crc_table();
210#endif /* DYNAMIC_CRC_TABLE */ 210#endif /* DYNAMIC_CRC_TABLE */
211 return (const unsigned long FAR *)crc_table; 211 return (const unsigned long FAR *)crc_table;
212} 212}
213 213
214/* ========================================================================= */ 214/* ========================================================================= */
215#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) 215#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
216#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 216#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
217 217
218/* ========================================================================= */ 218/* ========================================================================= */
219unsigned long ZEXPORT crc32(crc, buf, len) 219unsigned long ZEXPORT crc32(crc, buf, len)
220 unsigned long crc; 220 unsigned long crc;
221 const unsigned char FAR *buf; 221 const unsigned char FAR *buf;
222 unsigned len; 222 unsigned len;
223{ 223{
224 if (buf == Z_NULL) return 0UL; 224 if (buf == Z_NULL) return 0UL;
225 225
226#ifdef DYNAMIC_CRC_TABLE 226#ifdef DYNAMIC_CRC_TABLE
227 if (crc_table_empty) 227 if (crc_table_empty)
228 make_crc_table(); 228 make_crc_table();
229#endif /* DYNAMIC_CRC_TABLE */ 229#endif /* DYNAMIC_CRC_TABLE */
230 230
231#ifdef BYFOUR 231#ifdef BYFOUR
232 if (sizeof(void *) == sizeof(ptrdiff_t)) { 232 if (sizeof(void *) == sizeof(ptrdiff_t)) {
233 u4 endian; 233 u4 endian;
234 234
235 endian = 1; 235 endian = 1;
236 if (*((unsigned char *)(&endian))) 236 if (*((unsigned char *)(&endian)))
237 return crc32_little(crc, buf, len); 237 return crc32_little(crc, buf, len);
238 else 238 else
239 return crc32_big(crc, buf, len); 239 return crc32_big(crc, buf, len);
240 } 240 }
241#endif /* BYFOUR */ 241#endif /* BYFOUR */
242 crc = crc ^ 0xffffffffUL; 242 crc = crc ^ 0xffffffffUL;
243 while (len >= 8) { 243 while (len >= 8) {
244 DO8; 244 DO8;
245 len -= 8; 245 len -= 8;
246 } 246 }
247 if (len) do { 247 if (len) do {
248 DO1; 248 DO1;
249 } while (--len); 249 } while (--len);
250 return crc ^ 0xffffffffUL; 250 return crc ^ 0xffffffffUL;
251} 251}
252 252
253#ifdef BYFOUR 253#ifdef BYFOUR
254 254
255/* ========================================================================= */ 255/* ========================================================================= */
256#define DOLIT4 c ^= *buf4++; \ 256#define DOLIT4 c ^= *buf4++; \
257 c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ 257 c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
258 crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] 258 crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
259#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 259#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
260 260
261/* ========================================================================= */ 261/* ========================================================================= */
262local unsigned long crc32_little(crc, buf, len) 262local unsigned long crc32_little(crc, buf, len)
263 unsigned long crc; 263 unsigned long crc;
264 const unsigned char FAR *buf; 264 const unsigned char FAR *buf;
265 unsigned len; 265 unsigned len;
266{ 266{
267 register u4 c; 267 register u4 c;
268 register const u4 FAR *buf4; 268 register const u4 FAR *buf4;
269 269
270 c = (u4)crc; 270 c = (u4)crc;
271 c = ~c; 271 c = ~c;
272 while (len && ((ptrdiff_t)buf & 3)) { 272 while (len && ((ptrdiff_t)buf & 3)) {
273 c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); 273 c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
274 len--; 274 len--;
275 } 275 }
276 276
277 buf4 = (const u4 FAR *)(const void FAR *)buf; 277 buf4 = (const u4 FAR *)(const void FAR *)buf;
278 while (len >= 32) { 278 while (len >= 32) {
279 DOLIT32; 279 DOLIT32;
280 len -= 32; 280 len -= 32;
281 } 281 }
282 while (len >= 4) { 282 while (len >= 4) {
283 DOLIT4; 283 DOLIT4;
284 len -= 4; 284 len -= 4;
285 } 285 }
286 buf = (const unsigned char FAR *)buf4; 286 buf = (const unsigned char FAR *)buf4;
287 287
288 if (len) do { 288 if (len) do {
289 c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); 289 c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
290 } while (--len); 290 } while (--len);
291 c = ~c; 291 c = ~c;
292 return (unsigned long)c; 292 return (unsigned long)c;
293} 293}
294 294
295/* ========================================================================= */ 295/* ========================================================================= */
296#define DOBIG4 c ^= *++buf4; \ 296#define DOBIG4 c ^= *++buf4; \
297 c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ 297 c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
298 crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] 298 crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
299#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 299#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
300 300
301/* ========================================================================= */ 301/* ========================================================================= */
302local unsigned long crc32_big(crc, buf, len) 302local unsigned long crc32_big(crc, buf, len)
303 unsigned long crc; 303 unsigned long crc;
304 const unsigned char FAR *buf; 304 const unsigned char FAR *buf;
305 unsigned len; 305 unsigned len;
306{ 306{
307 register u4 c; 307 register u4 c;
308 register const u4 FAR *buf4; 308 register const u4 FAR *buf4;
309 309
310 c = REV((u4)crc); 310 c = REV((u4)crc);
311 c = ~c; 311 c = ~c;
312 while (len && ((ptrdiff_t)buf & 3)) { 312 while (len && ((ptrdiff_t)buf & 3)) {
313 c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); 313 c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
314 len--; 314 len--;
315 } 315 }
316 316
317 buf4 = (const u4 FAR *)(const void FAR *)buf; 317 buf4 = (const u4 FAR *)(const void FAR *)buf;
318 buf4--; 318 buf4--;
319 while (len >= 32) { 319 while (len >= 32) {
320 DOBIG32; 320 DOBIG32;
321 len -= 32; 321 len -= 32;
322 } 322 }
323 while (len >= 4) { 323 while (len >= 4) {
324 DOBIG4; 324 DOBIG4;
325 len -= 4; 325 len -= 4;
326 } 326 }
327 buf4++; 327 buf4++;
328 buf = (const unsigned char FAR *)buf4; 328 buf = (const unsigned char FAR *)buf4;
329 329
330 if (len) do { 330 if (len) do {
331 c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); 331 c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
332 } while (--len); 332 } while (--len);
333 c = ~c; 333 c = ~c;
334 return (unsigned long)(REV(c)); 334 return (unsigned long)(REV(c));
335} 335}
336 336
337#endif /* BYFOUR */ 337#endif /* BYFOUR */
338 338
339#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */ 339#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
340 340
341/* ========================================================================= */ 341/* ========================================================================= */
342local unsigned long gf2_matrix_times(mat, vec) 342local unsigned long gf2_matrix_times(mat, vec)
343 unsigned long *mat; 343 unsigned long *mat;
344 unsigned long vec; 344 unsigned long vec;
345{ 345{
346 unsigned long sum; 346 unsigned long sum;
347 347
348 sum = 0; 348 sum = 0;
349 while (vec) { 349 while (vec) {
350 if (vec & 1) 350 if (vec & 1)
351 sum ^= *mat; 351 sum ^= *mat;
352 vec >>= 1; 352 vec >>= 1;
353 mat++; 353 mat++;
354 } 354 }
355 return sum; 355 return sum;
356} 356}
357 357
358/* ========================================================================= */ 358/* ========================================================================= */
359local void gf2_matrix_square(square, mat) 359local void gf2_matrix_square(square, mat)
360 unsigned long *square; 360 unsigned long *square;
361 unsigned long *mat; 361 unsigned long *mat;
362{ 362{
363 int n; 363 int n;
364 364
365 for (n = 0; n < GF2_DIM; n++) 365 for (n = 0; n < GF2_DIM; n++)
366 square[n] = gf2_matrix_times(mat, mat[n]); 366 square[n] = gf2_matrix_times(mat, mat[n]);
367} 367}
368 368
369/* ========================================================================= */ 369/* ========================================================================= */
370uLong ZEXPORT crc32_combine(crc1, crc2, len2) 370uLong ZEXPORT crc32_combine(crc1, crc2, len2)
371 uLong crc1; 371 uLong crc1;
372 uLong crc2; 372 uLong crc2;
373 z_off_t len2; 373 z_off_t len2;
374{ 374{
375 int n; 375 int n;
376 unsigned long row; 376 unsigned long row;
377 unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ 377 unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
378 unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ 378 unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
379 379
380 /* degenerate case */ 380 /* degenerate case */
381 if (len2 == 0) 381 if (len2 == 0)
382 return crc1; 382 return crc1;
383 383
384 /* put operator for one zero bit in odd */ 384 /* put operator for one zero bit in odd */
385 odd[0] = 0xedb88320L; /* CRC-32 polynomial */ 385 odd[0] = 0xedb88320L; /* CRC-32 polynomial */
386 row = 1; 386 row = 1;
387 for (n = 1; n < GF2_DIM; n++) { 387 for (n = 1; n < GF2_DIM; n++) {
388 odd[n] = row; 388 odd[n] = row;
389 row <<= 1; 389 row <<= 1;
390 } 390 }
391 391
392 /* put operator for two zero bits in even */ 392 /* put operator for two zero bits in even */
393 gf2_matrix_square(even, odd); 393 gf2_matrix_square(even, odd);
394 394
395 /* put operator for four zero bits in odd */ 395 /* put operator for four zero bits in odd */
396 gf2_matrix_square(odd, even); 396 gf2_matrix_square(odd, even);
397 397
398 /* apply len2 zeros to crc1 (first square will put the operator for one 398 /* apply len2 zeros to crc1 (first square will put the operator for one
399 zero byte, eight zero bits, in even) */ 399 zero byte, eight zero bits, in even) */
400 do { 400 do {
401 /* apply zeros operator for this bit of len2 */ 401 /* apply zeros operator for this bit of len2 */
402 gf2_matrix_square(even, odd); 402 gf2_matrix_square(even, odd);
403 if (len2 & 1) 403 if (len2 & 1)
404 crc1 = gf2_matrix_times(even, crc1); 404 crc1 = gf2_matrix_times(even, crc1);
405 len2 >>= 1; 405 len2 >>= 1;
406 406
407 /* if no more bits set, then done */ 407 /* if no more bits set, then done */
408 if (len2 == 0) 408 if (len2 == 0)
409 break; 409 break;
410 410
411 /* another iteration of the loop with odd and even swapped */ 411 /* another iteration of the loop with odd and even swapped */
412 gf2_matrix_square(odd, even); 412 gf2_matrix_square(odd, even);
413 if (len2 & 1) 413 if (len2 & 1)
414 crc1 = gf2_matrix_times(odd, crc1); 414 crc1 = gf2_matrix_times(odd, crc1);
415 len2 >>= 1; 415 len2 >>= 1;
416 416
417 /* if no more bits set, then done */ 417 /* if no more bits set, then done */
418 } while (len2 != 0); 418 } while (len2 != 0);
419 419
420 /* return combined crc */ 420 /* return combined crc */
421 crc1 ^= crc2; 421 crc1 ^= crc2;
422 return crc1; 422 return crc1;
423} 423}
diff --git a/utils/zenutils/libraries/zlib123/zlib/crc32.h b/utils/zenutils/libraries/zlib123/zlib/crc32.h
index 5de49bc978..8053b6117c 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/crc32.h
+++ b/utils/zenutils/libraries/zlib123/zlib/crc32.h
@@ -1,441 +1,441 @@
1/* crc32.h -- tables for rapid CRC calculation 1/* crc32.h -- tables for rapid CRC calculation
2 * Generated automatically by crc32.c 2 * Generated automatically by crc32.c
3 */ 3 */
4 4
5local const unsigned long FAR crc_table[TBLS][256] = 5local const unsigned long FAR crc_table[TBLS][256] =
6{ 6{
7 { 7 {
8 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, 8 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
9 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, 9 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
10 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, 10 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
11 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, 11 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
12 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, 12 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
13 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, 13 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
14 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, 14 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
15 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, 15 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
16 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, 16 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
17 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, 17 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
18 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, 18 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
19 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, 19 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
20 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, 20 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
21 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, 21 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
22 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, 22 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
23 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, 23 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
24 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, 24 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
25 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, 25 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
26 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, 26 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
27 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, 27 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
28 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, 28 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
29 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, 29 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
30 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, 30 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
31 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, 31 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
32 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, 32 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
33 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, 33 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
34 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, 34 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
35 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, 35 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
36 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, 36 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
37 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, 37 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
38 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, 38 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
39 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, 39 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
40 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, 40 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
41 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, 41 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
42 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, 42 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
43 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, 43 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
44 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, 44 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
45 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, 45 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
46 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, 46 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
47 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, 47 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
48 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, 48 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
49 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, 49 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
50 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, 50 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
51 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, 51 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
52 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, 52 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
53 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, 53 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
54 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, 54 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
55 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, 55 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
56 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, 56 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
57 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, 57 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
58 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, 58 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
59 0x2d02ef8dUL 59 0x2d02ef8dUL
60#ifdef BYFOUR 60#ifdef BYFOUR
61 }, 61 },
62 { 62 {
63 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL, 63 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
64 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL, 64 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
65 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL, 65 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
66 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL, 66 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
67 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL, 67 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
68 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL, 68 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
69 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL, 69 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
70 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL, 70 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
71 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL, 71 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
72 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL, 72 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
73 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL, 73 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
74 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL, 74 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
75 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL, 75 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
76 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL, 76 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
77 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL, 77 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
78 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL, 78 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
79 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL, 79 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
80 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL, 80 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
81 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL, 81 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
82 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL, 82 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
83 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL, 83 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
84 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL, 84 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
85 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL, 85 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
86 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL, 86 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
87 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL, 87 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
88 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL, 88 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
89 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL, 89 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
90 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL, 90 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
91 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL, 91 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
92 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL, 92 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
93 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL, 93 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
94 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL, 94 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
95 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL, 95 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
96 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL, 96 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
97 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL, 97 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
98 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL, 98 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
99 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL, 99 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
100 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL, 100 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
101 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL, 101 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
102 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL, 102 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
103 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL, 103 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
104 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL, 104 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
105 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL, 105 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
106 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL, 106 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
107 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL, 107 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
108 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL, 108 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
109 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL, 109 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
110 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL, 110 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
111 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL, 111 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
112 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL, 112 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
113 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL, 113 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
114 0x9324fd72UL 114 0x9324fd72UL
115 }, 115 },
116 { 116 {
117 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL, 117 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
118 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL, 118 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
119 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL, 119 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
120 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL, 120 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
121 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL, 121 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
122 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL, 122 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
123 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL, 123 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
124 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL, 124 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
125 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL, 125 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
126 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL, 126 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
127 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL, 127 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
128 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL, 128 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
129 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL, 129 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
130 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL, 130 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
131 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL, 131 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
132 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL, 132 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
133 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL, 133 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
134 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL, 134 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
135 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL, 135 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
136 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL, 136 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
137 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL, 137 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
138 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL, 138 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
139 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL, 139 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
140 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL, 140 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
141 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL, 141 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
142 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL, 142 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
143 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL, 143 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
144 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL, 144 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
145 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL, 145 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
146 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL, 146 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
147 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL, 147 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
148 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL, 148 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
149 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL, 149 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
150 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL, 150 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
151 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL, 151 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
152 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL, 152 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
153 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL, 153 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
154 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL, 154 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
155 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL, 155 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
156 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL, 156 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
157 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL, 157 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
158 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL, 158 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
159 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL, 159 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
160 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL, 160 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
161 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL, 161 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
162 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL, 162 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
163 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL, 163 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
164 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL, 164 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
165 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL, 165 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
166 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL, 166 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
167 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL, 167 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
168 0xbe9834edUL 168 0xbe9834edUL
169 }, 169 },
170 { 170 {
171 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL, 171 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
172 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL, 172 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
173 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL, 173 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
174 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL, 174 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
175 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL, 175 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
176 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL, 176 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
177 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL, 177 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
178 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL, 178 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
179 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL, 179 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
180 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL, 180 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
181 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL, 181 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
182 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL, 182 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
183 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL, 183 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
184 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL, 184 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
185 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL, 185 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
186 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL, 186 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
187 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL, 187 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
188 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL, 188 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
189 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL, 189 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
190 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL, 190 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
191 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL, 191 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
192 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL, 192 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
193 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL, 193 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
194 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL, 194 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
195 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL, 195 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
196 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL, 196 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
197 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL, 197 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
198 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL, 198 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
199 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL, 199 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
200 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL, 200 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
201 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL, 201 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
202 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL, 202 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
203 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL, 203 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
204 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL, 204 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
205 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL, 205 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
206 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL, 206 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
207 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL, 207 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
208 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL, 208 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
209 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL, 209 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
210 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL, 210 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
211 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL, 211 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
212 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL, 212 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
213 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL, 213 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
214 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL, 214 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
215 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL, 215 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
216 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL, 216 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
217 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL, 217 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
218 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL, 218 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
219 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL, 219 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
220 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL, 220 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
221 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL, 221 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
222 0xde0506f1UL 222 0xde0506f1UL
223 }, 223 },
224 { 224 {
225 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL, 225 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
226 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL, 226 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
227 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL, 227 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
228 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL, 228 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
229 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL, 229 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
230 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL, 230 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
231 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL, 231 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
232 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL, 232 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
233 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL, 233 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
234 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL, 234 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
235 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL, 235 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
236 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL, 236 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
237 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL, 237 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
238 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL, 238 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
239 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL, 239 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
240 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL, 240 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
241 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL, 241 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
242 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL, 242 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
243 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL, 243 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
244 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL, 244 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
245 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL, 245 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
246 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL, 246 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
247 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL, 247 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
248 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL, 248 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
249 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL, 249 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
250 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL, 250 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
251 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL, 251 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
252 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL, 252 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
253 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL, 253 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
254 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL, 254 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
255 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL, 255 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
256 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL, 256 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
257 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL, 257 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
258 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL, 258 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
259 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL, 259 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
260 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL, 260 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
261 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL, 261 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
262 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL, 262 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
263 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL, 263 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
264 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL, 264 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
265 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL, 265 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
266 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL, 266 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
267 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL, 267 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
268 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL, 268 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
269 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL, 269 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
270 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL, 270 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
271 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL, 271 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
272 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL, 272 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
273 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL, 273 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
274 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL, 274 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
275 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL, 275 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
276 0x8def022dUL 276 0x8def022dUL
277 }, 277 },
278 { 278 {
279 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL, 279 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
280 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL, 280 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
281 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL, 281 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
282 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL, 282 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
283 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL, 283 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
284 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL, 284 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
285 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL, 285 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
286 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL, 286 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
287 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL, 287 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
288 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL, 288 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
289 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL, 289 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
290 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL, 290 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
291 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL, 291 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
292 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL, 292 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
293 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL, 293 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
294 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL, 294 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
295 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL, 295 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
296 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL, 296 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
297 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL, 297 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
298 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL, 298 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
299 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL, 299 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
300 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL, 300 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
301 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL, 301 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
302 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL, 302 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
303 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL, 303 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
304 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL, 304 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
305 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL, 305 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
306 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL, 306 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
307 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL, 307 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
308 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL, 308 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
309 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL, 309 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
310 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL, 310 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
311 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL, 311 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
312 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL, 312 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
313 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL, 313 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
314 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL, 314 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
315 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL, 315 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
316 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL, 316 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
317 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL, 317 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
318 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL, 318 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
319 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL, 319 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
320 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL, 320 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
321 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL, 321 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
322 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL, 322 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
323 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL, 323 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
324 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL, 324 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
325 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL, 325 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
326 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL, 326 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
327 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL, 327 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
328 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL, 328 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
329 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL, 329 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
330 0x72fd2493UL 330 0x72fd2493UL
331 }, 331 },
332 { 332 {
333 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL, 333 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
334 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL, 334 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
335 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL, 335 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
336 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL, 336 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
337 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL, 337 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
338 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL, 338 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
339 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL, 339 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
340 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL, 340 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
341 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL, 341 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
342 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL, 342 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
343 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL, 343 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
344 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL, 344 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
345 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL, 345 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
346 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL, 346 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
347 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL, 347 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
348 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL, 348 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
349 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL, 349 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
350 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL, 350 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
351 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL, 351 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
352 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL, 352 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
353 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL, 353 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
354 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL, 354 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
355 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL, 355 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
356 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL, 356 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
357 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL, 357 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
358 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL, 358 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
359 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL, 359 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
360 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL, 360 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
361 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL, 361 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
362 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL, 362 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
363 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL, 363 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
364 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL, 364 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
365 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL, 365 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
366 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL, 366 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
367 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL, 367 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
368 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL, 368 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
369 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL, 369 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
370 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL, 370 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
371 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL, 371 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
372 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL, 372 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
373 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL, 373 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
374 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL, 374 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
375 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL, 375 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
376 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL, 376 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
377 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL, 377 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
378 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL, 378 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
379 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL, 379 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
380 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL, 380 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
381 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL, 381 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
382 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL, 382 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
383 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL, 383 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
384 0xed3498beUL 384 0xed3498beUL
385 }, 385 },
386 { 386 {
387 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL, 387 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
388 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL, 388 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
389 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL, 389 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
390 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL, 390 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
391 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL, 391 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
392 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL, 392 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
393 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL, 393 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
394 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL, 394 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
395 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL, 395 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
396 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL, 396 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
397 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL, 397 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
398 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL, 398 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
399 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL, 399 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
400 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL, 400 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
401 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL, 401 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
402 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL, 402 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
403 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL, 403 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
404 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL, 404 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
405 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL, 405 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
406 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL, 406 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
407 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL, 407 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
408 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL, 408 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
409 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL, 409 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
410 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL, 410 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
411 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL, 411 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
412 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL, 412 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
413 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL, 413 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
414 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL, 414 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
415 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL, 415 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
416 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL, 416 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
417 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL, 417 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
418 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL, 418 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
419 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL, 419 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
420 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL, 420 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
421 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL, 421 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
422 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL, 422 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
423 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL, 423 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
424 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL, 424 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
425 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL, 425 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
426 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL, 426 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
427 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL, 427 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
428 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL, 428 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
429 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL, 429 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
430 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL, 430 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
431 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL, 431 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
432 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL, 432 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
433 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL, 433 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
434 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL, 434 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
435 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL, 435 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
436 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL, 436 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
437 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL, 437 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
438 0xf10605deUL 438 0xf10605deUL
439#endif 439#endif
440 } 440 }
441}; 441};
diff --git a/utils/zenutils/libraries/zlib123/zlib/deflate.c b/utils/zenutils/libraries/zlib123/zlib/deflate.c
index 529f716b7a..29ce1f64a5 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/deflate.c
+++ b/utils/zenutils/libraries/zlib123/zlib/deflate.c
@@ -1,1736 +1,1736 @@
1/* deflate.c -- compress data using the deflation algorithm 1/* deflate.c -- compress data using the deflation algorithm
2 * Copyright (C) 1995-2005 Jean-loup Gailly. 2 * Copyright (C) 1995-2005 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6/* 6/*
7 * ALGORITHM 7 * ALGORITHM
8 * 8 *
9 * The "deflation" process depends on being able to identify portions 9 * The "deflation" process depends on being able to identify portions
10 * of the input text which are identical to earlier input (within a 10 * of the input text which are identical to earlier input (within a
11 * sliding window trailing behind the input currently being processed). 11 * sliding window trailing behind the input currently being processed).
12 * 12 *
13 * The most straightforward technique turns out to be the fastest for 13 * The most straightforward technique turns out to be the fastest for
14 * most input files: try all possible matches and select the longest. 14 * most input files: try all possible matches and select the longest.
15 * The key feature of this algorithm is that insertions into the string 15 * The key feature of this algorithm is that insertions into the string
16 * dictionary are very simple and thus fast, and deletions are avoided 16 * dictionary are very simple and thus fast, and deletions are avoided
17 * completely. Insertions are performed at each input character, whereas 17 * completely. Insertions are performed at each input character, whereas
18 * string matches are performed only when the previous match ends. So it 18 * string matches are performed only when the previous match ends. So it
19 * is preferable to spend more time in matches to allow very fast string 19 * is preferable to spend more time in matches to allow very fast string
20 * insertions and avoid deletions. The matching algorithm for small 20 * insertions and avoid deletions. The matching algorithm for small
21 * strings is inspired from that of Rabin & Karp. A brute force approach 21 * strings is inspired from that of Rabin & Karp. A brute force approach
22 * is used to find longer strings when a small match has been found. 22 * is used to find longer strings when a small match has been found.
23 * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze 23 * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
24 * (by Leonid Broukhis). 24 * (by Leonid Broukhis).
25 * A previous version of this file used a more sophisticated algorithm 25 * A previous version of this file used a more sophisticated algorithm
26 * (by Fiala and Greene) which is guaranteed to run in linear amortized 26 * (by Fiala and Greene) which is guaranteed to run in linear amortized
27 * time, but has a larger average cost, uses more memory and is patented. 27 * time, but has a larger average cost, uses more memory and is patented.
28 * However the F&G algorithm may be faster for some highly redundant 28 * However the F&G algorithm may be faster for some highly redundant
29 * files if the parameter max_chain_length (described below) is too large. 29 * files if the parameter max_chain_length (described below) is too large.
30 * 30 *
31 * ACKNOWLEDGEMENTS 31 * ACKNOWLEDGEMENTS
32 * 32 *
33 * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and 33 * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
34 * I found it in 'freeze' written by Leonid Broukhis. 34 * I found it in 'freeze' written by Leonid Broukhis.
35 * Thanks to many people for bug reports and testing. 35 * Thanks to many people for bug reports and testing.
36 * 36 *
37 * REFERENCES 37 * REFERENCES
38 * 38 *
39 * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". 39 * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
40 * Available in http://www.ietf.org/rfc/rfc1951.txt 40 * Available in http://www.ietf.org/rfc/rfc1951.txt
41 * 41 *
42 * A description of the Rabin and Karp algorithm is given in the book 42 * A description of the Rabin and Karp algorithm is given in the book
43 * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. 43 * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
44 * 44 *
45 * Fiala,E.R., and Greene,D.H. 45 * Fiala,E.R., and Greene,D.H.
46 * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 46 * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
47 * 47 *
48 */ 48 */
49 49
50/* @(#) $Id$ */ 50/* @(#) $Id$ */
51 51
52#include "deflate.h" 52#include "deflate.h"
53 53
54const char deflate_copyright[] = 54const char deflate_copyright[] =
55 " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly "; 55 " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
56/* 56/*
57 If you use the zlib library in a product, an acknowledgment is welcome 57 If you use the zlib library in a product, an acknowledgment is welcome
58 in the documentation of your product. If for some reason you cannot 58 in the documentation of your product. If for some reason you cannot
59 include such an acknowledgment, I would appreciate that you keep this 59 include such an acknowledgment, I would appreciate that you keep this
60 copyright string in the executable of your product. 60 copyright string in the executable of your product.
61 */ 61 */
62 62
63/* =========================================================================== 63/* ===========================================================================
64 * Function prototypes. 64 * Function prototypes.
65 */ 65 */
66typedef enum { 66typedef enum {
67 need_more, /* block not completed, need more input or more output */ 67 need_more, /* block not completed, need more input or more output */
68 block_done, /* block flush performed */ 68 block_done, /* block flush performed */
69 finish_started, /* finish started, need only more output at next deflate */ 69 finish_started, /* finish started, need only more output at next deflate */
70 finish_done /* finish done, accept no more input or output */ 70 finish_done /* finish done, accept no more input or output */
71} block_state; 71} block_state;
72 72
73typedef block_state (*compress_func) OF((deflate_state *s, int flush)); 73typedef block_state (*compress_func) OF((deflate_state *s, int flush));
74/* Compression function. Returns the block state after the call. */ 74/* Compression function. Returns the block state after the call. */
75 75
76local void fill_window OF((deflate_state *s)); 76local void fill_window OF((deflate_state *s));
77local block_state deflate_stored OF((deflate_state *s, int flush)); 77local block_state deflate_stored OF((deflate_state *s, int flush));
78local block_state deflate_fast OF((deflate_state *s, int flush)); 78local block_state deflate_fast OF((deflate_state *s, int flush));
79#ifndef FASTEST 79#ifndef FASTEST
80local block_state deflate_slow OF((deflate_state *s, int flush)); 80local block_state deflate_slow OF((deflate_state *s, int flush));
81#endif 81#endif
82local void lm_init OF((deflate_state *s)); 82local void lm_init OF((deflate_state *s));
83local void putShortMSB OF((deflate_state *s, uInt b)); 83local void putShortMSB OF((deflate_state *s, uInt b));
84local void flush_pending OF((z_streamp strm)); 84local void flush_pending OF((z_streamp strm));
85local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); 85local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
86#ifndef FASTEST 86#ifndef FASTEST
87#ifdef ASMV 87#ifdef ASMV
88 void match_init OF((void)); /* asm code initialization */ 88 void match_init OF((void)); /* asm code initialization */
89 uInt longest_match OF((deflate_state *s, IPos cur_match)); 89 uInt longest_match OF((deflate_state *s, IPos cur_match));
90#else 90#else
91local uInt longest_match OF((deflate_state *s, IPos cur_match)); 91local uInt longest_match OF((deflate_state *s, IPos cur_match));
92#endif 92#endif
93#endif 93#endif
94local uInt longest_match_fast OF((deflate_state *s, IPos cur_match)); 94local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
95 95
96#ifdef DEBUG 96#ifdef DEBUG
97local void check_match OF((deflate_state *s, IPos start, IPos match, 97local void check_match OF((deflate_state *s, IPos start, IPos match,
98 int length)); 98 int length));
99#endif 99#endif
100 100
101/* =========================================================================== 101/* ===========================================================================
102 * Local data 102 * Local data
103 */ 103 */
104 104
105#define NIL 0 105#define NIL 0
106/* Tail of hash chains */ 106/* Tail of hash chains */
107 107
108#ifndef TOO_FAR 108#ifndef TOO_FAR
109# define TOO_FAR 4096 109# define TOO_FAR 4096
110#endif 110#endif
111/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ 111/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
112 112
113#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) 113#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
114/* Minimum amount of lookahead, except at the end of the input file. 114/* Minimum amount of lookahead, except at the end of the input file.
115 * See deflate.c for comments about the MIN_MATCH+1. 115 * See deflate.c for comments about the MIN_MATCH+1.
116 */ 116 */
117 117
118/* Values for max_lazy_match, good_match and max_chain_length, depending on 118/* Values for max_lazy_match, good_match and max_chain_length, depending on
119 * the desired pack level (0..9). The values given below have been tuned to 119 * the desired pack level (0..9). The values given below have been tuned to
120 * exclude worst case performance for pathological files. Better values may be 120 * exclude worst case performance for pathological files. Better values may be
121 * found for specific files. 121 * found for specific files.
122 */ 122 */
123typedef struct config_s { 123typedef struct config_s {
124 ush good_length; /* reduce lazy search above this match length */ 124 ush good_length; /* reduce lazy search above this match length */
125 ush max_lazy; /* do not perform lazy search above this match length */ 125 ush max_lazy; /* do not perform lazy search above this match length */
126 ush nice_length; /* quit search above this match length */ 126 ush nice_length; /* quit search above this match length */
127 ush max_chain; 127 ush max_chain;
128 compress_func func; 128 compress_func func;
129} config; 129} config;
130 130
131#ifdef FASTEST 131#ifdef FASTEST
132local const config configuration_table[2] = { 132local const config configuration_table[2] = {
133/* good lazy nice chain */ 133/* good lazy nice chain */
134/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ 134/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
135/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ 135/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
136#else 136#else
137local const config configuration_table[10] = { 137local const config configuration_table[10] = {
138/* good lazy nice chain */ 138/* good lazy nice chain */
139/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ 139/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
140/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ 140/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
141/* 2 */ {4, 5, 16, 8, deflate_fast}, 141/* 2 */ {4, 5, 16, 8, deflate_fast},
142/* 3 */ {4, 6, 32, 32, deflate_fast}, 142/* 3 */ {4, 6, 32, 32, deflate_fast},
143 143
144/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ 144/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
145/* 5 */ {8, 16, 32, 32, deflate_slow}, 145/* 5 */ {8, 16, 32, 32, deflate_slow},
146/* 6 */ {8, 16, 128, 128, deflate_slow}, 146/* 6 */ {8, 16, 128, 128, deflate_slow},
147/* 7 */ {8, 32, 128, 256, deflate_slow}, 147/* 7 */ {8, 32, 128, 256, deflate_slow},
148/* 8 */ {32, 128, 258, 1024, deflate_slow}, 148/* 8 */ {32, 128, 258, 1024, deflate_slow},
149/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ 149/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
150#endif 150#endif
151 151
152/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 152/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
153 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different 153 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
154 * meaning. 154 * meaning.
155 */ 155 */
156 156
157#define EQUAL 0 157#define EQUAL 0
158/* result of memcmp for equal strings */ 158/* result of memcmp for equal strings */
159 159
160#ifndef NO_DUMMY_DECL 160#ifndef NO_DUMMY_DECL
161struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ 161struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
162#endif 162#endif
163 163
164/* =========================================================================== 164/* ===========================================================================
165 * Update a hash value with the given input byte 165 * Update a hash value with the given input byte
166 * IN assertion: all calls to to UPDATE_HASH are made with consecutive 166 * IN assertion: all calls to to UPDATE_HASH are made with consecutive
167 * input characters, so that a running hash key can be computed from the 167 * input characters, so that a running hash key can be computed from the
168 * previous key instead of complete recalculation each time. 168 * previous key instead of complete recalculation each time.
169 */ 169 */
170#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask) 170#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
171 171
172 172
173/* =========================================================================== 173/* ===========================================================================
174 * Insert string str in the dictionary and set match_head to the previous head 174 * Insert string str in the dictionary and set match_head to the previous head
175 * of the hash chain (the most recent string with same hash key). Return 175 * of the hash chain (the most recent string with same hash key). Return
176 * the previous length of the hash chain. 176 * the previous length of the hash chain.
177 * If this file is compiled with -DFASTEST, the compression level is forced 177 * If this file is compiled with -DFASTEST, the compression level is forced
178 * to 1, and no hash chains are maintained. 178 * to 1, and no hash chains are maintained.
179 * IN assertion: all calls to to INSERT_STRING are made with consecutive 179 * IN assertion: all calls to to INSERT_STRING are made with consecutive
180 * input characters and the first MIN_MATCH bytes of str are valid 180 * input characters and the first MIN_MATCH bytes of str are valid
181 * (except for the last MIN_MATCH-1 bytes of the input file). 181 * (except for the last MIN_MATCH-1 bytes of the input file).
182 */ 182 */
183#ifdef FASTEST 183#ifdef FASTEST
184#define INSERT_STRING(s, str, match_head) \ 184#define INSERT_STRING(s, str, match_head) \
185 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ 185 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
186 match_head = s->head[s->ins_h], \ 186 match_head = s->head[s->ins_h], \
187 s->head[s->ins_h] = (Pos)(str)) 187 s->head[s->ins_h] = (Pos)(str))
188#else 188#else
189#define INSERT_STRING(s, str, match_head) \ 189#define INSERT_STRING(s, str, match_head) \
190 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ 190 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
191 match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ 191 match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
192 s->head[s->ins_h] = (Pos)(str)) 192 s->head[s->ins_h] = (Pos)(str))
193#endif 193#endif
194 194
195/* =========================================================================== 195/* ===========================================================================
196 * Initialize the hash table (avoiding 64K overflow for 16 bit systems). 196 * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
197 * prev[] will be initialized on the fly. 197 * prev[] will be initialized on the fly.
198 */ 198 */
199#define CLEAR_HASH(s) \ 199#define CLEAR_HASH(s) \
200 s->head[s->hash_size-1] = NIL; \ 200 s->head[s->hash_size-1] = NIL; \
201 zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); 201 zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
202 202
203/* ========================================================================= */ 203/* ========================================================================= */
204int ZEXPORT deflateInit_(strm, level, version, stream_size) 204int ZEXPORT deflateInit_(strm, level, version, stream_size)
205 z_streamp strm; 205 z_streamp strm;
206 int level; 206 int level;
207 const char *version; 207 const char *version;
208 int stream_size; 208 int stream_size;
209{ 209{
210 return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, 210 return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
211 Z_DEFAULT_STRATEGY, version, stream_size); 211 Z_DEFAULT_STRATEGY, version, stream_size);
212 /* To do: ignore strm->next_in if we use it as window */ 212 /* To do: ignore strm->next_in if we use it as window */
213} 213}
214 214
215/* ========================================================================= */ 215/* ========================================================================= */
216int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, 216int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
217 version, stream_size) 217 version, stream_size)
218 z_streamp strm; 218 z_streamp strm;
219 int level; 219 int level;
220 int method; 220 int method;
221 int windowBits; 221 int windowBits;
222 int memLevel; 222 int memLevel;
223 int strategy; 223 int strategy;
224 const char *version; 224 const char *version;
225 int stream_size; 225 int stream_size;
226{ 226{
227 deflate_state *s; 227 deflate_state *s;
228 int wrap = 1; 228 int wrap = 1;
229 static const char my_version[] = ZLIB_VERSION; 229 static const char my_version[] = ZLIB_VERSION;
230 230
231 ushf *overlay; 231 ushf *overlay;
232 /* We overlay pending_buf and d_buf+l_buf. This works since the average 232 /* We overlay pending_buf and d_buf+l_buf. This works since the average
233 * output size for (length,distance) codes is <= 24 bits. 233 * output size for (length,distance) codes is <= 24 bits.
234 */ 234 */
235 235
236 if (version == Z_NULL || version[0] != my_version[0] || 236 if (version == Z_NULL || version[0] != my_version[0] ||
237 stream_size != sizeof(z_stream)) { 237 stream_size != sizeof(z_stream)) {
238 return Z_VERSION_ERROR; 238 return Z_VERSION_ERROR;
239 } 239 }
240 if (strm == Z_NULL) return Z_STREAM_ERROR; 240 if (strm == Z_NULL) return Z_STREAM_ERROR;
241 241
242 strm->msg = Z_NULL; 242 strm->msg = Z_NULL;
243 if (strm->zalloc == (alloc_func)0) { 243 if (strm->zalloc == (alloc_func)0) {
244 strm->zalloc = zcalloc; 244 strm->zalloc = zcalloc;
245 strm->opaque = (voidpf)0; 245 strm->opaque = (voidpf)0;
246 } 246 }
247 if (strm->zfree == (free_func)0) strm->zfree = zcfree; 247 if (strm->zfree == (free_func)0) strm->zfree = zcfree;
248 248
249#ifdef FASTEST 249#ifdef FASTEST
250 if (level != 0) level = 1; 250 if (level != 0) level = 1;
251#else 251#else
252 if (level == Z_DEFAULT_COMPRESSION) level = 6; 252 if (level == Z_DEFAULT_COMPRESSION) level = 6;
253#endif 253#endif
254 254
255 if (windowBits < 0) { /* suppress zlib wrapper */ 255 if (windowBits < 0) { /* suppress zlib wrapper */
256 wrap = 0; 256 wrap = 0;
257 windowBits = -windowBits; 257 windowBits = -windowBits;
258 } 258 }
259#ifdef GZIP 259#ifdef GZIP
260 else if (windowBits > 15) { 260 else if (windowBits > 15) {
261 wrap = 2; /* write gzip wrapper instead */ 261 wrap = 2; /* write gzip wrapper instead */
262 windowBits -= 16; 262 windowBits -= 16;
263 } 263 }
264#endif 264#endif
265 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || 265 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
266 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || 266 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
267 strategy < 0 || strategy > Z_FIXED) { 267 strategy < 0 || strategy > Z_FIXED) {
268 return Z_STREAM_ERROR; 268 return Z_STREAM_ERROR;
269 } 269 }
270 if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ 270 if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
271 s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); 271 s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
272 if (s == Z_NULL) return Z_MEM_ERROR; 272 if (s == Z_NULL) return Z_MEM_ERROR;
273 strm->state = (struct internal_state FAR *)s; 273 strm->state = (struct internal_state FAR *)s;
274 s->strm = strm; 274 s->strm = strm;
275 275
276 s->wrap = wrap; 276 s->wrap = wrap;
277 s->gzhead = Z_NULL; 277 s->gzhead = Z_NULL;
278 s->w_bits = windowBits; 278 s->w_bits = windowBits;
279 s->w_size = 1 << s->w_bits; 279 s->w_size = 1 << s->w_bits;
280 s->w_mask = s->w_size - 1; 280 s->w_mask = s->w_size - 1;
281 281
282 s->hash_bits = memLevel + 7; 282 s->hash_bits = memLevel + 7;
283 s->hash_size = 1 << s->hash_bits; 283 s->hash_size = 1 << s->hash_bits;
284 s->hash_mask = s->hash_size - 1; 284 s->hash_mask = s->hash_size - 1;
285 s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); 285 s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
286 286
287 s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); 287 s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
288 s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); 288 s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
289 s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); 289 s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
290 290
291 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ 291 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
292 292
293 overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); 293 overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
294 s->pending_buf = (uchf *) overlay; 294 s->pending_buf = (uchf *) overlay;
295 s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); 295 s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
296 296
297 if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || 297 if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
298 s->pending_buf == Z_NULL) { 298 s->pending_buf == Z_NULL) {
299 s->status = FINISH_STATE; 299 s->status = FINISH_STATE;
300 strm->msg = (char*)ERR_MSG(Z_MEM_ERROR); 300 strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
301 deflateEnd (strm); 301 deflateEnd (strm);
302 return Z_MEM_ERROR; 302 return Z_MEM_ERROR;
303 } 303 }
304 s->d_buf = overlay + s->lit_bufsize/sizeof(ush); 304 s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
305 s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; 305 s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
306 306
307 s->level = level; 307 s->level = level;
308 s->strategy = strategy; 308 s->strategy = strategy;
309 s->method = (Byte)method; 309 s->method = (Byte)method;
310 310
311 return deflateReset(strm); 311 return deflateReset(strm);
312} 312}
313 313
314/* ========================================================================= */ 314/* ========================================================================= */
315int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) 315int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
316 z_streamp strm; 316 z_streamp strm;
317 const Bytef *dictionary; 317 const Bytef *dictionary;
318 uInt dictLength; 318 uInt dictLength;
319{ 319{
320 deflate_state *s; 320 deflate_state *s;
321 uInt length = dictLength; 321 uInt length = dictLength;
322 uInt n; 322 uInt n;
323 IPos hash_head = 0; 323 IPos hash_head = 0;
324 324
325 if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL || 325 if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
326 strm->state->wrap == 2 || 326 strm->state->wrap == 2 ||
327 (strm->state->wrap == 1 && strm->state->status != INIT_STATE)) 327 (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
328 return Z_STREAM_ERROR; 328 return Z_STREAM_ERROR;
329 329
330 s = strm->state; 330 s = strm->state;
331 if (s->wrap) 331 if (s->wrap)
332 strm->adler = adler32(strm->adler, dictionary, dictLength); 332 strm->adler = adler32(strm->adler, dictionary, dictLength);
333 333
334 if (length < MIN_MATCH) return Z_OK; 334 if (length < MIN_MATCH) return Z_OK;
335 if (length > MAX_DIST(s)) { 335 if (length > MAX_DIST(s)) {
336 length = MAX_DIST(s); 336 length = MAX_DIST(s);
337 dictionary += dictLength - length; /* use the tail of the dictionary */ 337 dictionary += dictLength - length; /* use the tail of the dictionary */
338 } 338 }
339 zmemcpy(s->window, dictionary, length); 339 zmemcpy(s->window, dictionary, length);
340 s->strstart = length; 340 s->strstart = length;
341 s->block_start = (long)length; 341 s->block_start = (long)length;
342 342
343 /* Insert all strings in the hash table (except for the last two bytes). 343 /* Insert all strings in the hash table (except for the last two bytes).
344 * s->lookahead stays null, so s->ins_h will be recomputed at the next 344 * s->lookahead stays null, so s->ins_h will be recomputed at the next
345 * call of fill_window. 345 * call of fill_window.
346 */ 346 */
347 s->ins_h = s->window[0]; 347 s->ins_h = s->window[0];
348 UPDATE_HASH(s, s->ins_h, s->window[1]); 348 UPDATE_HASH(s, s->ins_h, s->window[1]);
349 for (n = 0; n <= length - MIN_MATCH; n++) { 349 for (n = 0; n <= length - MIN_MATCH; n++) {
350 INSERT_STRING(s, n, hash_head); 350 INSERT_STRING(s, n, hash_head);
351 } 351 }
352 if (hash_head) hash_head = 0; /* to make compiler happy */ 352 if (hash_head) hash_head = 0; /* to make compiler happy */
353 return Z_OK; 353 return Z_OK;
354} 354}
355 355
356/* ========================================================================= */ 356/* ========================================================================= */
357int ZEXPORT deflateReset (strm) 357int ZEXPORT deflateReset (strm)
358 z_streamp strm; 358 z_streamp strm;
359{ 359{
360 deflate_state *s; 360 deflate_state *s;
361 361
362 if (strm == Z_NULL || strm->state == Z_NULL || 362 if (strm == Z_NULL || strm->state == Z_NULL ||
363 strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) { 363 strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
364 return Z_STREAM_ERROR; 364 return Z_STREAM_ERROR;
365 } 365 }
366 366
367 strm->total_in = strm->total_out = 0; 367 strm->total_in = strm->total_out = 0;
368 strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ 368 strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
369 strm->data_type = Z_UNKNOWN; 369 strm->data_type = Z_UNKNOWN;
370 370
371 s = (deflate_state *)strm->state; 371 s = (deflate_state *)strm->state;
372 s->pending = 0; 372 s->pending = 0;
373 s->pending_out = s->pending_buf; 373 s->pending_out = s->pending_buf;
374 374
375 if (s->wrap < 0) { 375 if (s->wrap < 0) {
376 s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ 376 s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
377 } 377 }
378 s->status = s->wrap ? INIT_STATE : BUSY_STATE; 378 s->status = s->wrap ? INIT_STATE : BUSY_STATE;
379 strm->adler = 379 strm->adler =
380#ifdef GZIP 380#ifdef GZIP
381 s->wrap == 2 ? crc32(0L, Z_NULL, 0) : 381 s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
382#endif 382#endif
383 adler32(0L, Z_NULL, 0); 383 adler32(0L, Z_NULL, 0);
384 s->last_flush = Z_NO_FLUSH; 384 s->last_flush = Z_NO_FLUSH;
385 385
386 _tr_init(s); 386 _tr_init(s);
387 lm_init(s); 387 lm_init(s);
388 388
389 return Z_OK; 389 return Z_OK;
390} 390}
391 391
392/* ========================================================================= */ 392/* ========================================================================= */
393int ZEXPORT deflateSetHeader (strm, head) 393int ZEXPORT deflateSetHeader (strm, head)
394 z_streamp strm; 394 z_streamp strm;
395 gz_headerp head; 395 gz_headerp head;
396{ 396{
397 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; 397 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
398 if (strm->state->wrap != 2) return Z_STREAM_ERROR; 398 if (strm->state->wrap != 2) return Z_STREAM_ERROR;
399 strm->state->gzhead = head; 399 strm->state->gzhead = head;
400 return Z_OK; 400 return Z_OK;
401} 401}
402 402
403/* ========================================================================= */ 403/* ========================================================================= */
404int ZEXPORT deflatePrime (strm, bits, value) 404int ZEXPORT deflatePrime (strm, bits, value)
405 z_streamp strm; 405 z_streamp strm;
406 int bits; 406 int bits;
407 int value; 407 int value;
408{ 408{
409 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; 409 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
410 strm->state->bi_valid = bits; 410 strm->state->bi_valid = bits;
411 strm->state->bi_buf = (ush)(value & ((1 << bits) - 1)); 411 strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
412 return Z_OK; 412 return Z_OK;
413} 413}
414 414
415/* ========================================================================= */ 415/* ========================================================================= */
416int ZEXPORT deflateParams(strm, level, strategy) 416int ZEXPORT deflateParams(strm, level, strategy)
417 z_streamp strm; 417 z_streamp strm;
418 int level; 418 int level;
419 int strategy; 419 int strategy;
420{ 420{
421 deflate_state *s; 421 deflate_state *s;
422 compress_func func; 422 compress_func func;
423 int err = Z_OK; 423 int err = Z_OK;
424 424
425 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; 425 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
426 s = strm->state; 426 s = strm->state;
427 427
428#ifdef FASTEST 428#ifdef FASTEST
429 if (level != 0) level = 1; 429 if (level != 0) level = 1;
430#else 430#else
431 if (level == Z_DEFAULT_COMPRESSION) level = 6; 431 if (level == Z_DEFAULT_COMPRESSION) level = 6;
432#endif 432#endif
433 if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { 433 if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
434 return Z_STREAM_ERROR; 434 return Z_STREAM_ERROR;
435 } 435 }
436 func = configuration_table[s->level].func; 436 func = configuration_table[s->level].func;
437 437
438 if (func != configuration_table[level].func && strm->total_in != 0) { 438 if (func != configuration_table[level].func && strm->total_in != 0) {
439 /* Flush the last buffer: */ 439 /* Flush the last buffer: */
440 err = deflate(strm, Z_PARTIAL_FLUSH); 440 err = deflate(strm, Z_PARTIAL_FLUSH);
441 } 441 }
442 if (s->level != level) { 442 if (s->level != level) {
443 s->level = level; 443 s->level = level;
444 s->max_lazy_match = configuration_table[level].max_lazy; 444 s->max_lazy_match = configuration_table[level].max_lazy;
445 s->good_match = configuration_table[level].good_length; 445 s->good_match = configuration_table[level].good_length;
446 s->nice_match = configuration_table[level].nice_length; 446 s->nice_match = configuration_table[level].nice_length;
447 s->max_chain_length = configuration_table[level].max_chain; 447 s->max_chain_length = configuration_table[level].max_chain;
448 } 448 }
449 s->strategy = strategy; 449 s->strategy = strategy;
450 return err; 450 return err;
451} 451}
452 452
453/* ========================================================================= */ 453/* ========================================================================= */
454int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) 454int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
455 z_streamp strm; 455 z_streamp strm;
456 int good_length; 456 int good_length;
457 int max_lazy; 457 int max_lazy;
458 int nice_length; 458 int nice_length;
459 int max_chain; 459 int max_chain;
460{ 460{
461 deflate_state *s; 461 deflate_state *s;
462 462
463 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; 463 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
464 s = strm->state; 464 s = strm->state;
465 s->good_match = good_length; 465 s->good_match = good_length;
466 s->max_lazy_match = max_lazy; 466 s->max_lazy_match = max_lazy;
467 s->nice_match = nice_length; 467 s->nice_match = nice_length;
468 s->max_chain_length = max_chain; 468 s->max_chain_length = max_chain;
469 return Z_OK; 469 return Z_OK;
470} 470}
471 471
472/* ========================================================================= 472/* =========================================================================
473 * For the default windowBits of 15 and memLevel of 8, this function returns 473 * For the default windowBits of 15 and memLevel of 8, this function returns
474 * a close to exact, as well as small, upper bound on the compressed size. 474 * a close to exact, as well as small, upper bound on the compressed size.
475 * They are coded as constants here for a reason--if the #define's are 475 * They are coded as constants here for a reason--if the #define's are
476 * changed, then this function needs to be changed as well. The return 476 * changed, then this function needs to be changed as well. The return
477 * value for 15 and 8 only works for those exact settings. 477 * value for 15 and 8 only works for those exact settings.
478 * 478 *
479 * For any setting other than those defaults for windowBits and memLevel, 479 * For any setting other than those defaults for windowBits and memLevel,
480 * the value returned is a conservative worst case for the maximum expansion 480 * the value returned is a conservative worst case for the maximum expansion
481 * resulting from using fixed blocks instead of stored blocks, which deflate 481 * resulting from using fixed blocks instead of stored blocks, which deflate
482 * can emit on compressed data for some combinations of the parameters. 482 * can emit on compressed data for some combinations of the parameters.
483 * 483 *
484 * This function could be more sophisticated to provide closer upper bounds 484 * This function could be more sophisticated to provide closer upper bounds
485 * for every combination of windowBits and memLevel, as well as wrap. 485 * for every combination of windowBits and memLevel, as well as wrap.
486 * But even the conservative upper bound of about 14% expansion does not 486 * But even the conservative upper bound of about 14% expansion does not
487 * seem onerous for output buffer allocation. 487 * seem onerous for output buffer allocation.
488 */ 488 */
489uLong ZEXPORT deflateBound(strm, sourceLen) 489uLong ZEXPORT deflateBound(strm, sourceLen)
490 z_streamp strm; 490 z_streamp strm;
491 uLong sourceLen; 491 uLong sourceLen;
492{ 492{
493 deflate_state *s; 493 deflate_state *s;
494 uLong destLen; 494 uLong destLen;
495 495
496 /* conservative upper bound */ 496 /* conservative upper bound */
497 destLen = sourceLen + 497 destLen = sourceLen +
498 ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11; 498 ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
499 499
500 /* if can't get parameters, return conservative bound */ 500 /* if can't get parameters, return conservative bound */
501 if (strm == Z_NULL || strm->state == Z_NULL) 501 if (strm == Z_NULL || strm->state == Z_NULL)
502 return destLen; 502 return destLen;
503 503
504 /* if not default parameters, return conservative bound */ 504 /* if not default parameters, return conservative bound */
505 s = strm->state; 505 s = strm->state;
506 if (s->w_bits != 15 || s->hash_bits != 8 + 7) 506 if (s->w_bits != 15 || s->hash_bits != 8 + 7)
507 return destLen; 507 return destLen;
508 508
509 /* default settings: return tight bound for that case */ 509 /* default settings: return tight bound for that case */
510 return compressBound(sourceLen); 510 return compressBound(sourceLen);
511} 511}
512 512
513/* ========================================================================= 513/* =========================================================================
514 * Put a short in the pending buffer. The 16-bit value is put in MSB order. 514 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
515 * IN assertion: the stream state is correct and there is enough room in 515 * IN assertion: the stream state is correct and there is enough room in
516 * pending_buf. 516 * pending_buf.
517 */ 517 */
518local void putShortMSB (s, b) 518local void putShortMSB (s, b)
519 deflate_state *s; 519 deflate_state *s;
520 uInt b; 520 uInt b;
521{ 521{
522 put_byte(s, (Byte)(b >> 8)); 522 put_byte(s, (Byte)(b >> 8));
523 put_byte(s, (Byte)(b & 0xff)); 523 put_byte(s, (Byte)(b & 0xff));
524} 524}
525 525
526/* ========================================================================= 526/* =========================================================================
527 * Flush as much pending output as possible. All deflate() output goes 527 * Flush as much pending output as possible. All deflate() output goes
528 * through this function so some applications may wish to modify it 528 * through this function so some applications may wish to modify it
529 * to avoid allocating a large strm->next_out buffer and copying into it. 529 * to avoid allocating a large strm->next_out buffer and copying into it.
530 * (See also read_buf()). 530 * (See also read_buf()).
531 */ 531 */
532local void flush_pending(strm) 532local void flush_pending(strm)
533 z_streamp strm; 533 z_streamp strm;
534{ 534{
535 unsigned len = strm->state->pending; 535 unsigned len = strm->state->pending;
536 536
537 if (len > strm->avail_out) len = strm->avail_out; 537 if (len > strm->avail_out) len = strm->avail_out;
538 if (len == 0) return; 538 if (len == 0) return;
539 539
540 zmemcpy(strm->next_out, strm->state->pending_out, len); 540 zmemcpy(strm->next_out, strm->state->pending_out, len);
541 strm->next_out += len; 541 strm->next_out += len;
542 strm->state->pending_out += len; 542 strm->state->pending_out += len;
543 strm->total_out += len; 543 strm->total_out += len;
544 strm->avail_out -= len; 544 strm->avail_out -= len;
545 strm->state->pending -= len; 545 strm->state->pending -= len;
546 if (strm->state->pending == 0) { 546 if (strm->state->pending == 0) {
547 strm->state->pending_out = strm->state->pending_buf; 547 strm->state->pending_out = strm->state->pending_buf;
548 } 548 }
549} 549}
550 550
551/* ========================================================================= */ 551/* ========================================================================= */
552int ZEXPORT deflate (strm, flush) 552int ZEXPORT deflate (strm, flush)
553 z_streamp strm; 553 z_streamp strm;
554 int flush; 554 int flush;
555{ 555{
556 int old_flush; /* value of flush param for previous deflate call */ 556 int old_flush; /* value of flush param for previous deflate call */
557 deflate_state *s; 557 deflate_state *s;
558 558
559 if (strm == Z_NULL || strm->state == Z_NULL || 559 if (strm == Z_NULL || strm->state == Z_NULL ||
560 flush > Z_FINISH || flush < 0) { 560 flush > Z_FINISH || flush < 0) {
561 return Z_STREAM_ERROR; 561 return Z_STREAM_ERROR;
562 } 562 }
563 s = strm->state; 563 s = strm->state;
564 564
565 if (strm->next_out == Z_NULL || 565 if (strm->next_out == Z_NULL ||
566 (strm->next_in == Z_NULL && strm->avail_in != 0) || 566 (strm->next_in == Z_NULL && strm->avail_in != 0) ||
567 (s->status == FINISH_STATE && flush != Z_FINISH)) { 567 (s->status == FINISH_STATE && flush != Z_FINISH)) {
568 ERR_RETURN(strm, Z_STREAM_ERROR); 568 ERR_RETURN(strm, Z_STREAM_ERROR);
569 } 569 }
570 if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); 570 if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
571 571
572 s->strm = strm; /* just in case */ 572 s->strm = strm; /* just in case */
573 old_flush = s->last_flush; 573 old_flush = s->last_flush;
574 s->last_flush = flush; 574 s->last_flush = flush;
575 575
576 /* Write the header */ 576 /* Write the header */
577 if (s->status == INIT_STATE) { 577 if (s->status == INIT_STATE) {
578#ifdef GZIP 578#ifdef GZIP
579 if (s->wrap == 2) { 579 if (s->wrap == 2) {
580 strm->adler = crc32(0L, Z_NULL, 0); 580 strm->adler = crc32(0L, Z_NULL, 0);
581 put_byte(s, 31); 581 put_byte(s, 31);
582 put_byte(s, 139); 582 put_byte(s, 139);
583 put_byte(s, 8); 583 put_byte(s, 8);
584 if (s->gzhead == NULL) { 584 if (s->gzhead == NULL) {
585 put_byte(s, 0); 585 put_byte(s, 0);
586 put_byte(s, 0); 586 put_byte(s, 0);
587 put_byte(s, 0); 587 put_byte(s, 0);
588 put_byte(s, 0); 588 put_byte(s, 0);
589 put_byte(s, 0); 589 put_byte(s, 0);
590 put_byte(s, s->level == 9 ? 2 : 590 put_byte(s, s->level == 9 ? 2 :
591 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 591 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
592 4 : 0)); 592 4 : 0));
593 put_byte(s, OS_CODE); 593 put_byte(s, OS_CODE);
594 s->status = BUSY_STATE; 594 s->status = BUSY_STATE;
595 } 595 }
596 else { 596 else {
597 put_byte(s, (s->gzhead->text ? 1 : 0) + 597 put_byte(s, (s->gzhead->text ? 1 : 0) +
598 (s->gzhead->hcrc ? 2 : 0) + 598 (s->gzhead->hcrc ? 2 : 0) +
599 (s->gzhead->extra == Z_NULL ? 0 : 4) + 599 (s->gzhead->extra == Z_NULL ? 0 : 4) +
600 (s->gzhead->name == Z_NULL ? 0 : 8) + 600 (s->gzhead->name == Z_NULL ? 0 : 8) +
601 (s->gzhead->comment == Z_NULL ? 0 : 16) 601 (s->gzhead->comment == Z_NULL ? 0 : 16)
602 ); 602 );
603 put_byte(s, (Byte)(s->gzhead->time & 0xff)); 603 put_byte(s, (Byte)(s->gzhead->time & 0xff));
604 put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); 604 put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
605 put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); 605 put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
606 put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); 606 put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
607 put_byte(s, s->level == 9 ? 2 : 607 put_byte(s, s->level == 9 ? 2 :
608 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 608 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
609 4 : 0)); 609 4 : 0));
610 put_byte(s, s->gzhead->os & 0xff); 610 put_byte(s, s->gzhead->os & 0xff);
611 if (s->gzhead->extra != NULL) { 611 if (s->gzhead->extra != NULL) {
612 put_byte(s, s->gzhead->extra_len & 0xff); 612 put_byte(s, s->gzhead->extra_len & 0xff);
613 put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); 613 put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
614 } 614 }
615 if (s->gzhead->hcrc) 615 if (s->gzhead->hcrc)
616 strm->adler = crc32(strm->adler, s->pending_buf, 616 strm->adler = crc32(strm->adler, s->pending_buf,
617 s->pending); 617 s->pending);
618 s->gzindex = 0; 618 s->gzindex = 0;
619 s->status = EXTRA_STATE; 619 s->status = EXTRA_STATE;
620 } 620 }
621 } 621 }
622 else 622 else
623#endif 623#endif
624 { 624 {
625 uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; 625 uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
626 uInt level_flags; 626 uInt level_flags;
627 627
628 if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) 628 if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
629 level_flags = 0; 629 level_flags = 0;
630 else if (s->level < 6) 630 else if (s->level < 6)
631 level_flags = 1; 631 level_flags = 1;
632 else if (s->level == 6) 632 else if (s->level == 6)
633 level_flags = 2; 633 level_flags = 2;
634 else 634 else
635 level_flags = 3; 635 level_flags = 3;
636 header |= (level_flags << 6); 636 header |= (level_flags << 6);
637 if (s->strstart != 0) header |= PRESET_DICT; 637 if (s->strstart != 0) header |= PRESET_DICT;
638 header += 31 - (header % 31); 638 header += 31 - (header % 31);
639 639
640 s->status = BUSY_STATE; 640 s->status = BUSY_STATE;
641 putShortMSB(s, header); 641 putShortMSB(s, header);
642 642
643 /* Save the adler32 of the preset dictionary: */ 643 /* Save the adler32 of the preset dictionary: */
644 if (s->strstart != 0) { 644 if (s->strstart != 0) {
645 putShortMSB(s, (uInt)(strm->adler >> 16)); 645 putShortMSB(s, (uInt)(strm->adler >> 16));
646 putShortMSB(s, (uInt)(strm->adler & 0xffff)); 646 putShortMSB(s, (uInt)(strm->adler & 0xffff));
647 } 647 }
648 strm->adler = adler32(0L, Z_NULL, 0); 648 strm->adler = adler32(0L, Z_NULL, 0);
649 } 649 }
650 } 650 }
651#ifdef GZIP 651#ifdef GZIP
652 if (s->status == EXTRA_STATE) { 652 if (s->status == EXTRA_STATE) {
653 if (s->gzhead->extra != NULL) { 653 if (s->gzhead->extra != NULL) {
654 uInt beg = s->pending; /* start of bytes to update crc */ 654 uInt beg = s->pending; /* start of bytes to update crc */
655 655
656 while (s->gzindex < (s->gzhead->extra_len & 0xffff)) { 656 while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
657 if (s->pending == s->pending_buf_size) { 657 if (s->pending == s->pending_buf_size) {
658 if (s->gzhead->hcrc && s->pending > beg) 658 if (s->gzhead->hcrc && s->pending > beg)
659 strm->adler = crc32(strm->adler, s->pending_buf + beg, 659 strm->adler = crc32(strm->adler, s->pending_buf + beg,
660 s->pending - beg); 660 s->pending - beg);
661 flush_pending(strm); 661 flush_pending(strm);
662 beg = s->pending; 662 beg = s->pending;
663 if (s->pending == s->pending_buf_size) 663 if (s->pending == s->pending_buf_size)
664 break; 664 break;
665 } 665 }
666 put_byte(s, s->gzhead->extra[s->gzindex]); 666 put_byte(s, s->gzhead->extra[s->gzindex]);
667 s->gzindex++; 667 s->gzindex++;
668 } 668 }
669 if (s->gzhead->hcrc && s->pending > beg) 669 if (s->gzhead->hcrc && s->pending > beg)
670 strm->adler = crc32(strm->adler, s->pending_buf + beg, 670 strm->adler = crc32(strm->adler, s->pending_buf + beg,
671 s->pending - beg); 671 s->pending - beg);
672 if (s->gzindex == s->gzhead->extra_len) { 672 if (s->gzindex == s->gzhead->extra_len) {
673 s->gzindex = 0; 673 s->gzindex = 0;
674 s->status = NAME_STATE; 674 s->status = NAME_STATE;
675 } 675 }
676 } 676 }
677 else 677 else
678 s->status = NAME_STATE; 678 s->status = NAME_STATE;
679 } 679 }
680 if (s->status == NAME_STATE) { 680 if (s->status == NAME_STATE) {
681 if (s->gzhead->name != NULL) { 681 if (s->gzhead->name != NULL) {
682 uInt beg = s->pending; /* start of bytes to update crc */ 682 uInt beg = s->pending; /* start of bytes to update crc */
683 int val; 683 int val;
684 684
685 do { 685 do {
686 if (s->pending == s->pending_buf_size) { 686 if (s->pending == s->pending_buf_size) {
687 if (s->gzhead->hcrc && s->pending > beg) 687 if (s->gzhead->hcrc && s->pending > beg)
688 strm->adler = crc32(strm->adler, s->pending_buf + beg, 688 strm->adler = crc32(strm->adler, s->pending_buf + beg,
689 s->pending - beg); 689 s->pending - beg);
690 flush_pending(strm); 690 flush_pending(strm);
691 beg = s->pending; 691 beg = s->pending;
692 if (s->pending == s->pending_buf_size) { 692 if (s->pending == s->pending_buf_size) {
693 val = 1; 693 val = 1;
694 break; 694 break;
695 } 695 }
696 } 696 }
697 val = s->gzhead->name[s->gzindex++]; 697 val = s->gzhead->name[s->gzindex++];
698 put_byte(s, val); 698 put_byte(s, val);
699 } while (val != 0); 699 } while (val != 0);
700 if (s->gzhead->hcrc && s->pending > beg) 700 if (s->gzhead->hcrc && s->pending > beg)
701 strm->adler = crc32(strm->adler, s->pending_buf + beg, 701 strm->adler = crc32(strm->adler, s->pending_buf + beg,
702 s->pending - beg); 702 s->pending - beg);
703 if (val == 0) { 703 if (val == 0) {
704 s->gzindex = 0; 704 s->gzindex = 0;
705 s->status = COMMENT_STATE; 705 s->status = COMMENT_STATE;
706 } 706 }
707 } 707 }
708 else 708 else
709 s->status = COMMENT_STATE; 709 s->status = COMMENT_STATE;
710 } 710 }
711 if (s->status == COMMENT_STATE) { 711 if (s->status == COMMENT_STATE) {
712 if (s->gzhead->comment != NULL) { 712 if (s->gzhead->comment != NULL) {
713 uInt beg = s->pending; /* start of bytes to update crc */ 713 uInt beg = s->pending; /* start of bytes to update crc */
714 int val; 714 int val;
715 715
716 do { 716 do {
717 if (s->pending == s->pending_buf_size) { 717 if (s->pending == s->pending_buf_size) {
718 if (s->gzhead->hcrc && s->pending > beg) 718 if (s->gzhead->hcrc && s->pending > beg)
719 strm->adler = crc32(strm->adler, s->pending_buf + beg, 719 strm->adler = crc32(strm->adler, s->pending_buf + beg,
720 s->pending - beg); 720 s->pending - beg);
721 flush_pending(strm); 721 flush_pending(strm);
722 beg = s->pending; 722 beg = s->pending;
723 if (s->pending == s->pending_buf_size) { 723 if (s->pending == s->pending_buf_size) {
724 val = 1; 724 val = 1;
725 break; 725 break;
726 } 726 }
727 } 727 }
728 val = s->gzhead->comment[s->gzindex++]; 728 val = s->gzhead->comment[s->gzindex++];
729 put_byte(s, val); 729 put_byte(s, val);
730 } while (val != 0); 730 } while (val != 0);
731 if (s->gzhead->hcrc && s->pending > beg) 731 if (s->gzhead->hcrc && s->pending > beg)
732 strm->adler = crc32(strm->adler, s->pending_buf + beg, 732 strm->adler = crc32(strm->adler, s->pending_buf + beg,
733 s->pending - beg); 733 s->pending - beg);
734 if (val == 0) 734 if (val == 0)
735 s->status = HCRC_STATE; 735 s->status = HCRC_STATE;
736 } 736 }
737 else 737 else
738 s->status = HCRC_STATE; 738 s->status = HCRC_STATE;
739 } 739 }
740 if (s->status == HCRC_STATE) { 740 if (s->status == HCRC_STATE) {
741 if (s->gzhead->hcrc) { 741 if (s->gzhead->hcrc) {
742 if (s->pending + 2 > s->pending_buf_size) 742 if (s->pending + 2 > s->pending_buf_size)
743 flush_pending(strm); 743 flush_pending(strm);
744 if (s->pending + 2 <= s->pending_buf_size) { 744 if (s->pending + 2 <= s->pending_buf_size) {
745 put_byte(s, (Byte)(strm->adler & 0xff)); 745 put_byte(s, (Byte)(strm->adler & 0xff));
746 put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); 746 put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
747 strm->adler = crc32(0L, Z_NULL, 0); 747 strm->adler = crc32(0L, Z_NULL, 0);
748 s->status = BUSY_STATE; 748 s->status = BUSY_STATE;
749 } 749 }
750 } 750 }
751 else 751 else
752 s->status = BUSY_STATE; 752 s->status = BUSY_STATE;
753 } 753 }
754#endif 754#endif
755 755
756 /* Flush as much pending output as possible */ 756 /* Flush as much pending output as possible */
757 if (s->pending != 0) { 757 if (s->pending != 0) {
758 flush_pending(strm); 758 flush_pending(strm);
759 if (strm->avail_out == 0) { 759 if (strm->avail_out == 0) {
760 /* Since avail_out is 0, deflate will be called again with 760 /* Since avail_out is 0, deflate will be called again with
761 * more output space, but possibly with both pending and 761 * more output space, but possibly with both pending and
762 * avail_in equal to zero. There won't be anything to do, 762 * avail_in equal to zero. There won't be anything to do,
763 * but this is not an error situation so make sure we 763 * but this is not an error situation so make sure we
764 * return OK instead of BUF_ERROR at next call of deflate: 764 * return OK instead of BUF_ERROR at next call of deflate:
765 */ 765 */
766 s->last_flush = -1; 766 s->last_flush = -1;
767 return Z_OK; 767 return Z_OK;
768 } 768 }
769 769
770 /* Make sure there is something to do and avoid duplicate consecutive 770 /* Make sure there is something to do and avoid duplicate consecutive
771 * flushes. For repeated and useless calls with Z_FINISH, we keep 771 * flushes. For repeated and useless calls with Z_FINISH, we keep
772 * returning Z_STREAM_END instead of Z_BUF_ERROR. 772 * returning Z_STREAM_END instead of Z_BUF_ERROR.
773 */ 773 */
774 } else if (strm->avail_in == 0 && flush <= old_flush && 774 } else if (strm->avail_in == 0 && flush <= old_flush &&
775 flush != Z_FINISH) { 775 flush != Z_FINISH) {
776 ERR_RETURN(strm, Z_BUF_ERROR); 776 ERR_RETURN(strm, Z_BUF_ERROR);
777 } 777 }
778 778
779 /* User must not provide more input after the first FINISH: */ 779 /* User must not provide more input after the first FINISH: */
780 if (s->status == FINISH_STATE && strm->avail_in != 0) { 780 if (s->status == FINISH_STATE && strm->avail_in != 0) {
781 ERR_RETURN(strm, Z_BUF_ERROR); 781 ERR_RETURN(strm, Z_BUF_ERROR);
782 } 782 }
783 783
784 /* Start a new block or continue the current one. 784 /* Start a new block or continue the current one.
785 */ 785 */
786 if (strm->avail_in != 0 || s->lookahead != 0 || 786 if (strm->avail_in != 0 || s->lookahead != 0 ||
787 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { 787 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
788 block_state bstate; 788 block_state bstate;
789 789
790 bstate = (*(configuration_table[s->level].func))(s, flush); 790 bstate = (*(configuration_table[s->level].func))(s, flush);
791 791
792 if (bstate == finish_started || bstate == finish_done) { 792 if (bstate == finish_started || bstate == finish_done) {
793 s->status = FINISH_STATE; 793 s->status = FINISH_STATE;
794 } 794 }
795 if (bstate == need_more || bstate == finish_started) { 795 if (bstate == need_more || bstate == finish_started) {
796 if (strm->avail_out == 0) { 796 if (strm->avail_out == 0) {
797 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ 797 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
798 } 798 }
799 return Z_OK; 799 return Z_OK;
800 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call 800 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
801 * of deflate should use the same flush parameter to make sure 801 * of deflate should use the same flush parameter to make sure
802 * that the flush is complete. So we don't have to output an 802 * that the flush is complete. So we don't have to output an
803 * empty block here, this will be done at next call. This also 803 * empty block here, this will be done at next call. This also
804 * ensures that for a very small output buffer, we emit at most 804 * ensures that for a very small output buffer, we emit at most
805 * one empty block. 805 * one empty block.
806 */ 806 */
807 } 807 }
808 if (bstate == block_done) { 808 if (bstate == block_done) {
809 if (flush == Z_PARTIAL_FLUSH) { 809 if (flush == Z_PARTIAL_FLUSH) {
810 _tr_align(s); 810 _tr_align(s);
811 } else { /* FULL_FLUSH or SYNC_FLUSH */ 811 } else { /* FULL_FLUSH or SYNC_FLUSH */
812 _tr_stored_block(s, (char*)0, 0L, 0); 812 _tr_stored_block(s, (char*)0, 0L, 0);
813 /* For a full flush, this empty block will be recognized 813 /* For a full flush, this empty block will be recognized
814 * as a special marker by inflate_sync(). 814 * as a special marker by inflate_sync().
815 */ 815 */
816 if (flush == Z_FULL_FLUSH) { 816 if (flush == Z_FULL_FLUSH) {
817 CLEAR_HASH(s); /* forget history */ 817 CLEAR_HASH(s); /* forget history */
818 } 818 }
819 } 819 }
820 flush_pending(strm); 820 flush_pending(strm);
821 if (strm->avail_out == 0) { 821 if (strm->avail_out == 0) {
822 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ 822 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
823 return Z_OK; 823 return Z_OK;
824 } 824 }
825 } 825 }
826 } 826 }
827 Assert(strm->avail_out > 0, "bug2"); 827 Assert(strm->avail_out > 0, "bug2");
828 828
829 if (flush != Z_FINISH) return Z_OK; 829 if (flush != Z_FINISH) return Z_OK;
830 if (s->wrap <= 0) return Z_STREAM_END; 830 if (s->wrap <= 0) return Z_STREAM_END;
831 831
832 /* Write the trailer */ 832 /* Write the trailer */
833#ifdef GZIP 833#ifdef GZIP
834 if (s->wrap == 2) { 834 if (s->wrap == 2) {
835 put_byte(s, (Byte)(strm->adler & 0xff)); 835 put_byte(s, (Byte)(strm->adler & 0xff));
836 put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); 836 put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
837 put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); 837 put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
838 put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); 838 put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
839 put_byte(s, (Byte)(strm->total_in & 0xff)); 839 put_byte(s, (Byte)(strm->total_in & 0xff));
840 put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); 840 put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
841 put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); 841 put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
842 put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); 842 put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
843 } 843 }
844 else 844 else
845#endif 845#endif
846 { 846 {
847 putShortMSB(s, (uInt)(strm->adler >> 16)); 847 putShortMSB(s, (uInt)(strm->adler >> 16));
848 putShortMSB(s, (uInt)(strm->adler & 0xffff)); 848 putShortMSB(s, (uInt)(strm->adler & 0xffff));
849 } 849 }
850 flush_pending(strm); 850 flush_pending(strm);
851 /* If avail_out is zero, the application will call deflate again 851 /* If avail_out is zero, the application will call deflate again
852 * to flush the rest. 852 * to flush the rest.
853 */ 853 */
854 if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ 854 if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
855 return s->pending != 0 ? Z_OK : Z_STREAM_END; 855 return s->pending != 0 ? Z_OK : Z_STREAM_END;
856} 856}
857 857
858/* ========================================================================= */ 858/* ========================================================================= */
859int ZEXPORT deflateEnd (strm) 859int ZEXPORT deflateEnd (strm)
860 z_streamp strm; 860 z_streamp strm;
861{ 861{
862 int status; 862 int status;
863 863
864 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; 864 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
865 865
866 status = strm->state->status; 866 status = strm->state->status;
867 if (status != INIT_STATE && 867 if (status != INIT_STATE &&
868 status != EXTRA_STATE && 868 status != EXTRA_STATE &&
869 status != NAME_STATE && 869 status != NAME_STATE &&
870 status != COMMENT_STATE && 870 status != COMMENT_STATE &&
871 status != HCRC_STATE && 871 status != HCRC_STATE &&
872 status != BUSY_STATE && 872 status != BUSY_STATE &&
873 status != FINISH_STATE) { 873 status != FINISH_STATE) {
874 return Z_STREAM_ERROR; 874 return Z_STREAM_ERROR;
875 } 875 }
876 876
877 /* Deallocate in reverse order of allocations: */ 877 /* Deallocate in reverse order of allocations: */
878 TRY_FREE(strm, strm->state->pending_buf); 878 TRY_FREE(strm, strm->state->pending_buf);
879 TRY_FREE(strm, strm->state->head); 879 TRY_FREE(strm, strm->state->head);
880 TRY_FREE(strm, strm->state->prev); 880 TRY_FREE(strm, strm->state->prev);
881 TRY_FREE(strm, strm->state->window); 881 TRY_FREE(strm, strm->state->window);
882 882
883 ZFREE(strm, strm->state); 883 ZFREE(strm, strm->state);
884 strm->state = Z_NULL; 884 strm->state = Z_NULL;
885 885
886 return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; 886 return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
887} 887}
888 888
889/* ========================================================================= 889/* =========================================================================
890 * Copy the source state to the destination state. 890 * Copy the source state to the destination state.
891 * To simplify the source, this is not supported for 16-bit MSDOS (which 891 * To simplify the source, this is not supported for 16-bit MSDOS (which
892 * doesn't have enough memory anyway to duplicate compression states). 892 * doesn't have enough memory anyway to duplicate compression states).
893 */ 893 */
894int ZEXPORT deflateCopy (dest, source) 894int ZEXPORT deflateCopy (dest, source)
895 z_streamp dest; 895 z_streamp dest;
896 z_streamp source; 896 z_streamp source;
897{ 897{
898#ifdef MAXSEG_64K 898#ifdef MAXSEG_64K
899 return Z_STREAM_ERROR; 899 return Z_STREAM_ERROR;
900#else 900#else
901 deflate_state *ds; 901 deflate_state *ds;
902 deflate_state *ss; 902 deflate_state *ss;
903 ushf *overlay; 903 ushf *overlay;
904 904
905 905
906 if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) { 906 if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
907 return Z_STREAM_ERROR; 907 return Z_STREAM_ERROR;
908 } 908 }
909 909
910 ss = source->state; 910 ss = source->state;
911 911
912 zmemcpy(dest, source, sizeof(z_stream)); 912 zmemcpy(dest, source, sizeof(z_stream));
913 913
914 ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); 914 ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
915 if (ds == Z_NULL) return Z_MEM_ERROR; 915 if (ds == Z_NULL) return Z_MEM_ERROR;
916 dest->state = (struct internal_state FAR *) ds; 916 dest->state = (struct internal_state FAR *) ds;
917 zmemcpy(ds, ss, sizeof(deflate_state)); 917 zmemcpy(ds, ss, sizeof(deflate_state));
918 ds->strm = dest; 918 ds->strm = dest;
919 919
920 ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); 920 ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
921 ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); 921 ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
922 ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); 922 ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
923 overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); 923 overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
924 ds->pending_buf = (uchf *) overlay; 924 ds->pending_buf = (uchf *) overlay;
925 925
926 if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || 926 if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
927 ds->pending_buf == Z_NULL) { 927 ds->pending_buf == Z_NULL) {
928 deflateEnd (dest); 928 deflateEnd (dest);
929 return Z_MEM_ERROR; 929 return Z_MEM_ERROR;
930 } 930 }
931 /* following zmemcpy do not work for 16-bit MSDOS */ 931 /* following zmemcpy do not work for 16-bit MSDOS */
932 zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); 932 zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
933 zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos)); 933 zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
934 zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos)); 934 zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
935 zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); 935 zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
936 936
937 ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); 937 ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
938 ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); 938 ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
939 ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; 939 ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
940 940
941 ds->l_desc.dyn_tree = ds->dyn_ltree; 941 ds->l_desc.dyn_tree = ds->dyn_ltree;
942 ds->d_desc.dyn_tree = ds->dyn_dtree; 942 ds->d_desc.dyn_tree = ds->dyn_dtree;
943 ds->bl_desc.dyn_tree = ds->bl_tree; 943 ds->bl_desc.dyn_tree = ds->bl_tree;
944 944
945 return Z_OK; 945 return Z_OK;
946#endif /* MAXSEG_64K */ 946#endif /* MAXSEG_64K */
947} 947}
948 948
949/* =========================================================================== 949/* ===========================================================================
950 * Read a new buffer from the current input stream, update the adler32 950 * Read a new buffer from the current input stream, update the adler32
951 * and total number of bytes read. All deflate() input goes through 951 * and total number of bytes read. All deflate() input goes through
952 * this function so some applications may wish to modify it to avoid 952 * this function so some applications may wish to modify it to avoid
953 * allocating a large strm->next_in buffer and copying from it. 953 * allocating a large strm->next_in buffer and copying from it.
954 * (See also flush_pending()). 954 * (See also flush_pending()).
955 */ 955 */
956local int read_buf(strm, buf, size) 956local int read_buf(strm, buf, size)
957 z_streamp strm; 957 z_streamp strm;
958 Bytef *buf; 958 Bytef *buf;
959 unsigned size; 959 unsigned size;
960{ 960{
961 unsigned len = strm->avail_in; 961 unsigned len = strm->avail_in;
962 962
963 if (len > size) len = size; 963 if (len > size) len = size;
964 if (len == 0) return 0; 964 if (len == 0) return 0;
965 965
966 strm->avail_in -= len; 966 strm->avail_in -= len;
967 967
968 if (strm->state->wrap == 1) { 968 if (strm->state->wrap == 1) {
969 strm->adler = adler32(strm->adler, strm->next_in, len); 969 strm->adler = adler32(strm->adler, strm->next_in, len);
970 } 970 }
971#ifdef GZIP 971#ifdef GZIP
972 else if (strm->state->wrap == 2) { 972 else if (strm->state->wrap == 2) {
973 strm->adler = crc32(strm->adler, strm->next_in, len); 973 strm->adler = crc32(strm->adler, strm->next_in, len);
974 } 974 }
975#endif 975#endif
976 zmemcpy(buf, strm->next_in, len); 976 zmemcpy(buf, strm->next_in, len);
977 strm->next_in += len; 977 strm->next_in += len;
978 strm->total_in += len; 978 strm->total_in += len;
979 979
980 return (int)len; 980 return (int)len;
981} 981}
982 982
983/* =========================================================================== 983/* ===========================================================================
984 * Initialize the "longest match" routines for a new zlib stream 984 * Initialize the "longest match" routines for a new zlib stream
985 */ 985 */
986local void lm_init (s) 986local void lm_init (s)
987 deflate_state *s; 987 deflate_state *s;
988{ 988{
989 s->window_size = (ulg)2L*s->w_size; 989 s->window_size = (ulg)2L*s->w_size;
990 990
991 CLEAR_HASH(s); 991 CLEAR_HASH(s);
992 992
993 /* Set the default configuration parameters: 993 /* Set the default configuration parameters:
994 */ 994 */
995 s->max_lazy_match = configuration_table[s->level].max_lazy; 995 s->max_lazy_match = configuration_table[s->level].max_lazy;
996 s->good_match = configuration_table[s->level].good_length; 996 s->good_match = configuration_table[s->level].good_length;
997 s->nice_match = configuration_table[s->level].nice_length; 997 s->nice_match = configuration_table[s->level].nice_length;
998 s->max_chain_length = configuration_table[s->level].max_chain; 998 s->max_chain_length = configuration_table[s->level].max_chain;
999 999
1000 s->strstart = 0; 1000 s->strstart = 0;
1001 s->block_start = 0L; 1001 s->block_start = 0L;
1002 s->lookahead = 0; 1002 s->lookahead = 0;
1003 s->match_length = s->prev_length = MIN_MATCH-1; 1003 s->match_length = s->prev_length = MIN_MATCH-1;
1004 s->match_available = 0; 1004 s->match_available = 0;
1005 s->ins_h = 0; 1005 s->ins_h = 0;
1006#ifndef FASTEST 1006#ifndef FASTEST
1007#ifdef ASMV 1007#ifdef ASMV
1008 match_init(); /* initialize the asm code */ 1008 match_init(); /* initialize the asm code */
1009#endif 1009#endif
1010#endif 1010#endif
1011} 1011}
1012 1012
1013#ifndef FASTEST 1013#ifndef FASTEST
1014/* =========================================================================== 1014/* ===========================================================================
1015 * Set match_start to the longest match starting at the given string and 1015 * Set match_start to the longest match starting at the given string and
1016 * return its length. Matches shorter or equal to prev_length are discarded, 1016 * return its length. Matches shorter or equal to prev_length are discarded,
1017 * in which case the result is equal to prev_length and match_start is 1017 * in which case the result is equal to prev_length and match_start is
1018 * garbage. 1018 * garbage.
1019 * IN assertions: cur_match is the head of the hash chain for the current 1019 * IN assertions: cur_match is the head of the hash chain for the current
1020 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 1020 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1021 * OUT assertion: the match length is not greater than s->lookahead. 1021 * OUT assertion: the match length is not greater than s->lookahead.
1022 */ 1022 */
1023#ifndef ASMV 1023#ifndef ASMV
1024/* For 80x86 and 680x0, an optimized version will be provided in match.asm or 1024/* For 80x86 and 680x0, an optimized version will be provided in match.asm or
1025 * match.S. The code will be functionally equivalent. 1025 * match.S. The code will be functionally equivalent.
1026 */ 1026 */
1027local uInt longest_match(s, cur_match) 1027local uInt longest_match(s, cur_match)
1028 deflate_state *s; 1028 deflate_state *s;
1029 IPos cur_match; /* current match */ 1029 IPos cur_match; /* current match */
1030{ 1030{
1031 unsigned chain_length = s->max_chain_length;/* max hash chain length */ 1031 unsigned chain_length = s->max_chain_length;/* max hash chain length */
1032 register Bytef *scan = s->window + s->strstart; /* current string */ 1032 register Bytef *scan = s->window + s->strstart; /* current string */
1033 register Bytef *match; /* matched string */ 1033 register Bytef *match; /* matched string */
1034 register int len; /* length of current match */ 1034 register int len; /* length of current match */
1035 int best_len = s->prev_length; /* best match length so far */ 1035 int best_len = s->prev_length; /* best match length so far */
1036 int nice_match = s->nice_match; /* stop if match long enough */ 1036 int nice_match = s->nice_match; /* stop if match long enough */
1037 IPos limit = s->strstart > (IPos)MAX_DIST(s) ? 1037 IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
1038 s->strstart - (IPos)MAX_DIST(s) : NIL; 1038 s->strstart - (IPos)MAX_DIST(s) : NIL;
1039 /* Stop when cur_match becomes <= limit. To simplify the code, 1039 /* Stop when cur_match becomes <= limit. To simplify the code,
1040 * we prevent matches with the string of window index 0. 1040 * we prevent matches with the string of window index 0.
1041 */ 1041 */
1042 Posf *prev = s->prev; 1042 Posf *prev = s->prev;
1043 uInt wmask = s->w_mask; 1043 uInt wmask = s->w_mask;
1044 1044
1045#ifdef UNALIGNED_OK 1045#ifdef UNALIGNED_OK
1046 /* Compare two bytes at a time. Note: this is not always beneficial. 1046 /* Compare two bytes at a time. Note: this is not always beneficial.
1047 * Try with and without -DUNALIGNED_OK to check. 1047 * Try with and without -DUNALIGNED_OK to check.
1048 */ 1048 */
1049 register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; 1049 register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
1050 register ush scan_start = *(ushf*)scan; 1050 register ush scan_start = *(ushf*)scan;
1051 register ush scan_end = *(ushf*)(scan+best_len-1); 1051 register ush scan_end = *(ushf*)(scan+best_len-1);
1052#else 1052#else
1053 register Bytef *strend = s->window + s->strstart + MAX_MATCH; 1053 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1054 register Byte scan_end1 = scan[best_len-1]; 1054 register Byte scan_end1 = scan[best_len-1];
1055 register Byte scan_end = scan[best_len]; 1055 register Byte scan_end = scan[best_len];
1056#endif 1056#endif
1057 1057
1058 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. 1058 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1059 * It is easy to get rid of this optimization if necessary. 1059 * It is easy to get rid of this optimization if necessary.
1060 */ 1060 */
1061 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); 1061 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1062 1062
1063 /* Do not waste too much time if we already have a good match: */ 1063 /* Do not waste too much time if we already have a good match: */
1064 if (s->prev_length >= s->good_match) { 1064 if (s->prev_length >= s->good_match) {
1065 chain_length >>= 2; 1065 chain_length >>= 2;
1066 } 1066 }
1067 /* Do not look for matches beyond the end of the input. This is necessary 1067 /* Do not look for matches beyond the end of the input. This is necessary
1068 * to make deflate deterministic. 1068 * to make deflate deterministic.
1069 */ 1069 */
1070 if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; 1070 if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
1071 1071
1072 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); 1072 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1073 1073
1074 do { 1074 do {
1075 Assert(cur_match < s->strstart, "no future"); 1075 Assert(cur_match < s->strstart, "no future");
1076 match = s->window + cur_match; 1076 match = s->window + cur_match;
1077 1077
1078 /* Skip to next match if the match length cannot increase 1078 /* Skip to next match if the match length cannot increase
1079 * or if the match length is less than 2. Note that the checks below 1079 * or if the match length is less than 2. Note that the checks below
1080 * for insufficient lookahead only occur occasionally for performance 1080 * for insufficient lookahead only occur occasionally for performance
1081 * reasons. Therefore uninitialized memory will be accessed, and 1081 * reasons. Therefore uninitialized memory will be accessed, and
1082 * conditional jumps will be made that depend on those values. 1082 * conditional jumps will be made that depend on those values.
1083 * However the length of the match is limited to the lookahead, so 1083 * However the length of the match is limited to the lookahead, so
1084 * the output of deflate is not affected by the uninitialized values. 1084 * the output of deflate is not affected by the uninitialized values.
1085 */ 1085 */
1086#if (defined(UNALIGNED_OK) && MAX_MATCH == 258) 1086#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
1087 /* This code assumes sizeof(unsigned short) == 2. Do not use 1087 /* This code assumes sizeof(unsigned short) == 2. Do not use
1088 * UNALIGNED_OK if your compiler uses a different size. 1088 * UNALIGNED_OK if your compiler uses a different size.
1089 */ 1089 */
1090 if (*(ushf*)(match+best_len-1) != scan_end || 1090 if (*(ushf*)(match+best_len-1) != scan_end ||
1091 *(ushf*)match != scan_start) continue; 1091 *(ushf*)match != scan_start) continue;
1092 1092
1093 /* It is not necessary to compare scan[2] and match[2] since they are 1093 /* It is not necessary to compare scan[2] and match[2] since they are
1094 * always equal when the other bytes match, given that the hash keys 1094 * always equal when the other bytes match, given that the hash keys
1095 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at 1095 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1096 * strstart+3, +5, ... up to strstart+257. We check for insufficient 1096 * strstart+3, +5, ... up to strstart+257. We check for insufficient
1097 * lookahead only every 4th comparison; the 128th check will be made 1097 * lookahead only every 4th comparison; the 128th check will be made
1098 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is 1098 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
1099 * necessary to put more guard bytes at the end of the window, or 1099 * necessary to put more guard bytes at the end of the window, or
1100 * to check more often for insufficient lookahead. 1100 * to check more often for insufficient lookahead.
1101 */ 1101 */
1102 Assert(scan[2] == match[2], "scan[2]?"); 1102 Assert(scan[2] == match[2], "scan[2]?");
1103 scan++, match++; 1103 scan++, match++;
1104 do { 1104 do {
1105 } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && 1105 } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1106 *(ushf*)(scan+=2) == *(ushf*)(match+=2) && 1106 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1107 *(ushf*)(scan+=2) == *(ushf*)(match+=2) && 1107 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1108 *(ushf*)(scan+=2) == *(ushf*)(match+=2) && 1108 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1109 scan < strend); 1109 scan < strend);
1110 /* The funny "do {}" generates better code on most compilers */ 1110 /* The funny "do {}" generates better code on most compilers */
1111 1111
1112 /* Here, scan <= window+strstart+257 */ 1112 /* Here, scan <= window+strstart+257 */
1113 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); 1113 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1114 if (*scan == *match) scan++; 1114 if (*scan == *match) scan++;
1115 1115
1116 len = (MAX_MATCH - 1) - (int)(strend-scan); 1116 len = (MAX_MATCH - 1) - (int)(strend-scan);
1117 scan = strend - (MAX_MATCH-1); 1117 scan = strend - (MAX_MATCH-1);
1118 1118
1119#else /* UNALIGNED_OK */ 1119#else /* UNALIGNED_OK */
1120 1120
1121 if (match[best_len] != scan_end || 1121 if (match[best_len] != scan_end ||
1122 match[best_len-1] != scan_end1 || 1122 match[best_len-1] != scan_end1 ||
1123 *match != *scan || 1123 *match != *scan ||
1124 *++match != scan[1]) continue; 1124 *++match != scan[1]) continue;
1125 1125
1126 /* The check at best_len-1 can be removed because it will be made 1126 /* The check at best_len-1 can be removed because it will be made
1127 * again later. (This heuristic is not always a win.) 1127 * again later. (This heuristic is not always a win.)
1128 * It is not necessary to compare scan[2] and match[2] since they 1128 * It is not necessary to compare scan[2] and match[2] since they
1129 * are always equal when the other bytes match, given that 1129 * are always equal when the other bytes match, given that
1130 * the hash keys are equal and that HASH_BITS >= 8. 1130 * the hash keys are equal and that HASH_BITS >= 8.
1131 */ 1131 */
1132 scan += 2, match++; 1132 scan += 2, match++;
1133 Assert(*scan == *match, "match[2]?"); 1133 Assert(*scan == *match, "match[2]?");
1134 1134
1135 /* We check for insufficient lookahead only every 8th comparison; 1135 /* We check for insufficient lookahead only every 8th comparison;
1136 * the 256th check will be made at strstart+258. 1136 * the 256th check will be made at strstart+258.
1137 */ 1137 */
1138 do { 1138 do {
1139 } while (*++scan == *++match && *++scan == *++match && 1139 } while (*++scan == *++match && *++scan == *++match &&
1140 *++scan == *++match && *++scan == *++match && 1140 *++scan == *++match && *++scan == *++match &&
1141 *++scan == *++match && *++scan == *++match && 1141 *++scan == *++match && *++scan == *++match &&
1142 *++scan == *++match && *++scan == *++match && 1142 *++scan == *++match && *++scan == *++match &&
1143 scan < strend); 1143 scan < strend);
1144 1144
1145 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); 1145 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1146 1146
1147 len = MAX_MATCH - (int)(strend - scan); 1147 len = MAX_MATCH - (int)(strend - scan);
1148 scan = strend - MAX_MATCH; 1148 scan = strend - MAX_MATCH;
1149 1149
1150#endif /* UNALIGNED_OK */ 1150#endif /* UNALIGNED_OK */
1151 1151
1152 if (len > best_len) { 1152 if (len > best_len) {
1153 s->match_start = cur_match; 1153 s->match_start = cur_match;
1154 best_len = len; 1154 best_len = len;
1155 if (len >= nice_match) break; 1155 if (len >= nice_match) break;
1156#ifdef UNALIGNED_OK 1156#ifdef UNALIGNED_OK
1157 scan_end = *(ushf*)(scan+best_len-1); 1157 scan_end = *(ushf*)(scan+best_len-1);
1158#else 1158#else
1159 scan_end1 = scan[best_len-1]; 1159 scan_end1 = scan[best_len-1];
1160 scan_end = scan[best_len]; 1160 scan_end = scan[best_len];
1161#endif 1161#endif
1162 } 1162 }
1163 } while ((cur_match = prev[cur_match & wmask]) > limit 1163 } while ((cur_match = prev[cur_match & wmask]) > limit
1164 && --chain_length != 0); 1164 && --chain_length != 0);
1165 1165
1166 if ((uInt)best_len <= s->lookahead) return (uInt)best_len; 1166 if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
1167 return s->lookahead; 1167 return s->lookahead;
1168} 1168}
1169#endif /* ASMV */ 1169#endif /* ASMV */
1170#endif /* FASTEST */ 1170#endif /* FASTEST */
1171 1171
1172/* --------------------------------------------------------------------------- 1172/* ---------------------------------------------------------------------------
1173 * Optimized version for level == 1 or strategy == Z_RLE only 1173 * Optimized version for level == 1 or strategy == Z_RLE only
1174 */ 1174 */
1175local uInt longest_match_fast(s, cur_match) 1175local uInt longest_match_fast(s, cur_match)
1176 deflate_state *s; 1176 deflate_state *s;
1177 IPos cur_match; /* current match */ 1177 IPos cur_match; /* current match */
1178{ 1178{
1179 register Bytef *scan = s->window + s->strstart; /* current string */ 1179 register Bytef *scan = s->window + s->strstart; /* current string */
1180 register Bytef *match; /* matched string */ 1180 register Bytef *match; /* matched string */
1181 register int len; /* length of current match */ 1181 register int len; /* length of current match */
1182 register Bytef *strend = s->window + s->strstart + MAX_MATCH; 1182 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1183 1183
1184 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. 1184 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1185 * It is easy to get rid of this optimization if necessary. 1185 * It is easy to get rid of this optimization if necessary.
1186 */ 1186 */
1187 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); 1187 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1188 1188
1189 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); 1189 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1190 1190
1191 Assert(cur_match < s->strstart, "no future"); 1191 Assert(cur_match < s->strstart, "no future");
1192 1192
1193 match = s->window + cur_match; 1193 match = s->window + cur_match;
1194 1194
1195 /* Return failure if the match length is less than 2: 1195 /* Return failure if the match length is less than 2:
1196 */ 1196 */
1197 if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; 1197 if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
1198 1198
1199 /* The check at best_len-1 can be removed because it will be made 1199 /* The check at best_len-1 can be removed because it will be made
1200 * again later. (This heuristic is not always a win.) 1200 * again later. (This heuristic is not always a win.)
1201 * It is not necessary to compare scan[2] and match[2] since they 1201 * It is not necessary to compare scan[2] and match[2] since they
1202 * are always equal when the other bytes match, given that 1202 * are always equal when the other bytes match, given that
1203 * the hash keys are equal and that HASH_BITS >= 8. 1203 * the hash keys are equal and that HASH_BITS >= 8.
1204 */ 1204 */
1205 scan += 2, match += 2; 1205 scan += 2, match += 2;
1206 Assert(*scan == *match, "match[2]?"); 1206 Assert(*scan == *match, "match[2]?");
1207 1207
1208 /* We check for insufficient lookahead only every 8th comparison; 1208 /* We check for insufficient lookahead only every 8th comparison;
1209 * the 256th check will be made at strstart+258. 1209 * the 256th check will be made at strstart+258.
1210 */ 1210 */
1211 do { 1211 do {
1212 } while (*++scan == *++match && *++scan == *++match && 1212 } while (*++scan == *++match && *++scan == *++match &&
1213 *++scan == *++match && *++scan == *++match && 1213 *++scan == *++match && *++scan == *++match &&
1214 *++scan == *++match && *++scan == *++match && 1214 *++scan == *++match && *++scan == *++match &&
1215 *++scan == *++match && *++scan == *++match && 1215 *++scan == *++match && *++scan == *++match &&
1216 scan < strend); 1216 scan < strend);
1217 1217
1218 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); 1218 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1219 1219
1220 len = MAX_MATCH - (int)(strend - scan); 1220 len = MAX_MATCH - (int)(strend - scan);
1221 1221
1222 if (len < MIN_MATCH) return MIN_MATCH - 1; 1222 if (len < MIN_MATCH) return MIN_MATCH - 1;
1223 1223
1224 s->match_start = cur_match; 1224 s->match_start = cur_match;
1225 return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; 1225 return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
1226} 1226}
1227 1227
1228#ifdef DEBUG 1228#ifdef DEBUG
1229/* =========================================================================== 1229/* ===========================================================================
1230 * Check that the match at match_start is indeed a match. 1230 * Check that the match at match_start is indeed a match.
1231 */ 1231 */
1232local void check_match(s, start, match, length) 1232local void check_match(s, start, match, length)
1233 deflate_state *s; 1233 deflate_state *s;
1234 IPos start, match; 1234 IPos start, match;
1235 int length; 1235 int length;
1236{ 1236{
1237 /* check that the match is indeed a match */ 1237 /* check that the match is indeed a match */
1238 if (zmemcmp(s->window + match, 1238 if (zmemcmp(s->window + match,
1239 s->window + start, length) != EQUAL) { 1239 s->window + start, length) != EQUAL) {
1240 fprintf(stderr, " start %u, match %u, length %d\n", 1240 fprintf(stderr, " start %u, match %u, length %d\n",
1241 start, match, length); 1241 start, match, length);
1242 do { 1242 do {
1243 fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); 1243 fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
1244 } while (--length != 0); 1244 } while (--length != 0);
1245 z_error("invalid match"); 1245 z_error("invalid match");
1246 } 1246 }
1247 if (z_verbose > 1) { 1247 if (z_verbose > 1) {
1248 fprintf(stderr,"\\[%d,%d]", start-match, length); 1248 fprintf(stderr,"\\[%d,%d]", start-match, length);
1249 do { putc(s->window[start++], stderr); } while (--length != 0); 1249 do { putc(s->window[start++], stderr); } while (--length != 0);
1250 } 1250 }
1251} 1251}
1252#else 1252#else
1253# define check_match(s, start, match, length) 1253# define check_match(s, start, match, length)
1254#endif /* DEBUG */ 1254#endif /* DEBUG */
1255 1255
1256/* =========================================================================== 1256/* ===========================================================================
1257 * Fill the window when the lookahead becomes insufficient. 1257 * Fill the window when the lookahead becomes insufficient.
1258 * Updates strstart and lookahead. 1258 * Updates strstart and lookahead.
1259 * 1259 *
1260 * IN assertion: lookahead < MIN_LOOKAHEAD 1260 * IN assertion: lookahead < MIN_LOOKAHEAD
1261 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD 1261 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1262 * At least one byte has been read, or avail_in == 0; reads are 1262 * At least one byte has been read, or avail_in == 0; reads are
1263 * performed for at least two bytes (required for the zip translate_eol 1263 * performed for at least two bytes (required for the zip translate_eol
1264 * option -- not supported here). 1264 * option -- not supported here).
1265 */ 1265 */
1266local void fill_window(s) 1266local void fill_window(s)
1267 deflate_state *s; 1267 deflate_state *s;
1268{ 1268{
1269 register unsigned n, m; 1269 register unsigned n, m;
1270 register Posf *p; 1270 register Posf *p;
1271 unsigned more; /* Amount of free space at the end of the window. */ 1271 unsigned more; /* Amount of free space at the end of the window. */
1272 uInt wsize = s->w_size; 1272 uInt wsize = s->w_size;
1273 1273
1274 do { 1274 do {
1275 more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); 1275 more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
1276 1276
1277 /* Deal with !@#$% 64K limit: */ 1277 /* Deal with !@#$% 64K limit: */
1278 if (sizeof(int) <= 2) { 1278 if (sizeof(int) <= 2) {
1279 if (more == 0 && s->strstart == 0 && s->lookahead == 0) { 1279 if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1280 more = wsize; 1280 more = wsize;
1281 1281
1282 } else if (more == (unsigned)(-1)) { 1282 } else if (more == (unsigned)(-1)) {
1283 /* Very unlikely, but possible on 16 bit machine if 1283 /* Very unlikely, but possible on 16 bit machine if
1284 * strstart == 0 && lookahead == 1 (input done a byte at time) 1284 * strstart == 0 && lookahead == 1 (input done a byte at time)
1285 */ 1285 */
1286 more--; 1286 more--;
1287 } 1287 }
1288 } 1288 }
1289 1289
1290 /* If the window is almost full and there is insufficient lookahead, 1290 /* If the window is almost full and there is insufficient lookahead,
1291 * move the upper half to the lower one to make room in the upper half. 1291 * move the upper half to the lower one to make room in the upper half.
1292 */ 1292 */
1293 if (s->strstart >= wsize+MAX_DIST(s)) { 1293 if (s->strstart >= wsize+MAX_DIST(s)) {
1294 1294
1295 zmemcpy(s->window, s->window+wsize, (unsigned)wsize); 1295 zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
1296 s->match_start -= wsize; 1296 s->match_start -= wsize;
1297 s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ 1297 s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
1298 s->block_start -= (long) wsize; 1298 s->block_start -= (long) wsize;
1299 1299
1300 /* Slide the hash table (could be avoided with 32 bit values 1300 /* Slide the hash table (could be avoided with 32 bit values
1301 at the expense of memory usage). We slide even when level == 0 1301 at the expense of memory usage). We slide even when level == 0
1302 to keep the hash table consistent if we switch back to level > 0 1302 to keep the hash table consistent if we switch back to level > 0
1303 later. (Using level 0 permanently is not an optimal usage of 1303 later. (Using level 0 permanently is not an optimal usage of
1304 zlib, so we don't care about this pathological case.) 1304 zlib, so we don't care about this pathological case.)
1305 */ 1305 */
1306 /* %%% avoid this when Z_RLE */ 1306 /* %%% avoid this when Z_RLE */
1307 n = s->hash_size; 1307 n = s->hash_size;
1308 p = &s->head[n]; 1308 p = &s->head[n];
1309 do { 1309 do {
1310 m = *--p; 1310 m = *--p;
1311 *p = (Pos)(m >= wsize ? m-wsize : NIL); 1311 *p = (Pos)(m >= wsize ? m-wsize : NIL);
1312 } while (--n); 1312 } while (--n);
1313 1313
1314 n = wsize; 1314 n = wsize;
1315#ifndef FASTEST 1315#ifndef FASTEST
1316 p = &s->prev[n]; 1316 p = &s->prev[n];
1317 do { 1317 do {
1318 m = *--p; 1318 m = *--p;
1319 *p = (Pos)(m >= wsize ? m-wsize : NIL); 1319 *p = (Pos)(m >= wsize ? m-wsize : NIL);
1320 /* If n is not on any hash chain, prev[n] is garbage but 1320 /* If n is not on any hash chain, prev[n] is garbage but
1321 * its value will never be used. 1321 * its value will never be used.
1322 */ 1322 */
1323 } while (--n); 1323 } while (--n);
1324#endif 1324#endif
1325 more += wsize; 1325 more += wsize;
1326 } 1326 }
1327 if (s->strm->avail_in == 0) return; 1327 if (s->strm->avail_in == 0) return;
1328 1328
1329 /* If there was no sliding: 1329 /* If there was no sliding:
1330 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && 1330 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1331 * more == window_size - lookahead - strstart 1331 * more == window_size - lookahead - strstart
1332 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) 1332 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1333 * => more >= window_size - 2*WSIZE + 2 1333 * => more >= window_size - 2*WSIZE + 2
1334 * In the BIG_MEM or MMAP case (not yet supported), 1334 * In the BIG_MEM or MMAP case (not yet supported),
1335 * window_size == input_size + MIN_LOOKAHEAD && 1335 * window_size == input_size + MIN_LOOKAHEAD &&
1336 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. 1336 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1337 * Otherwise, window_size == 2*WSIZE so more >= 2. 1337 * Otherwise, window_size == 2*WSIZE so more >= 2.
1338 * If there was sliding, more >= WSIZE. So in all cases, more >= 2. 1338 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1339 */ 1339 */
1340 Assert(more >= 2, "more < 2"); 1340 Assert(more >= 2, "more < 2");
1341 1341
1342 n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); 1342 n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1343 s->lookahead += n; 1343 s->lookahead += n;
1344 1344
1345 /* Initialize the hash value now that we have some input: */ 1345 /* Initialize the hash value now that we have some input: */
1346 if (s->lookahead >= MIN_MATCH) { 1346 if (s->lookahead >= MIN_MATCH) {
1347 s->ins_h = s->window[s->strstart]; 1347 s->ins_h = s->window[s->strstart];
1348 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); 1348 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1349#if MIN_MATCH != 3 1349#if MIN_MATCH != 3
1350 Call UPDATE_HASH() MIN_MATCH-3 more times 1350 Call UPDATE_HASH() MIN_MATCH-3 more times
1351#endif 1351#endif
1352 } 1352 }
1353 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, 1353 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1354 * but this is not important since only literal bytes will be emitted. 1354 * but this is not important since only literal bytes will be emitted.
1355 */ 1355 */
1356 1356
1357 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); 1357 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1358} 1358}
1359 1359
1360/* =========================================================================== 1360/* ===========================================================================
1361 * Flush the current block, with given end-of-file flag. 1361 * Flush the current block, with given end-of-file flag.
1362 * IN assertion: strstart is set to the end of the current match. 1362 * IN assertion: strstart is set to the end of the current match.
1363 */ 1363 */
1364#define FLUSH_BLOCK_ONLY(s, eof) { \ 1364#define FLUSH_BLOCK_ONLY(s, eof) { \
1365 _tr_flush_block(s, (s->block_start >= 0L ? \ 1365 _tr_flush_block(s, (s->block_start >= 0L ? \
1366 (charf *)&s->window[(unsigned)s->block_start] : \ 1366 (charf *)&s->window[(unsigned)s->block_start] : \
1367 (charf *)Z_NULL), \ 1367 (charf *)Z_NULL), \
1368 (ulg)((long)s->strstart - s->block_start), \ 1368 (ulg)((long)s->strstart - s->block_start), \
1369 (eof)); \ 1369 (eof)); \
1370 s->block_start = s->strstart; \ 1370 s->block_start = s->strstart; \
1371 flush_pending(s->strm); \ 1371 flush_pending(s->strm); \
1372 Tracev((stderr,"[FLUSH]")); \ 1372 Tracev((stderr,"[FLUSH]")); \
1373} 1373}
1374 1374
1375/* Same but force premature exit if necessary. */ 1375/* Same but force premature exit if necessary. */
1376#define FLUSH_BLOCK(s, eof) { \ 1376#define FLUSH_BLOCK(s, eof) { \
1377 FLUSH_BLOCK_ONLY(s, eof); \ 1377 FLUSH_BLOCK_ONLY(s, eof); \
1378 if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \ 1378 if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
1379} 1379}
1380 1380
1381/* =========================================================================== 1381/* ===========================================================================
1382 * Copy without compression as much as possible from the input stream, return 1382 * Copy without compression as much as possible from the input stream, return
1383 * the current block state. 1383 * the current block state.
1384 * This function does not insert new strings in the dictionary since 1384 * This function does not insert new strings in the dictionary since
1385 * uncompressible data is probably not useful. This function is used 1385 * uncompressible data is probably not useful. This function is used
1386 * only for the level=0 compression option. 1386 * only for the level=0 compression option.
1387 * NOTE: this function should be optimized to avoid extra copying from 1387 * NOTE: this function should be optimized to avoid extra copying from
1388 * window to pending_buf. 1388 * window to pending_buf.
1389 */ 1389 */
1390local block_state deflate_stored(s, flush) 1390local block_state deflate_stored(s, flush)
1391 deflate_state *s; 1391 deflate_state *s;
1392 int flush; 1392 int flush;
1393{ 1393{
1394 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited 1394 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
1395 * to pending_buf_size, and each stored block has a 5 byte header: 1395 * to pending_buf_size, and each stored block has a 5 byte header:
1396 */ 1396 */
1397 ulg max_block_size = 0xffff; 1397 ulg max_block_size = 0xffff;
1398 ulg max_start; 1398 ulg max_start;
1399 1399
1400 if (max_block_size > s->pending_buf_size - 5) { 1400 if (max_block_size > s->pending_buf_size - 5) {
1401 max_block_size = s->pending_buf_size - 5; 1401 max_block_size = s->pending_buf_size - 5;
1402 } 1402 }
1403 1403
1404 /* Copy as much as possible from input to output: */ 1404 /* Copy as much as possible from input to output: */
1405 for (;;) { 1405 for (;;) {
1406 /* Fill the window as much as possible: */ 1406 /* Fill the window as much as possible: */
1407 if (s->lookahead <= 1) { 1407 if (s->lookahead <= 1) {
1408 1408
1409 Assert(s->strstart < s->w_size+MAX_DIST(s) || 1409 Assert(s->strstart < s->w_size+MAX_DIST(s) ||
1410 s->block_start >= (long)s->w_size, "slide too late"); 1410 s->block_start >= (long)s->w_size, "slide too late");
1411 1411
1412 fill_window(s); 1412 fill_window(s);
1413 if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; 1413 if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
1414 1414
1415 if (s->lookahead == 0) break; /* flush the current block */ 1415 if (s->lookahead == 0) break; /* flush the current block */
1416 } 1416 }
1417 Assert(s->block_start >= 0L, "block gone"); 1417 Assert(s->block_start >= 0L, "block gone");
1418 1418
1419 s->strstart += s->lookahead; 1419 s->strstart += s->lookahead;
1420 s->lookahead = 0; 1420 s->lookahead = 0;
1421 1421
1422 /* Emit a stored block if pending_buf will be full: */ 1422 /* Emit a stored block if pending_buf will be full: */
1423 max_start = s->block_start + max_block_size; 1423 max_start = s->block_start + max_block_size;
1424 if (s->strstart == 0 || (ulg)s->strstart >= max_start) { 1424 if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
1425 /* strstart == 0 is possible when wraparound on 16-bit machine */ 1425 /* strstart == 0 is possible when wraparound on 16-bit machine */
1426 s->lookahead = (uInt)(s->strstart - max_start); 1426 s->lookahead = (uInt)(s->strstart - max_start);
1427 s->strstart = (uInt)max_start; 1427 s->strstart = (uInt)max_start;
1428 FLUSH_BLOCK(s, 0); 1428 FLUSH_BLOCK(s, 0);
1429 } 1429 }
1430 /* Flush if we may have to slide, otherwise block_start may become 1430 /* Flush if we may have to slide, otherwise block_start may become
1431 * negative and the data will be gone: 1431 * negative and the data will be gone:
1432 */ 1432 */
1433 if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { 1433 if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
1434 FLUSH_BLOCK(s, 0); 1434 FLUSH_BLOCK(s, 0);
1435 } 1435 }
1436 } 1436 }
1437 FLUSH_BLOCK(s, flush == Z_FINISH); 1437 FLUSH_BLOCK(s, flush == Z_FINISH);
1438 return flush == Z_FINISH ? finish_done : block_done; 1438 return flush == Z_FINISH ? finish_done : block_done;
1439} 1439}
1440 1440
1441/* =========================================================================== 1441/* ===========================================================================
1442 * Compress as much as possible from the input stream, return the current 1442 * Compress as much as possible from the input stream, return the current
1443 * block state. 1443 * block state.
1444 * This function does not perform lazy evaluation of matches and inserts 1444 * This function does not perform lazy evaluation of matches and inserts
1445 * new strings in the dictionary only for unmatched strings or for short 1445 * new strings in the dictionary only for unmatched strings or for short
1446 * matches. It is used only for the fast compression options. 1446 * matches. It is used only for the fast compression options.
1447 */ 1447 */
1448local block_state deflate_fast(s, flush) 1448local block_state deflate_fast(s, flush)
1449 deflate_state *s; 1449 deflate_state *s;
1450 int flush; 1450 int flush;
1451{ 1451{
1452 IPos hash_head = NIL; /* head of the hash chain */ 1452 IPos hash_head = NIL; /* head of the hash chain */
1453 int bflush; /* set if current block must be flushed */ 1453 int bflush; /* set if current block must be flushed */
1454 1454
1455 for (;;) { 1455 for (;;) {
1456 /* Make sure that we always have enough lookahead, except 1456 /* Make sure that we always have enough lookahead, except
1457 * at the end of the input file. We need MAX_MATCH bytes 1457 * at the end of the input file. We need MAX_MATCH bytes
1458 * for the next match, plus MIN_MATCH bytes to insert the 1458 * for the next match, plus MIN_MATCH bytes to insert the
1459 * string following the next match. 1459 * string following the next match.
1460 */ 1460 */
1461 if (s->lookahead < MIN_LOOKAHEAD) { 1461 if (s->lookahead < MIN_LOOKAHEAD) {
1462 fill_window(s); 1462 fill_window(s);
1463 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { 1463 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1464 return need_more; 1464 return need_more;
1465 } 1465 }
1466 if (s->lookahead == 0) break; /* flush the current block */ 1466 if (s->lookahead == 0) break; /* flush the current block */
1467 } 1467 }
1468 1468
1469 /* Insert the string window[strstart .. strstart+2] in the 1469 /* Insert the string window[strstart .. strstart+2] in the
1470 * dictionary, and set hash_head to the head of the hash chain: 1470 * dictionary, and set hash_head to the head of the hash chain:
1471 */ 1471 */
1472 if (s->lookahead >= MIN_MATCH) { 1472 if (s->lookahead >= MIN_MATCH) {
1473 INSERT_STRING(s, s->strstart, hash_head); 1473 INSERT_STRING(s, s->strstart, hash_head);
1474 } 1474 }
1475 1475
1476 /* Find the longest match, discarding those <= prev_length. 1476 /* Find the longest match, discarding those <= prev_length.
1477 * At this point we have always match_length < MIN_MATCH 1477 * At this point we have always match_length < MIN_MATCH
1478 */ 1478 */
1479 if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { 1479 if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1480 /* To simplify the code, we prevent matches with the string 1480 /* To simplify the code, we prevent matches with the string
1481 * of window index 0 (in particular we have to avoid a match 1481 * of window index 0 (in particular we have to avoid a match
1482 * of the string with itself at the start of the input file). 1482 * of the string with itself at the start of the input file).
1483 */ 1483 */
1484#ifdef FASTEST 1484#ifdef FASTEST
1485 if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) || 1485 if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
1486 (s->strategy == Z_RLE && s->strstart - hash_head == 1)) { 1486 (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
1487 s->match_length = longest_match_fast (s, hash_head); 1487 s->match_length = longest_match_fast (s, hash_head);
1488 } 1488 }
1489#else 1489#else
1490 if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) { 1490 if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
1491 s->match_length = longest_match (s, hash_head); 1491 s->match_length = longest_match (s, hash_head);
1492 } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { 1492 } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
1493 s->match_length = longest_match_fast (s, hash_head); 1493 s->match_length = longest_match_fast (s, hash_head);
1494 } 1494 }
1495#endif 1495#endif
1496 /* longest_match() or longest_match_fast() sets match_start */ 1496 /* longest_match() or longest_match_fast() sets match_start */
1497 } 1497 }
1498 if (s->match_length >= MIN_MATCH) { 1498 if (s->match_length >= MIN_MATCH) {
1499 check_match(s, s->strstart, s->match_start, s->match_length); 1499 check_match(s, s->strstart, s->match_start, s->match_length);
1500 1500
1501 _tr_tally_dist(s, s->strstart - s->match_start, 1501 _tr_tally_dist(s, s->strstart - s->match_start,
1502 s->match_length - MIN_MATCH, bflush); 1502 s->match_length - MIN_MATCH, bflush);
1503 1503
1504 s->lookahead -= s->match_length; 1504 s->lookahead -= s->match_length;
1505 1505
1506 /* Insert new strings in the hash table only if the match length 1506 /* Insert new strings in the hash table only if the match length
1507 * is not too large. This saves time but degrades compression. 1507 * is not too large. This saves time but degrades compression.
1508 */ 1508 */
1509#ifndef FASTEST 1509#ifndef FASTEST
1510 if (s->match_length <= s->max_insert_length && 1510 if (s->match_length <= s->max_insert_length &&
1511 s->lookahead >= MIN_MATCH) { 1511 s->lookahead >= MIN_MATCH) {
1512 s->match_length--; /* string at strstart already in table */ 1512 s->match_length--; /* string at strstart already in table */
1513 do { 1513 do {
1514 s->strstart++; 1514 s->strstart++;
1515 INSERT_STRING(s, s->strstart, hash_head); 1515 INSERT_STRING(s, s->strstart, hash_head);
1516 /* strstart never exceeds WSIZE-MAX_MATCH, so there are 1516 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1517 * always MIN_MATCH bytes ahead. 1517 * always MIN_MATCH bytes ahead.
1518 */ 1518 */
1519 } while (--s->match_length != 0); 1519 } while (--s->match_length != 0);
1520 s->strstart++; 1520 s->strstart++;
1521 } else 1521 } else
1522#endif 1522#endif
1523 { 1523 {
1524 s->strstart += s->match_length; 1524 s->strstart += s->match_length;
1525 s->match_length = 0; 1525 s->match_length = 0;
1526 s->ins_h = s->window[s->strstart]; 1526 s->ins_h = s->window[s->strstart];
1527 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); 1527 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1528#if MIN_MATCH != 3 1528#if MIN_MATCH != 3
1529 Call UPDATE_HASH() MIN_MATCH-3 more times 1529 Call UPDATE_HASH() MIN_MATCH-3 more times
1530#endif 1530#endif
1531 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not 1531 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1532 * matter since it will be recomputed at next deflate call. 1532 * matter since it will be recomputed at next deflate call.
1533 */ 1533 */
1534 } 1534 }
1535 } else { 1535 } else {
1536 /* No match, output a literal byte */ 1536 /* No match, output a literal byte */
1537 Tracevv((stderr,"%c", s->window[s->strstart])); 1537 Tracevv((stderr,"%c", s->window[s->strstart]));
1538 _tr_tally_lit (s, s->window[s->strstart], bflush); 1538 _tr_tally_lit (s, s->window[s->strstart], bflush);
1539 s->lookahead--; 1539 s->lookahead--;
1540 s->strstart++; 1540 s->strstart++;
1541 } 1541 }
1542 if (bflush) FLUSH_BLOCK(s, 0); 1542 if (bflush) FLUSH_BLOCK(s, 0);
1543 } 1543 }
1544 FLUSH_BLOCK(s, flush == Z_FINISH); 1544 FLUSH_BLOCK(s, flush == Z_FINISH);
1545 return flush == Z_FINISH ? finish_done : block_done; 1545 return flush == Z_FINISH ? finish_done : block_done;
1546} 1546}
1547 1547
1548#ifndef FASTEST 1548#ifndef FASTEST
1549/* =========================================================================== 1549/* ===========================================================================
1550 * Same as above, but achieves better compression. We use a lazy 1550 * Same as above, but achieves better compression. We use a lazy
1551 * evaluation for matches: a match is finally adopted only if there is 1551 * evaluation for matches: a match is finally adopted only if there is
1552 * no better match at the next window position. 1552 * no better match at the next window position.
1553 */ 1553 */
1554local block_state deflate_slow(s, flush) 1554local block_state deflate_slow(s, flush)
1555 deflate_state *s; 1555 deflate_state *s;
1556 int flush; 1556 int flush;
1557{ 1557{
1558 IPos hash_head = NIL; /* head of hash chain */ 1558 IPos hash_head = NIL; /* head of hash chain */
1559 int bflush; /* set if current block must be flushed */ 1559 int bflush; /* set if current block must be flushed */
1560 1560
1561 /* Process the input block. */ 1561 /* Process the input block. */
1562 for (;;) { 1562 for (;;) {
1563 /* Make sure that we always have enough lookahead, except 1563 /* Make sure that we always have enough lookahead, except
1564 * at the end of the input file. We need MAX_MATCH bytes 1564 * at the end of the input file. We need MAX_MATCH bytes
1565 * for the next match, plus MIN_MATCH bytes to insert the 1565 * for the next match, plus MIN_MATCH bytes to insert the
1566 * string following the next match. 1566 * string following the next match.
1567 */ 1567 */
1568 if (s->lookahead < MIN_LOOKAHEAD) { 1568 if (s->lookahead < MIN_LOOKAHEAD) {
1569 fill_window(s); 1569 fill_window(s);
1570 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { 1570 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1571 return need_more; 1571 return need_more;
1572 } 1572 }
1573 if (s->lookahead == 0) break; /* flush the current block */ 1573 if (s->lookahead == 0) break; /* flush the current block */
1574 } 1574 }
1575 1575
1576 /* Insert the string window[strstart .. strstart+2] in the 1576 /* Insert the string window[strstart .. strstart+2] in the
1577 * dictionary, and set hash_head to the head of the hash chain: 1577 * dictionary, and set hash_head to the head of the hash chain:
1578 */ 1578 */
1579 if (s->lookahead >= MIN_MATCH) { 1579 if (s->lookahead >= MIN_MATCH) {
1580 INSERT_STRING(s, s->strstart, hash_head); 1580 INSERT_STRING(s, s->strstart, hash_head);
1581 } 1581 }
1582 1582
1583 /* Find the longest match, discarding those <= prev_length. 1583 /* Find the longest match, discarding those <= prev_length.
1584 */ 1584 */
1585 s->prev_length = s->match_length, s->prev_match = s->match_start; 1585 s->prev_length = s->match_length, s->prev_match = s->match_start;
1586 s->match_length = MIN_MATCH-1; 1586 s->match_length = MIN_MATCH-1;
1587 1587
1588 if (hash_head != NIL && s->prev_length < s->max_lazy_match && 1588 if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
1589 s->strstart - hash_head <= MAX_DIST(s)) { 1589 s->strstart - hash_head <= MAX_DIST(s)) {
1590 /* To simplify the code, we prevent matches with the string 1590 /* To simplify the code, we prevent matches with the string
1591 * of window index 0 (in particular we have to avoid a match 1591 * of window index 0 (in particular we have to avoid a match
1592 * of the string with itself at the start of the input file). 1592 * of the string with itself at the start of the input file).
1593 */ 1593 */
1594 if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) { 1594 if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
1595 s->match_length = longest_match (s, hash_head); 1595 s->match_length = longest_match (s, hash_head);
1596 } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { 1596 } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
1597 s->match_length = longest_match_fast (s, hash_head); 1597 s->match_length = longest_match_fast (s, hash_head);
1598 } 1598 }
1599 /* longest_match() or longest_match_fast() sets match_start */ 1599 /* longest_match() or longest_match_fast() sets match_start */
1600 1600
1601 if (s->match_length <= 5 && (s->strategy == Z_FILTERED 1601 if (s->match_length <= 5 && (s->strategy == Z_FILTERED
1602#if TOO_FAR <= 32767 1602#if TOO_FAR <= 32767
1603 || (s->match_length == MIN_MATCH && 1603 || (s->match_length == MIN_MATCH &&
1604 s->strstart - s->match_start > TOO_FAR) 1604 s->strstart - s->match_start > TOO_FAR)
1605#endif 1605#endif
1606 )) { 1606 )) {
1607 1607
1608 /* If prev_match is also MIN_MATCH, match_start is garbage 1608 /* If prev_match is also MIN_MATCH, match_start is garbage
1609 * but we will ignore the current match anyway. 1609 * but we will ignore the current match anyway.
1610 */ 1610 */
1611 s->match_length = MIN_MATCH-1; 1611 s->match_length = MIN_MATCH-1;
1612 } 1612 }
1613 } 1613 }
1614 /* If there was a match at the previous step and the current 1614 /* If there was a match at the previous step and the current
1615 * match is not better, output the previous match: 1615 * match is not better, output the previous match:
1616 */ 1616 */
1617 if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { 1617 if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
1618 uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; 1618 uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
1619 /* Do not insert strings in hash table beyond this. */ 1619 /* Do not insert strings in hash table beyond this. */
1620 1620
1621 check_match(s, s->strstart-1, s->prev_match, s->prev_length); 1621 check_match(s, s->strstart-1, s->prev_match, s->prev_length);
1622 1622
1623 _tr_tally_dist(s, s->strstart -1 - s->prev_match, 1623 _tr_tally_dist(s, s->strstart -1 - s->prev_match,
1624 s->prev_length - MIN_MATCH, bflush); 1624 s->prev_length - MIN_MATCH, bflush);
1625 1625
1626 /* Insert in hash table all strings up to the end of the match. 1626 /* Insert in hash table all strings up to the end of the match.
1627 * strstart-1 and strstart are already inserted. If there is not 1627 * strstart-1 and strstart are already inserted. If there is not
1628 * enough lookahead, the last two strings are not inserted in 1628 * enough lookahead, the last two strings are not inserted in
1629 * the hash table. 1629 * the hash table.
1630 */ 1630 */
1631 s->lookahead -= s->prev_length-1; 1631 s->lookahead -= s->prev_length-1;
1632 s->prev_length -= 2; 1632 s->prev_length -= 2;
1633 do { 1633 do {
1634 if (++s->strstart <= max_insert) { 1634 if (++s->strstart <= max_insert) {
1635 INSERT_STRING(s, s->strstart, hash_head); 1635 INSERT_STRING(s, s->strstart, hash_head);
1636 } 1636 }
1637 } while (--s->prev_length != 0); 1637 } while (--s->prev_length != 0);
1638 s->match_available = 0; 1638 s->match_available = 0;
1639 s->match_length = MIN_MATCH-1; 1639 s->match_length = MIN_MATCH-1;
1640 s->strstart++; 1640 s->strstart++;
1641 1641
1642 if (bflush) FLUSH_BLOCK(s, 0); 1642 if (bflush) FLUSH_BLOCK(s, 0);
1643 1643
1644 } else if (s->match_available) { 1644 } else if (s->match_available) {
1645 /* If there was no match at the previous position, output a 1645 /* If there was no match at the previous position, output a
1646 * single literal. If there was a match but the current match 1646 * single literal. If there was a match but the current match
1647 * is longer, truncate the previous match to a single literal. 1647 * is longer, truncate the previous match to a single literal.
1648 */ 1648 */
1649 Tracevv((stderr,"%c", s->window[s->strstart-1])); 1649 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1650 _tr_tally_lit(s, s->window[s->strstart-1], bflush); 1650 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1651 if (bflush) { 1651 if (bflush) {
1652 FLUSH_BLOCK_ONLY(s, 0); 1652 FLUSH_BLOCK_ONLY(s, 0);
1653 } 1653 }
1654 s->strstart++; 1654 s->strstart++;
1655 s->lookahead--; 1655 s->lookahead--;
1656 if (s->strm->avail_out == 0) return need_more; 1656 if (s->strm->avail_out == 0) return need_more;
1657 } else { 1657 } else {
1658 /* There is no previous match to compare with, wait for 1658 /* There is no previous match to compare with, wait for
1659 * the next step to decide. 1659 * the next step to decide.
1660 */ 1660 */
1661 s->match_available = 1; 1661 s->match_available = 1;
1662 s->strstart++; 1662 s->strstart++;
1663 s->lookahead--; 1663 s->lookahead--;
1664 } 1664 }
1665 } 1665 }
1666 Assert (flush != Z_NO_FLUSH, "no flush?"); 1666 Assert (flush != Z_NO_FLUSH, "no flush?");
1667 if (s->match_available) { 1667 if (s->match_available) {
1668 Tracevv((stderr,"%c", s->window[s->strstart-1])); 1668 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1669 _tr_tally_lit(s, s->window[s->strstart-1], bflush); 1669 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1670 s->match_available = 0; 1670 s->match_available = 0;
1671 } 1671 }
1672 FLUSH_BLOCK(s, flush == Z_FINISH); 1672 FLUSH_BLOCK(s, flush == Z_FINISH);
1673 return flush == Z_FINISH ? finish_done : block_done; 1673 return flush == Z_FINISH ? finish_done : block_done;
1674} 1674}
1675#endif /* FASTEST */ 1675#endif /* FASTEST */
1676 1676
1677#if 0 1677#if 0
1678/* =========================================================================== 1678/* ===========================================================================
1679 * For Z_RLE, simply look for runs of bytes, generate matches only of distance 1679 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
1680 * one. Do not maintain a hash table. (It will be regenerated if this run of 1680 * one. Do not maintain a hash table. (It will be regenerated if this run of
1681 * deflate switches away from Z_RLE.) 1681 * deflate switches away from Z_RLE.)
1682 */ 1682 */
1683local block_state deflate_rle(s, flush) 1683local block_state deflate_rle(s, flush)
1684 deflate_state *s; 1684 deflate_state *s;
1685 int flush; 1685 int flush;
1686{ 1686{
1687 int bflush; /* set if current block must be flushed */ 1687 int bflush; /* set if current block must be flushed */
1688 uInt run; /* length of run */ 1688 uInt run; /* length of run */
1689 uInt max; /* maximum length of run */ 1689 uInt max; /* maximum length of run */
1690 uInt prev; /* byte at distance one to match */ 1690 uInt prev; /* byte at distance one to match */
1691 Bytef *scan; /* scan for end of run */ 1691 Bytef *scan; /* scan for end of run */
1692 1692
1693 for (;;) { 1693 for (;;) {
1694 /* Make sure that we always have enough lookahead, except 1694 /* Make sure that we always have enough lookahead, except
1695 * at the end of the input file. We need MAX_MATCH bytes 1695 * at the end of the input file. We need MAX_MATCH bytes
1696 * for the longest encodable run. 1696 * for the longest encodable run.
1697 */ 1697 */
1698 if (s->lookahead < MAX_MATCH) { 1698 if (s->lookahead < MAX_MATCH) {
1699 fill_window(s); 1699 fill_window(s);
1700 if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) { 1700 if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
1701 return need_more; 1701 return need_more;
1702 } 1702 }
1703 if (s->lookahead == 0) break; /* flush the current block */ 1703 if (s->lookahead == 0) break; /* flush the current block */
1704 } 1704 }
1705 1705
1706 /* See how many times the previous byte repeats */ 1706 /* See how many times the previous byte repeats */
1707 run = 0; 1707 run = 0;
1708 if (s->strstart > 0) { /* if there is a previous byte, that is */ 1708 if (s->strstart > 0) { /* if there is a previous byte, that is */
1709 max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH; 1709 max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
1710 scan = s->window + s->strstart - 1; 1710 scan = s->window + s->strstart - 1;
1711 prev = *scan++; 1711 prev = *scan++;
1712 do { 1712 do {
1713 if (*scan++ != prev) 1713 if (*scan++ != prev)
1714 break; 1714 break;
1715 } while (++run < max); 1715 } while (++run < max);
1716 } 1716 }
1717 1717
1718 /* Emit match if have run of MIN_MATCH or longer, else emit literal */ 1718 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
1719 if (run >= MIN_MATCH) { 1719 if (run >= MIN_MATCH) {
1720 check_match(s, s->strstart, s->strstart - 1, run); 1720 check_match(s, s->strstart, s->strstart - 1, run);
1721 _tr_tally_dist(s, 1, run - MIN_MATCH, bflush); 1721 _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
1722 s->lookahead -= run; 1722 s->lookahead -= run;
1723 s->strstart += run; 1723 s->strstart += run;
1724 } else { 1724 } else {
1725 /* No match, output a literal byte */ 1725 /* No match, output a literal byte */
1726 Tracevv((stderr,"%c", s->window[s->strstart])); 1726 Tracevv((stderr,"%c", s->window[s->strstart]));
1727 _tr_tally_lit (s, s->window[s->strstart], bflush); 1727 _tr_tally_lit (s, s->window[s->strstart], bflush);
1728 s->lookahead--; 1728 s->lookahead--;
1729 s->strstart++; 1729 s->strstart++;
1730 } 1730 }
1731 if (bflush) FLUSH_BLOCK(s, 0); 1731 if (bflush) FLUSH_BLOCK(s, 0);
1732 } 1732 }
1733 FLUSH_BLOCK(s, flush == Z_FINISH); 1733 FLUSH_BLOCK(s, flush == Z_FINISH);
1734 return flush == Z_FINISH ? finish_done : block_done; 1734 return flush == Z_FINISH ? finish_done : block_done;
1735} 1735}
1736#endif 1736#endif
diff --git a/utils/zenutils/libraries/zlib123/zlib/deflate.h b/utils/zenutils/libraries/zlib123/zlib/deflate.h
index 222c53e043..05a5ab3a2c 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/deflate.h
+++ b/utils/zenutils/libraries/zlib123/zlib/deflate.h
@@ -1,331 +1,331 @@
1/* deflate.h -- internal compression state 1/* deflate.h -- internal compression state
2 * Copyright (C) 1995-2004 Jean-loup Gailly 2 * Copyright (C) 1995-2004 Jean-loup Gailly
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6/* WARNING: this file should *not* be used by applications. It is 6/* WARNING: this file should *not* be used by applications. It is
7 part of the implementation of the compression library and is 7 part of the implementation of the compression library and is
8 subject to change. Applications should only use zlib.h. 8 subject to change. Applications should only use zlib.h.
9 */ 9 */
10 10
11/* @(#) $Id$ */ 11/* @(#) $Id$ */
12 12
13#ifndef DEFLATE_H 13#ifndef DEFLATE_H
14#define DEFLATE_H 14#define DEFLATE_H
15 15
16#include "zutil.h" 16#include "zutil.h"
17 17
18/* define NO_GZIP when compiling if you want to disable gzip header and 18/* define NO_GZIP when compiling if you want to disable gzip header and
19 trailer creation by deflate(). NO_GZIP would be used to avoid linking in 19 trailer creation by deflate(). NO_GZIP would be used to avoid linking in
20 the crc code when it is not needed. For shared libraries, gzip encoding 20 the crc code when it is not needed. For shared libraries, gzip encoding
21 should be left enabled. */ 21 should be left enabled. */
22#ifndef NO_GZIP 22#ifndef NO_GZIP
23# define GZIP 23# define GZIP
24#endif 24#endif
25 25
26/* =========================================================================== 26/* ===========================================================================
27 * Internal compression state. 27 * Internal compression state.
28 */ 28 */
29 29
30#define LENGTH_CODES 29 30#define LENGTH_CODES 29
31/* number of length codes, not counting the special END_BLOCK code */ 31/* number of length codes, not counting the special END_BLOCK code */
32 32
33#define LITERALS 256 33#define LITERALS 256
34/* number of literal bytes 0..255 */ 34/* number of literal bytes 0..255 */
35 35
36#define L_CODES (LITERALS+1+LENGTH_CODES) 36#define L_CODES (LITERALS+1+LENGTH_CODES)
37/* number of Literal or Length codes, including the END_BLOCK code */ 37/* number of Literal or Length codes, including the END_BLOCK code */
38 38
39#define D_CODES 30 39#define D_CODES 30
40/* number of distance codes */ 40/* number of distance codes */
41 41
42#define BL_CODES 19 42#define BL_CODES 19
43/* number of codes used to transfer the bit lengths */ 43/* number of codes used to transfer the bit lengths */
44 44
45#define HEAP_SIZE (2*L_CODES+1) 45#define HEAP_SIZE (2*L_CODES+1)
46/* maximum heap size */ 46/* maximum heap size */
47 47
48#define MAX_BITS 15 48#define MAX_BITS 15
49/* All codes must not exceed MAX_BITS bits */ 49/* All codes must not exceed MAX_BITS bits */
50 50
51#define INIT_STATE 42 51#define INIT_STATE 42
52#define EXTRA_STATE 69 52#define EXTRA_STATE 69
53#define NAME_STATE 73 53#define NAME_STATE 73
54#define COMMENT_STATE 91 54#define COMMENT_STATE 91
55#define HCRC_STATE 103 55#define HCRC_STATE 103
56#define BUSY_STATE 113 56#define BUSY_STATE 113
57#define FINISH_STATE 666 57#define FINISH_STATE 666
58/* Stream status */ 58/* Stream status */
59 59
60 60
61/* Data structure describing a single value and its code string. */ 61/* Data structure describing a single value and its code string. */
62typedef struct ct_data_s { 62typedef struct ct_data_s {
63 union { 63 union {
64 ush freq; /* frequency count */ 64 ush freq; /* frequency count */
65 ush code; /* bit string */ 65 ush code; /* bit string */
66 } fc; 66 } fc;
67 union { 67 union {
68 ush dad; /* father node in Huffman tree */ 68 ush dad; /* father node in Huffman tree */
69 ush len; /* length of bit string */ 69 ush len; /* length of bit string */
70 } dl; 70 } dl;
71} FAR ct_data; 71} FAR ct_data;
72 72
73#define Freq fc.freq 73#define Freq fc.freq
74#define Code fc.code 74#define Code fc.code
75#define Dad dl.dad 75#define Dad dl.dad
76#define Len dl.len 76#define Len dl.len
77 77
78typedef struct static_tree_desc_s static_tree_desc; 78typedef struct static_tree_desc_s static_tree_desc;
79 79
80typedef struct tree_desc_s { 80typedef struct tree_desc_s {
81 ct_data *dyn_tree; /* the dynamic tree */ 81 ct_data *dyn_tree; /* the dynamic tree */
82 int max_code; /* largest code with non zero frequency */ 82 int max_code; /* largest code with non zero frequency */
83 static_tree_desc *stat_desc; /* the corresponding static tree */ 83 static_tree_desc *stat_desc; /* the corresponding static tree */
84} FAR tree_desc; 84} FAR tree_desc;
85 85
86typedef ush Pos; 86typedef ush Pos;
87typedef Pos FAR Posf; 87typedef Pos FAR Posf;
88typedef unsigned IPos; 88typedef unsigned IPos;
89 89
90/* A Pos is an index in the character window. We use short instead of int to 90/* A Pos is an index in the character window. We use short instead of int to
91 * save space in the various tables. IPos is used only for parameter passing. 91 * save space in the various tables. IPos is used only for parameter passing.
92 */ 92 */
93 93
94typedef struct internal_state { 94typedef struct internal_state {
95 z_streamp strm; /* pointer back to this zlib stream */ 95 z_streamp strm; /* pointer back to this zlib stream */
96 int status; /* as the name implies */ 96 int status; /* as the name implies */
97 Bytef *pending_buf; /* output still pending */ 97 Bytef *pending_buf; /* output still pending */
98 ulg pending_buf_size; /* size of pending_buf */ 98 ulg pending_buf_size; /* size of pending_buf */
99 Bytef *pending_out; /* next pending byte to output to the stream */ 99 Bytef *pending_out; /* next pending byte to output to the stream */
100 uInt pending; /* nb of bytes in the pending buffer */ 100 uInt pending; /* nb of bytes in the pending buffer */
101 int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ 101 int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
102 gz_headerp gzhead; /* gzip header information to write */ 102 gz_headerp gzhead; /* gzip header information to write */
103 uInt gzindex; /* where in extra, name, or comment */ 103 uInt gzindex; /* where in extra, name, or comment */
104 Byte method; /* STORED (for zip only) or DEFLATED */ 104 Byte method; /* STORED (for zip only) or DEFLATED */
105 int last_flush; /* value of flush param for previous deflate call */ 105 int last_flush; /* value of flush param for previous deflate call */
106 106
107 /* used by deflate.c: */ 107 /* used by deflate.c: */
108 108
109 uInt w_size; /* LZ77 window size (32K by default) */ 109 uInt w_size; /* LZ77 window size (32K by default) */
110 uInt w_bits; /* log2(w_size) (8..16) */ 110 uInt w_bits; /* log2(w_size) (8..16) */
111 uInt w_mask; /* w_size - 1 */ 111 uInt w_mask; /* w_size - 1 */
112 112
113 Bytef *window; 113 Bytef *window;
114 /* Sliding window. Input bytes are read into the second half of the window, 114 /* Sliding window. Input bytes are read into the second half of the window,
115 * and move to the first half later to keep a dictionary of at least wSize 115 * and move to the first half later to keep a dictionary of at least wSize
116 * bytes. With this organization, matches are limited to a distance of 116 * bytes. With this organization, matches are limited to a distance of
117 * wSize-MAX_MATCH bytes, but this ensures that IO is always 117 * wSize-MAX_MATCH bytes, but this ensures that IO is always
118 * performed with a length multiple of the block size. Also, it limits 118 * performed with a length multiple of the block size. Also, it limits
119 * the window size to 64K, which is quite useful on MSDOS. 119 * the window size to 64K, which is quite useful on MSDOS.
120 * To do: use the user input buffer as sliding window. 120 * To do: use the user input buffer as sliding window.
121 */ 121 */
122 122
123 ulg window_size; 123 ulg window_size;
124 /* Actual size of window: 2*wSize, except when the user input buffer 124 /* Actual size of window: 2*wSize, except when the user input buffer
125 * is directly used as sliding window. 125 * is directly used as sliding window.
126 */ 126 */
127 127
128 Posf *prev; 128 Posf *prev;
129 /* Link to older string with same hash index. To limit the size of this 129 /* Link to older string with same hash index. To limit the size of this
130 * array to 64K, this link is maintained only for the last 32K strings. 130 * array to 64K, this link is maintained only for the last 32K strings.
131 * An index in this array is thus a window index modulo 32K. 131 * An index in this array is thus a window index modulo 32K.
132 */ 132 */
133 133
134 Posf *head; /* Heads of the hash chains or NIL. */ 134 Posf *head; /* Heads of the hash chains or NIL. */
135 135
136 uInt ins_h; /* hash index of string to be inserted */ 136 uInt ins_h; /* hash index of string to be inserted */
137 uInt hash_size; /* number of elements in hash table */ 137 uInt hash_size; /* number of elements in hash table */
138 uInt hash_bits; /* log2(hash_size) */ 138 uInt hash_bits; /* log2(hash_size) */
139 uInt hash_mask; /* hash_size-1 */ 139 uInt hash_mask; /* hash_size-1 */
140 140
141 uInt hash_shift; 141 uInt hash_shift;
142 /* Number of bits by which ins_h must be shifted at each input 142 /* Number of bits by which ins_h must be shifted at each input
143 * step. It must be such that after MIN_MATCH steps, the oldest 143 * step. It must be such that after MIN_MATCH steps, the oldest
144 * byte no longer takes part in the hash key, that is: 144 * byte no longer takes part in the hash key, that is:
145 * hash_shift * MIN_MATCH >= hash_bits 145 * hash_shift * MIN_MATCH >= hash_bits
146 */ 146 */
147 147
148 long block_start; 148 long block_start;
149 /* Window position at the beginning of the current output block. Gets 149 /* Window position at the beginning of the current output block. Gets
150 * negative when the window is moved backwards. 150 * negative when the window is moved backwards.
151 */ 151 */
152 152
153 uInt match_length; /* length of best match */ 153 uInt match_length; /* length of best match */
154 IPos prev_match; /* previous match */ 154 IPos prev_match; /* previous match */
155 int match_available; /* set if previous match exists */ 155 int match_available; /* set if previous match exists */
156 uInt strstart; /* start of string to insert */ 156 uInt strstart; /* start of string to insert */
157 uInt match_start; /* start of matching string */ 157 uInt match_start; /* start of matching string */
158 uInt lookahead; /* number of valid bytes ahead in window */ 158 uInt lookahead; /* number of valid bytes ahead in window */
159 159
160 uInt prev_length; 160 uInt prev_length;
161 /* Length of the best match at previous step. Matches not greater than this 161 /* Length of the best match at previous step. Matches not greater than this
162 * are discarded. This is used in the lazy match evaluation. 162 * are discarded. This is used in the lazy match evaluation.
163 */ 163 */
164 164
165 uInt max_chain_length; 165 uInt max_chain_length;
166 /* To speed up deflation, hash chains are never searched beyond this 166 /* To speed up deflation, hash chains are never searched beyond this
167 * length. A higher limit improves compression ratio but degrades the 167 * length. A higher limit improves compression ratio but degrades the
168 * speed. 168 * speed.
169 */ 169 */
170 170
171 uInt max_lazy_match; 171 uInt max_lazy_match;
172 /* Attempt to find a better match only when the current match is strictly 172 /* Attempt to find a better match only when the current match is strictly
173 * smaller than this value. This mechanism is used only for compression 173 * smaller than this value. This mechanism is used only for compression
174 * levels >= 4. 174 * levels >= 4.
175 */ 175 */
176# define max_insert_length max_lazy_match 176# define max_insert_length max_lazy_match
177 /* Insert new strings in the hash table only if the match length is not 177 /* Insert new strings in the hash table only if the match length is not
178 * greater than this length. This saves time but degrades compression. 178 * greater than this length. This saves time but degrades compression.
179 * max_insert_length is used only for compression levels <= 3. 179 * max_insert_length is used only for compression levels <= 3.
180 */ 180 */
181 181
182 int level; /* compression level (1..9) */ 182 int level; /* compression level (1..9) */
183 int strategy; /* favor or force Huffman coding*/ 183 int strategy; /* favor or force Huffman coding*/
184 184
185 uInt good_match; 185 uInt good_match;
186 /* Use a faster search when the previous match is longer than this */ 186 /* Use a faster search when the previous match is longer than this */
187 187
188 int nice_match; /* Stop searching when current match exceeds this */ 188 int nice_match; /* Stop searching when current match exceeds this */
189 189
190 /* used by trees.c: */ 190 /* used by trees.c: */
191 /* Didn't use ct_data typedef below to supress compiler warning */ 191 /* Didn't use ct_data typedef below to supress compiler warning */
192 struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ 192 struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
193 struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ 193 struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
194 struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ 194 struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
195 195
196 struct tree_desc_s l_desc; /* desc. for literal tree */ 196 struct tree_desc_s l_desc; /* desc. for literal tree */
197 struct tree_desc_s d_desc; /* desc. for distance tree */ 197 struct tree_desc_s d_desc; /* desc. for distance tree */
198 struct tree_desc_s bl_desc; /* desc. for bit length tree */ 198 struct tree_desc_s bl_desc; /* desc. for bit length tree */
199 199
200 ush bl_count[MAX_BITS+1]; 200 ush bl_count[MAX_BITS+1];
201 /* number of codes at each bit length for an optimal tree */ 201 /* number of codes at each bit length for an optimal tree */
202 202
203 int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ 203 int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
204 int heap_len; /* number of elements in the heap */ 204 int heap_len; /* number of elements in the heap */
205 int heap_max; /* element of largest frequency */ 205 int heap_max; /* element of largest frequency */
206 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. 206 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
207 * The same heap array is used to build all trees. 207 * The same heap array is used to build all trees.
208 */ 208 */
209 209
210 uch depth[2*L_CODES+1]; 210 uch depth[2*L_CODES+1];
211 /* Depth of each subtree used as tie breaker for trees of equal frequency 211 /* Depth of each subtree used as tie breaker for trees of equal frequency
212 */ 212 */
213 213
214 uchf *l_buf; /* buffer for literals or lengths */ 214 uchf *l_buf; /* buffer for literals or lengths */
215 215
216 uInt lit_bufsize; 216 uInt lit_bufsize;
217 /* Size of match buffer for literals/lengths. There are 4 reasons for 217 /* Size of match buffer for literals/lengths. There are 4 reasons for
218 * limiting lit_bufsize to 64K: 218 * limiting lit_bufsize to 64K:
219 * - frequencies can be kept in 16 bit counters 219 * - frequencies can be kept in 16 bit counters
220 * - if compression is not successful for the first block, all input 220 * - if compression is not successful for the first block, all input
221 * data is still in the window so we can still emit a stored block even 221 * data is still in the window so we can still emit a stored block even
222 * when input comes from standard input. (This can also be done for 222 * when input comes from standard input. (This can also be done for
223 * all blocks if lit_bufsize is not greater than 32K.) 223 * all blocks if lit_bufsize is not greater than 32K.)
224 * - if compression is not successful for a file smaller than 64K, we can 224 * - if compression is not successful for a file smaller than 64K, we can
225 * even emit a stored file instead of a stored block (saving 5 bytes). 225 * even emit a stored file instead of a stored block (saving 5 bytes).
226 * This is applicable only for zip (not gzip or zlib). 226 * This is applicable only for zip (not gzip or zlib).
227 * - creating new Huffman trees less frequently may not provide fast 227 * - creating new Huffman trees less frequently may not provide fast
228 * adaptation to changes in the input data statistics. (Take for 228 * adaptation to changes in the input data statistics. (Take for
229 * example a binary file with poorly compressible code followed by 229 * example a binary file with poorly compressible code followed by
230 * a highly compressible string table.) Smaller buffer sizes give 230 * a highly compressible string table.) Smaller buffer sizes give
231 * fast adaptation but have of course the overhead of transmitting 231 * fast adaptation but have of course the overhead of transmitting
232 * trees more frequently. 232 * trees more frequently.
233 * - I can't count above 4 233 * - I can't count above 4
234 */ 234 */
235 235
236 uInt last_lit; /* running index in l_buf */ 236 uInt last_lit; /* running index in l_buf */
237 237
238 ushf *d_buf; 238 ushf *d_buf;
239 /* Buffer for distances. To simplify the code, d_buf and l_buf have 239 /* Buffer for distances. To simplify the code, d_buf and l_buf have
240 * the same number of elements. To use different lengths, an extra flag 240 * the same number of elements. To use different lengths, an extra flag
241 * array would be necessary. 241 * array would be necessary.
242 */ 242 */
243 243
244 ulg opt_len; /* bit length of current block with optimal trees */ 244 ulg opt_len; /* bit length of current block with optimal trees */
245 ulg static_len; /* bit length of current block with static trees */ 245 ulg static_len; /* bit length of current block with static trees */
246 uInt matches; /* number of string matches in current block */ 246 uInt matches; /* number of string matches in current block */
247 int last_eob_len; /* bit length of EOB code for last block */ 247 int last_eob_len; /* bit length of EOB code for last block */
248 248
249#ifdef DEBUG 249#ifdef DEBUG
250 ulg compressed_len; /* total bit length of compressed file mod 2^32 */ 250 ulg compressed_len; /* total bit length of compressed file mod 2^32 */
251 ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ 251 ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
252#endif 252#endif
253 253
254 ush bi_buf; 254 ush bi_buf;
255 /* Output buffer. bits are inserted starting at the bottom (least 255 /* Output buffer. bits are inserted starting at the bottom (least
256 * significant bits). 256 * significant bits).
257 */ 257 */
258 int bi_valid; 258 int bi_valid;
259 /* Number of valid bits in bi_buf. All bits above the last valid bit 259 /* Number of valid bits in bi_buf. All bits above the last valid bit
260 * are always zero. 260 * are always zero.
261 */ 261 */
262 262
263} FAR deflate_state; 263} FAR deflate_state;
264 264
265/* Output a byte on the stream. 265/* Output a byte on the stream.
266 * IN assertion: there is enough room in pending_buf. 266 * IN assertion: there is enough room in pending_buf.
267 */ 267 */
268#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);} 268#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
269 269
270 270
271#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) 271#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
272/* Minimum amount of lookahead, except at the end of the input file. 272/* Minimum amount of lookahead, except at the end of the input file.
273 * See deflate.c for comments about the MIN_MATCH+1. 273 * See deflate.c for comments about the MIN_MATCH+1.
274 */ 274 */
275 275
276#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) 276#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
277/* In order to simplify the code, particularly on 16 bit machines, match 277/* In order to simplify the code, particularly on 16 bit machines, match
278 * distances are limited to MAX_DIST instead of WSIZE. 278 * distances are limited to MAX_DIST instead of WSIZE.
279 */ 279 */
280 280
281 /* in trees.c */ 281 /* in trees.c */
282void _tr_init OF((deflate_state *s)); 282void _tr_init OF((deflate_state *s));
283int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); 283int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
284void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len, 284void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
285 int eof)); 285 int eof));
286void _tr_align OF((deflate_state *s)); 286void _tr_align OF((deflate_state *s));
287void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len, 287void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
288 int eof)); 288 int eof));
289 289
290#define d_code(dist) \ 290#define d_code(dist) \
291 ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) 291 ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
292/* Mapping from a distance to a distance code. dist is the distance - 1 and 292/* Mapping from a distance to a distance code. dist is the distance - 1 and
293 * must not have side effects. _dist_code[256] and _dist_code[257] are never 293 * must not have side effects. _dist_code[256] and _dist_code[257] are never
294 * used. 294 * used.
295 */ 295 */
296 296
297#ifndef DEBUG 297#ifndef DEBUG
298/* Inline versions of _tr_tally for speed: */ 298/* Inline versions of _tr_tally for speed: */
299 299
300#if defined(GEN_TREES_H) || !defined(STDC) 300#if defined(GEN_TREES_H) || !defined(STDC)
301 extern uch _length_code[]; 301 extern uch _length_code[];
302 extern uch _dist_code[]; 302 extern uch _dist_code[];
303#else 303#else
304 extern const uch _length_code[]; 304 extern const uch _length_code[];
305 extern const uch _dist_code[]; 305 extern const uch _dist_code[];
306#endif 306#endif
307 307
308# define _tr_tally_lit(s, c, flush) \ 308# define _tr_tally_lit(s, c, flush) \
309 { uch cc = (c); \ 309 { uch cc = (c); \
310 s->d_buf[s->last_lit] = 0; \ 310 s->d_buf[s->last_lit] = 0; \
311 s->l_buf[s->last_lit++] = cc; \ 311 s->l_buf[s->last_lit++] = cc; \
312 s->dyn_ltree[cc].Freq++; \ 312 s->dyn_ltree[cc].Freq++; \
313 flush = (s->last_lit == s->lit_bufsize-1); \ 313 flush = (s->last_lit == s->lit_bufsize-1); \
314 } 314 }
315# define _tr_tally_dist(s, distance, length, flush) \ 315# define _tr_tally_dist(s, distance, length, flush) \
316 { uch len = (length); \ 316 { uch len = (length); \
317 ush dist = (distance); \ 317 ush dist = (distance); \
318 s->d_buf[s->last_lit] = dist; \ 318 s->d_buf[s->last_lit] = dist; \
319 s->l_buf[s->last_lit++] = len; \ 319 s->l_buf[s->last_lit++] = len; \
320 dist--; \ 320 dist--; \
321 s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ 321 s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
322 s->dyn_dtree[d_code(dist)].Freq++; \ 322 s->dyn_dtree[d_code(dist)].Freq++; \
323 flush = (s->last_lit == s->lit_bufsize-1); \ 323 flush = (s->last_lit == s->lit_bufsize-1); \
324 } 324 }
325#else 325#else
326# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) 326# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
327# define _tr_tally_dist(s, distance, length, flush) \ 327# define _tr_tally_dist(s, distance, length, flush) \
328 flush = _tr_tally(s, distance, length) 328 flush = _tr_tally(s, distance, length)
329#endif 329#endif
330 330
331#endif /* DEFLATE_H */ 331#endif /* DEFLATE_H */
diff --git a/utils/zenutils/libraries/zlib123/zlib/example.c b/utils/zenutils/libraries/zlib123/zlib/example.c
index 455a1d062a..6c8a0ee763 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/example.c
+++ b/utils/zenutils/libraries/zlib123/zlib/example.c
@@ -1,565 +1,565 @@
1/* example.c -- usage example of the zlib compression library 1/* example.c -- usage example of the zlib compression library
2 * Copyright (C) 1995-2004 Jean-loup Gailly. 2 * Copyright (C) 1995-2004 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6/* @(#) $Id$ */ 6/* @(#) $Id$ */
7 7
8#include <stdio.h> 8#include <stdio.h>
9#include "zlib.h" 9#include "zlib.h"
10 10
11#ifdef STDC 11#ifdef STDC
12# include <string.h> 12# include <string.h>
13# include <stdlib.h> 13# include <stdlib.h>
14#endif 14#endif
15 15
16#if defined(VMS) || defined(RISCOS) 16#if defined(VMS) || defined(RISCOS)
17# define TESTFILE "foo-gz" 17# define TESTFILE "foo-gz"
18#else 18#else
19# define TESTFILE "foo.gz" 19# define TESTFILE "foo.gz"
20#endif 20#endif
21 21
22#define CHECK_ERR(err, msg) { \ 22#define CHECK_ERR(err, msg) { \
23 if (err != Z_OK) { \ 23 if (err != Z_OK) { \
24 fprintf(stderr, "%s error: %d\n", msg, err); \ 24 fprintf(stderr, "%s error: %d\n", msg, err); \
25 exit(1); \ 25 exit(1); \
26 } \ 26 } \
27} 27}
28 28
29const char hello[] = "hello, hello!"; 29const char hello[] = "hello, hello!";
30/* "hello world" would be more standard, but the repeated "hello" 30/* "hello world" would be more standard, but the repeated "hello"
31 * stresses the compression code better, sorry... 31 * stresses the compression code better, sorry...
32 */ 32 */
33 33
34const char dictionary[] = "hello"; 34const char dictionary[] = "hello";
35uLong dictId; /* Adler32 value of the dictionary */ 35uLong dictId; /* Adler32 value of the dictionary */
36 36
37void test_compress OF((Byte *compr, uLong comprLen, 37void test_compress OF((Byte *compr, uLong comprLen,
38 Byte *uncompr, uLong uncomprLen)); 38 Byte *uncompr, uLong uncomprLen));
39void test_gzio OF((const char *fname, 39void test_gzio OF((const char *fname,
40 Byte *uncompr, uLong uncomprLen)); 40 Byte *uncompr, uLong uncomprLen));
41void test_deflate OF((Byte *compr, uLong comprLen)); 41void test_deflate OF((Byte *compr, uLong comprLen));
42void test_inflate OF((Byte *compr, uLong comprLen, 42void test_inflate OF((Byte *compr, uLong comprLen,
43 Byte *uncompr, uLong uncomprLen)); 43 Byte *uncompr, uLong uncomprLen));
44void test_large_deflate OF((Byte *compr, uLong comprLen, 44void test_large_deflate OF((Byte *compr, uLong comprLen,
45 Byte *uncompr, uLong uncomprLen)); 45 Byte *uncompr, uLong uncomprLen));
46void test_large_inflate OF((Byte *compr, uLong comprLen, 46void test_large_inflate OF((Byte *compr, uLong comprLen,
47 Byte *uncompr, uLong uncomprLen)); 47 Byte *uncompr, uLong uncomprLen));
48void test_flush OF((Byte *compr, uLong *comprLen)); 48void test_flush OF((Byte *compr, uLong *comprLen));
49void test_sync OF((Byte *compr, uLong comprLen, 49void test_sync OF((Byte *compr, uLong comprLen,
50 Byte *uncompr, uLong uncomprLen)); 50 Byte *uncompr, uLong uncomprLen));
51void test_dict_deflate OF((Byte *compr, uLong comprLen)); 51void test_dict_deflate OF((Byte *compr, uLong comprLen));
52void test_dict_inflate OF((Byte *compr, uLong comprLen, 52void test_dict_inflate OF((Byte *compr, uLong comprLen,
53 Byte *uncompr, uLong uncomprLen)); 53 Byte *uncompr, uLong uncomprLen));
54int main OF((int argc, char *argv[])); 54int main OF((int argc, char *argv[]));
55 55
56/* =========================================================================== 56/* ===========================================================================
57 * Test compress() and uncompress() 57 * Test compress() and uncompress()
58 */ 58 */
59void test_compress(compr, comprLen, uncompr, uncomprLen) 59void test_compress(compr, comprLen, uncompr, uncomprLen)
60 Byte *compr, *uncompr; 60 Byte *compr, *uncompr;
61 uLong comprLen, uncomprLen; 61 uLong comprLen, uncomprLen;
62{ 62{
63 int err; 63 int err;
64 uLong len = (uLong)strlen(hello)+1; 64 uLong len = (uLong)strlen(hello)+1;
65 65
66 err = compress(compr, &comprLen, (const Bytef*)hello, len); 66 err = compress(compr, &comprLen, (const Bytef*)hello, len);
67 CHECK_ERR(err, "compress"); 67 CHECK_ERR(err, "compress");
68 68
69 strcpy((char*)uncompr, "garbage"); 69 strcpy((char*)uncompr, "garbage");
70 70
71 err = uncompress(uncompr, &uncomprLen, compr, comprLen); 71 err = uncompress(uncompr, &uncomprLen, compr, comprLen);
72 CHECK_ERR(err, "uncompress"); 72 CHECK_ERR(err, "uncompress");
73 73
74 if (strcmp((char*)uncompr, hello)) { 74 if (strcmp((char*)uncompr, hello)) {
75 fprintf(stderr, "bad uncompress\n"); 75 fprintf(stderr, "bad uncompress\n");
76 exit(1); 76 exit(1);
77 } else { 77 } else {
78 printf("uncompress(): %s\n", (char *)uncompr); 78 printf("uncompress(): %s\n", (char *)uncompr);
79 } 79 }
80} 80}
81 81
82/* =========================================================================== 82/* ===========================================================================
83 * Test read/write of .gz files 83 * Test read/write of .gz files
84 */ 84 */
85void test_gzio(fname, uncompr, uncomprLen) 85void test_gzio(fname, uncompr, uncomprLen)
86 const char *fname; /* compressed file name */ 86 const char *fname; /* compressed file name */
87 Byte *uncompr; 87 Byte *uncompr;
88 uLong uncomprLen; 88 uLong uncomprLen;
89{ 89{
90#ifdef NO_GZCOMPRESS 90#ifdef NO_GZCOMPRESS
91 fprintf(stderr, "NO_GZCOMPRESS -- gz* functions cannot compress\n"); 91 fprintf(stderr, "NO_GZCOMPRESS -- gz* functions cannot compress\n");
92#else 92#else
93 int err; 93 int err;
94 int len = (int)strlen(hello)+1; 94 int len = (int)strlen(hello)+1;
95 gzFile file; 95 gzFile file;
96 z_off_t pos; 96 z_off_t pos;
97 97
98 file = gzopen(fname, "wb"); 98 file = gzopen(fname, "wb");
99 if (file == NULL) { 99 if (file == NULL) {
100 fprintf(stderr, "gzopen error\n"); 100 fprintf(stderr, "gzopen error\n");
101 exit(1); 101 exit(1);
102 } 102 }
103 gzputc(file, 'h'); 103 gzputc(file, 'h');
104 if (gzputs(file, "ello") != 4) { 104 if (gzputs(file, "ello") != 4) {
105 fprintf(stderr, "gzputs err: %s\n", gzerror(file, &err)); 105 fprintf(stderr, "gzputs err: %s\n", gzerror(file, &err));
106 exit(1); 106 exit(1);
107 } 107 }
108 if (gzprintf(file, ", %s!", "hello") != 8) { 108 if (gzprintf(file, ", %s!", "hello") != 8) {
109 fprintf(stderr, "gzprintf err: %s\n", gzerror(file, &err)); 109 fprintf(stderr, "gzprintf err: %s\n", gzerror(file, &err));
110 exit(1); 110 exit(1);
111 } 111 }
112 gzseek(file, 1L, SEEK_CUR); /* add one zero byte */ 112 gzseek(file, 1L, SEEK_CUR); /* add one zero byte */
113 gzclose(file); 113 gzclose(file);
114 114
115 file = gzopen(fname, "rb"); 115 file = gzopen(fname, "rb");
116 if (file == NULL) { 116 if (file == NULL) {
117 fprintf(stderr, "gzopen error\n"); 117 fprintf(stderr, "gzopen error\n");
118 exit(1); 118 exit(1);
119 } 119 }
120 strcpy((char*)uncompr, "garbage"); 120 strcpy((char*)uncompr, "garbage");
121 121
122 if (gzread(file, uncompr, (unsigned)uncomprLen) != len) { 122 if (gzread(file, uncompr, (unsigned)uncomprLen) != len) {
123 fprintf(stderr, "gzread err: %s\n", gzerror(file, &err)); 123 fprintf(stderr, "gzread err: %s\n", gzerror(file, &err));
124 exit(1); 124 exit(1);
125 } 125 }
126 if (strcmp((char*)uncompr, hello)) { 126 if (strcmp((char*)uncompr, hello)) {
127 fprintf(stderr, "bad gzread: %s\n", (char*)uncompr); 127 fprintf(stderr, "bad gzread: %s\n", (char*)uncompr);
128 exit(1); 128 exit(1);
129 } else { 129 } else {
130 printf("gzread(): %s\n", (char*)uncompr); 130 printf("gzread(): %s\n", (char*)uncompr);
131 } 131 }
132 132
133 pos = gzseek(file, -8L, SEEK_CUR); 133 pos = gzseek(file, -8L, SEEK_CUR);
134 if (pos != 6 || gztell(file) != pos) { 134 if (pos != 6 || gztell(file) != pos) {
135 fprintf(stderr, "gzseek error, pos=%ld, gztell=%ld\n", 135 fprintf(stderr, "gzseek error, pos=%ld, gztell=%ld\n",
136 (long)pos, (long)gztell(file)); 136 (long)pos, (long)gztell(file));
137 exit(1); 137 exit(1);
138 } 138 }
139 139
140 if (gzgetc(file) != ' ') { 140 if (gzgetc(file) != ' ') {
141 fprintf(stderr, "gzgetc error\n"); 141 fprintf(stderr, "gzgetc error\n");
142 exit(1); 142 exit(1);
143 } 143 }
144 144
145 if (gzungetc(' ', file) != ' ') { 145 if (gzungetc(' ', file) != ' ') {
146 fprintf(stderr, "gzungetc error\n"); 146 fprintf(stderr, "gzungetc error\n");
147 exit(1); 147 exit(1);
148 } 148 }
149 149
150 gzgets(file, (char*)uncompr, (int)uncomprLen); 150 gzgets(file, (char*)uncompr, (int)uncomprLen);
151 if (strlen((char*)uncompr) != 7) { /* " hello!" */ 151 if (strlen((char*)uncompr) != 7) { /* " hello!" */
152 fprintf(stderr, "gzgets err after gzseek: %s\n", gzerror(file, &err)); 152 fprintf(stderr, "gzgets err after gzseek: %s\n", gzerror(file, &err));
153 exit(1); 153 exit(1);
154 } 154 }
155 if (strcmp((char*)uncompr, hello + 6)) { 155 if (strcmp((char*)uncompr, hello + 6)) {
156 fprintf(stderr, "bad gzgets after gzseek\n"); 156 fprintf(stderr, "bad gzgets after gzseek\n");
157 exit(1); 157 exit(1);
158 } else { 158 } else {
159 printf("gzgets() after gzseek: %s\n", (char*)uncompr); 159 printf("gzgets() after gzseek: %s\n", (char*)uncompr);
160 } 160 }
161 161
162 gzclose(file); 162 gzclose(file);
163#endif 163#endif
164} 164}
165 165
166/* =========================================================================== 166/* ===========================================================================
167 * Test deflate() with small buffers 167 * Test deflate() with small buffers
168 */ 168 */
169void test_deflate(compr, comprLen) 169void test_deflate(compr, comprLen)
170 Byte *compr; 170 Byte *compr;
171 uLong comprLen; 171 uLong comprLen;
172{ 172{
173 z_stream c_stream; /* compression stream */ 173 z_stream c_stream; /* compression stream */
174 int err; 174 int err;
175 uLong len = (uLong)strlen(hello)+1; 175 uLong len = (uLong)strlen(hello)+1;
176 176
177 c_stream.zalloc = (alloc_func)0; 177 c_stream.zalloc = (alloc_func)0;
178 c_stream.zfree = (free_func)0; 178 c_stream.zfree = (free_func)0;
179 c_stream.opaque = (voidpf)0; 179 c_stream.opaque = (voidpf)0;
180 180
181 err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); 181 err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);
182 CHECK_ERR(err, "deflateInit"); 182 CHECK_ERR(err, "deflateInit");
183 183
184 c_stream.next_in = (Bytef*)hello; 184 c_stream.next_in = (Bytef*)hello;
185 c_stream.next_out = compr; 185 c_stream.next_out = compr;
186 186
187 while (c_stream.total_in != len && c_stream.total_out < comprLen) { 187 while (c_stream.total_in != len && c_stream.total_out < comprLen) {
188 c_stream.avail_in = c_stream.avail_out = 1; /* force small buffers */ 188 c_stream.avail_in = c_stream.avail_out = 1; /* force small buffers */
189 err = deflate(&c_stream, Z_NO_FLUSH); 189 err = deflate(&c_stream, Z_NO_FLUSH);
190 CHECK_ERR(err, "deflate"); 190 CHECK_ERR(err, "deflate");
191 } 191 }
192 /* Finish the stream, still forcing small buffers: */ 192 /* Finish the stream, still forcing small buffers: */
193 for (;;) { 193 for (;;) {
194 c_stream.avail_out = 1; 194 c_stream.avail_out = 1;
195 err = deflate(&c_stream, Z_FINISH); 195 err = deflate(&c_stream, Z_FINISH);
196 if (err == Z_STREAM_END) break; 196 if (err == Z_STREAM_END) break;
197 CHECK_ERR(err, "deflate"); 197 CHECK_ERR(err, "deflate");
198 } 198 }
199 199
200 err = deflateEnd(&c_stream); 200 err = deflateEnd(&c_stream);
201 CHECK_ERR(err, "deflateEnd"); 201 CHECK_ERR(err, "deflateEnd");
202} 202}
203 203
204/* =========================================================================== 204/* ===========================================================================
205 * Test inflate() with small buffers 205 * Test inflate() with small buffers
206 */ 206 */
207void test_inflate(compr, comprLen, uncompr, uncomprLen) 207void test_inflate(compr, comprLen, uncompr, uncomprLen)
208 Byte *compr, *uncompr; 208 Byte *compr, *uncompr;
209 uLong comprLen, uncomprLen; 209 uLong comprLen, uncomprLen;
210{ 210{
211 int err; 211 int err;
212 z_stream d_stream; /* decompression stream */ 212 z_stream d_stream; /* decompression stream */
213 213
214 strcpy((char*)uncompr, "garbage"); 214 strcpy((char*)uncompr, "garbage");
215 215
216 d_stream.zalloc = (alloc_func)0; 216 d_stream.zalloc = (alloc_func)0;
217 d_stream.zfree = (free_func)0; 217 d_stream.zfree = (free_func)0;
218 d_stream.opaque = (voidpf)0; 218 d_stream.opaque = (voidpf)0;
219 219
220 d_stream.next_in = compr; 220 d_stream.next_in = compr;
221 d_stream.avail_in = 0; 221 d_stream.avail_in = 0;
222 d_stream.next_out = uncompr; 222 d_stream.next_out = uncompr;
223 223
224 err = inflateInit(&d_stream); 224 err = inflateInit(&d_stream);
225 CHECK_ERR(err, "inflateInit"); 225 CHECK_ERR(err, "inflateInit");
226 226
227 while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen) { 227 while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen) {
228 d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */ 228 d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */
229 err = inflate(&d_stream, Z_NO_FLUSH); 229 err = inflate(&d_stream, Z_NO_FLUSH);
230 if (err == Z_STREAM_END) break; 230 if (err == Z_STREAM_END) break;
231 CHECK_ERR(err, "inflate"); 231 CHECK_ERR(err, "inflate");
232 } 232 }
233 233
234 err = inflateEnd(&d_stream); 234 err = inflateEnd(&d_stream);
235 CHECK_ERR(err, "inflateEnd"); 235 CHECK_ERR(err, "inflateEnd");
236 236
237 if (strcmp((char*)uncompr, hello)) { 237 if (strcmp((char*)uncompr, hello)) {
238 fprintf(stderr, "bad inflate\n"); 238 fprintf(stderr, "bad inflate\n");
239 exit(1); 239 exit(1);
240 } else { 240 } else {
241 printf("inflate(): %s\n", (char *)uncompr); 241 printf("inflate(): %s\n", (char *)uncompr);
242 } 242 }
243} 243}
244 244
245/* =========================================================================== 245/* ===========================================================================
246 * Test deflate() with large buffers and dynamic change of compression level 246 * Test deflate() with large buffers and dynamic change of compression level
247 */ 247 */
248void test_large_deflate(compr, comprLen, uncompr, uncomprLen) 248void test_large_deflate(compr, comprLen, uncompr, uncomprLen)
249 Byte *compr, *uncompr; 249 Byte *compr, *uncompr;
250 uLong comprLen, uncomprLen; 250 uLong comprLen, uncomprLen;
251{ 251{
252 z_stream c_stream; /* compression stream */ 252 z_stream c_stream; /* compression stream */
253 int err; 253 int err;
254 254
255 c_stream.zalloc = (alloc_func)0; 255 c_stream.zalloc = (alloc_func)0;
256 c_stream.zfree = (free_func)0; 256 c_stream.zfree = (free_func)0;
257 c_stream.opaque = (voidpf)0; 257 c_stream.opaque = (voidpf)0;
258 258
259 err = deflateInit(&c_stream, Z_BEST_SPEED); 259 err = deflateInit(&c_stream, Z_BEST_SPEED);
260 CHECK_ERR(err, "deflateInit"); 260 CHECK_ERR(err, "deflateInit");
261 261
262 c_stream.next_out = compr; 262 c_stream.next_out = compr;
263 c_stream.avail_out = (uInt)comprLen; 263 c_stream.avail_out = (uInt)comprLen;
264 264
265 /* At this point, uncompr is still mostly zeroes, so it should compress 265 /* At this point, uncompr is still mostly zeroes, so it should compress
266 * very well: 266 * very well:
267 */ 267 */
268 c_stream.next_in = uncompr; 268 c_stream.next_in = uncompr;
269 c_stream.avail_in = (uInt)uncomprLen; 269 c_stream.avail_in = (uInt)uncomprLen;
270 err = deflate(&c_stream, Z_NO_FLUSH); 270 err = deflate(&c_stream, Z_NO_FLUSH);
271 CHECK_ERR(err, "deflate"); 271 CHECK_ERR(err, "deflate");
272 if (c_stream.avail_in != 0) { 272 if (c_stream.avail_in != 0) {
273 fprintf(stderr, "deflate not greedy\n"); 273 fprintf(stderr, "deflate not greedy\n");
274 exit(1); 274 exit(1);
275 } 275 }
276 276
277 /* Feed in already compressed data and switch to no compression: */ 277 /* Feed in already compressed data and switch to no compression: */
278 deflateParams(&c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY); 278 deflateParams(&c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY);
279 c_stream.next_in = compr; 279 c_stream.next_in = compr;
280 c_stream.avail_in = (uInt)comprLen/2; 280 c_stream.avail_in = (uInt)comprLen/2;
281 err = deflate(&c_stream, Z_NO_FLUSH); 281 err = deflate(&c_stream, Z_NO_FLUSH);
282 CHECK_ERR(err, "deflate"); 282 CHECK_ERR(err, "deflate");
283 283
284 /* Switch back to compressing mode: */ 284 /* Switch back to compressing mode: */
285 deflateParams(&c_stream, Z_BEST_COMPRESSION, Z_FILTERED); 285 deflateParams(&c_stream, Z_BEST_COMPRESSION, Z_FILTERED);
286 c_stream.next_in = uncompr; 286 c_stream.next_in = uncompr;
287 c_stream.avail_in = (uInt)uncomprLen; 287 c_stream.avail_in = (uInt)uncomprLen;
288 err = deflate(&c_stream, Z_NO_FLUSH); 288 err = deflate(&c_stream, Z_NO_FLUSH);
289 CHECK_ERR(err, "deflate"); 289 CHECK_ERR(err, "deflate");
290 290
291 err = deflate(&c_stream, Z_FINISH); 291 err = deflate(&c_stream, Z_FINISH);
292 if (err != Z_STREAM_END) { 292 if (err != Z_STREAM_END) {
293 fprintf(stderr, "deflate should report Z_STREAM_END\n"); 293 fprintf(stderr, "deflate should report Z_STREAM_END\n");
294 exit(1); 294 exit(1);
295 } 295 }
296 err = deflateEnd(&c_stream); 296 err = deflateEnd(&c_stream);
297 CHECK_ERR(err, "deflateEnd"); 297 CHECK_ERR(err, "deflateEnd");
298} 298}
299 299
300/* =========================================================================== 300/* ===========================================================================
301 * Test inflate() with large buffers 301 * Test inflate() with large buffers
302 */ 302 */
303void test_large_inflate(compr, comprLen, uncompr, uncomprLen) 303void test_large_inflate(compr, comprLen, uncompr, uncomprLen)
304 Byte *compr, *uncompr; 304 Byte *compr, *uncompr;
305 uLong comprLen, uncomprLen; 305 uLong comprLen, uncomprLen;
306{ 306{
307 int err; 307 int err;
308 z_stream d_stream; /* decompression stream */ 308 z_stream d_stream; /* decompression stream */
309 309
310 strcpy((char*)uncompr, "garbage"); 310 strcpy((char*)uncompr, "garbage");
311 311
312 d_stream.zalloc = (alloc_func)0; 312 d_stream.zalloc = (alloc_func)0;
313 d_stream.zfree = (free_func)0; 313 d_stream.zfree = (free_func)0;
314 d_stream.opaque = (voidpf)0; 314 d_stream.opaque = (voidpf)0;
315 315
316 d_stream.next_in = compr; 316 d_stream.next_in = compr;
317 d_stream.avail_in = (uInt)comprLen; 317 d_stream.avail_in = (uInt)comprLen;
318 318
319 err = inflateInit(&d_stream); 319 err = inflateInit(&d_stream);
320 CHECK_ERR(err, "inflateInit"); 320 CHECK_ERR(err, "inflateInit");
321 321
322 for (;;) { 322 for (;;) {
323 d_stream.next_out = uncompr; /* discard the output */ 323 d_stream.next_out = uncompr; /* discard the output */
324 d_stream.avail_out = (uInt)uncomprLen; 324 d_stream.avail_out = (uInt)uncomprLen;
325 err = inflate(&d_stream, Z_NO_FLUSH); 325 err = inflate(&d_stream, Z_NO_FLUSH);
326 if (err == Z_STREAM_END) break; 326 if (err == Z_STREAM_END) break;
327 CHECK_ERR(err, "large inflate"); 327 CHECK_ERR(err, "large inflate");
328 } 328 }
329 329
330 err = inflateEnd(&d_stream); 330 err = inflateEnd(&d_stream);
331 CHECK_ERR(err, "inflateEnd"); 331 CHECK_ERR(err, "inflateEnd");
332 332
333 if (d_stream.total_out != 2*uncomprLen + comprLen/2) { 333 if (d_stream.total_out != 2*uncomprLen + comprLen/2) {
334 fprintf(stderr, "bad large inflate: %ld\n", d_stream.total_out); 334 fprintf(stderr, "bad large inflate: %ld\n", d_stream.total_out);
335 exit(1); 335 exit(1);
336 } else { 336 } else {
337 printf("large_inflate(): OK\n"); 337 printf("large_inflate(): OK\n");
338 } 338 }
339} 339}
340 340
341/* =========================================================================== 341/* ===========================================================================
342 * Test deflate() with full flush 342 * Test deflate() with full flush
343 */ 343 */
344void test_flush(compr, comprLen) 344void test_flush(compr, comprLen)
345 Byte *compr; 345 Byte *compr;
346 uLong *comprLen; 346 uLong *comprLen;
347{ 347{
348 z_stream c_stream; /* compression stream */ 348 z_stream c_stream; /* compression stream */
349 int err; 349 int err;
350 uInt len = (uInt)strlen(hello)+1; 350 uInt len = (uInt)strlen(hello)+1;
351 351
352 c_stream.zalloc = (alloc_func)0; 352 c_stream.zalloc = (alloc_func)0;
353 c_stream.zfree = (free_func)0; 353 c_stream.zfree = (free_func)0;
354 c_stream.opaque = (voidpf)0; 354 c_stream.opaque = (voidpf)0;
355 355
356 err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); 356 err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);
357 CHECK_ERR(err, "deflateInit"); 357 CHECK_ERR(err, "deflateInit");
358 358
359 c_stream.next_in = (Bytef*)hello; 359 c_stream.next_in = (Bytef*)hello;
360 c_stream.next_out = compr; 360 c_stream.next_out = compr;
361 c_stream.avail_in = 3; 361 c_stream.avail_in = 3;
362 c_stream.avail_out = (uInt)*comprLen; 362 c_stream.avail_out = (uInt)*comprLen;
363 err = deflate(&c_stream, Z_FULL_FLUSH); 363 err = deflate(&c_stream, Z_FULL_FLUSH);
364 CHECK_ERR(err, "deflate"); 364 CHECK_ERR(err, "deflate");
365 365
366 compr[3]++; /* force an error in first compressed block */ 366 compr[3]++; /* force an error in first compressed block */
367 c_stream.avail_in = len - 3; 367 c_stream.avail_in = len - 3;
368 368
369 err = deflate(&c_stream, Z_FINISH); 369 err = deflate(&c_stream, Z_FINISH);
370 if (err != Z_STREAM_END) { 370 if (err != Z_STREAM_END) {
371 CHECK_ERR(err, "deflate"); 371 CHECK_ERR(err, "deflate");
372 } 372 }
373 err = deflateEnd(&c_stream); 373 err = deflateEnd(&c_stream);
374 CHECK_ERR(err, "deflateEnd"); 374 CHECK_ERR(err, "deflateEnd");
375 375
376 *comprLen = c_stream.total_out; 376 *comprLen = c_stream.total_out;
377} 377}
378 378
379/* =========================================================================== 379/* ===========================================================================
380 * Test inflateSync() 380 * Test inflateSync()
381 */ 381 */
382void test_sync(compr, comprLen, uncompr, uncomprLen) 382void test_sync(compr, comprLen, uncompr, uncomprLen)
383 Byte *compr, *uncompr; 383 Byte *compr, *uncompr;
384 uLong comprLen, uncomprLen; 384 uLong comprLen, uncomprLen;
385{ 385{
386 int err; 386 int err;
387 z_stream d_stream; /* decompression stream */ 387 z_stream d_stream; /* decompression stream */
388 388
389 strcpy((char*)uncompr, "garbage"); 389 strcpy((char*)uncompr, "garbage");
390 390
391 d_stream.zalloc = (alloc_func)0; 391 d_stream.zalloc = (alloc_func)0;
392 d_stream.zfree = (free_func)0; 392 d_stream.zfree = (free_func)0;
393 d_stream.opaque = (voidpf)0; 393 d_stream.opaque = (voidpf)0;
394 394
395 d_stream.next_in = compr; 395 d_stream.next_in = compr;
396 d_stream.avail_in = 2; /* just read the zlib header */ 396 d_stream.avail_in = 2; /* just read the zlib header */
397 397
398 err = inflateInit(&d_stream); 398 err = inflateInit(&d_stream);
399 CHECK_ERR(err, "inflateInit"); 399 CHECK_ERR(err, "inflateInit");
400 400
401 d_stream.next_out = uncompr; 401 d_stream.next_out = uncompr;
402 d_stream.avail_out = (uInt)uncomprLen; 402 d_stream.avail_out = (uInt)uncomprLen;
403 403
404 inflate(&d_stream, Z_NO_FLUSH); 404 inflate(&d_stream, Z_NO_FLUSH);
405 CHECK_ERR(err, "inflate"); 405 CHECK_ERR(err, "inflate");
406 406
407 d_stream.avail_in = (uInt)comprLen-2; /* read all compressed data */ 407 d_stream.avail_in = (uInt)comprLen-2; /* read all compressed data */
408 err = inflateSync(&d_stream); /* but skip the damaged part */ 408 err = inflateSync(&d_stream); /* but skip the damaged part */
409 CHECK_ERR(err, "inflateSync"); 409 CHECK_ERR(err, "inflateSync");
410 410
411 err = inflate(&d_stream, Z_FINISH); 411 err = inflate(&d_stream, Z_FINISH);
412 if (err != Z_DATA_ERROR) { 412 if (err != Z_DATA_ERROR) {
413 fprintf(stderr, "inflate should report DATA_ERROR\n"); 413 fprintf(stderr, "inflate should report DATA_ERROR\n");
414 /* Because of incorrect adler32 */ 414 /* Because of incorrect adler32 */
415 exit(1); 415 exit(1);
416 } 416 }
417 err = inflateEnd(&d_stream); 417 err = inflateEnd(&d_stream);
418 CHECK_ERR(err, "inflateEnd"); 418 CHECK_ERR(err, "inflateEnd");
419 419
420 printf("after inflateSync(): hel%s\n", (char *)uncompr); 420 printf("after inflateSync(): hel%s\n", (char *)uncompr);
421} 421}
422 422
423/* =========================================================================== 423/* ===========================================================================
424 * Test deflate() with preset dictionary 424 * Test deflate() with preset dictionary
425 */ 425 */
426void test_dict_deflate(compr, comprLen) 426void test_dict_deflate(compr, comprLen)
427 Byte *compr; 427 Byte *compr;
428 uLong comprLen; 428 uLong comprLen;
429{ 429{
430 z_stream c_stream; /* compression stream */ 430 z_stream c_stream; /* compression stream */
431 int err; 431 int err;
432 432
433 c_stream.zalloc = (alloc_func)0; 433 c_stream.zalloc = (alloc_func)0;
434 c_stream.zfree = (free_func)0; 434 c_stream.zfree = (free_func)0;
435 c_stream.opaque = (voidpf)0; 435 c_stream.opaque = (voidpf)0;
436 436
437 err = deflateInit(&c_stream, Z_BEST_COMPRESSION); 437 err = deflateInit(&c_stream, Z_BEST_COMPRESSION);
438 CHECK_ERR(err, "deflateInit"); 438 CHECK_ERR(err, "deflateInit");
439 439
440 err = deflateSetDictionary(&c_stream, 440 err = deflateSetDictionary(&c_stream,
441 (const Bytef*)dictionary, sizeof(dictionary)); 441 (const Bytef*)dictionary, sizeof(dictionary));
442 CHECK_ERR(err, "deflateSetDictionary"); 442 CHECK_ERR(err, "deflateSetDictionary");
443 443
444 dictId = c_stream.adler; 444 dictId = c_stream.adler;
445 c_stream.next_out = compr; 445 c_stream.next_out = compr;
446 c_stream.avail_out = (uInt)comprLen; 446 c_stream.avail_out = (uInt)comprLen;
447 447
448 c_stream.next_in = (Bytef*)hello; 448 c_stream.next_in = (Bytef*)hello;
449 c_stream.avail_in = (uInt)strlen(hello)+1; 449 c_stream.avail_in = (uInt)strlen(hello)+1;
450 450
451 err = deflate(&c_stream, Z_FINISH); 451 err = deflate(&c_stream, Z_FINISH);
452 if (err != Z_STREAM_END) { 452 if (err != Z_STREAM_END) {
453 fprintf(stderr, "deflate should report Z_STREAM_END\n"); 453 fprintf(stderr, "deflate should report Z_STREAM_END\n");
454 exit(1); 454 exit(1);
455 } 455 }
456 err = deflateEnd(&c_stream); 456 err = deflateEnd(&c_stream);
457 CHECK_ERR(err, "deflateEnd"); 457 CHECK_ERR(err, "deflateEnd");
458} 458}
459 459
460/* =========================================================================== 460/* ===========================================================================
461 * Test inflate() with a preset dictionary 461 * Test inflate() with a preset dictionary
462 */ 462 */
463void test_dict_inflate(compr, comprLen, uncompr, uncomprLen) 463void test_dict_inflate(compr, comprLen, uncompr, uncomprLen)
464 Byte *compr, *uncompr; 464 Byte *compr, *uncompr;
465 uLong comprLen, uncomprLen; 465 uLong comprLen, uncomprLen;
466{ 466{
467 int err; 467 int err;
468 z_stream d_stream; /* decompression stream */ 468 z_stream d_stream; /* decompression stream */
469 469
470 strcpy((char*)uncompr, "garbage"); 470 strcpy((char*)uncompr, "garbage");
471 471
472 d_stream.zalloc = (alloc_func)0; 472 d_stream.zalloc = (alloc_func)0;
473 d_stream.zfree = (free_func)0; 473 d_stream.zfree = (free_func)0;
474 d_stream.opaque = (voidpf)0; 474 d_stream.opaque = (voidpf)0;
475 475
476 d_stream.next_in = compr; 476 d_stream.next_in = compr;
477 d_stream.avail_in = (uInt)comprLen; 477 d_stream.avail_in = (uInt)comprLen;
478 478
479 err = inflateInit(&d_stream); 479 err = inflateInit(&d_stream);
480 CHECK_ERR(err, "inflateInit"); 480 CHECK_ERR(err, "inflateInit");
481 481
482 d_stream.next_out = uncompr; 482 d_stream.next_out = uncompr;
483 d_stream.avail_out = (uInt)uncomprLen; 483 d_stream.avail_out = (uInt)uncomprLen;
484 484
485 for (;;) { 485 for (;;) {
486 err = inflate(&d_stream, Z_NO_FLUSH); 486 err = inflate(&d_stream, Z_NO_FLUSH);
487 if (err == Z_STREAM_END) break; 487 if (err == Z_STREAM_END) break;
488 if (err == Z_NEED_DICT) { 488 if (err == Z_NEED_DICT) {
489 if (d_stream.adler != dictId) { 489 if (d_stream.adler != dictId) {
490 fprintf(stderr, "unexpected dictionary"); 490 fprintf(stderr, "unexpected dictionary");
491 exit(1); 491 exit(1);
492 } 492 }
493 err = inflateSetDictionary(&d_stream, (const Bytef*)dictionary, 493 err = inflateSetDictionary(&d_stream, (const Bytef*)dictionary,
494 sizeof(dictionary)); 494 sizeof(dictionary));
495 } 495 }
496 CHECK_ERR(err, "inflate with dict"); 496 CHECK_ERR(err, "inflate with dict");
497 } 497 }
498 498
499 err = inflateEnd(&d_stream); 499 err = inflateEnd(&d_stream);
500 CHECK_ERR(err, "inflateEnd"); 500 CHECK_ERR(err, "inflateEnd");
501 501
502 if (strcmp((char*)uncompr, hello)) { 502 if (strcmp((char*)uncompr, hello)) {
503 fprintf(stderr, "bad inflate with dict\n"); 503 fprintf(stderr, "bad inflate with dict\n");
504 exit(1); 504 exit(1);
505 } else { 505 } else {
506 printf("inflate with dictionary: %s\n", (char *)uncompr); 506 printf("inflate with dictionary: %s\n", (char *)uncompr);
507 } 507 }
508} 508}
509 509
510/* =========================================================================== 510/* ===========================================================================
511 * Usage: example [output.gz [input.gz]] 511 * Usage: example [output.gz [input.gz]]
512 */ 512 */
513 513
514int main(argc, argv) 514int main(argc, argv)
515 int argc; 515 int argc;
516 char *argv[]; 516 char *argv[];
517{ 517{
518 Byte *compr, *uncompr; 518 Byte *compr, *uncompr;
519 uLong comprLen = 10000*sizeof(int); /* don't overflow on MSDOS */ 519 uLong comprLen = 10000*sizeof(int); /* don't overflow on MSDOS */
520 uLong uncomprLen = comprLen; 520 uLong uncomprLen = comprLen;
521 static const char* myVersion = ZLIB_VERSION; 521 static const char* myVersion = ZLIB_VERSION;
522 522
523 if (zlibVersion()[0] != myVersion[0]) { 523 if (zlibVersion()[0] != myVersion[0]) {
524 fprintf(stderr, "incompatible zlib version\n"); 524 fprintf(stderr, "incompatible zlib version\n");
525 exit(1); 525 exit(1);
526 526
527 } else if (strcmp(zlibVersion(), ZLIB_VERSION) != 0) { 527 } else if (strcmp(zlibVersion(), ZLIB_VERSION) != 0) {
528 fprintf(stderr, "warning: different zlib version\n"); 528 fprintf(stderr, "warning: different zlib version\n");
529 } 529 }
530 530
531 printf("zlib version %s = 0x%04x, compile flags = 0x%lx\n", 531 printf("zlib version %s = 0x%04x, compile flags = 0x%lx\n",
532 ZLIB_VERSION, ZLIB_VERNUM, zlibCompileFlags()); 532 ZLIB_VERSION, ZLIB_VERNUM, zlibCompileFlags());
533 533
534 compr = (Byte*)calloc((uInt)comprLen, 1); 534 compr = (Byte*)calloc((uInt)comprLen, 1);
535 uncompr = (Byte*)calloc((uInt)uncomprLen, 1); 535 uncompr = (Byte*)calloc((uInt)uncomprLen, 1);
536 /* compr and uncompr are cleared to avoid reading uninitialized 536 /* compr and uncompr are cleared to avoid reading uninitialized
537 * data and to ensure that uncompr compresses well. 537 * data and to ensure that uncompr compresses well.
538 */ 538 */
539 if (compr == Z_NULL || uncompr == Z_NULL) { 539 if (compr == Z_NULL || uncompr == Z_NULL) {
540 printf("out of memory\n"); 540 printf("out of memory\n");
541 exit(1); 541 exit(1);
542 } 542 }
543 test_compress(compr, comprLen, uncompr, uncomprLen); 543 test_compress(compr, comprLen, uncompr, uncomprLen);
544 544
545 test_gzio((argc > 1 ? argv[1] : TESTFILE), 545 test_gzio((argc > 1 ? argv[1] : TESTFILE),
546 uncompr, uncomprLen); 546 uncompr, uncomprLen);
547 547
548 test_deflate(compr, comprLen); 548 test_deflate(compr, comprLen);
549 test_inflate(compr, comprLen, uncompr, uncomprLen); 549 test_inflate(compr, comprLen, uncompr, uncomprLen);
550 550
551 test_large_deflate(compr, comprLen, uncompr, uncomprLen); 551 test_large_deflate(compr, comprLen, uncompr, uncomprLen);
552 test_large_inflate(compr, comprLen, uncompr, uncomprLen); 552 test_large_inflate(compr, comprLen, uncompr, uncomprLen);
553 553
554 test_flush(compr, &comprLen); 554 test_flush(compr, &comprLen);
555 test_sync(compr, comprLen, uncompr, uncomprLen); 555 test_sync(compr, comprLen, uncompr, uncomprLen);
556 comprLen = uncomprLen; 556 comprLen = uncomprLen;
557 557
558 test_dict_deflate(compr, comprLen); 558 test_dict_deflate(compr, comprLen);
559 test_dict_inflate(compr, comprLen, uncompr, uncomprLen); 559 test_dict_inflate(compr, comprLen, uncompr, uncomprLen);
560 560
561 free(compr); 561 free(compr);
562 free(uncompr); 562 free(uncompr);
563 563
564 return 0; 564 return 0;
565} 565}
diff --git a/utils/zenutils/libraries/zlib123/zlib/gzio.c b/utils/zenutils/libraries/zlib123/zlib/gzio.c
index 5e20a4aa0d..7e90f4928f 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/gzio.c
+++ b/utils/zenutils/libraries/zlib123/zlib/gzio.c
@@ -1,1026 +1,1026 @@
1/* gzio.c -- IO on .gz files 1/* gzio.c -- IO on .gz files
2 * Copyright (C) 1995-2005 Jean-loup Gailly. 2 * Copyright (C) 1995-2005 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 * 4 *
5 * Compile this file with -DNO_GZCOMPRESS to avoid the compression code. 5 * Compile this file with -DNO_GZCOMPRESS to avoid the compression code.
6 */ 6 */
7 7
8/* @(#) $Id$ */ 8/* @(#) $Id$ */
9 9
10#include <stdio.h> 10#include <stdio.h>
11 11
12#include "zutil.h" 12#include "zutil.h"
13 13
14#ifdef NO_DEFLATE /* for compatibility with old definition */ 14#ifdef NO_DEFLATE /* for compatibility with old definition */
15# define NO_GZCOMPRESS 15# define NO_GZCOMPRESS
16#endif 16#endif
17 17
18#ifndef NO_DUMMY_DECL 18#ifndef NO_DUMMY_DECL
19struct internal_state {int dummy;}; /* for buggy compilers */ 19struct internal_state {int dummy;}; /* for buggy compilers */
20#endif 20#endif
21 21
22#ifndef Z_BUFSIZE 22#ifndef Z_BUFSIZE
23# ifdef MAXSEG_64K 23# ifdef MAXSEG_64K
24# define Z_BUFSIZE 4096 /* minimize memory usage for 16-bit DOS */ 24# define Z_BUFSIZE 4096 /* minimize memory usage for 16-bit DOS */
25# else 25# else
26# define Z_BUFSIZE 16384 26# define Z_BUFSIZE 16384
27# endif 27# endif
28#endif 28#endif
29#ifndef Z_PRINTF_BUFSIZE 29#ifndef Z_PRINTF_BUFSIZE
30# define Z_PRINTF_BUFSIZE 4096 30# define Z_PRINTF_BUFSIZE 4096
31#endif 31#endif
32 32
33#ifdef __MVS__ 33#ifdef __MVS__
34# pragma map (fdopen , "\174\174FDOPEN") 34# pragma map (fdopen , "\174\174FDOPEN")
35 FILE *fdopen(int, const char *); 35 FILE *fdopen(int, const char *);
36#endif 36#endif
37 37
38#ifndef STDC 38#ifndef STDC
39extern voidp malloc OF((uInt size)); 39extern voidp malloc OF((uInt size));
40extern void free OF((voidpf ptr)); 40extern void free OF((voidpf ptr));
41#endif 41#endif
42 42
43#define ALLOC(size) malloc(size) 43#define ALLOC(size) malloc(size)
44#define TRYFREE(p) {if (p) free(p);} 44#define TRYFREE(p) {if (p) free(p);}
45 45
46static int const gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */ 46static int const gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
47 47
48/* gzip flag byte */ 48/* gzip flag byte */
49#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */ 49#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
50#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */ 50#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */
51#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */ 51#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
52#define ORIG_NAME 0x08 /* bit 3 set: original file name present */ 52#define ORIG_NAME 0x08 /* bit 3 set: original file name present */
53#define COMMENT 0x10 /* bit 4 set: file comment present */ 53#define COMMENT 0x10 /* bit 4 set: file comment present */
54#define RESERVED 0xE0 /* bits 5..7: reserved */ 54#define RESERVED 0xE0 /* bits 5..7: reserved */
55 55
56typedef struct gz_stream { 56typedef struct gz_stream {
57 z_stream stream; 57 z_stream stream;
58 int z_err; /* error code for last stream operation */ 58 int z_err; /* error code for last stream operation */
59 int z_eof; /* set if end of input file */ 59 int z_eof; /* set if end of input file */
60 FILE *file; /* .gz file */ 60 FILE *file; /* .gz file */
61 Byte *inbuf; /* input buffer */ 61 Byte *inbuf; /* input buffer */
62 Byte *outbuf; /* output buffer */ 62 Byte *outbuf; /* output buffer */
63 uLong crc; /* crc32 of uncompressed data */ 63 uLong crc; /* crc32 of uncompressed data */
64 char *msg; /* error message */ 64 char *msg; /* error message */
65 char *path; /* path name for debugging only */ 65 char *path; /* path name for debugging only */
66 int transparent; /* 1 if input file is not a .gz file */ 66 int transparent; /* 1 if input file is not a .gz file */
67 char mode; /* 'w' or 'r' */ 67 char mode; /* 'w' or 'r' */
68 z_off_t start; /* start of compressed data in file (header skipped) */ 68 z_off_t start; /* start of compressed data in file (header skipped) */
69 z_off_t in; /* bytes into deflate or inflate */ 69 z_off_t in; /* bytes into deflate or inflate */
70 z_off_t out; /* bytes out of deflate or inflate */ 70 z_off_t out; /* bytes out of deflate or inflate */
71 int back; /* one character push-back */ 71 int back; /* one character push-back */
72 int last; /* true if push-back is last character */ 72 int last; /* true if push-back is last character */
73} gz_stream; 73} gz_stream;
74 74
75 75
76local gzFile gz_open OF((const char *path, const char *mode, int fd)); 76local gzFile gz_open OF((const char *path, const char *mode, int fd));
77local int do_flush OF((gzFile file, int flush)); 77local int do_flush OF((gzFile file, int flush));
78local int get_byte OF((gz_stream *s)); 78local int get_byte OF((gz_stream *s));
79local void check_header OF((gz_stream *s)); 79local void check_header OF((gz_stream *s));
80local int destroy OF((gz_stream *s)); 80local int destroy OF((gz_stream *s));
81local void putLong OF((FILE *file, uLong x)); 81local void putLong OF((FILE *file, uLong x));
82local uLong getLong OF((gz_stream *s)); 82local uLong getLong OF((gz_stream *s));
83 83
84/* =========================================================================== 84/* ===========================================================================
85 Opens a gzip (.gz) file for reading or writing. The mode parameter 85 Opens a gzip (.gz) file for reading or writing. The mode parameter
86 is as in fopen ("rb" or "wb"). The file is given either by file descriptor 86 is as in fopen ("rb" or "wb"). The file is given either by file descriptor
87 or path name (if fd == -1). 87 or path name (if fd == -1).
88 gz_open returns NULL if the file could not be opened or if there was 88 gz_open returns NULL if the file could not be opened or if there was
89 insufficient memory to allocate the (de)compression state; errno 89 insufficient memory to allocate the (de)compression state; errno
90 can be checked to distinguish the two cases (if errno is zero, the 90 can be checked to distinguish the two cases (if errno is zero, the
91 zlib error is Z_MEM_ERROR). 91 zlib error is Z_MEM_ERROR).
92*/ 92*/
93local gzFile gz_open (path, mode, fd) 93local gzFile gz_open (path, mode, fd)
94 const char *path; 94 const char *path;
95 const char *mode; 95 const char *mode;
96 int fd; 96 int fd;
97{ 97{
98 int err; 98 int err;
99 int level = Z_DEFAULT_COMPRESSION; /* compression level */ 99 int level = Z_DEFAULT_COMPRESSION; /* compression level */
100 int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */ 100 int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */
101 char *p = (char*)mode; 101 char *p = (char*)mode;
102 gz_stream *s; 102 gz_stream *s;
103 char fmode[80]; /* copy of mode, without the compression level */ 103 char fmode[80]; /* copy of mode, without the compression level */
104 char *m = fmode; 104 char *m = fmode;
105 105
106 if (!path || !mode) return Z_NULL; 106 if (!path || !mode) return Z_NULL;
107 107
108 s = (gz_stream *)ALLOC(sizeof(gz_stream)); 108 s = (gz_stream *)ALLOC(sizeof(gz_stream));
109 if (!s) return Z_NULL; 109 if (!s) return Z_NULL;
110 110
111 s->stream.zalloc = (alloc_func)0; 111 s->stream.zalloc = (alloc_func)0;
112 s->stream.zfree = (free_func)0; 112 s->stream.zfree = (free_func)0;
113 s->stream.opaque = (voidpf)0; 113 s->stream.opaque = (voidpf)0;
114 s->stream.next_in = s->inbuf = Z_NULL; 114 s->stream.next_in = s->inbuf = Z_NULL;
115 s->stream.next_out = s->outbuf = Z_NULL; 115 s->stream.next_out = s->outbuf = Z_NULL;
116 s->stream.avail_in = s->stream.avail_out = 0; 116 s->stream.avail_in = s->stream.avail_out = 0;
117 s->file = NULL; 117 s->file = NULL;
118 s->z_err = Z_OK; 118 s->z_err = Z_OK;
119 s->z_eof = 0; 119 s->z_eof = 0;
120 s->in = 0; 120 s->in = 0;
121 s->out = 0; 121 s->out = 0;
122 s->back = EOF; 122 s->back = EOF;
123 s->crc = crc32(0L, Z_NULL, 0); 123 s->crc = crc32(0L, Z_NULL, 0);
124 s->msg = NULL; 124 s->msg = NULL;
125 s->transparent = 0; 125 s->transparent = 0;
126 126
127 s->path = (char*)ALLOC(strlen(path)+1); 127 s->path = (char*)ALLOC(strlen(path)+1);
128 if (s->path == NULL) { 128 if (s->path == NULL) {
129 return destroy(s), (gzFile)Z_NULL; 129 return destroy(s), (gzFile)Z_NULL;
130 } 130 }
131 strcpy(s->path, path); /* do this early for debugging */ 131 strcpy(s->path, path); /* do this early for debugging */
132 132
133 s->mode = '\0'; 133 s->mode = '\0';
134 do { 134 do {
135 if (*p == 'r') s->mode = 'r'; 135 if (*p == 'r') s->mode = 'r';
136 if (*p == 'w' || *p == 'a') s->mode = 'w'; 136 if (*p == 'w' || *p == 'a') s->mode = 'w';
137 if (*p >= '0' && *p <= '9') { 137 if (*p >= '0' && *p <= '9') {
138 level = *p - '0'; 138 level = *p - '0';
139 } else if (*p == 'f') { 139 } else if (*p == 'f') {
140 strategy = Z_FILTERED; 140 strategy = Z_FILTERED;
141 } else if (*p == 'h') { 141 } else if (*p == 'h') {
142 strategy = Z_HUFFMAN_ONLY; 142 strategy = Z_HUFFMAN_ONLY;
143 } else if (*p == 'R') { 143 } else if (*p == 'R') {
144 strategy = Z_RLE; 144 strategy = Z_RLE;
145 } else { 145 } else {
146 *m++ = *p; /* copy the mode */ 146 *m++ = *p; /* copy the mode */
147 } 147 }
148 } while (*p++ && m != fmode + sizeof(fmode)); 148 } while (*p++ && m != fmode + sizeof(fmode));
149 if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL; 149 if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL;
150 150
151 if (s->mode == 'w') { 151 if (s->mode == 'w') {
152#ifdef NO_GZCOMPRESS 152#ifdef NO_GZCOMPRESS
153 err = Z_STREAM_ERROR; 153 err = Z_STREAM_ERROR;
154#else 154#else
155 err = deflateInit2(&(s->stream), level, 155 err = deflateInit2(&(s->stream), level,
156 Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy); 156 Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy);
157 /* windowBits is passed < 0 to suppress zlib header */ 157 /* windowBits is passed < 0 to suppress zlib header */
158 158
159 s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); 159 s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
160#endif 160#endif
161 if (err != Z_OK || s->outbuf == Z_NULL) { 161 if (err != Z_OK || s->outbuf == Z_NULL) {
162 return destroy(s), (gzFile)Z_NULL; 162 return destroy(s), (gzFile)Z_NULL;
163 } 163 }
164 } else { 164 } else {
165 s->stream.next_in = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); 165 s->stream.next_in = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE);
166 166
167 err = inflateInit2(&(s->stream), -MAX_WBITS); 167 err = inflateInit2(&(s->stream), -MAX_WBITS);
168 /* windowBits is passed < 0 to tell that there is no zlib header. 168 /* windowBits is passed < 0 to tell that there is no zlib header.
169 * Note that in this case inflate *requires* an extra "dummy" byte 169 * Note that in this case inflate *requires* an extra "dummy" byte
170 * after the compressed stream in order to complete decompression and 170 * after the compressed stream in order to complete decompression and
171 * return Z_STREAM_END. Here the gzip CRC32 ensures that 4 bytes are 171 * return Z_STREAM_END. Here the gzip CRC32 ensures that 4 bytes are
172 * present after the compressed stream. 172 * present after the compressed stream.
173 */ 173 */
174 if (err != Z_OK || s->inbuf == Z_NULL) { 174 if (err != Z_OK || s->inbuf == Z_NULL) {
175 return destroy(s), (gzFile)Z_NULL; 175 return destroy(s), (gzFile)Z_NULL;
176 } 176 }
177 } 177 }
178 s->stream.avail_out = Z_BUFSIZE; 178 s->stream.avail_out = Z_BUFSIZE;
179 179
180 errno = 0; 180 errno = 0;
181 s->file = fd < 0 ? F_OPEN(path, fmode) : (FILE*)fdopen(fd, fmode); 181 s->file = fd < 0 ? F_OPEN(path, fmode) : (FILE*)fdopen(fd, fmode);
182 182
183 if (s->file == NULL) { 183 if (s->file == NULL) {
184 return destroy(s), (gzFile)Z_NULL; 184 return destroy(s), (gzFile)Z_NULL;
185 } 185 }
186 if (s->mode == 'w') { 186 if (s->mode == 'w') {
187 /* Write a very simple .gz header: 187 /* Write a very simple .gz header:
188 */ 188 */
189 fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1], 189 fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1],
190 Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE); 190 Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE);
191 s->start = 10L; 191 s->start = 10L;
192 /* We use 10L instead of ftell(s->file) to because ftell causes an 192 /* We use 10L instead of ftell(s->file) to because ftell causes an
193 * fflush on some systems. This version of the library doesn't use 193 * fflush on some systems. This version of the library doesn't use
194 * start anyway in write mode, so this initialization is not 194 * start anyway in write mode, so this initialization is not
195 * necessary. 195 * necessary.
196 */ 196 */
197 } else { 197 } else {
198 check_header(s); /* skip the .gz header */ 198 check_header(s); /* skip the .gz header */
199 s->start = ftell(s->file) - s->stream.avail_in; 199 s->start = ftell(s->file) - s->stream.avail_in;
200 } 200 }
201 201
202 return (gzFile)s; 202 return (gzFile)s;
203} 203}
204 204
205/* =========================================================================== 205/* ===========================================================================
206 Opens a gzip (.gz) file for reading or writing. 206 Opens a gzip (.gz) file for reading or writing.
207*/ 207*/
208gzFile ZEXPORT gzopen (path, mode) 208gzFile ZEXPORT gzopen (path, mode)
209 const char *path; 209 const char *path;
210 const char *mode; 210 const char *mode;
211{ 211{
212 return gz_open (path, mode, -1); 212 return gz_open (path, mode, -1);
213} 213}
214 214
215/* =========================================================================== 215/* ===========================================================================
216 Associate a gzFile with the file descriptor fd. fd is not dup'ed here 216 Associate a gzFile with the file descriptor fd. fd is not dup'ed here
217 to mimic the behavio(u)r of fdopen. 217 to mimic the behavio(u)r of fdopen.
218*/ 218*/
219gzFile ZEXPORT gzdopen (fd, mode) 219gzFile ZEXPORT gzdopen (fd, mode)
220 int fd; 220 int fd;
221 const char *mode; 221 const char *mode;
222{ 222{
223 char name[46]; /* allow for up to 128-bit integers */ 223 char name[46]; /* allow for up to 128-bit integers */
224 224
225 if (fd < 0) return (gzFile)Z_NULL; 225 if (fd < 0) return (gzFile)Z_NULL;
226 sprintf(name, "<fd:%d>", fd); /* for debugging */ 226 sprintf(name, "<fd:%d>", fd); /* for debugging */
227 227
228 return gz_open (name, mode, fd); 228 return gz_open (name, mode, fd);
229} 229}
230 230
231/* =========================================================================== 231/* ===========================================================================
232 * Update the compression level and strategy 232 * Update the compression level and strategy
233 */ 233 */
234int ZEXPORT gzsetparams (file, level, strategy) 234int ZEXPORT gzsetparams (file, level, strategy)
235 gzFile file; 235 gzFile file;
236 int level; 236 int level;
237 int strategy; 237 int strategy;
238{ 238{
239 gz_stream *s = (gz_stream*)file; 239 gz_stream *s = (gz_stream*)file;
240 240
241 if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; 241 if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
242 242
243 /* Make room to allow flushing */ 243 /* Make room to allow flushing */
244 if (s->stream.avail_out == 0) { 244 if (s->stream.avail_out == 0) {
245 245
246 s->stream.next_out = s->outbuf; 246 s->stream.next_out = s->outbuf;
247 if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) { 247 if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
248 s->z_err = Z_ERRNO; 248 s->z_err = Z_ERRNO;
249 } 249 }
250 s->stream.avail_out = Z_BUFSIZE; 250 s->stream.avail_out = Z_BUFSIZE;
251 } 251 }
252 252
253 return deflateParams (&(s->stream), level, strategy); 253 return deflateParams (&(s->stream), level, strategy);
254} 254}
255 255
256/* =========================================================================== 256/* ===========================================================================
257 Read a byte from a gz_stream; update next_in and avail_in. Return EOF 257 Read a byte from a gz_stream; update next_in and avail_in. Return EOF
258 for end of file. 258 for end of file.
259 IN assertion: the stream s has been sucessfully opened for reading. 259 IN assertion: the stream s has been sucessfully opened for reading.
260*/ 260*/
261local int get_byte(s) 261local int get_byte(s)
262 gz_stream *s; 262 gz_stream *s;
263{ 263{
264 if (s->z_eof) return EOF; 264 if (s->z_eof) return EOF;
265 if (s->stream.avail_in == 0) { 265 if (s->stream.avail_in == 0) {
266 errno = 0; 266 errno = 0;
267 s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file); 267 s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file);
268 if (s->stream.avail_in == 0) { 268 if (s->stream.avail_in == 0) {
269 s->z_eof = 1; 269 s->z_eof = 1;
270 if (ferror(s->file)) s->z_err = Z_ERRNO; 270 if (ferror(s->file)) s->z_err = Z_ERRNO;
271 return EOF; 271 return EOF;
272 } 272 }
273 s->stream.next_in = s->inbuf; 273 s->stream.next_in = s->inbuf;
274 } 274 }
275 s->stream.avail_in--; 275 s->stream.avail_in--;
276 return *(s->stream.next_in)++; 276 return *(s->stream.next_in)++;
277} 277}
278 278
279/* =========================================================================== 279/* ===========================================================================
280 Check the gzip header of a gz_stream opened for reading. Set the stream 280 Check the gzip header of a gz_stream opened for reading. Set the stream
281 mode to transparent if the gzip magic header is not present; set s->err 281 mode to transparent if the gzip magic header is not present; set s->err
282 to Z_DATA_ERROR if the magic header is present but the rest of the header 282 to Z_DATA_ERROR if the magic header is present but the rest of the header
283 is incorrect. 283 is incorrect.
284 IN assertion: the stream s has already been created sucessfully; 284 IN assertion: the stream s has already been created sucessfully;
285 s->stream.avail_in is zero for the first time, but may be non-zero 285 s->stream.avail_in is zero for the first time, but may be non-zero
286 for concatenated .gz files. 286 for concatenated .gz files.
287*/ 287*/
288local void check_header(s) 288local void check_header(s)
289 gz_stream *s; 289 gz_stream *s;
290{ 290{
291 int method; /* method byte */ 291 int method; /* method byte */
292 int flags; /* flags byte */ 292 int flags; /* flags byte */
293 uInt len; 293 uInt len;
294 int c; 294 int c;
295 295
296 /* Assure two bytes in the buffer so we can peek ahead -- handle case 296 /* Assure two bytes in the buffer so we can peek ahead -- handle case
297 where first byte of header is at the end of the buffer after the last 297 where first byte of header is at the end of the buffer after the last
298 gzip segment */ 298 gzip segment */
299 len = s->stream.avail_in; 299 len = s->stream.avail_in;
300 if (len < 2) { 300 if (len < 2) {
301 if (len) s->inbuf[0] = s->stream.next_in[0]; 301 if (len) s->inbuf[0] = s->stream.next_in[0];
302 errno = 0; 302 errno = 0;
303 len = (uInt)fread(s->inbuf + len, 1, Z_BUFSIZE >> len, s->file); 303 len = (uInt)fread(s->inbuf + len, 1, Z_BUFSIZE >> len, s->file);
304 if (len == 0 && ferror(s->file)) s->z_err = Z_ERRNO; 304 if (len == 0 && ferror(s->file)) s->z_err = Z_ERRNO;
305 s->stream.avail_in += len; 305 s->stream.avail_in += len;
306 s->stream.next_in = s->inbuf; 306 s->stream.next_in = s->inbuf;
307 if (s->stream.avail_in < 2) { 307 if (s->stream.avail_in < 2) {
308 s->transparent = s->stream.avail_in; 308 s->transparent = s->stream.avail_in;
309 return; 309 return;
310 } 310 }
311 } 311 }
312 312
313 /* Peek ahead to check the gzip magic header */ 313 /* Peek ahead to check the gzip magic header */
314 if (s->stream.next_in[0] != gz_magic[0] || 314 if (s->stream.next_in[0] != gz_magic[0] ||
315 s->stream.next_in[1] != gz_magic[1]) { 315 s->stream.next_in[1] != gz_magic[1]) {
316 s->transparent = 1; 316 s->transparent = 1;
317 return; 317 return;
318 } 318 }
319 s->stream.avail_in -= 2; 319 s->stream.avail_in -= 2;
320 s->stream.next_in += 2; 320 s->stream.next_in += 2;
321 321
322 /* Check the rest of the gzip header */ 322 /* Check the rest of the gzip header */
323 method = get_byte(s); 323 method = get_byte(s);
324 flags = get_byte(s); 324 flags = get_byte(s);
325 if (method != Z_DEFLATED || (flags & RESERVED) != 0) { 325 if (method != Z_DEFLATED || (flags & RESERVED) != 0) {
326 s->z_err = Z_DATA_ERROR; 326 s->z_err = Z_DATA_ERROR;
327 return; 327 return;
328 } 328 }
329 329
330 /* Discard time, xflags and OS code: */ 330 /* Discard time, xflags and OS code: */
331 for (len = 0; len < 6; len++) (void)get_byte(s); 331 for (len = 0; len < 6; len++) (void)get_byte(s);
332 332
333 if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */ 333 if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */
334 len = (uInt)get_byte(s); 334 len = (uInt)get_byte(s);
335 len += ((uInt)get_byte(s))<<8; 335 len += ((uInt)get_byte(s))<<8;
336 /* len is garbage if EOF but the loop below will quit anyway */ 336 /* len is garbage if EOF but the loop below will quit anyway */
337 while (len-- != 0 && get_byte(s) != EOF) ; 337 while (len-- != 0 && get_byte(s) != EOF) ;
338 } 338 }
339 if ((flags & ORIG_NAME) != 0) { /* skip the original file name */ 339 if ((flags & ORIG_NAME) != 0) { /* skip the original file name */
340 while ((c = get_byte(s)) != 0 && c != EOF) ; 340 while ((c = get_byte(s)) != 0 && c != EOF) ;
341 } 341 }
342 if ((flags & COMMENT) != 0) { /* skip the .gz file comment */ 342 if ((flags & COMMENT) != 0) { /* skip the .gz file comment */
343 while ((c = get_byte(s)) != 0 && c != EOF) ; 343 while ((c = get_byte(s)) != 0 && c != EOF) ;
344 } 344 }
345 if ((flags & HEAD_CRC) != 0) { /* skip the header crc */ 345 if ((flags & HEAD_CRC) != 0) { /* skip the header crc */
346 for (len = 0; len < 2; len++) (void)get_byte(s); 346 for (len = 0; len < 2; len++) (void)get_byte(s);
347 } 347 }
348 s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK; 348 s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK;
349} 349}
350 350
351 /* =========================================================================== 351 /* ===========================================================================
352 * Cleanup then free the given gz_stream. Return a zlib error code. 352 * Cleanup then free the given gz_stream. Return a zlib error code.
353 Try freeing in the reverse order of allocations. 353 Try freeing in the reverse order of allocations.
354 */ 354 */
355local int destroy (s) 355local int destroy (s)
356 gz_stream *s; 356 gz_stream *s;
357{ 357{
358 int err = Z_OK; 358 int err = Z_OK;
359 359
360 if (!s) return Z_STREAM_ERROR; 360 if (!s) return Z_STREAM_ERROR;
361 361
362 TRYFREE(s->msg); 362 TRYFREE(s->msg);
363 363
364 if (s->stream.state != NULL) { 364 if (s->stream.state != NULL) {
365 if (s->mode == 'w') { 365 if (s->mode == 'w') {
366#ifdef NO_GZCOMPRESS 366#ifdef NO_GZCOMPRESS
367 err = Z_STREAM_ERROR; 367 err = Z_STREAM_ERROR;
368#else 368#else
369 err = deflateEnd(&(s->stream)); 369 err = deflateEnd(&(s->stream));
370#endif 370#endif
371 } else if (s->mode == 'r') { 371 } else if (s->mode == 'r') {
372 err = inflateEnd(&(s->stream)); 372 err = inflateEnd(&(s->stream));
373 } 373 }
374 } 374 }
375 if (s->file != NULL && fclose(s->file)) { 375 if (s->file != NULL && fclose(s->file)) {
376#ifdef ESPIPE 376#ifdef ESPIPE
377 if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */ 377 if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */
378#endif 378#endif
379 err = Z_ERRNO; 379 err = Z_ERRNO;
380 } 380 }
381 if (s->z_err < 0) err = s->z_err; 381 if (s->z_err < 0) err = s->z_err;
382 382
383 TRYFREE(s->inbuf); 383 TRYFREE(s->inbuf);
384 TRYFREE(s->outbuf); 384 TRYFREE(s->outbuf);
385 TRYFREE(s->path); 385 TRYFREE(s->path);
386 TRYFREE(s); 386 TRYFREE(s);
387 return err; 387 return err;
388} 388}
389 389
390/* =========================================================================== 390/* ===========================================================================
391 Reads the given number of uncompressed bytes from the compressed file. 391 Reads the given number of uncompressed bytes from the compressed file.
392 gzread returns the number of bytes actually read (0 for end of file). 392 gzread returns the number of bytes actually read (0 for end of file).
393*/ 393*/
394int ZEXPORT gzread (file, buf, len) 394int ZEXPORT gzread (file, buf, len)
395 gzFile file; 395 gzFile file;
396 voidp buf; 396 voidp buf;
397 unsigned len; 397 unsigned len;
398{ 398{
399 gz_stream *s = (gz_stream*)file; 399 gz_stream *s = (gz_stream*)file;
400 Bytef *start = (Bytef*)buf; /* starting point for crc computation */ 400 Bytef *start = (Bytef*)buf; /* starting point for crc computation */
401 Byte *next_out; /* == stream.next_out but not forced far (for MSDOS) */ 401 Byte *next_out; /* == stream.next_out but not forced far (for MSDOS) */
402 402
403 if (s == NULL || s->mode != 'r') return Z_STREAM_ERROR; 403 if (s == NULL || s->mode != 'r') return Z_STREAM_ERROR;
404 404
405 if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1; 405 if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1;
406 if (s->z_err == Z_STREAM_END) return 0; /* EOF */ 406 if (s->z_err == Z_STREAM_END) return 0; /* EOF */
407 407
408 next_out = (Byte*)buf; 408 next_out = (Byte*)buf;
409 s->stream.next_out = (Bytef*)buf; 409 s->stream.next_out = (Bytef*)buf;
410 s->stream.avail_out = len; 410 s->stream.avail_out = len;
411 411
412 if (s->stream.avail_out && s->back != EOF) { 412 if (s->stream.avail_out && s->back != EOF) {
413 *next_out++ = s->back; 413 *next_out++ = s->back;
414 s->stream.next_out++; 414 s->stream.next_out++;
415 s->stream.avail_out--; 415 s->stream.avail_out--;
416 s->back = EOF; 416 s->back = EOF;
417 s->out++; 417 s->out++;
418 start++; 418 start++;
419 if (s->last) { 419 if (s->last) {
420 s->z_err = Z_STREAM_END; 420 s->z_err = Z_STREAM_END;
421 return 1; 421 return 1;
422 } 422 }
423 } 423 }
424 424
425 while (s->stream.avail_out != 0) { 425 while (s->stream.avail_out != 0) {
426 426
427 if (s->transparent) { 427 if (s->transparent) {
428 /* Copy first the lookahead bytes: */ 428 /* Copy first the lookahead bytes: */
429 uInt n = s->stream.avail_in; 429 uInt n = s->stream.avail_in;
430 if (n > s->stream.avail_out) n = s->stream.avail_out; 430 if (n > s->stream.avail_out) n = s->stream.avail_out;
431 if (n > 0) { 431 if (n > 0) {
432 zmemcpy(s->stream.next_out, s->stream.next_in, n); 432 zmemcpy(s->stream.next_out, s->stream.next_in, n);
433 next_out += n; 433 next_out += n;
434 s->stream.next_out = next_out; 434 s->stream.next_out = next_out;
435 s->stream.next_in += n; 435 s->stream.next_in += n;
436 s->stream.avail_out -= n; 436 s->stream.avail_out -= n;
437 s->stream.avail_in -= n; 437 s->stream.avail_in -= n;
438 } 438 }
439 if (s->stream.avail_out > 0) { 439 if (s->stream.avail_out > 0) {
440 s->stream.avail_out -= 440 s->stream.avail_out -=
441 (uInt)fread(next_out, 1, s->stream.avail_out, s->file); 441 (uInt)fread(next_out, 1, s->stream.avail_out, s->file);
442 } 442 }
443 len -= s->stream.avail_out; 443 len -= s->stream.avail_out;
444 s->in += len; 444 s->in += len;
445 s->out += len; 445 s->out += len;
446 if (len == 0) s->z_eof = 1; 446 if (len == 0) s->z_eof = 1;
447 return (int)len; 447 return (int)len;
448 } 448 }
449 if (s->stream.avail_in == 0 && !s->z_eof) { 449 if (s->stream.avail_in == 0 && !s->z_eof) {
450 450
451 errno = 0; 451 errno = 0;
452 s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file); 452 s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file);
453 if (s->stream.avail_in == 0) { 453 if (s->stream.avail_in == 0) {
454 s->z_eof = 1; 454 s->z_eof = 1;
455 if (ferror(s->file)) { 455 if (ferror(s->file)) {
456 s->z_err = Z_ERRNO; 456 s->z_err = Z_ERRNO;
457 break; 457 break;
458 } 458 }
459 } 459 }
460 s->stream.next_in = s->inbuf; 460 s->stream.next_in = s->inbuf;
461 } 461 }
462 s->in += s->stream.avail_in; 462 s->in += s->stream.avail_in;
463 s->out += s->stream.avail_out; 463 s->out += s->stream.avail_out;
464 s->z_err = inflate(&(s->stream), Z_NO_FLUSH); 464 s->z_err = inflate(&(s->stream), Z_NO_FLUSH);
465 s->in -= s->stream.avail_in; 465 s->in -= s->stream.avail_in;
466 s->out -= s->stream.avail_out; 466 s->out -= s->stream.avail_out;
467 467
468 if (s->z_err == Z_STREAM_END) { 468 if (s->z_err == Z_STREAM_END) {
469 /* Check CRC and original size */ 469 /* Check CRC and original size */
470 s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); 470 s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
471 start = s->stream.next_out; 471 start = s->stream.next_out;
472 472
473 if (getLong(s) != s->crc) { 473 if (getLong(s) != s->crc) {
474 s->z_err = Z_DATA_ERROR; 474 s->z_err = Z_DATA_ERROR;
475 } else { 475 } else {
476 (void)getLong(s); 476 (void)getLong(s);
477 /* The uncompressed length returned by above getlong() may be 477 /* The uncompressed length returned by above getlong() may be
478 * different from s->out in case of concatenated .gz files. 478 * different from s->out in case of concatenated .gz files.
479 * Check for such files: 479 * Check for such files:
480 */ 480 */
481 check_header(s); 481 check_header(s);
482 if (s->z_err == Z_OK) { 482 if (s->z_err == Z_OK) {
483 inflateReset(&(s->stream)); 483 inflateReset(&(s->stream));
484 s->crc = crc32(0L, Z_NULL, 0); 484 s->crc = crc32(0L, Z_NULL, 0);
485 } 485 }
486 } 486 }
487 } 487 }
488 if (s->z_err != Z_OK || s->z_eof) break; 488 if (s->z_err != Z_OK || s->z_eof) break;
489 } 489 }
490 s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); 490 s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
491 491
492 if (len == s->stream.avail_out && 492 if (len == s->stream.avail_out &&
493 (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO)) 493 (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO))
494 return -1; 494 return -1;
495 return (int)(len - s->stream.avail_out); 495 return (int)(len - s->stream.avail_out);
496} 496}
497 497
498 498
499/* =========================================================================== 499/* ===========================================================================
500 Reads one byte from the compressed file. gzgetc returns this byte 500 Reads one byte from the compressed file. gzgetc returns this byte
501 or -1 in case of end of file or error. 501 or -1 in case of end of file or error.
502*/ 502*/
503int ZEXPORT gzgetc(file) 503int ZEXPORT gzgetc(file)
504 gzFile file; 504 gzFile file;
505{ 505{
506 unsigned char c; 506 unsigned char c;
507 507
508 return gzread(file, &c, 1) == 1 ? c : -1; 508 return gzread(file, &c, 1) == 1 ? c : -1;
509} 509}
510 510
511 511
512/* =========================================================================== 512/* ===========================================================================
513 Push one byte back onto the stream. 513 Push one byte back onto the stream.
514*/ 514*/
515int ZEXPORT gzungetc(c, file) 515int ZEXPORT gzungetc(c, file)
516 int c; 516 int c;
517 gzFile file; 517 gzFile file;
518{ 518{
519 gz_stream *s = (gz_stream*)file; 519 gz_stream *s = (gz_stream*)file;
520 520
521 if (s == NULL || s->mode != 'r' || c == EOF || s->back != EOF) return EOF; 521 if (s == NULL || s->mode != 'r' || c == EOF || s->back != EOF) return EOF;
522 s->back = c; 522 s->back = c;
523 s->out--; 523 s->out--;
524 s->last = (s->z_err == Z_STREAM_END); 524 s->last = (s->z_err == Z_STREAM_END);
525 if (s->last) s->z_err = Z_OK; 525 if (s->last) s->z_err = Z_OK;
526 s->z_eof = 0; 526 s->z_eof = 0;
527 return c; 527 return c;
528} 528}
529 529
530 530
531/* =========================================================================== 531/* ===========================================================================
532 Reads bytes from the compressed file until len-1 characters are 532 Reads bytes from the compressed file until len-1 characters are
533 read, or a newline character is read and transferred to buf, or an 533 read, or a newline character is read and transferred to buf, or an
534 end-of-file condition is encountered. The string is then terminated 534 end-of-file condition is encountered. The string is then terminated
535 with a null character. 535 with a null character.
536 gzgets returns buf, or Z_NULL in case of error. 536 gzgets returns buf, or Z_NULL in case of error.
537 537
538 The current implementation is not optimized at all. 538 The current implementation is not optimized at all.
539*/ 539*/
540char * ZEXPORT gzgets(file, buf, len) 540char * ZEXPORT gzgets(file, buf, len)
541 gzFile file; 541 gzFile file;
542 char *buf; 542 char *buf;
543 int len; 543 int len;
544{ 544{
545 char *b = buf; 545 char *b = buf;
546 if (buf == Z_NULL || len <= 0) return Z_NULL; 546 if (buf == Z_NULL || len <= 0) return Z_NULL;
547 547
548 while (--len > 0 && gzread(file, buf, 1) == 1 && *buf++ != '\n') ; 548 while (--len > 0 && gzread(file, buf, 1) == 1 && *buf++ != '\n') ;
549 *buf = '\0'; 549 *buf = '\0';
550 return b == buf && len > 0 ? Z_NULL : b; 550 return b == buf && len > 0 ? Z_NULL : b;
551} 551}
552 552
553 553
554#ifndef NO_GZCOMPRESS 554#ifndef NO_GZCOMPRESS
555/* =========================================================================== 555/* ===========================================================================
556 Writes the given number of uncompressed bytes into the compressed file. 556 Writes the given number of uncompressed bytes into the compressed file.
557 gzwrite returns the number of bytes actually written (0 in case of error). 557 gzwrite returns the number of bytes actually written (0 in case of error).
558*/ 558*/
559int ZEXPORT gzwrite (file, buf, len) 559int ZEXPORT gzwrite (file, buf, len)
560 gzFile file; 560 gzFile file;
561 voidpc buf; 561 voidpc buf;
562 unsigned len; 562 unsigned len;
563{ 563{
564 gz_stream *s = (gz_stream*)file; 564 gz_stream *s = (gz_stream*)file;
565 565
566 if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; 566 if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
567 567
568 s->stream.next_in = (Bytef*)buf; 568 s->stream.next_in = (Bytef*)buf;
569 s->stream.avail_in = len; 569 s->stream.avail_in = len;
570 570
571 while (s->stream.avail_in != 0) { 571 while (s->stream.avail_in != 0) {
572 572
573 if (s->stream.avail_out == 0) { 573 if (s->stream.avail_out == 0) {
574 574
575 s->stream.next_out = s->outbuf; 575 s->stream.next_out = s->outbuf;
576 if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) { 576 if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
577 s->z_err = Z_ERRNO; 577 s->z_err = Z_ERRNO;
578 break; 578 break;
579 } 579 }
580 s->stream.avail_out = Z_BUFSIZE; 580 s->stream.avail_out = Z_BUFSIZE;
581 } 581 }
582 s->in += s->stream.avail_in; 582 s->in += s->stream.avail_in;
583 s->out += s->stream.avail_out; 583 s->out += s->stream.avail_out;
584 s->z_err = deflate(&(s->stream), Z_NO_FLUSH); 584 s->z_err = deflate(&(s->stream), Z_NO_FLUSH);
585 s->in -= s->stream.avail_in; 585 s->in -= s->stream.avail_in;
586 s->out -= s->stream.avail_out; 586 s->out -= s->stream.avail_out;
587 if (s->z_err != Z_OK) break; 587 if (s->z_err != Z_OK) break;
588 } 588 }
589 s->crc = crc32(s->crc, (const Bytef *)buf, len); 589 s->crc = crc32(s->crc, (const Bytef *)buf, len);
590 590
591 return (int)(len - s->stream.avail_in); 591 return (int)(len - s->stream.avail_in);
592} 592}
593 593
594 594
595/* =========================================================================== 595/* ===========================================================================
596 Converts, formats, and writes the args to the compressed file under 596 Converts, formats, and writes the args to the compressed file under
597 control of the format string, as in fprintf. gzprintf returns the number of 597 control of the format string, as in fprintf. gzprintf returns the number of
598 uncompressed bytes actually written (0 in case of error). 598 uncompressed bytes actually written (0 in case of error).
599*/ 599*/
600#ifdef STDC 600#ifdef STDC
601#include <stdarg.h> 601#include <stdarg.h>
602 602
603int ZEXPORTVA gzprintf (gzFile file, const char *format, /* args */ ...) 603int ZEXPORTVA gzprintf (gzFile file, const char *format, /* args */ ...)
604{ 604{
605 char buf[Z_PRINTF_BUFSIZE]; 605 char buf[Z_PRINTF_BUFSIZE];
606 va_list va; 606 va_list va;
607 int len; 607 int len;
608 608
609 buf[sizeof(buf) - 1] = 0; 609 buf[sizeof(buf) - 1] = 0;
610 va_start(va, format); 610 va_start(va, format);
611#ifdef NO_vsnprintf 611#ifdef NO_vsnprintf
612# ifdef HAS_vsprintf_void 612# ifdef HAS_vsprintf_void
613 (void)vsprintf(buf, format, va); 613 (void)vsprintf(buf, format, va);
614 va_end(va); 614 va_end(va);
615 for (len = 0; len < sizeof(buf); len++) 615 for (len = 0; len < sizeof(buf); len++)
616 if (buf[len] == 0) break; 616 if (buf[len] == 0) break;
617# else 617# else
618 len = vsprintf(buf, format, va); 618 len = vsprintf(buf, format, va);
619 va_end(va); 619 va_end(va);
620# endif 620# endif
621#else 621#else
622# ifdef HAS_vsnprintf_void 622# ifdef HAS_vsnprintf_void
623 (void)vsnprintf(buf, sizeof(buf), format, va); 623 (void)vsnprintf(buf, sizeof(buf), format, va);
624 va_end(va); 624 va_end(va);
625 len = strlen(buf); 625 len = strlen(buf);
626# else 626# else
627 len = vsnprintf(buf, sizeof(buf), format, va); 627 len = vsnprintf(buf, sizeof(buf), format, va);
628 va_end(va); 628 va_end(va);
629# endif 629# endif
630#endif 630#endif
631 if (len <= 0 || len >= (int)sizeof(buf) || buf[sizeof(buf) - 1] != 0) 631 if (len <= 0 || len >= (int)sizeof(buf) || buf[sizeof(buf) - 1] != 0)
632 return 0; 632 return 0;
633 return gzwrite(file, buf, (unsigned)len); 633 return gzwrite(file, buf, (unsigned)len);
634} 634}
635#else /* not ANSI C */ 635#else /* not ANSI C */
636 636
637int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, 637int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
638 a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) 638 a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)
639 gzFile file; 639 gzFile file;
640 const char *format; 640 const char *format;
641 int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, 641 int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
642 a11, a12, a13, a14, a15, a16, a17, a18, a19, a20; 642 a11, a12, a13, a14, a15, a16, a17, a18, a19, a20;
643{ 643{
644 char buf[Z_PRINTF_BUFSIZE]; 644 char buf[Z_PRINTF_BUFSIZE];
645 int len; 645 int len;
646 646
647 buf[sizeof(buf) - 1] = 0; 647 buf[sizeof(buf) - 1] = 0;
648#ifdef NO_snprintf 648#ifdef NO_snprintf
649# ifdef HAS_sprintf_void 649# ifdef HAS_sprintf_void
650 sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8, 650 sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8,
651 a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); 651 a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
652 for (len = 0; len < sizeof(buf); len++) 652 for (len = 0; len < sizeof(buf); len++)
653 if (buf[len] == 0) break; 653 if (buf[len] == 0) break;
654# else 654# else
655 len = sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8, 655 len = sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8,
656 a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); 656 a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
657# endif 657# endif
658#else 658#else
659# ifdef HAS_snprintf_void 659# ifdef HAS_snprintf_void
660 snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8, 660 snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8,
661 a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); 661 a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
662 len = strlen(buf); 662 len = strlen(buf);
663# else 663# else
664 len = snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8, 664 len = snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8,
665 a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); 665 a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
666# endif 666# endif
667#endif 667#endif
668 if (len <= 0 || len >= sizeof(buf) || buf[sizeof(buf) - 1] != 0) 668 if (len <= 0 || len >= sizeof(buf) || buf[sizeof(buf) - 1] != 0)
669 return 0; 669 return 0;
670 return gzwrite(file, buf, len); 670 return gzwrite(file, buf, len);
671} 671}
672#endif 672#endif
673 673
674/* =========================================================================== 674/* ===========================================================================
675 Writes c, converted to an unsigned char, into the compressed file. 675 Writes c, converted to an unsigned char, into the compressed file.
676 gzputc returns the value that was written, or -1 in case of error. 676 gzputc returns the value that was written, or -1 in case of error.
677*/ 677*/
678int ZEXPORT gzputc(file, c) 678int ZEXPORT gzputc(file, c)
679 gzFile file; 679 gzFile file;
680 int c; 680 int c;
681{ 681{
682 unsigned char cc = (unsigned char) c; /* required for big endian systems */ 682 unsigned char cc = (unsigned char) c; /* required for big endian systems */
683 683
684 return gzwrite(file, &cc, 1) == 1 ? (int)cc : -1; 684 return gzwrite(file, &cc, 1) == 1 ? (int)cc : -1;
685} 685}
686 686
687 687
688/* =========================================================================== 688/* ===========================================================================
689 Writes the given null-terminated string to the compressed file, excluding 689 Writes the given null-terminated string to the compressed file, excluding
690 the terminating null character. 690 the terminating null character.
691 gzputs returns the number of characters written, or -1 in case of error. 691 gzputs returns the number of characters written, or -1 in case of error.
692*/ 692*/
693int ZEXPORT gzputs(file, s) 693int ZEXPORT gzputs(file, s)
694 gzFile file; 694 gzFile file;
695 const char *s; 695 const char *s;
696{ 696{
697 return gzwrite(file, (char*)s, (unsigned)strlen(s)); 697 return gzwrite(file, (char*)s, (unsigned)strlen(s));
698} 698}
699 699
700 700
701/* =========================================================================== 701/* ===========================================================================
702 Flushes all pending output into the compressed file. The parameter 702 Flushes all pending output into the compressed file. The parameter
703 flush is as in the deflate() function. 703 flush is as in the deflate() function.
704*/ 704*/
705local int do_flush (file, flush) 705local int do_flush (file, flush)
706 gzFile file; 706 gzFile file;
707 int flush; 707 int flush;
708{ 708{
709 uInt len; 709 uInt len;
710 int done = 0; 710 int done = 0;
711 gz_stream *s = (gz_stream*)file; 711 gz_stream *s = (gz_stream*)file;
712 712
713 if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; 713 if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
714 714
715 s->stream.avail_in = 0; /* should be zero already anyway */ 715 s->stream.avail_in = 0; /* should be zero already anyway */
716 716
717 for (;;) { 717 for (;;) {
718 len = Z_BUFSIZE - s->stream.avail_out; 718 len = Z_BUFSIZE - s->stream.avail_out;
719 719
720 if (len != 0) { 720 if (len != 0) {
721 if ((uInt)fwrite(s->outbuf, 1, len, s->file) != len) { 721 if ((uInt)fwrite(s->outbuf, 1, len, s->file) != len) {
722 s->z_err = Z_ERRNO; 722 s->z_err = Z_ERRNO;
723 return Z_ERRNO; 723 return Z_ERRNO;
724 } 724 }
725 s->stream.next_out = s->outbuf; 725 s->stream.next_out = s->outbuf;
726 s->stream.avail_out = Z_BUFSIZE; 726 s->stream.avail_out = Z_BUFSIZE;
727 } 727 }
728 if (done) break; 728 if (done) break;
729 s->out += s->stream.avail_out; 729 s->out += s->stream.avail_out;
730 s->z_err = deflate(&(s->stream), flush); 730 s->z_err = deflate(&(s->stream), flush);
731 s->out -= s->stream.avail_out; 731 s->out -= s->stream.avail_out;
732 732
733 /* Ignore the second of two consecutive flushes: */ 733 /* Ignore the second of two consecutive flushes: */
734 if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK; 734 if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK;
735 735
736 /* deflate has finished flushing only when it hasn't used up 736 /* deflate has finished flushing only when it hasn't used up
737 * all the available space in the output buffer: 737 * all the available space in the output buffer:
738 */ 738 */
739 done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END); 739 done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END);
740 740
741 if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break; 741 if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break;
742 } 742 }
743 return s->z_err == Z_STREAM_END ? Z_OK : s->z_err; 743 return s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
744} 744}
745 745
746int ZEXPORT gzflush (file, flush) 746int ZEXPORT gzflush (file, flush)
747 gzFile file; 747 gzFile file;
748 int flush; 748 int flush;
749{ 749{
750 gz_stream *s = (gz_stream*)file; 750 gz_stream *s = (gz_stream*)file;
751 int err = do_flush (file, flush); 751 int err = do_flush (file, flush);
752 752
753 if (err) return err; 753 if (err) return err;
754 fflush(s->file); 754 fflush(s->file);
755 return s->z_err == Z_STREAM_END ? Z_OK : s->z_err; 755 return s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
756} 756}
757#endif /* NO_GZCOMPRESS */ 757#endif /* NO_GZCOMPRESS */
758 758
759/* =========================================================================== 759/* ===========================================================================
760 Sets the starting position for the next gzread or gzwrite on the given 760 Sets the starting position for the next gzread or gzwrite on the given
761 compressed file. The offset represents a number of bytes in the 761 compressed file. The offset represents a number of bytes in the
762 gzseek returns the resulting offset location as measured in bytes from 762 gzseek returns the resulting offset location as measured in bytes from
763 the beginning of the uncompressed stream, or -1 in case of error. 763 the beginning of the uncompressed stream, or -1 in case of error.
764 SEEK_END is not implemented, returns error. 764 SEEK_END is not implemented, returns error.
765 In this version of the library, gzseek can be extremely slow. 765 In this version of the library, gzseek can be extremely slow.
766*/ 766*/
767z_off_t ZEXPORT gzseek (file, offset, whence) 767z_off_t ZEXPORT gzseek (file, offset, whence)
768 gzFile file; 768 gzFile file;
769 z_off_t offset; 769 z_off_t offset;
770 int whence; 770 int whence;
771{ 771{
772 gz_stream *s = (gz_stream*)file; 772 gz_stream *s = (gz_stream*)file;
773 773
774 if (s == NULL || whence == SEEK_END || 774 if (s == NULL || whence == SEEK_END ||
775 s->z_err == Z_ERRNO || s->z_err == Z_DATA_ERROR) { 775 s->z_err == Z_ERRNO || s->z_err == Z_DATA_ERROR) {
776 return -1L; 776 return -1L;
777 } 777 }
778 778
779 if (s->mode == 'w') { 779 if (s->mode == 'w') {
780#ifdef NO_GZCOMPRESS 780#ifdef NO_GZCOMPRESS
781 return -1L; 781 return -1L;
782#else 782#else
783 if (whence == SEEK_SET) { 783 if (whence == SEEK_SET) {
784 offset -= s->in; 784 offset -= s->in;
785 } 785 }
786 if (offset < 0) return -1L; 786 if (offset < 0) return -1L;
787 787
788 /* At this point, offset is the number of zero bytes to write. */ 788 /* At this point, offset is the number of zero bytes to write. */
789 if (s->inbuf == Z_NULL) { 789 if (s->inbuf == Z_NULL) {
790 s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); /* for seeking */ 790 s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); /* for seeking */
791 if (s->inbuf == Z_NULL) return -1L; 791 if (s->inbuf == Z_NULL) return -1L;
792 zmemzero(s->inbuf, Z_BUFSIZE); 792 zmemzero(s->inbuf, Z_BUFSIZE);
793 } 793 }
794 while (offset > 0) { 794 while (offset > 0) {
795 uInt size = Z_BUFSIZE; 795 uInt size = Z_BUFSIZE;
796 if (offset < Z_BUFSIZE) size = (uInt)offset; 796 if (offset < Z_BUFSIZE) size = (uInt)offset;
797 797
798 size = gzwrite(file, s->inbuf, size); 798 size = gzwrite(file, s->inbuf, size);
799 if (size == 0) return -1L; 799 if (size == 0) return -1L;
800 800
801 offset -= size; 801 offset -= size;
802 } 802 }
803 return s->in; 803 return s->in;
804#endif 804#endif
805 } 805 }
806 /* Rest of function is for reading only */ 806 /* Rest of function is for reading only */
807 807
808 /* compute absolute position */ 808 /* compute absolute position */
809 if (whence == SEEK_CUR) { 809 if (whence == SEEK_CUR) {
810 offset += s->out; 810 offset += s->out;
811 } 811 }
812 if (offset < 0) return -1L; 812 if (offset < 0) return -1L;
813 813
814 if (s->transparent) { 814 if (s->transparent) {
815 /* map to fseek */ 815 /* map to fseek */
816 s->back = EOF; 816 s->back = EOF;
817 s->stream.avail_in = 0; 817 s->stream.avail_in = 0;
818 s->stream.next_in = s->inbuf; 818 s->stream.next_in = s->inbuf;
819 if (fseek(s->file, offset, SEEK_SET) < 0) return -1L; 819 if (fseek(s->file, offset, SEEK_SET) < 0) return -1L;
820 820
821 s->in = s->out = offset; 821 s->in = s->out = offset;
822 return offset; 822 return offset;
823 } 823 }
824 824
825 /* For a negative seek, rewind and use positive seek */ 825 /* For a negative seek, rewind and use positive seek */
826 if (offset >= s->out) { 826 if (offset >= s->out) {
827 offset -= s->out; 827 offset -= s->out;
828 } else if (gzrewind(file) < 0) { 828 } else if (gzrewind(file) < 0) {
829 return -1L; 829 return -1L;
830 } 830 }
831 /* offset is now the number of bytes to skip. */ 831 /* offset is now the number of bytes to skip. */
832 832
833 if (offset != 0 && s->outbuf == Z_NULL) { 833 if (offset != 0 && s->outbuf == Z_NULL) {
834 s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); 834 s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
835 if (s->outbuf == Z_NULL) return -1L; 835 if (s->outbuf == Z_NULL) return -1L;
836 } 836 }
837 if (offset && s->back != EOF) { 837 if (offset && s->back != EOF) {
838 s->back = EOF; 838 s->back = EOF;
839 s->out++; 839 s->out++;
840 offset--; 840 offset--;
841 if (s->last) s->z_err = Z_STREAM_END; 841 if (s->last) s->z_err = Z_STREAM_END;
842 } 842 }
843 while (offset > 0) { 843 while (offset > 0) {
844 int size = Z_BUFSIZE; 844 int size = Z_BUFSIZE;
845 if (offset < Z_BUFSIZE) size = (int)offset; 845 if (offset < Z_BUFSIZE) size = (int)offset;
846 846
847 size = gzread(file, s->outbuf, (uInt)size); 847 size = gzread(file, s->outbuf, (uInt)size);
848 if (size <= 0) return -1L; 848 if (size <= 0) return -1L;
849 offset -= size; 849 offset -= size;
850 } 850 }
851 return s->out; 851 return s->out;
852} 852}
853 853
854/* =========================================================================== 854/* ===========================================================================
855 Rewinds input file. 855 Rewinds input file.
856*/ 856*/
857int ZEXPORT gzrewind (file) 857int ZEXPORT gzrewind (file)
858 gzFile file; 858 gzFile file;
859{ 859{
860 gz_stream *s = (gz_stream*)file; 860 gz_stream *s = (gz_stream*)file;
861 861
862 if (s == NULL || s->mode != 'r') return -1; 862 if (s == NULL || s->mode != 'r') return -1;
863 863
864 s->z_err = Z_OK; 864 s->z_err = Z_OK;
865 s->z_eof = 0; 865 s->z_eof = 0;
866 s->back = EOF; 866 s->back = EOF;
867 s->stream.avail_in = 0; 867 s->stream.avail_in = 0;
868 s->stream.next_in = s->inbuf; 868 s->stream.next_in = s->inbuf;
869 s->crc = crc32(0L, Z_NULL, 0); 869 s->crc = crc32(0L, Z_NULL, 0);
870 if (!s->transparent) (void)inflateReset(&s->stream); 870 if (!s->transparent) (void)inflateReset(&s->stream);
871 s->in = 0; 871 s->in = 0;
872 s->out = 0; 872 s->out = 0;
873 return fseek(s->file, s->start, SEEK_SET); 873 return fseek(s->file, s->start, SEEK_SET);
874} 874}
875 875
876/* =========================================================================== 876/* ===========================================================================
877 Returns the starting position for the next gzread or gzwrite on the 877 Returns the starting position for the next gzread or gzwrite on the
878 given compressed file. This position represents a number of bytes in the 878 given compressed file. This position represents a number of bytes in the
879 uncompressed data stream. 879 uncompressed data stream.
880*/ 880*/
881z_off_t ZEXPORT gztell (file) 881z_off_t ZEXPORT gztell (file)
882 gzFile file; 882 gzFile file;
883{ 883{
884 return gzseek(file, 0L, SEEK_CUR); 884 return gzseek(file, 0L, SEEK_CUR);
885} 885}
886 886
887/* =========================================================================== 887/* ===========================================================================
888 Returns 1 when EOF has previously been detected reading the given 888 Returns 1 when EOF has previously been detected reading the given
889 input stream, otherwise zero. 889 input stream, otherwise zero.
890*/ 890*/
891int ZEXPORT gzeof (file) 891int ZEXPORT gzeof (file)
892 gzFile file; 892 gzFile file;
893{ 893{
894 gz_stream *s = (gz_stream*)file; 894 gz_stream *s = (gz_stream*)file;
895 895
896 /* With concatenated compressed files that can have embedded 896 /* With concatenated compressed files that can have embedded
897 * crc trailers, z_eof is no longer the only/best indicator of EOF 897 * crc trailers, z_eof is no longer the only/best indicator of EOF
898 * on a gz_stream. Handle end-of-stream error explicitly here. 898 * on a gz_stream. Handle end-of-stream error explicitly here.
899 */ 899 */
900 if (s == NULL || s->mode != 'r') return 0; 900 if (s == NULL || s->mode != 'r') return 0;
901 if (s->z_eof) return 1; 901 if (s->z_eof) return 1;
902 return s->z_err == Z_STREAM_END; 902 return s->z_err == Z_STREAM_END;
903} 903}
904 904
905/* =========================================================================== 905/* ===========================================================================
906 Returns 1 if reading and doing so transparently, otherwise zero. 906 Returns 1 if reading and doing so transparently, otherwise zero.
907*/ 907*/
908int ZEXPORT gzdirect (file) 908int ZEXPORT gzdirect (file)
909 gzFile file; 909 gzFile file;
910{ 910{
911 gz_stream *s = (gz_stream*)file; 911 gz_stream *s = (gz_stream*)file;
912 912
913 if (s == NULL || s->mode != 'r') return 0; 913 if (s == NULL || s->mode != 'r') return 0;
914 return s->transparent; 914 return s->transparent;
915} 915}
916 916
917/* =========================================================================== 917/* ===========================================================================
918 Outputs a long in LSB order to the given file 918 Outputs a long in LSB order to the given file
919*/ 919*/
920local void putLong (file, x) 920local void putLong (file, x)
921 FILE *file; 921 FILE *file;
922 uLong x; 922 uLong x;
923{ 923{
924 int n; 924 int n;
925 for (n = 0; n < 4; n++) { 925 for (n = 0; n < 4; n++) {
926 fputc((int)(x & 0xff), file); 926 fputc((int)(x & 0xff), file);
927 x >>= 8; 927 x >>= 8;
928 } 928 }
929} 929}
930 930
931/* =========================================================================== 931/* ===========================================================================
932 Reads a long in LSB order from the given gz_stream. Sets z_err in case 932 Reads a long in LSB order from the given gz_stream. Sets z_err in case
933 of error. 933 of error.
934*/ 934*/
935local uLong getLong (s) 935local uLong getLong (s)
936 gz_stream *s; 936 gz_stream *s;
937{ 937{
938 uLong x = (uLong)get_byte(s); 938 uLong x = (uLong)get_byte(s);
939 int c; 939 int c;
940 940
941 x += ((uLong)get_byte(s))<<8; 941 x += ((uLong)get_byte(s))<<8;
942 x += ((uLong)get_byte(s))<<16; 942 x += ((uLong)get_byte(s))<<16;
943 c = get_byte(s); 943 c = get_byte(s);
944 if (c == EOF) s->z_err = Z_DATA_ERROR; 944 if (c == EOF) s->z_err = Z_DATA_ERROR;
945 x += ((uLong)c)<<24; 945 x += ((uLong)c)<<24;
946 return x; 946 return x;
947} 947}
948 948
949/* =========================================================================== 949/* ===========================================================================
950 Flushes all pending output if necessary, closes the compressed file 950 Flushes all pending output if necessary, closes the compressed file
951 and deallocates all the (de)compression state. 951 and deallocates all the (de)compression state.
952*/ 952*/
953int ZEXPORT gzclose (file) 953int ZEXPORT gzclose (file)
954 gzFile file; 954 gzFile file;
955{ 955{
956 gz_stream *s = (gz_stream*)file; 956 gz_stream *s = (gz_stream*)file;
957 957
958 if (s == NULL) return Z_STREAM_ERROR; 958 if (s == NULL) return Z_STREAM_ERROR;
959 959
960 if (s->mode == 'w') { 960 if (s->mode == 'w') {
961#ifdef NO_GZCOMPRESS 961#ifdef NO_GZCOMPRESS
962 return Z_STREAM_ERROR; 962 return Z_STREAM_ERROR;
963#else 963#else
964 if (do_flush (file, Z_FINISH) != Z_OK) 964 if (do_flush (file, Z_FINISH) != Z_OK)
965 return destroy((gz_stream*)file); 965 return destroy((gz_stream*)file);
966 966
967 putLong (s->file, s->crc); 967 putLong (s->file, s->crc);
968 putLong (s->file, (uLong)(s->in & 0xffffffff)); 968 putLong (s->file, (uLong)(s->in & 0xffffffff));
969#endif 969#endif
970 } 970 }
971 return destroy((gz_stream*)file); 971 return destroy((gz_stream*)file);
972} 972}
973 973
974#ifdef STDC 974#ifdef STDC
975# define zstrerror(errnum) strerror(errnum) 975# define zstrerror(errnum) strerror(errnum)
976#else 976#else
977# define zstrerror(errnum) "" 977# define zstrerror(errnum) ""
978#endif 978#endif
979 979
980/* =========================================================================== 980/* ===========================================================================
981 Returns the error message for the last error which occurred on the 981 Returns the error message for the last error which occurred on the
982 given compressed file. errnum is set to zlib error number. If an 982 given compressed file. errnum is set to zlib error number. If an
983 error occurred in the file system and not in the compression library, 983 error occurred in the file system and not in the compression library,
984 errnum is set to Z_ERRNO and the application may consult errno 984 errnum is set to Z_ERRNO and the application may consult errno
985 to get the exact error code. 985 to get the exact error code.
986*/ 986*/
987const char * ZEXPORT gzerror (file, errnum) 987const char * ZEXPORT gzerror (file, errnum)
988 gzFile file; 988 gzFile file;
989 int *errnum; 989 int *errnum;
990{ 990{
991 char *m; 991 char *m;
992 gz_stream *s = (gz_stream*)file; 992 gz_stream *s = (gz_stream*)file;
993 993
994 if (s == NULL) { 994 if (s == NULL) {
995 *errnum = Z_STREAM_ERROR; 995 *errnum = Z_STREAM_ERROR;
996 return (const char*)ERR_MSG(Z_STREAM_ERROR); 996 return (const char*)ERR_MSG(Z_STREAM_ERROR);
997 } 997 }
998 *errnum = s->z_err; 998 *errnum = s->z_err;
999 if (*errnum == Z_OK) return (const char*)""; 999 if (*errnum == Z_OK) return (const char*)"";
1000 1000
1001 m = (char*)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg); 1001 m = (char*)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg);
1002 1002
1003 if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err); 1003 if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err);
1004 1004
1005 TRYFREE(s->msg); 1005 TRYFREE(s->msg);
1006 s->msg = (char*)ALLOC(strlen(s->path) + strlen(m) + 3); 1006 s->msg = (char*)ALLOC(strlen(s->path) + strlen(m) + 3);
1007 if (s->msg == Z_NULL) return (const char*)ERR_MSG(Z_MEM_ERROR); 1007 if (s->msg == Z_NULL) return (const char*)ERR_MSG(Z_MEM_ERROR);
1008 strcpy(s->msg, s->path); 1008 strcpy(s->msg, s->path);
1009 strcat(s->msg, ": "); 1009 strcat(s->msg, ": ");
1010 strcat(s->msg, m); 1010 strcat(s->msg, m);
1011 return (const char*)s->msg; 1011 return (const char*)s->msg;
1012} 1012}
1013 1013
1014/* =========================================================================== 1014/* ===========================================================================
1015 Clear the error and end-of-file flags, and do the same for the real file. 1015 Clear the error and end-of-file flags, and do the same for the real file.
1016*/ 1016*/
1017void ZEXPORT gzclearerr (file) 1017void ZEXPORT gzclearerr (file)
1018 gzFile file; 1018 gzFile file;
1019{ 1019{
1020 gz_stream *s = (gz_stream*)file; 1020 gz_stream *s = (gz_stream*)file;
1021 1021
1022 if (s == NULL) return; 1022 if (s == NULL) return;
1023 if (s->z_err != Z_STREAM_END) s->z_err = Z_OK; 1023 if (s->z_err != Z_STREAM_END) s->z_err = Z_OK;
1024 s->z_eof = 0; 1024 s->z_eof = 0;
1025 clearerr(s->file); 1025 clearerr(s->file);
1026} 1026}
diff --git a/utils/zenutils/libraries/zlib123/zlib/infback.c b/utils/zenutils/libraries/zlib123/zlib/infback.c
index 1e03e1bab0..455dbc9ee8 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/infback.c
+++ b/utils/zenutils/libraries/zlib123/zlib/infback.c
@@ -1,623 +1,623 @@
1/* infback.c -- inflate using a call-back interface 1/* infback.c -- inflate using a call-back interface
2 * Copyright (C) 1995-2005 Mark Adler 2 * Copyright (C) 1995-2005 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6/* 6/*
7 This code is largely copied from inflate.c. Normally either infback.o or 7 This code is largely copied from inflate.c. Normally either infback.o or
8 inflate.o would be linked into an application--not both. The interface 8 inflate.o would be linked into an application--not both. The interface
9 with inffast.c is retained so that optimized assembler-coded versions of 9 with inffast.c is retained so that optimized assembler-coded versions of
10 inflate_fast() can be used with either inflate.c or infback.c. 10 inflate_fast() can be used with either inflate.c or infback.c.
11 */ 11 */
12 12
13#include "zutil.h" 13#include "zutil.h"
14#include "inftrees.h" 14#include "inftrees.h"
15#include "inflate.h" 15#include "inflate.h"
16#include "inffast.h" 16#include "inffast.h"
17 17
18/* function prototypes */ 18/* function prototypes */
19local void fixedtables OF((struct inflate_state FAR *state)); 19local void fixedtables OF((struct inflate_state FAR *state));
20 20
21/* 21/*
22 strm provides memory allocation functions in zalloc and zfree, or 22 strm provides memory allocation functions in zalloc and zfree, or
23 Z_NULL to use the library memory allocation functions. 23 Z_NULL to use the library memory allocation functions.
24 24
25 windowBits is in the range 8..15, and window is a user-supplied 25 windowBits is in the range 8..15, and window is a user-supplied
26 window and output buffer that is 2**windowBits bytes. 26 window and output buffer that is 2**windowBits bytes.
27 */ 27 */
28int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) 28int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size)
29z_streamp strm; 29z_streamp strm;
30int windowBits; 30int windowBits;
31unsigned char FAR *window; 31unsigned char FAR *window;
32const char *version; 32const char *version;
33int stream_size; 33int stream_size;
34{ 34{
35 struct inflate_state FAR *state; 35 struct inflate_state FAR *state;
36 36
37 if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || 37 if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
38 stream_size != (int)(sizeof(z_stream))) 38 stream_size != (int)(sizeof(z_stream)))
39 return Z_VERSION_ERROR; 39 return Z_VERSION_ERROR;
40 if (strm == Z_NULL || window == Z_NULL || 40 if (strm == Z_NULL || window == Z_NULL ||
41 windowBits < 8 || windowBits > 15) 41 windowBits < 8 || windowBits > 15)
42 return Z_STREAM_ERROR; 42 return Z_STREAM_ERROR;
43 strm->msg = Z_NULL; /* in case we return an error */ 43 strm->msg = Z_NULL; /* in case we return an error */
44 if (strm->zalloc == (alloc_func)0) { 44 if (strm->zalloc == (alloc_func)0) {
45 strm->zalloc = zcalloc; 45 strm->zalloc = zcalloc;
46 strm->opaque = (voidpf)0; 46 strm->opaque = (voidpf)0;
47 } 47 }
48 if (strm->zfree == (free_func)0) strm->zfree = zcfree; 48 if (strm->zfree == (free_func)0) strm->zfree = zcfree;
49 state = (struct inflate_state FAR *)ZALLOC(strm, 1, 49 state = (struct inflate_state FAR *)ZALLOC(strm, 1,
50 sizeof(struct inflate_state)); 50 sizeof(struct inflate_state));
51 if (state == Z_NULL) return Z_MEM_ERROR; 51 if (state == Z_NULL) return Z_MEM_ERROR;
52 Tracev((stderr, "inflate: allocated\n")); 52 Tracev((stderr, "inflate: allocated\n"));
53 strm->state = (struct internal_state FAR *)state; 53 strm->state = (struct internal_state FAR *)state;
54 state->dmax = 32768U; 54 state->dmax = 32768U;
55 state->wbits = windowBits; 55 state->wbits = windowBits;
56 state->wsize = 1U << windowBits; 56 state->wsize = 1U << windowBits;
57 state->window = window; 57 state->window = window;
58 state->write = 0; 58 state->write = 0;
59 state->whave = 0; 59 state->whave = 0;
60 return Z_OK; 60 return Z_OK;
61} 61}
62 62
63/* 63/*
64 Return state with length and distance decoding tables and index sizes set to 64 Return state with length and distance decoding tables and index sizes set to
65 fixed code decoding. Normally this returns fixed tables from inffixed.h. 65 fixed code decoding. Normally this returns fixed tables from inffixed.h.
66 If BUILDFIXED is defined, then instead this routine builds the tables the 66 If BUILDFIXED is defined, then instead this routine builds the tables the
67 first time it's called, and returns those tables the first time and 67 first time it's called, and returns those tables the first time and
68 thereafter. This reduces the size of the code by about 2K bytes, in 68 thereafter. This reduces the size of the code by about 2K bytes, in
69 exchange for a little execution time. However, BUILDFIXED should not be 69 exchange for a little execution time. However, BUILDFIXED should not be
70 used for threaded applications, since the rewriting of the tables and virgin 70 used for threaded applications, since the rewriting of the tables and virgin
71 may not be thread-safe. 71 may not be thread-safe.
72 */ 72 */
73local void fixedtables(state) 73local void fixedtables(state)
74struct inflate_state FAR *state; 74struct inflate_state FAR *state;
75{ 75{
76#ifdef BUILDFIXED 76#ifdef BUILDFIXED
77 static int virgin = 1; 77 static int virgin = 1;
78 static code *lenfix, *distfix; 78 static code *lenfix, *distfix;
79 static code fixed[544]; 79 static code fixed[544];
80 80
81 /* build fixed huffman tables if first call (may not be thread safe) */ 81 /* build fixed huffman tables if first call (may not be thread safe) */
82 if (virgin) { 82 if (virgin) {
83 unsigned sym, bits; 83 unsigned sym, bits;
84 static code *next; 84 static code *next;
85 85
86 /* literal/length table */ 86 /* literal/length table */
87 sym = 0; 87 sym = 0;
88 while (sym < 144) state->lens[sym++] = 8; 88 while (sym < 144) state->lens[sym++] = 8;
89 while (sym < 256) state->lens[sym++] = 9; 89 while (sym < 256) state->lens[sym++] = 9;
90 while (sym < 280) state->lens[sym++] = 7; 90 while (sym < 280) state->lens[sym++] = 7;
91 while (sym < 288) state->lens[sym++] = 8; 91 while (sym < 288) state->lens[sym++] = 8;
92 next = fixed; 92 next = fixed;
93 lenfix = next; 93 lenfix = next;
94 bits = 9; 94 bits = 9;
95 inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); 95 inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
96 96
97 /* distance table */ 97 /* distance table */
98 sym = 0; 98 sym = 0;
99 while (sym < 32) state->lens[sym++] = 5; 99 while (sym < 32) state->lens[sym++] = 5;
100 distfix = next; 100 distfix = next;
101 bits = 5; 101 bits = 5;
102 inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); 102 inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
103 103
104 /* do this just once */ 104 /* do this just once */
105 virgin = 0; 105 virgin = 0;
106 } 106 }
107#else /* !BUILDFIXED */ 107#else /* !BUILDFIXED */
108# include "inffixed.h" 108# include "inffixed.h"
109#endif /* BUILDFIXED */ 109#endif /* BUILDFIXED */
110 state->lencode = lenfix; 110 state->lencode = lenfix;
111 state->lenbits = 9; 111 state->lenbits = 9;
112 state->distcode = distfix; 112 state->distcode = distfix;
113 state->distbits = 5; 113 state->distbits = 5;
114} 114}
115 115
116/* Macros for inflateBack(): */ 116/* Macros for inflateBack(): */
117 117
118/* Load returned state from inflate_fast() */ 118/* Load returned state from inflate_fast() */
119#define LOAD() \ 119#define LOAD() \
120 do { \ 120 do { \
121 put = strm->next_out; \ 121 put = strm->next_out; \
122 left = strm->avail_out; \ 122 left = strm->avail_out; \
123 next = strm->next_in; \ 123 next = strm->next_in; \
124 have = strm->avail_in; \ 124 have = strm->avail_in; \
125 hold = state->hold; \ 125 hold = state->hold; \
126 bits = state->bits; \ 126 bits = state->bits; \
127 } while (0) 127 } while (0)
128 128
129/* Set state from registers for inflate_fast() */ 129/* Set state from registers for inflate_fast() */
130#define RESTORE() \ 130#define RESTORE() \
131 do { \ 131 do { \
132 strm->next_out = put; \ 132 strm->next_out = put; \
133 strm->avail_out = left; \ 133 strm->avail_out = left; \
134 strm->next_in = next; \ 134 strm->next_in = next; \
135 strm->avail_in = have; \ 135 strm->avail_in = have; \
136 state->hold = hold; \ 136 state->hold = hold; \
137 state->bits = bits; \ 137 state->bits = bits; \
138 } while (0) 138 } while (0)
139 139
140/* Clear the input bit accumulator */ 140/* Clear the input bit accumulator */
141#define INITBITS() \ 141#define INITBITS() \
142 do { \ 142 do { \
143 hold = 0; \ 143 hold = 0; \
144 bits = 0; \ 144 bits = 0; \
145 } while (0) 145 } while (0)
146 146
147/* Assure that some input is available. If input is requested, but denied, 147/* Assure that some input is available. If input is requested, but denied,
148 then return a Z_BUF_ERROR from inflateBack(). */ 148 then return a Z_BUF_ERROR from inflateBack(). */
149#define PULL() \ 149#define PULL() \
150 do { \ 150 do { \
151 if (have == 0) { \ 151 if (have == 0) { \
152 have = in(in_desc, &next); \ 152 have = in(in_desc, &next); \
153 if (have == 0) { \ 153 if (have == 0) { \
154 next = Z_NULL; \ 154 next = Z_NULL; \
155 ret = Z_BUF_ERROR; \ 155 ret = Z_BUF_ERROR; \
156 goto inf_leave; \ 156 goto inf_leave; \
157 } \ 157 } \
158 } \ 158 } \
159 } while (0) 159 } while (0)
160 160
161/* Get a byte of input into the bit accumulator, or return from inflateBack() 161/* Get a byte of input into the bit accumulator, or return from inflateBack()
162 with an error if there is no input available. */ 162 with an error if there is no input available. */
163#define PULLBYTE() \ 163#define PULLBYTE() \
164 do { \ 164 do { \
165 PULL(); \ 165 PULL(); \
166 have--; \ 166 have--; \
167 hold += (unsigned long)(*next++) << bits; \ 167 hold += (unsigned long)(*next++) << bits; \
168 bits += 8; \ 168 bits += 8; \
169 } while (0) 169 } while (0)
170 170
171/* Assure that there are at least n bits in the bit accumulator. If there is 171/* Assure that there are at least n bits in the bit accumulator. If there is
172 not enough available input to do that, then return from inflateBack() with 172 not enough available input to do that, then return from inflateBack() with
173 an error. */ 173 an error. */
174#define NEEDBITS(n) \ 174#define NEEDBITS(n) \
175 do { \ 175 do { \
176 while (bits < (unsigned)(n)) \ 176 while (bits < (unsigned)(n)) \
177 PULLBYTE(); \ 177 PULLBYTE(); \
178 } while (0) 178 } while (0)
179 179
180/* Return the low n bits of the bit accumulator (n < 16) */ 180/* Return the low n bits of the bit accumulator (n < 16) */
181#define BITS(n) \ 181#define BITS(n) \
182 ((unsigned)hold & ((1U << (n)) - 1)) 182 ((unsigned)hold & ((1U << (n)) - 1))
183 183
184/* Remove n bits from the bit accumulator */ 184/* Remove n bits from the bit accumulator */
185#define DROPBITS(n) \ 185#define DROPBITS(n) \
186 do { \ 186 do { \
187 hold >>= (n); \ 187 hold >>= (n); \
188 bits -= (unsigned)(n); \ 188 bits -= (unsigned)(n); \
189 } while (0) 189 } while (0)
190 190
191/* Remove zero to seven bits as needed to go to a byte boundary */ 191/* Remove zero to seven bits as needed to go to a byte boundary */
192#define BYTEBITS() \ 192#define BYTEBITS() \
193 do { \ 193 do { \
194 hold >>= bits & 7; \ 194 hold >>= bits & 7; \
195 bits -= bits & 7; \ 195 bits -= bits & 7; \
196 } while (0) 196 } while (0)
197 197
198/* Assure that some output space is available, by writing out the window 198/* Assure that some output space is available, by writing out the window
199 if it's full. If the write fails, return from inflateBack() with a 199 if it's full. If the write fails, return from inflateBack() with a
200 Z_BUF_ERROR. */ 200 Z_BUF_ERROR. */
201#define ROOM() \ 201#define ROOM() \
202 do { \ 202 do { \
203 if (left == 0) { \ 203 if (left == 0) { \
204 put = state->window; \ 204 put = state->window; \
205 left = state->wsize; \ 205 left = state->wsize; \
206 state->whave = left; \ 206 state->whave = left; \
207 if (out(out_desc, put, left)) { \ 207 if (out(out_desc, put, left)) { \
208 ret = Z_BUF_ERROR; \ 208 ret = Z_BUF_ERROR; \
209 goto inf_leave; \ 209 goto inf_leave; \
210 } \ 210 } \
211 } \ 211 } \
212 } while (0) 212 } while (0)
213 213
214/* 214/*
215 strm provides the memory allocation functions and window buffer on input, 215 strm provides the memory allocation functions and window buffer on input,
216 and provides information on the unused input on return. For Z_DATA_ERROR 216 and provides information on the unused input on return. For Z_DATA_ERROR
217 returns, strm will also provide an error message. 217 returns, strm will also provide an error message.
218 218
219 in() and out() are the call-back input and output functions. When 219 in() and out() are the call-back input and output functions. When
220 inflateBack() needs more input, it calls in(). When inflateBack() has 220 inflateBack() needs more input, it calls in(). When inflateBack() has
221 filled the window with output, or when it completes with data in the 221 filled the window with output, or when it completes with data in the
222 window, it calls out() to write out the data. The application must not 222 window, it calls out() to write out the data. The application must not
223 change the provided input until in() is called again or inflateBack() 223 change the provided input until in() is called again or inflateBack()
224 returns. The application must not change the window/output buffer until 224 returns. The application must not change the window/output buffer until
225 inflateBack() returns. 225 inflateBack() returns.
226 226
227 in() and out() are called with a descriptor parameter provided in the 227 in() and out() are called with a descriptor parameter provided in the
228 inflateBack() call. This parameter can be a structure that provides the 228 inflateBack() call. This parameter can be a structure that provides the
229 information required to do the read or write, as well as accumulated 229 information required to do the read or write, as well as accumulated
230 information on the input and output such as totals and check values. 230 information on the input and output such as totals and check values.
231 231
232 in() should return zero on failure. out() should return non-zero on 232 in() should return zero on failure. out() should return non-zero on
233 failure. If either in() or out() fails, than inflateBack() returns a 233 failure. If either in() or out() fails, than inflateBack() returns a
234 Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it 234 Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it
235 was in() or out() that caused in the error. Otherwise, inflateBack() 235 was in() or out() that caused in the error. Otherwise, inflateBack()
236 returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format 236 returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format
237 error, or Z_MEM_ERROR if it could not allocate memory for the state. 237 error, or Z_MEM_ERROR if it could not allocate memory for the state.
238 inflateBack() can also return Z_STREAM_ERROR if the input parameters 238 inflateBack() can also return Z_STREAM_ERROR if the input parameters
239 are not correct, i.e. strm is Z_NULL or the state was not initialized. 239 are not correct, i.e. strm is Z_NULL or the state was not initialized.
240 */ 240 */
241int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) 241int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc)
242z_streamp strm; 242z_streamp strm;
243in_func in; 243in_func in;
244void FAR *in_desc; 244void FAR *in_desc;
245out_func out; 245out_func out;
246void FAR *out_desc; 246void FAR *out_desc;
247{ 247{
248 struct inflate_state FAR *state; 248 struct inflate_state FAR *state;
249 unsigned char FAR *next; /* next input */ 249 unsigned char FAR *next; /* next input */
250 unsigned char FAR *put; /* next output */ 250 unsigned char FAR *put; /* next output */
251 unsigned have, left; /* available input and output */ 251 unsigned have, left; /* available input and output */
252 unsigned long hold; /* bit buffer */ 252 unsigned long hold; /* bit buffer */
253 unsigned bits; /* bits in bit buffer */ 253 unsigned bits; /* bits in bit buffer */
254 unsigned copy; /* number of stored or match bytes to copy */ 254 unsigned copy; /* number of stored or match bytes to copy */
255 unsigned char FAR *from; /* where to copy match bytes from */ 255 unsigned char FAR *from; /* where to copy match bytes from */
256 code this; /* current decoding table entry */ 256 code this; /* current decoding table entry */
257 code last; /* parent table entry */ 257 code last; /* parent table entry */
258 unsigned len; /* length to copy for repeats, bits to drop */ 258 unsigned len; /* length to copy for repeats, bits to drop */
259 int ret; /* return code */ 259 int ret; /* return code */
260 static const unsigned short order[19] = /* permutation of code lengths */ 260 static const unsigned short order[19] = /* permutation of code lengths */
261 {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; 261 {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
262 262
263 /* Check that the strm exists and that the state was initialized */ 263 /* Check that the strm exists and that the state was initialized */
264 if (strm == Z_NULL || strm->state == Z_NULL) 264 if (strm == Z_NULL || strm->state == Z_NULL)
265 return Z_STREAM_ERROR; 265 return Z_STREAM_ERROR;
266 state = (struct inflate_state FAR *)strm->state; 266 state = (struct inflate_state FAR *)strm->state;
267 267
268 /* Reset the state */ 268 /* Reset the state */
269 strm->msg = Z_NULL; 269 strm->msg = Z_NULL;
270 state->mode = TYPE; 270 state->mode = TYPE;
271 state->last = 0; 271 state->last = 0;
272 state->whave = 0; 272 state->whave = 0;
273 next = strm->next_in; 273 next = strm->next_in;
274 have = next != Z_NULL ? strm->avail_in : 0; 274 have = next != Z_NULL ? strm->avail_in : 0;
275 hold = 0; 275 hold = 0;
276 bits = 0; 276 bits = 0;
277 put = state->window; 277 put = state->window;
278 left = state->wsize; 278 left = state->wsize;
279 279
280 /* Inflate until end of block marked as last */ 280 /* Inflate until end of block marked as last */
281 for (;;) 281 for (;;)
282 switch (state->mode) { 282 switch (state->mode) {
283 case TYPE: 283 case TYPE:
284 /* determine and dispatch block type */ 284 /* determine and dispatch block type */
285 if (state->last) { 285 if (state->last) {
286 BYTEBITS(); 286 BYTEBITS();
287 state->mode = DONE; 287 state->mode = DONE;
288 break; 288 break;
289 } 289 }
290 NEEDBITS(3); 290 NEEDBITS(3);
291 state->last = BITS(1); 291 state->last = BITS(1);
292 DROPBITS(1); 292 DROPBITS(1);
293 switch (BITS(2)) { 293 switch (BITS(2)) {
294 case 0: /* stored block */ 294 case 0: /* stored block */
295 Tracev((stderr, "inflate: stored block%s\n", 295 Tracev((stderr, "inflate: stored block%s\n",
296 state->last ? " (last)" : "")); 296 state->last ? " (last)" : ""));
297 state->mode = STORED; 297 state->mode = STORED;
298 break; 298 break;
299 case 1: /* fixed block */ 299 case 1: /* fixed block */
300 fixedtables(state); 300 fixedtables(state);
301 Tracev((stderr, "inflate: fixed codes block%s\n", 301 Tracev((stderr, "inflate: fixed codes block%s\n",
302 state->last ? " (last)" : "")); 302 state->last ? " (last)" : ""));
303 state->mode = LEN; /* decode codes */ 303 state->mode = LEN; /* decode codes */
304 break; 304 break;
305 case 2: /* dynamic block */ 305 case 2: /* dynamic block */
306 Tracev((stderr, "inflate: dynamic codes block%s\n", 306 Tracev((stderr, "inflate: dynamic codes block%s\n",
307 state->last ? " (last)" : "")); 307 state->last ? " (last)" : ""));
308 state->mode = TABLE; 308 state->mode = TABLE;
309 break; 309 break;
310 case 3: 310 case 3:
311 strm->msg = (char *)"invalid block type"; 311 strm->msg = (char *)"invalid block type";
312 state->mode = BAD; 312 state->mode = BAD;
313 } 313 }
314 DROPBITS(2); 314 DROPBITS(2);
315 break; 315 break;
316 316
317 case STORED: 317 case STORED:
318 /* get and verify stored block length */ 318 /* get and verify stored block length */
319 BYTEBITS(); /* go to byte boundary */ 319 BYTEBITS(); /* go to byte boundary */
320 NEEDBITS(32); 320 NEEDBITS(32);
321 if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { 321 if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
322 strm->msg = (char *)"invalid stored block lengths"; 322 strm->msg = (char *)"invalid stored block lengths";
323 state->mode = BAD; 323 state->mode = BAD;
324 break; 324 break;
325 } 325 }
326 state->length = (unsigned)hold & 0xffff; 326 state->length = (unsigned)hold & 0xffff;
327 Tracev((stderr, "inflate: stored length %u\n", 327 Tracev((stderr, "inflate: stored length %u\n",
328 state->length)); 328 state->length));
329 INITBITS(); 329 INITBITS();
330 330
331 /* copy stored block from input to output */ 331 /* copy stored block from input to output */
332 while (state->length != 0) { 332 while (state->length != 0) {
333 copy = state->length; 333 copy = state->length;
334 PULL(); 334 PULL();
335 ROOM(); 335 ROOM();
336 if (copy > have) copy = have; 336 if (copy > have) copy = have;
337 if (copy > left) copy = left; 337 if (copy > left) copy = left;
338 zmemcpy(put, next, copy); 338 zmemcpy(put, next, copy);
339 have -= copy; 339 have -= copy;
340 next += copy; 340 next += copy;
341 left -= copy; 341 left -= copy;
342 put += copy; 342 put += copy;
343 state->length -= copy; 343 state->length -= copy;
344 } 344 }
345 Tracev((stderr, "inflate: stored end\n")); 345 Tracev((stderr, "inflate: stored end\n"));
346 state->mode = TYPE; 346 state->mode = TYPE;
347 break; 347 break;
348 348
349 case TABLE: 349 case TABLE:
350 /* get dynamic table entries descriptor */ 350 /* get dynamic table entries descriptor */
351 NEEDBITS(14); 351 NEEDBITS(14);
352 state->nlen = BITS(5) + 257; 352 state->nlen = BITS(5) + 257;
353 DROPBITS(5); 353 DROPBITS(5);
354 state->ndist = BITS(5) + 1; 354 state->ndist = BITS(5) + 1;
355 DROPBITS(5); 355 DROPBITS(5);
356 state->ncode = BITS(4) + 4; 356 state->ncode = BITS(4) + 4;
357 DROPBITS(4); 357 DROPBITS(4);
358#ifndef PKZIP_BUG_WORKAROUND 358#ifndef PKZIP_BUG_WORKAROUND
359 if (state->nlen > 286 || state->ndist > 30) { 359 if (state->nlen > 286 || state->ndist > 30) {
360 strm->msg = (char *)"too many length or distance symbols"; 360 strm->msg = (char *)"too many length or distance symbols";
361 state->mode = BAD; 361 state->mode = BAD;
362 break; 362 break;
363 } 363 }
364#endif 364#endif
365 Tracev((stderr, "inflate: table sizes ok\n")); 365 Tracev((stderr, "inflate: table sizes ok\n"));
366 366
367 /* get code length code lengths (not a typo) */ 367 /* get code length code lengths (not a typo) */
368 state->have = 0; 368 state->have = 0;
369 while (state->have < state->ncode) { 369 while (state->have < state->ncode) {
370 NEEDBITS(3); 370 NEEDBITS(3);
371 state->lens[order[state->have++]] = (unsigned short)BITS(3); 371 state->lens[order[state->have++]] = (unsigned short)BITS(3);
372 DROPBITS(3); 372 DROPBITS(3);
373 } 373 }
374 while (state->have < 19) 374 while (state->have < 19)
375 state->lens[order[state->have++]] = 0; 375 state->lens[order[state->have++]] = 0;
376 state->next = state->codes; 376 state->next = state->codes;
377 state->lencode = (code const FAR *)(state->next); 377 state->lencode = (code const FAR *)(state->next);
378 state->lenbits = 7; 378 state->lenbits = 7;
379 ret = inflate_table(CODES, state->lens, 19, &(state->next), 379 ret = inflate_table(CODES, state->lens, 19, &(state->next),
380 &(state->lenbits), state->work); 380 &(state->lenbits), state->work);
381 if (ret) { 381 if (ret) {
382 strm->msg = (char *)"invalid code lengths set"; 382 strm->msg = (char *)"invalid code lengths set";
383 state->mode = BAD; 383 state->mode = BAD;
384 break; 384 break;
385 } 385 }
386 Tracev((stderr, "inflate: code lengths ok\n")); 386 Tracev((stderr, "inflate: code lengths ok\n"));
387 387
388 /* get length and distance code code lengths */ 388 /* get length and distance code code lengths */
389 state->have = 0; 389 state->have = 0;
390 while (state->have < state->nlen + state->ndist) { 390 while (state->have < state->nlen + state->ndist) {
391 for (;;) { 391 for (;;) {
392 this = state->lencode[BITS(state->lenbits)]; 392 this = state->lencode[BITS(state->lenbits)];
393 if ((unsigned)(this.bits) <= bits) break; 393 if ((unsigned)(this.bits) <= bits) break;
394 PULLBYTE(); 394 PULLBYTE();
395 } 395 }
396 if (this.val < 16) { 396 if (this.val < 16) {
397 NEEDBITS(this.bits); 397 NEEDBITS(this.bits);
398 DROPBITS(this.bits); 398 DROPBITS(this.bits);
399 state->lens[state->have++] = this.val; 399 state->lens[state->have++] = this.val;
400 } 400 }
401 else { 401 else {
402 if (this.val == 16) { 402 if (this.val == 16) {
403 NEEDBITS(this.bits + 2); 403 NEEDBITS(this.bits + 2);
404 DROPBITS(this.bits); 404 DROPBITS(this.bits);
405 if (state->have == 0) { 405 if (state->have == 0) {
406 strm->msg = (char *)"invalid bit length repeat"; 406 strm->msg = (char *)"invalid bit length repeat";
407 state->mode = BAD; 407 state->mode = BAD;
408 break; 408 break;
409 } 409 }
410 len = (unsigned)(state->lens[state->have - 1]); 410 len = (unsigned)(state->lens[state->have - 1]);
411 copy = 3 + BITS(2); 411 copy = 3 + BITS(2);
412 DROPBITS(2); 412 DROPBITS(2);
413 } 413 }
414 else if (this.val == 17) { 414 else if (this.val == 17) {
415 NEEDBITS(this.bits + 3); 415 NEEDBITS(this.bits + 3);
416 DROPBITS(this.bits); 416 DROPBITS(this.bits);
417 len = 0; 417 len = 0;
418 copy = 3 + BITS(3); 418 copy = 3 + BITS(3);
419 DROPBITS(3); 419 DROPBITS(3);
420 } 420 }
421 else { 421 else {
422 NEEDBITS(this.bits + 7); 422 NEEDBITS(this.bits + 7);
423 DROPBITS(this.bits); 423 DROPBITS(this.bits);
424 len = 0; 424 len = 0;
425 copy = 11 + BITS(7); 425 copy = 11 + BITS(7);
426 DROPBITS(7); 426 DROPBITS(7);
427 } 427 }
428 if (state->have + copy > state->nlen + state->ndist) { 428 if (state->have + copy > state->nlen + state->ndist) {
429 strm->msg = (char *)"invalid bit length repeat"; 429 strm->msg = (char *)"invalid bit length repeat";
430 state->mode = BAD; 430 state->mode = BAD;
431 break; 431 break;
432 } 432 }
433 while (copy--) 433 while (copy--)
434 state->lens[state->have++] = (unsigned short)len; 434 state->lens[state->have++] = (unsigned short)len;
435 } 435 }
436 } 436 }
437 437
438 /* handle error breaks in while */ 438 /* handle error breaks in while */
439 if (state->mode == BAD) break; 439 if (state->mode == BAD) break;
440 440
441 /* build code tables */ 441 /* build code tables */
442 state->next = state->codes; 442 state->next = state->codes;
443 state->lencode = (code const FAR *)(state->next); 443 state->lencode = (code const FAR *)(state->next);
444 state->lenbits = 9; 444 state->lenbits = 9;
445 ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), 445 ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
446 &(state->lenbits), state->work); 446 &(state->lenbits), state->work);
447 if (ret) { 447 if (ret) {
448 strm->msg = (char *)"invalid literal/lengths set"; 448 strm->msg = (char *)"invalid literal/lengths set";
449 state->mode = BAD; 449 state->mode = BAD;
450 break; 450 break;
451 } 451 }
452 state->distcode = (code const FAR *)(state->next); 452 state->distcode = (code const FAR *)(state->next);
453 state->distbits = 6; 453 state->distbits = 6;
454 ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, 454 ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
455 &(state->next), &(state->distbits), state->work); 455 &(state->next), &(state->distbits), state->work);
456 if (ret) { 456 if (ret) {
457 strm->msg = (char *)"invalid distances set"; 457 strm->msg = (char *)"invalid distances set";
458 state->mode = BAD; 458 state->mode = BAD;
459 break; 459 break;
460 } 460 }
461 Tracev((stderr, "inflate: codes ok\n")); 461 Tracev((stderr, "inflate: codes ok\n"));
462 state->mode = LEN; 462 state->mode = LEN;
463 463
464 case LEN: 464 case LEN:
465 /* use inflate_fast() if we have enough input and output */ 465 /* use inflate_fast() if we have enough input and output */
466 if (have >= 6 && left >= 258) { 466 if (have >= 6 && left >= 258) {
467 RESTORE(); 467 RESTORE();
468 if (state->whave < state->wsize) 468 if (state->whave < state->wsize)
469 state->whave = state->wsize - left; 469 state->whave = state->wsize - left;
470 inflate_fast(strm, state->wsize); 470 inflate_fast(strm, state->wsize);
471 LOAD(); 471 LOAD();
472 break; 472 break;
473 } 473 }
474 474
475 /* get a literal, length, or end-of-block code */ 475 /* get a literal, length, or end-of-block code */
476 for (;;) { 476 for (;;) {
477 this = state->lencode[BITS(state->lenbits)]; 477 this = state->lencode[BITS(state->lenbits)];
478 if ((unsigned)(this.bits) <= bits) break; 478 if ((unsigned)(this.bits) <= bits) break;
479 PULLBYTE(); 479 PULLBYTE();
480 } 480 }
481 if (this.op && (this.op & 0xf0) == 0) { 481 if (this.op && (this.op & 0xf0) == 0) {
482 last = this; 482 last = this;
483 for (;;) { 483 for (;;) {
484 this = state->lencode[last.val + 484 this = state->lencode[last.val +
485 (BITS(last.bits + last.op) >> last.bits)]; 485 (BITS(last.bits + last.op) >> last.bits)];
486 if ((unsigned)(last.bits + this.bits) <= bits) break; 486 if ((unsigned)(last.bits + this.bits) <= bits) break;
487 PULLBYTE(); 487 PULLBYTE();
488 } 488 }
489 DROPBITS(last.bits); 489 DROPBITS(last.bits);
490 } 490 }
491 DROPBITS(this.bits); 491 DROPBITS(this.bits);
492 state->length = (unsigned)this.val; 492 state->length = (unsigned)this.val;
493 493
494 /* process literal */ 494 /* process literal */
495 if (this.op == 0) { 495 if (this.op == 0) {
496 Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? 496 Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
497 "inflate: literal '%c'\n" : 497 "inflate: literal '%c'\n" :
498 "inflate: literal 0x%02x\n", this.val)); 498 "inflate: literal 0x%02x\n", this.val));
499 ROOM(); 499 ROOM();
500 *put++ = (unsigned char)(state->length); 500 *put++ = (unsigned char)(state->length);
501 left--; 501 left--;
502 state->mode = LEN; 502 state->mode = LEN;
503 break; 503 break;
504 } 504 }
505 505
506 /* process end of block */ 506 /* process end of block */
507 if (this.op & 32) { 507 if (this.op & 32) {
508 Tracevv((stderr, "inflate: end of block\n")); 508 Tracevv((stderr, "inflate: end of block\n"));
509 state->mode = TYPE; 509 state->mode = TYPE;
510 break; 510 break;
511 } 511 }
512 512
513 /* invalid code */ 513 /* invalid code */
514 if (this.op & 64) { 514 if (this.op & 64) {
515 strm->msg = (char *)"invalid literal/length code"; 515 strm->msg = (char *)"invalid literal/length code";
516 state->mode = BAD; 516 state->mode = BAD;
517 break; 517 break;
518 } 518 }
519 519
520 /* length code -- get extra bits, if any */ 520 /* length code -- get extra bits, if any */
521 state->extra = (unsigned)(this.op) & 15; 521 state->extra = (unsigned)(this.op) & 15;
522 if (state->extra != 0) { 522 if (state->extra != 0) {
523 NEEDBITS(state->extra); 523 NEEDBITS(state->extra);
524 state->length += BITS(state->extra); 524 state->length += BITS(state->extra);
525 DROPBITS(state->extra); 525 DROPBITS(state->extra);
526 } 526 }
527 Tracevv((stderr, "inflate: length %u\n", state->length)); 527 Tracevv((stderr, "inflate: length %u\n", state->length));
528 528
529 /* get distance code */ 529 /* get distance code */
530 for (;;) { 530 for (;;) {
531 this = state->distcode[BITS(state->distbits)]; 531 this = state->distcode[BITS(state->distbits)];
532 if ((unsigned)(this.bits) <= bits) break; 532 if ((unsigned)(this.bits) <= bits) break;
533 PULLBYTE(); 533 PULLBYTE();
534 } 534 }
535 if ((this.op & 0xf0) == 0) { 535 if ((this.op & 0xf0) == 0) {
536 last = this; 536 last = this;
537 for (;;) { 537 for (;;) {
538 this = state->distcode[last.val + 538 this = state->distcode[last.val +
539 (BITS(last.bits + last.op) >> last.bits)]; 539 (BITS(last.bits + last.op) >> last.bits)];
540 if ((unsigned)(last.bits + this.bits) <= bits) break; 540 if ((unsigned)(last.bits + this.bits) <= bits) break;
541 PULLBYTE(); 541 PULLBYTE();
542 } 542 }
543 DROPBITS(last.bits); 543 DROPBITS(last.bits);
544 } 544 }
545 DROPBITS(this.bits); 545 DROPBITS(this.bits);
546 if (this.op & 64) { 546 if (this.op & 64) {
547 strm->msg = (char *)"invalid distance code"; 547 strm->msg = (char *)"invalid distance code";
548 state->mode = BAD; 548 state->mode = BAD;
549 break; 549 break;
550 } 550 }
551 state->offset = (unsigned)this.val; 551 state->offset = (unsigned)this.val;
552 552
553 /* get distance extra bits, if any */ 553 /* get distance extra bits, if any */
554 state->extra = (unsigned)(this.op) & 15; 554 state->extra = (unsigned)(this.op) & 15;
555 if (state->extra != 0) { 555 if (state->extra != 0) {
556 NEEDBITS(state->extra); 556 NEEDBITS(state->extra);
557 state->offset += BITS(state->extra); 557 state->offset += BITS(state->extra);
558 DROPBITS(state->extra); 558 DROPBITS(state->extra);
559 } 559 }
560 if (state->offset > state->wsize - (state->whave < state->wsize ? 560 if (state->offset > state->wsize - (state->whave < state->wsize ?
561 left : 0)) { 561 left : 0)) {
562 strm->msg = (char *)"invalid distance too far back"; 562 strm->msg = (char *)"invalid distance too far back";
563 state->mode = BAD; 563 state->mode = BAD;
564 break; 564 break;
565 } 565 }
566 Tracevv((stderr, "inflate: distance %u\n", state->offset)); 566 Tracevv((stderr, "inflate: distance %u\n", state->offset));
567 567
568 /* copy match from window to output */ 568 /* copy match from window to output */
569 do { 569 do {
570 ROOM(); 570 ROOM();
571 copy = state->wsize - state->offset; 571 copy = state->wsize - state->offset;
572 if (copy < left) { 572 if (copy < left) {
573 from = put + copy; 573 from = put + copy;
574 copy = left - copy; 574 copy = left - copy;
575 } 575 }
576 else { 576 else {
577 from = put - state->offset; 577 from = put - state->offset;
578 copy = left; 578 copy = left;
579 } 579 }
580 if (copy > state->length) copy = state->length; 580 if (copy > state->length) copy = state->length;
581 state->length -= copy; 581 state->length -= copy;
582 left -= copy; 582 left -= copy;
583 do { 583 do {
584 *put++ = *from++; 584 *put++ = *from++;
585 } while (--copy); 585 } while (--copy);
586 } while (state->length != 0); 586 } while (state->length != 0);
587 break; 587 break;
588 588
589 case DONE: 589 case DONE:
590 /* inflate stream terminated properly -- write leftover output */ 590 /* inflate stream terminated properly -- write leftover output */
591 ret = Z_STREAM_END; 591 ret = Z_STREAM_END;
592 if (left < state->wsize) { 592 if (left < state->wsize) {
593 if (out(out_desc, state->window, state->wsize - left)) 593 if (out(out_desc, state->window, state->wsize - left))
594 ret = Z_BUF_ERROR; 594 ret = Z_BUF_ERROR;
595 } 595 }
596 goto inf_leave; 596 goto inf_leave;
597 597
598 case BAD: 598 case BAD:
599 ret = Z_DATA_ERROR; 599 ret = Z_DATA_ERROR;
600 goto inf_leave; 600 goto inf_leave;
601 601
602 default: /* can't happen, but makes compilers happy */ 602 default: /* can't happen, but makes compilers happy */
603 ret = Z_STREAM_ERROR; 603 ret = Z_STREAM_ERROR;
604 goto inf_leave; 604 goto inf_leave;
605 } 605 }
606 606
607 /* Return unused input */ 607 /* Return unused input */
608 inf_leave: 608 inf_leave:
609 strm->next_in = next; 609 strm->next_in = next;
610 strm->avail_in = have; 610 strm->avail_in = have;
611 return ret; 611 return ret;
612} 612}
613 613
614int ZEXPORT inflateBackEnd(strm) 614int ZEXPORT inflateBackEnd(strm)
615z_streamp strm; 615z_streamp strm;
616{ 616{
617 if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) 617 if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
618 return Z_STREAM_ERROR; 618 return Z_STREAM_ERROR;
619 ZFREE(strm, strm->state); 619 ZFREE(strm, strm->state);
620 strm->state = Z_NULL; 620 strm->state = Z_NULL;
621 Tracev((stderr, "inflate: end\n")); 621 Tracev((stderr, "inflate: end\n"));
622 return Z_OK; 622 return Z_OK;
623} 623}
diff --git a/utils/zenutils/libraries/zlib123/zlib/inffast.c b/utils/zenutils/libraries/zlib123/zlib/inffast.c
index fa31cad905..bbee92ed1e 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/inffast.c
+++ b/utils/zenutils/libraries/zlib123/zlib/inffast.c
@@ -1,318 +1,318 @@
1/* inffast.c -- fast decoding 1/* inffast.c -- fast decoding
2 * Copyright (C) 1995-2004 Mark Adler 2 * Copyright (C) 1995-2004 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6#include "zutil.h" 6#include "zutil.h"
7#include "inftrees.h" 7#include "inftrees.h"
8#include "inflate.h" 8#include "inflate.h"
9#include "inffast.h" 9#include "inffast.h"
10 10
11#ifndef ASMINF 11#ifndef ASMINF
12 12
13/* Allow machine dependent optimization for post-increment or pre-increment. 13/* Allow machine dependent optimization for post-increment or pre-increment.
14 Based on testing to date, 14 Based on testing to date,
15 Pre-increment preferred for: 15 Pre-increment preferred for:
16 - PowerPC G3 (Adler) 16 - PowerPC G3 (Adler)
17 - MIPS R5000 (Randers-Pehrson) 17 - MIPS R5000 (Randers-Pehrson)
18 Post-increment preferred for: 18 Post-increment preferred for:
19 - none 19 - none
20 No measurable difference: 20 No measurable difference:
21 - Pentium III (Anderson) 21 - Pentium III (Anderson)
22 - M68060 (Nikl) 22 - M68060 (Nikl)
23 */ 23 */
24#ifdef POSTINC 24#ifdef POSTINC
25# define OFF 0 25# define OFF 0
26# define PUP(a) *(a)++ 26# define PUP(a) *(a)++
27#else 27#else
28# define OFF 1 28# define OFF 1
29# define PUP(a) *++(a) 29# define PUP(a) *++(a)
30#endif 30#endif
31 31
32/* 32/*
33 Decode literal, length, and distance codes and write out the resulting 33 Decode literal, length, and distance codes and write out the resulting
34 literal and match bytes until either not enough input or output is 34 literal and match bytes until either not enough input or output is
35 available, an end-of-block is encountered, or a data error is encountered. 35 available, an end-of-block is encountered, or a data error is encountered.
36 When large enough input and output buffers are supplied to inflate(), for 36 When large enough input and output buffers are supplied to inflate(), for
37 example, a 16K input buffer and a 64K output buffer, more than 95% of the 37 example, a 16K input buffer and a 64K output buffer, more than 95% of the
38 inflate execution time is spent in this routine. 38 inflate execution time is spent in this routine.
39 39
40 Entry assumptions: 40 Entry assumptions:
41 41
42 state->mode == LEN 42 state->mode == LEN
43 strm->avail_in >= 6 43 strm->avail_in >= 6
44 strm->avail_out >= 258 44 strm->avail_out >= 258
45 start >= strm->avail_out 45 start >= strm->avail_out
46 state->bits < 8 46 state->bits < 8
47 47
48 On return, state->mode is one of: 48 On return, state->mode is one of:
49 49
50 LEN -- ran out of enough output space or enough available input 50 LEN -- ran out of enough output space or enough available input
51 TYPE -- reached end of block code, inflate() to interpret next block 51 TYPE -- reached end of block code, inflate() to interpret next block
52 BAD -- error in block data 52 BAD -- error in block data
53 53
54 Notes: 54 Notes:
55 55
56 - The maximum input bits used by a length/distance pair is 15 bits for the 56 - The maximum input bits used by a length/distance pair is 15 bits for the
57 length code, 5 bits for the length extra, 15 bits for the distance code, 57 length code, 5 bits for the length extra, 15 bits for the distance code,
58 and 13 bits for the distance extra. This totals 48 bits, or six bytes. 58 and 13 bits for the distance extra. This totals 48 bits, or six bytes.
59 Therefore if strm->avail_in >= 6, then there is enough input to avoid 59 Therefore if strm->avail_in >= 6, then there is enough input to avoid
60 checking for available input while decoding. 60 checking for available input while decoding.
61 61
62 - The maximum bytes that a single length/distance pair can output is 258 62 - The maximum bytes that a single length/distance pair can output is 258
63 bytes, which is the maximum length that can be coded. inflate_fast() 63 bytes, which is the maximum length that can be coded. inflate_fast()
64 requires strm->avail_out >= 258 for each loop to avoid checking for 64 requires strm->avail_out >= 258 for each loop to avoid checking for
65 output space. 65 output space.
66 */ 66 */
67void inflate_fast(strm, start) 67void inflate_fast(strm, start)
68z_streamp strm; 68z_streamp strm;
69unsigned start; /* inflate()'s starting value for strm->avail_out */ 69unsigned start; /* inflate()'s starting value for strm->avail_out */
70{ 70{
71 struct inflate_state FAR *state; 71 struct inflate_state FAR *state;
72 unsigned char FAR *in; /* local strm->next_in */ 72 unsigned char FAR *in; /* local strm->next_in */
73 unsigned char FAR *last; /* while in < last, enough input available */ 73 unsigned char FAR *last; /* while in < last, enough input available */
74 unsigned char FAR *out; /* local strm->next_out */ 74 unsigned char FAR *out; /* local strm->next_out */
75 unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ 75 unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
76 unsigned char FAR *end; /* while out < end, enough space available */ 76 unsigned char FAR *end; /* while out < end, enough space available */
77#ifdef INFLATE_STRICT 77#ifdef INFLATE_STRICT
78 unsigned dmax; /* maximum distance from zlib header */ 78 unsigned dmax; /* maximum distance from zlib header */
79#endif 79#endif
80 unsigned wsize; /* window size or zero if not using window */ 80 unsigned wsize; /* window size or zero if not using window */
81 unsigned whave; /* valid bytes in the window */ 81 unsigned whave; /* valid bytes in the window */
82 unsigned write; /* window write index */ 82 unsigned write; /* window write index */
83 unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ 83 unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
84 unsigned long hold; /* local strm->hold */ 84 unsigned long hold; /* local strm->hold */
85 unsigned bits; /* local strm->bits */ 85 unsigned bits; /* local strm->bits */
86 code const FAR *lcode; /* local strm->lencode */ 86 code const FAR *lcode; /* local strm->lencode */
87 code const FAR *dcode; /* local strm->distcode */ 87 code const FAR *dcode; /* local strm->distcode */
88 unsigned lmask; /* mask for first level of length codes */ 88 unsigned lmask; /* mask for first level of length codes */
89 unsigned dmask; /* mask for first level of distance codes */ 89 unsigned dmask; /* mask for first level of distance codes */
90 code this; /* retrieved table entry */ 90 code this; /* retrieved table entry */
91 unsigned op; /* code bits, operation, extra bits, or */ 91 unsigned op; /* code bits, operation, extra bits, or */
92 /* window position, window bytes to copy */ 92 /* window position, window bytes to copy */
93 unsigned len; /* match length, unused bytes */ 93 unsigned len; /* match length, unused bytes */
94 unsigned dist; /* match distance */ 94 unsigned dist; /* match distance */
95 unsigned char FAR *from; /* where to copy match from */ 95 unsigned char FAR *from; /* where to copy match from */
96 96
97 /* copy state to local variables */ 97 /* copy state to local variables */
98 state = (struct inflate_state FAR *)strm->state; 98 state = (struct inflate_state FAR *)strm->state;
99 in = strm->next_in - OFF; 99 in = strm->next_in - OFF;
100 last = in + (strm->avail_in - 5); 100 last = in + (strm->avail_in - 5);
101 out = strm->next_out - OFF; 101 out = strm->next_out - OFF;
102 beg = out - (start - strm->avail_out); 102 beg = out - (start - strm->avail_out);
103 end = out + (strm->avail_out - 257); 103 end = out + (strm->avail_out - 257);
104#ifdef INFLATE_STRICT 104#ifdef INFLATE_STRICT
105 dmax = state->dmax; 105 dmax = state->dmax;
106#endif 106#endif
107 wsize = state->wsize; 107 wsize = state->wsize;
108 whave = state->whave; 108 whave = state->whave;
109 write = state->write; 109 write = state->write;
110 window = state->window; 110 window = state->window;
111 hold = state->hold; 111 hold = state->hold;
112 bits = state->bits; 112 bits = state->bits;
113 lcode = state->lencode; 113 lcode = state->lencode;
114 dcode = state->distcode; 114 dcode = state->distcode;
115 lmask = (1U << state->lenbits) - 1; 115 lmask = (1U << state->lenbits) - 1;
116 dmask = (1U << state->distbits) - 1; 116 dmask = (1U << state->distbits) - 1;
117 117
118 /* decode literals and length/distances until end-of-block or not enough 118 /* decode literals and length/distances until end-of-block or not enough
119 input data or output space */ 119 input data or output space */
120 do { 120 do {
121 if (bits < 15) { 121 if (bits < 15) {
122 hold += (unsigned long)(PUP(in)) << bits; 122 hold += (unsigned long)(PUP(in)) << bits;
123 bits += 8; 123 bits += 8;
124 hold += (unsigned long)(PUP(in)) << bits; 124 hold += (unsigned long)(PUP(in)) << bits;
125 bits += 8; 125 bits += 8;
126 } 126 }
127 this = lcode[hold & lmask]; 127 this = lcode[hold & lmask];
128 dolen: 128 dolen:
129 op = (unsigned)(this.bits); 129 op = (unsigned)(this.bits);
130 hold >>= op; 130 hold >>= op;
131 bits -= op; 131 bits -= op;
132 op = (unsigned)(this.op); 132 op = (unsigned)(this.op);
133 if (op == 0) { /* literal */ 133 if (op == 0) { /* literal */
134 Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? 134 Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
135 "inflate: literal '%c'\n" : 135 "inflate: literal '%c'\n" :
136 "inflate: literal 0x%02x\n", this.val)); 136 "inflate: literal 0x%02x\n", this.val));
137 PUP(out) = (unsigned char)(this.val); 137 PUP(out) = (unsigned char)(this.val);
138 } 138 }
139 else if (op & 16) { /* length base */ 139 else if (op & 16) { /* length base */
140 len = (unsigned)(this.val); 140 len = (unsigned)(this.val);
141 op &= 15; /* number of extra bits */ 141 op &= 15; /* number of extra bits */
142 if (op) { 142 if (op) {
143 if (bits < op) { 143 if (bits < op) {
144 hold += (unsigned long)(PUP(in)) << bits; 144 hold += (unsigned long)(PUP(in)) << bits;
145 bits += 8; 145 bits += 8;
146 } 146 }
147 len += (unsigned)hold & ((1U << op) - 1); 147 len += (unsigned)hold & ((1U << op) - 1);
148 hold >>= op; 148 hold >>= op;
149 bits -= op; 149 bits -= op;
150 } 150 }
151 Tracevv((stderr, "inflate: length %u\n", len)); 151 Tracevv((stderr, "inflate: length %u\n", len));
152 if (bits < 15) { 152 if (bits < 15) {
153 hold += (unsigned long)(PUP(in)) << bits; 153 hold += (unsigned long)(PUP(in)) << bits;
154 bits += 8; 154 bits += 8;
155 hold += (unsigned long)(PUP(in)) << bits; 155 hold += (unsigned long)(PUP(in)) << bits;
156 bits += 8; 156 bits += 8;
157 } 157 }
158 this = dcode[hold & dmask]; 158 this = dcode[hold & dmask];
159 dodist: 159 dodist:
160 op = (unsigned)(this.bits); 160 op = (unsigned)(this.bits);
161 hold >>= op; 161 hold >>= op;
162 bits -= op; 162 bits -= op;
163 op = (unsigned)(this.op); 163 op = (unsigned)(this.op);
164 if (op & 16) { /* distance base */ 164 if (op & 16) { /* distance base */
165 dist = (unsigned)(this.val); 165 dist = (unsigned)(this.val);
166 op &= 15; /* number of extra bits */ 166 op &= 15; /* number of extra bits */
167 if (bits < op) { 167 if (bits < op) {
168 hold += (unsigned long)(PUP(in)) << bits; 168 hold += (unsigned long)(PUP(in)) << bits;
169 bits += 8; 169 bits += 8;
170 if (bits < op) { 170 if (bits < op) {
171 hold += (unsigned long)(PUP(in)) << bits; 171 hold += (unsigned long)(PUP(in)) << bits;
172 bits += 8; 172 bits += 8;
173 } 173 }
174 } 174 }
175 dist += (unsigned)hold & ((1U << op) - 1); 175 dist += (unsigned)hold & ((1U << op) - 1);
176#ifdef INFLATE_STRICT 176#ifdef INFLATE_STRICT
177 if (dist > dmax) { 177 if (dist > dmax) {
178 strm->msg = (char *)"invalid distance too far back"; 178 strm->msg = (char *)"invalid distance too far back";
179 state->mode = BAD; 179 state->mode = BAD;
180 break; 180 break;
181 } 181 }
182#endif 182#endif
183 hold >>= op; 183 hold >>= op;
184 bits -= op; 184 bits -= op;
185 Tracevv((stderr, "inflate: distance %u\n", dist)); 185 Tracevv((stderr, "inflate: distance %u\n", dist));
186 op = (unsigned)(out - beg); /* max distance in output */ 186 op = (unsigned)(out - beg); /* max distance in output */
187 if (dist > op) { /* see if copy from window */ 187 if (dist > op) { /* see if copy from window */
188 op = dist - op; /* distance back in window */ 188 op = dist - op; /* distance back in window */
189 if (op > whave) { 189 if (op > whave) {
190 strm->msg = (char *)"invalid distance too far back"; 190 strm->msg = (char *)"invalid distance too far back";
191 state->mode = BAD; 191 state->mode = BAD;
192 break; 192 break;
193 } 193 }
194 from = window - OFF; 194 from = window - OFF;
195 if (write == 0) { /* very common case */ 195 if (write == 0) { /* very common case */
196 from += wsize - op; 196 from += wsize - op;
197 if (op < len) { /* some from window */ 197 if (op < len) { /* some from window */
198 len -= op; 198 len -= op;
199 do { 199 do {
200 PUP(out) = PUP(from); 200 PUP(out) = PUP(from);
201 } while (--op); 201 } while (--op);
202 from = out - dist; /* rest from output */ 202 from = out - dist; /* rest from output */
203 } 203 }
204 } 204 }
205 else if (write < op) { /* wrap around window */ 205 else if (write < op) { /* wrap around window */
206 from += wsize + write - op; 206 from += wsize + write - op;
207 op -= write; 207 op -= write;
208 if (op < len) { /* some from end of window */ 208 if (op < len) { /* some from end of window */
209 len -= op; 209 len -= op;
210 do { 210 do {
211 PUP(out) = PUP(from); 211 PUP(out) = PUP(from);
212 } while (--op); 212 } while (--op);
213 from = window - OFF; 213 from = window - OFF;
214 if (write < len) { /* some from start of window */ 214 if (write < len) { /* some from start of window */
215 op = write; 215 op = write;
216 len -= op; 216 len -= op;
217 do { 217 do {
218 PUP(out) = PUP(from); 218 PUP(out) = PUP(from);
219 } while (--op); 219 } while (--op);
220 from = out - dist; /* rest from output */ 220 from = out - dist; /* rest from output */
221 } 221 }
222 } 222 }
223 } 223 }
224 else { /* contiguous in window */ 224 else { /* contiguous in window */
225 from += write - op; 225 from += write - op;
226 if (op < len) { /* some from window */ 226 if (op < len) { /* some from window */
227 len -= op; 227 len -= op;
228 do { 228 do {
229 PUP(out) = PUP(from); 229 PUP(out) = PUP(from);
230 } while (--op); 230 } while (--op);
231 from = out - dist; /* rest from output */ 231 from = out - dist; /* rest from output */
232 } 232 }
233 } 233 }
234 while (len > 2) { 234 while (len > 2) {
235 PUP(out) = PUP(from); 235 PUP(out) = PUP(from);
236 PUP(out) = PUP(from); 236 PUP(out) = PUP(from);
237 PUP(out) = PUP(from); 237 PUP(out) = PUP(from);
238 len -= 3; 238 len -= 3;
239 } 239 }
240 if (len) { 240 if (len) {
241 PUP(out) = PUP(from); 241 PUP(out) = PUP(from);
242 if (len > 1) 242 if (len > 1)
243 PUP(out) = PUP(from); 243 PUP(out) = PUP(from);
244 } 244 }
245 } 245 }
246 else { 246 else {
247 from = out - dist; /* copy direct from output */ 247 from = out - dist; /* copy direct from output */
248 do { /* minimum length is three */ 248 do { /* minimum length is three */
249 PUP(out) = PUP(from); 249 PUP(out) = PUP(from);
250 PUP(out) = PUP(from); 250 PUP(out) = PUP(from);
251 PUP(out) = PUP(from); 251 PUP(out) = PUP(from);
252 len -= 3; 252 len -= 3;
253 } while (len > 2); 253 } while (len > 2);
254 if (len) { 254 if (len) {
255 PUP(out) = PUP(from); 255 PUP(out) = PUP(from);
256 if (len > 1) 256 if (len > 1)
257 PUP(out) = PUP(from); 257 PUP(out) = PUP(from);
258 } 258 }
259 } 259 }
260 } 260 }
261 else if ((op & 64) == 0) { /* 2nd level distance code */ 261 else if ((op & 64) == 0) { /* 2nd level distance code */
262 this = dcode[this.val + (hold & ((1U << op) - 1))]; 262 this = dcode[this.val + (hold & ((1U << op) - 1))];
263 goto dodist; 263 goto dodist;
264 } 264 }
265 else { 265 else {
266 strm->msg = (char *)"invalid distance code"; 266 strm->msg = (char *)"invalid distance code";
267 state->mode = BAD; 267 state->mode = BAD;
268 break; 268 break;
269 } 269 }
270 } 270 }
271 else if ((op & 64) == 0) { /* 2nd level length code */ 271 else if ((op & 64) == 0) { /* 2nd level length code */
272 this = lcode[this.val + (hold & ((1U << op) - 1))]; 272 this = lcode[this.val + (hold & ((1U << op) - 1))];
273 goto dolen; 273 goto dolen;
274 } 274 }
275 else if (op & 32) { /* end-of-block */ 275 else if (op & 32) { /* end-of-block */
276 Tracevv((stderr, "inflate: end of block\n")); 276 Tracevv((stderr, "inflate: end of block\n"));
277 state->mode = TYPE; 277 state->mode = TYPE;
278 break; 278 break;
279 } 279 }
280 else { 280 else {
281 strm->msg = (char *)"invalid literal/length code"; 281 strm->msg = (char *)"invalid literal/length code";
282 state->mode = BAD; 282 state->mode = BAD;
283 break; 283 break;
284 } 284 }
285 } while (in < last && out < end); 285 } while (in < last && out < end);
286 286
287 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ 287 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
288 len = bits >> 3; 288 len = bits >> 3;
289 in -= len; 289 in -= len;
290 bits -= len << 3; 290 bits -= len << 3;
291 hold &= (1U << bits) - 1; 291 hold &= (1U << bits) - 1;
292 292
293 /* update state and return */ 293 /* update state and return */
294 strm->next_in = in + OFF; 294 strm->next_in = in + OFF;
295 strm->next_out = out + OFF; 295 strm->next_out = out + OFF;
296 strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); 296 strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
297 strm->avail_out = (unsigned)(out < end ? 297 strm->avail_out = (unsigned)(out < end ?
298 257 + (end - out) : 257 - (out - end)); 298 257 + (end - out) : 257 - (out - end));
299 state->hold = hold; 299 state->hold = hold;
300 state->bits = bits; 300 state->bits = bits;
301 return; 301 return;
302} 302}
303 303
304/* 304/*
305 inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): 305 inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
306 - Using bit fields for code structure 306 - Using bit fields for code structure
307 - Different op definition to avoid & for extra bits (do & for table bits) 307 - Different op definition to avoid & for extra bits (do & for table bits)
308 - Three separate decoding do-loops for direct, window, and write == 0 308 - Three separate decoding do-loops for direct, window, and write == 0
309 - Special case for distance > 1 copies to do overlapped load and store copy 309 - Special case for distance > 1 copies to do overlapped load and store copy
310 - Explicit branch predictions (based on measured branch probabilities) 310 - Explicit branch predictions (based on measured branch probabilities)
311 - Deferring match copy and interspersed it with decoding subsequent codes 311 - Deferring match copy and interspersed it with decoding subsequent codes
312 - Swapping literal/length else 312 - Swapping literal/length else
313 - Swapping window/direct else 313 - Swapping window/direct else
314 - Larger unrolled copy loops (three is about right) 314 - Larger unrolled copy loops (three is about right)
315 - Moving len -= 3 statement into middle of loop 315 - Moving len -= 3 statement into middle of loop
316 */ 316 */
317 317
318#endif /* !ASMINF */ 318#endif /* !ASMINF */
diff --git a/utils/zenutils/libraries/zlib123/zlib/inffast.h b/utils/zenutils/libraries/zlib123/zlib/inffast.h
index 614fa7877d..1e88d2d97b 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/inffast.h
+++ b/utils/zenutils/libraries/zlib123/zlib/inffast.h
@@ -1,11 +1,11 @@
1/* inffast.h -- header to use inffast.c 1/* inffast.h -- header to use inffast.c
2 * Copyright (C) 1995-2003 Mark Adler 2 * Copyright (C) 1995-2003 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6/* WARNING: this file should *not* be used by applications. It is 6/* WARNING: this file should *not* be used by applications. It is
7 part of the implementation of the compression library and is 7 part of the implementation of the compression library and is
8 subject to change. Applications should only use zlib.h. 8 subject to change. Applications should only use zlib.h.
9 */ 9 */
10 10
11void inflate_fast OF((z_streamp strm, unsigned start)); 11void inflate_fast OF((z_streamp strm, unsigned start));
diff --git a/utils/zenutils/libraries/zlib123/zlib/inffixed.h b/utils/zenutils/libraries/zlib123/zlib/inffixed.h
index 423d5c5b50..75ed4b5978 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/inffixed.h
+++ b/utils/zenutils/libraries/zlib123/zlib/inffixed.h
@@ -1,94 +1,94 @@
1 /* inffixed.h -- table for decoding fixed codes 1 /* inffixed.h -- table for decoding fixed codes
2 * Generated automatically by makefixed(). 2 * Generated automatically by makefixed().
3 */ 3 */
4 4
5 /* WARNING: this file should *not* be used by applications. It 5 /* WARNING: this file should *not* be used by applications. It
6 is part of the implementation of the compression library and 6 is part of the implementation of the compression library and
7 is subject to change. Applications should only use zlib.h. 7 is subject to change. Applications should only use zlib.h.
8 */ 8 */
9 9
10 static const code lenfix[512] = { 10 static const code lenfix[512] = {
11 {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48}, 11 {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
12 {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128}, 12 {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
13 {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59}, 13 {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
14 {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176}, 14 {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
15 {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20}, 15 {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
16 {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100}, 16 {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
17 {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8}, 17 {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
18 {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216}, 18 {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
19 {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76}, 19 {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
20 {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114}, 20 {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
21 {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2}, 21 {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
22 {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148}, 22 {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
23 {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42}, 23 {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
24 {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86}, 24 {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
25 {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15}, 25 {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
26 {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236}, 26 {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
27 {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62}, 27 {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
28 {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, 28 {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
29 {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31}, 29 {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
30 {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162}, 30 {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
31 {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25}, 31 {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
32 {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105}, 32 {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
33 {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4}, 33 {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
34 {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202}, 34 {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
35 {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69}, 35 {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
36 {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125}, 36 {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
37 {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13}, 37 {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
38 {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195}, 38 {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
39 {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35}, 39 {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
40 {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91}, 40 {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
41 {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19}, 41 {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
42 {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246}, 42 {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
43 {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55}, 43 {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
44 {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135}, 44 {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
45 {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99}, 45 {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
46 {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190}, 46 {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
47 {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16}, 47 {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
48 {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96}, 48 {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
49 {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6}, 49 {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
50 {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209}, 50 {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
51 {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72}, 51 {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
52 {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116}, 52 {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
53 {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4}, 53 {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
54 {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153}, 54 {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
55 {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44}, 55 {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
56 {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82}, 56 {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
57 {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11}, 57 {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
58 {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, 58 {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
59 {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58}, 59 {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
60 {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138}, 60 {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
61 {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51}, 61 {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
62 {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173}, 62 {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
63 {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30}, 63 {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
64 {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110}, 64 {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
65 {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0}, 65 {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
66 {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195}, 66 {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
67 {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65}, 67 {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
68 {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121}, 68 {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
69 {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9}, 69 {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
70 {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258}, 70 {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
71 {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37}, 71 {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
72 {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93}, 72 {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
73 {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23}, 73 {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
74 {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251}, 74 {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
75 {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51}, 75 {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
76 {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, 76 {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
77 {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67}, 77 {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
78 {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183}, 78 {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
79 {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23}, 79 {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
80 {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103}, 80 {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
81 {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9}, 81 {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
82 {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223}, 82 {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
83 {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79}, 83 {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
84 {0,9,255} 84 {0,9,255}
85 }; 85 };
86 86
87 static const code distfix[32] = { 87 static const code distfix[32] = {
88 {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025}, 88 {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
89 {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193}, 89 {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
90 {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385}, 90 {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
91 {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577}, 91 {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
92 {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073}, 92 {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
93 {22,5,193},{64,5,0} 93 {22,5,193},{64,5,0}
94 }; 94 };
diff --git a/utils/zenutils/libraries/zlib123/zlib/inflate.c b/utils/zenutils/libraries/zlib123/zlib/inflate.c
index 33ea902928..792fdee8e9 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/inflate.c
+++ b/utils/zenutils/libraries/zlib123/zlib/inflate.c
@@ -1,1368 +1,1368 @@
1/* inflate.c -- zlib decompression 1/* inflate.c -- zlib decompression
2 * Copyright (C) 1995-2005 Mark Adler 2 * Copyright (C) 1995-2005 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6/* 6/*
7 * Change history: 7 * Change history:
8 * 8 *
9 * 1.2.beta0 24 Nov 2002 9 * 1.2.beta0 24 Nov 2002
10 * - First version -- complete rewrite of inflate to simplify code, avoid 10 * - First version -- complete rewrite of inflate to simplify code, avoid
11 * creation of window when not needed, minimize use of window when it is 11 * creation of window when not needed, minimize use of window when it is
12 * needed, make inffast.c even faster, implement gzip decoding, and to 12 * needed, make inffast.c even faster, implement gzip decoding, and to
13 * improve code readability and style over the previous zlib inflate code 13 * improve code readability and style over the previous zlib inflate code
14 * 14 *
15 * 1.2.beta1 25 Nov 2002 15 * 1.2.beta1 25 Nov 2002
16 * - Use pointers for available input and output checking in inffast.c 16 * - Use pointers for available input and output checking in inffast.c
17 * - Remove input and output counters in inffast.c 17 * - Remove input and output counters in inffast.c
18 * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 18 * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
19 * - Remove unnecessary second byte pull from length extra in inffast.c 19 * - Remove unnecessary second byte pull from length extra in inffast.c
20 * - Unroll direct copy to three copies per loop in inffast.c 20 * - Unroll direct copy to three copies per loop in inffast.c
21 * 21 *
22 * 1.2.beta2 4 Dec 2002 22 * 1.2.beta2 4 Dec 2002
23 * - Change external routine names to reduce potential conflicts 23 * - Change external routine names to reduce potential conflicts
24 * - Correct filename to inffixed.h for fixed tables in inflate.c 24 * - Correct filename to inffixed.h for fixed tables in inflate.c
25 * - Make hbuf[] unsigned char to match parameter type in inflate.c 25 * - Make hbuf[] unsigned char to match parameter type in inflate.c
26 * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) 26 * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
27 * to avoid negation problem on Alphas (64 bit) in inflate.c 27 * to avoid negation problem on Alphas (64 bit) in inflate.c
28 * 28 *
29 * 1.2.beta3 22 Dec 2002 29 * 1.2.beta3 22 Dec 2002
30 * - Add comments on state->bits assertion in inffast.c 30 * - Add comments on state->bits assertion in inffast.c
31 * - Add comments on op field in inftrees.h 31 * - Add comments on op field in inftrees.h
32 * - Fix bug in reuse of allocated window after inflateReset() 32 * - Fix bug in reuse of allocated window after inflateReset()
33 * - Remove bit fields--back to byte structure for speed 33 * - Remove bit fields--back to byte structure for speed
34 * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths 34 * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
35 * - Change post-increments to pre-increments in inflate_fast(), PPC biased? 35 * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
36 * - Add compile time option, POSTINC, to use post-increments instead (Intel?) 36 * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
37 * - Make MATCH copy in inflate() much faster for when inflate_fast() not used 37 * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
38 * - Use local copies of stream next and avail values, as well as local bit 38 * - Use local copies of stream next and avail values, as well as local bit
39 * buffer and bit count in inflate()--for speed when inflate_fast() not used 39 * buffer and bit count in inflate()--for speed when inflate_fast() not used
40 * 40 *
41 * 1.2.beta4 1 Jan 2003 41 * 1.2.beta4 1 Jan 2003
42 * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings 42 * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
43 * - Move a comment on output buffer sizes from inffast.c to inflate.c 43 * - Move a comment on output buffer sizes from inffast.c to inflate.c
44 * - Add comments in inffast.c to introduce the inflate_fast() routine 44 * - Add comments in inffast.c to introduce the inflate_fast() routine
45 * - Rearrange window copies in inflate_fast() for speed and simplification 45 * - Rearrange window copies in inflate_fast() for speed and simplification
46 * - Unroll last copy for window match in inflate_fast() 46 * - Unroll last copy for window match in inflate_fast()
47 * - Use local copies of window variables in inflate_fast() for speed 47 * - Use local copies of window variables in inflate_fast() for speed
48 * - Pull out common write == 0 case for speed in inflate_fast() 48 * - Pull out common write == 0 case for speed in inflate_fast()
49 * - Make op and len in inflate_fast() unsigned for consistency 49 * - Make op and len in inflate_fast() unsigned for consistency
50 * - Add FAR to lcode and dcode declarations in inflate_fast() 50 * - Add FAR to lcode and dcode declarations in inflate_fast()
51 * - Simplified bad distance check in inflate_fast() 51 * - Simplified bad distance check in inflate_fast()
52 * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new 52 * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
53 * source file infback.c to provide a call-back interface to inflate for 53 * source file infback.c to provide a call-back interface to inflate for
54 * programs like gzip and unzip -- uses window as output buffer to avoid 54 * programs like gzip and unzip -- uses window as output buffer to avoid
55 * window copying 55 * window copying
56 * 56 *
57 * 1.2.beta5 1 Jan 2003 57 * 1.2.beta5 1 Jan 2003
58 * - Improved inflateBack() interface to allow the caller to provide initial 58 * - Improved inflateBack() interface to allow the caller to provide initial
59 * input in strm. 59 * input in strm.
60 * - Fixed stored blocks bug in inflateBack() 60 * - Fixed stored blocks bug in inflateBack()
61 * 61 *
62 * 1.2.beta6 4 Jan 2003 62 * 1.2.beta6 4 Jan 2003
63 * - Added comments in inffast.c on effectiveness of POSTINC 63 * - Added comments in inffast.c on effectiveness of POSTINC
64 * - Typecasting all around to reduce compiler warnings 64 * - Typecasting all around to reduce compiler warnings
65 * - Changed loops from while (1) or do {} while (1) to for (;;), again to 65 * - Changed loops from while (1) or do {} while (1) to for (;;), again to
66 * make compilers happy 66 * make compilers happy
67 * - Changed type of window in inflateBackInit() to unsigned char * 67 * - Changed type of window in inflateBackInit() to unsigned char *
68 * 68 *
69 * 1.2.beta7 27 Jan 2003 69 * 1.2.beta7 27 Jan 2003
70 * - Changed many types to unsigned or unsigned short to avoid warnings 70 * - Changed many types to unsigned or unsigned short to avoid warnings
71 * - Added inflateCopy() function 71 * - Added inflateCopy() function
72 * 72 *
73 * 1.2.0 9 Mar 2003 73 * 1.2.0 9 Mar 2003
74 * - Changed inflateBack() interface to provide separate opaque descriptors 74 * - Changed inflateBack() interface to provide separate opaque descriptors
75 * for the in() and out() functions 75 * for the in() and out() functions
76 * - Changed inflateBack() argument and in_func typedef to swap the length 76 * - Changed inflateBack() argument and in_func typedef to swap the length
77 * and buffer address return values for the input function 77 * and buffer address return values for the input function
78 * - Check next_in and next_out for Z_NULL on entry to inflate() 78 * - Check next_in and next_out for Z_NULL on entry to inflate()
79 * 79 *
80 * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. 80 * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
81 */ 81 */
82 82
83#include "zutil.h" 83#include "zutil.h"
84#include "inftrees.h" 84#include "inftrees.h"
85#include "inflate.h" 85#include "inflate.h"
86#include "inffast.h" 86#include "inffast.h"
87 87
88#ifdef MAKEFIXED 88#ifdef MAKEFIXED
89# ifndef BUILDFIXED 89# ifndef BUILDFIXED
90# define BUILDFIXED 90# define BUILDFIXED
91# endif 91# endif
92#endif 92#endif
93 93
94/* function prototypes */ 94/* function prototypes */
95local void fixedtables OF((struct inflate_state FAR *state)); 95local void fixedtables OF((struct inflate_state FAR *state));
96local int updatewindow OF((z_streamp strm, unsigned out)); 96local int updatewindow OF((z_streamp strm, unsigned out));
97#ifdef BUILDFIXED 97#ifdef BUILDFIXED
98 void makefixed OF((void)); 98 void makefixed OF((void));
99#endif 99#endif
100local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf, 100local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
101 unsigned len)); 101 unsigned len));
102 102
103int ZEXPORT inflateReset(strm) 103int ZEXPORT inflateReset(strm)
104z_streamp strm; 104z_streamp strm;
105{ 105{
106 struct inflate_state FAR *state; 106 struct inflate_state FAR *state;
107 107
108 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; 108 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
109 state = (struct inflate_state FAR *)strm->state; 109 state = (struct inflate_state FAR *)strm->state;
110 strm->total_in = strm->total_out = state->total = 0; 110 strm->total_in = strm->total_out = state->total = 0;
111 strm->msg = Z_NULL; 111 strm->msg = Z_NULL;
112 strm->adler = 1; /* to support ill-conceived Java test suite */ 112 strm->adler = 1; /* to support ill-conceived Java test suite */
113 state->mode = HEAD; 113 state->mode = HEAD;
114 state->last = 0; 114 state->last = 0;
115 state->havedict = 0; 115 state->havedict = 0;
116 state->dmax = 32768U; 116 state->dmax = 32768U;
117 state->head = Z_NULL; 117 state->head = Z_NULL;
118 state->wsize = 0; 118 state->wsize = 0;
119 state->whave = 0; 119 state->whave = 0;
120 state->write = 0; 120 state->write = 0;
121 state->hold = 0; 121 state->hold = 0;
122 state->bits = 0; 122 state->bits = 0;
123 state->lencode = state->distcode = state->next = state->codes; 123 state->lencode = state->distcode = state->next = state->codes;
124 Tracev((stderr, "inflate: reset\n")); 124 Tracev((stderr, "inflate: reset\n"));
125 return Z_OK; 125 return Z_OK;
126} 126}
127 127
128int ZEXPORT inflatePrime(strm, bits, value) 128int ZEXPORT inflatePrime(strm, bits, value)
129z_streamp strm; 129z_streamp strm;
130int bits; 130int bits;
131int value; 131int value;
132{ 132{
133 struct inflate_state FAR *state; 133 struct inflate_state FAR *state;
134 134
135 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; 135 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
136 state = (struct inflate_state FAR *)strm->state; 136 state = (struct inflate_state FAR *)strm->state;
137 if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR; 137 if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
138 value &= (1L << bits) - 1; 138 value &= (1L << bits) - 1;
139 state->hold += value << state->bits; 139 state->hold += value << state->bits;
140 state->bits += bits; 140 state->bits += bits;
141 return Z_OK; 141 return Z_OK;
142} 142}
143 143
144int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) 144int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)
145z_streamp strm; 145z_streamp strm;
146int windowBits; 146int windowBits;
147const char *version; 147const char *version;
148int stream_size; 148int stream_size;
149{ 149{
150 struct inflate_state FAR *state; 150 struct inflate_state FAR *state;
151 151
152 if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || 152 if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
153 stream_size != (int)(sizeof(z_stream))) 153 stream_size != (int)(sizeof(z_stream)))
154 return Z_VERSION_ERROR; 154 return Z_VERSION_ERROR;
155 if (strm == Z_NULL) return Z_STREAM_ERROR; 155 if (strm == Z_NULL) return Z_STREAM_ERROR;
156 strm->msg = Z_NULL; /* in case we return an error */ 156 strm->msg = Z_NULL; /* in case we return an error */
157 if (strm->zalloc == (alloc_func)0) { 157 if (strm->zalloc == (alloc_func)0) {
158 strm->zalloc = zcalloc; 158 strm->zalloc = zcalloc;
159 strm->opaque = (voidpf)0; 159 strm->opaque = (voidpf)0;
160 } 160 }
161 if (strm->zfree == (free_func)0) strm->zfree = zcfree; 161 if (strm->zfree == (free_func)0) strm->zfree = zcfree;
162 state = (struct inflate_state FAR *) 162 state = (struct inflate_state FAR *)
163 ZALLOC(strm, 1, sizeof(struct inflate_state)); 163 ZALLOC(strm, 1, sizeof(struct inflate_state));
164 if (state == Z_NULL) return Z_MEM_ERROR; 164 if (state == Z_NULL) return Z_MEM_ERROR;
165 Tracev((stderr, "inflate: allocated\n")); 165 Tracev((stderr, "inflate: allocated\n"));
166 strm->state = (struct internal_state FAR *)state; 166 strm->state = (struct internal_state FAR *)state;
167 if (windowBits < 0) { 167 if (windowBits < 0) {
168 state->wrap = 0; 168 state->wrap = 0;
169 windowBits = -windowBits; 169 windowBits = -windowBits;
170 } 170 }
171 else { 171 else {
172 state->wrap = (windowBits >> 4) + 1; 172 state->wrap = (windowBits >> 4) + 1;
173#ifdef GUNZIP 173#ifdef GUNZIP
174 if (windowBits < 48) windowBits &= 15; 174 if (windowBits < 48) windowBits &= 15;
175#endif 175#endif
176 } 176 }
177 if (windowBits < 8 || windowBits > 15) { 177 if (windowBits < 8 || windowBits > 15) {
178 ZFREE(strm, state); 178 ZFREE(strm, state);
179 strm->state = Z_NULL; 179 strm->state = Z_NULL;
180 return Z_STREAM_ERROR; 180 return Z_STREAM_ERROR;
181 } 181 }
182 state->wbits = (unsigned)windowBits; 182 state->wbits = (unsigned)windowBits;
183 state->window = Z_NULL; 183 state->window = Z_NULL;
184 return inflateReset(strm); 184 return inflateReset(strm);
185} 185}
186 186
187int ZEXPORT inflateInit_(strm, version, stream_size) 187int ZEXPORT inflateInit_(strm, version, stream_size)
188z_streamp strm; 188z_streamp strm;
189const char *version; 189const char *version;
190int stream_size; 190int stream_size;
191{ 191{
192 return inflateInit2_(strm, DEF_WBITS, version, stream_size); 192 return inflateInit2_(strm, DEF_WBITS, version, stream_size);
193} 193}
194 194
195/* 195/*
196 Return state with length and distance decoding tables and index sizes set to 196 Return state with length and distance decoding tables and index sizes set to
197 fixed code decoding. Normally this returns fixed tables from inffixed.h. 197 fixed code decoding. Normally this returns fixed tables from inffixed.h.
198 If BUILDFIXED is defined, then instead this routine builds the tables the 198 If BUILDFIXED is defined, then instead this routine builds the tables the
199 first time it's called, and returns those tables the first time and 199 first time it's called, and returns those tables the first time and
200 thereafter. This reduces the size of the code by about 2K bytes, in 200 thereafter. This reduces the size of the code by about 2K bytes, in
201 exchange for a little execution time. However, BUILDFIXED should not be 201 exchange for a little execution time. However, BUILDFIXED should not be
202 used for threaded applications, since the rewriting of the tables and virgin 202 used for threaded applications, since the rewriting of the tables and virgin
203 may not be thread-safe. 203 may not be thread-safe.
204 */ 204 */
205local void fixedtables(state) 205local void fixedtables(state)
206struct inflate_state FAR *state; 206struct inflate_state FAR *state;
207{ 207{
208#ifdef BUILDFIXED 208#ifdef BUILDFIXED
209 static int virgin = 1; 209 static int virgin = 1;
210 static code *lenfix, *distfix; 210 static code *lenfix, *distfix;
211 static code fixed[544]; 211 static code fixed[544];
212 212
213 /* build fixed huffman tables if first call (may not be thread safe) */ 213 /* build fixed huffman tables if first call (may not be thread safe) */
214 if (virgin) { 214 if (virgin) {
215 unsigned sym, bits; 215 unsigned sym, bits;
216 static code *next; 216 static code *next;
217 217
218 /* literal/length table */ 218 /* literal/length table */
219 sym = 0; 219 sym = 0;
220 while (sym < 144) state->lens[sym++] = 8; 220 while (sym < 144) state->lens[sym++] = 8;
221 while (sym < 256) state->lens[sym++] = 9; 221 while (sym < 256) state->lens[sym++] = 9;
222 while (sym < 280) state->lens[sym++] = 7; 222 while (sym < 280) state->lens[sym++] = 7;
223 while (sym < 288) state->lens[sym++] = 8; 223 while (sym < 288) state->lens[sym++] = 8;
224 next = fixed; 224 next = fixed;
225 lenfix = next; 225 lenfix = next;
226 bits = 9; 226 bits = 9;
227 inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); 227 inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
228 228
229 /* distance table */ 229 /* distance table */
230 sym = 0; 230 sym = 0;
231 while (sym < 32) state->lens[sym++] = 5; 231 while (sym < 32) state->lens[sym++] = 5;
232 distfix = next; 232 distfix = next;
233 bits = 5; 233 bits = 5;
234 inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); 234 inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
235 235
236 /* do this just once */ 236 /* do this just once */
237 virgin = 0; 237 virgin = 0;
238 } 238 }
239#else /* !BUILDFIXED */ 239#else /* !BUILDFIXED */
240# include "inffixed.h" 240# include "inffixed.h"
241#endif /* BUILDFIXED */ 241#endif /* BUILDFIXED */
242 state->lencode = lenfix; 242 state->lencode = lenfix;
243 state->lenbits = 9; 243 state->lenbits = 9;
244 state->distcode = distfix; 244 state->distcode = distfix;
245 state->distbits = 5; 245 state->distbits = 5;
246} 246}
247 247
248#ifdef MAKEFIXED 248#ifdef MAKEFIXED
249#include <stdio.h> 249#include <stdio.h>
250 250
251/* 251/*
252 Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also 252 Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
253 defines BUILDFIXED, so the tables are built on the fly. makefixed() writes 253 defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
254 those tables to stdout, which would be piped to inffixed.h. A small program 254 those tables to stdout, which would be piped to inffixed.h. A small program
255 can simply call makefixed to do this: 255 can simply call makefixed to do this:
256 256
257 void makefixed(void); 257 void makefixed(void);
258 258
259 int main(void) 259 int main(void)
260 { 260 {
261 makefixed(); 261 makefixed();
262 return 0; 262 return 0;
263 } 263 }
264 264
265 Then that can be linked with zlib built with MAKEFIXED defined and run: 265 Then that can be linked with zlib built with MAKEFIXED defined and run:
266 266
267 a.out > inffixed.h 267 a.out > inffixed.h
268 */ 268 */
269void makefixed() 269void makefixed()
270{ 270{
271 unsigned low, size; 271 unsigned low, size;
272 struct inflate_state state; 272 struct inflate_state state;
273 273
274 fixedtables(&state); 274 fixedtables(&state);
275 puts(" /* inffixed.h -- table for decoding fixed codes"); 275 puts(" /* inffixed.h -- table for decoding fixed codes");
276 puts(" * Generated automatically by makefixed()."); 276 puts(" * Generated automatically by makefixed().");
277 puts(" */"); 277 puts(" */");
278 puts(""); 278 puts("");
279 puts(" /* WARNING: this file should *not* be used by applications."); 279 puts(" /* WARNING: this file should *not* be used by applications.");
280 puts(" It is part of the implementation of this library and is"); 280 puts(" It is part of the implementation of this library and is");
281 puts(" subject to change. Applications should only use zlib.h."); 281 puts(" subject to change. Applications should only use zlib.h.");
282 puts(" */"); 282 puts(" */");
283 puts(""); 283 puts("");
284 size = 1U << 9; 284 size = 1U << 9;
285 printf(" static const code lenfix[%u] = {", size); 285 printf(" static const code lenfix[%u] = {", size);
286 low = 0; 286 low = 0;
287 for (;;) { 287 for (;;) {
288 if ((low % 7) == 0) printf("\n "); 288 if ((low % 7) == 0) printf("\n ");
289 printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits, 289 printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
290 state.lencode[low].val); 290 state.lencode[low].val);
291 if (++low == size) break; 291 if (++low == size) break;
292 putchar(','); 292 putchar(',');
293 } 293 }
294 puts("\n };"); 294 puts("\n };");
295 size = 1U << 5; 295 size = 1U << 5;
296 printf("\n static const code distfix[%u] = {", size); 296 printf("\n static const code distfix[%u] = {", size);
297 low = 0; 297 low = 0;
298 for (;;) { 298 for (;;) {
299 if ((low % 6) == 0) printf("\n "); 299 if ((low % 6) == 0) printf("\n ");
300 printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, 300 printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
301 state.distcode[low].val); 301 state.distcode[low].val);
302 if (++low == size) break; 302 if (++low == size) break;
303 putchar(','); 303 putchar(',');
304 } 304 }
305 puts("\n };"); 305 puts("\n };");
306} 306}
307#endif /* MAKEFIXED */ 307#endif /* MAKEFIXED */
308 308
309/* 309/*
310 Update the window with the last wsize (normally 32K) bytes written before 310 Update the window with the last wsize (normally 32K) bytes written before
311 returning. If window does not exist yet, create it. This is only called 311 returning. If window does not exist yet, create it. This is only called
312 when a window is already in use, or when output has been written during this 312 when a window is already in use, or when output has been written during this
313 inflate call, but the end of the deflate stream has not been reached yet. 313 inflate call, but the end of the deflate stream has not been reached yet.
314 It is also called to create a window for dictionary data when a dictionary 314 It is also called to create a window for dictionary data when a dictionary
315 is loaded. 315 is loaded.
316 316
317 Providing output buffers larger than 32K to inflate() should provide a speed 317 Providing output buffers larger than 32K to inflate() should provide a speed
318 advantage, since only the last 32K of output is copied to the sliding window 318 advantage, since only the last 32K of output is copied to the sliding window
319 upon return from inflate(), and since all distances after the first 32K of 319 upon return from inflate(), and since all distances after the first 32K of
320 output will fall in the output data, making match copies simpler and faster. 320 output will fall in the output data, making match copies simpler and faster.
321 The advantage may be dependent on the size of the processor's data caches. 321 The advantage may be dependent on the size of the processor's data caches.
322 */ 322 */
323local int updatewindow(strm, out) 323local int updatewindow(strm, out)
324z_streamp strm; 324z_streamp strm;
325unsigned out; 325unsigned out;
326{ 326{
327 struct inflate_state FAR *state; 327 struct inflate_state FAR *state;
328 unsigned copy, dist; 328 unsigned copy, dist;
329 329
330 state = (struct inflate_state FAR *)strm->state; 330 state = (struct inflate_state FAR *)strm->state;
331 331
332 /* if it hasn't been done already, allocate space for the window */ 332 /* if it hasn't been done already, allocate space for the window */
333 if (state->window == Z_NULL) { 333 if (state->window == Z_NULL) {
334 state->window = (unsigned char FAR *) 334 state->window = (unsigned char FAR *)
335 ZALLOC(strm, 1U << state->wbits, 335 ZALLOC(strm, 1U << state->wbits,
336 sizeof(unsigned char)); 336 sizeof(unsigned char));
337 if (state->window == Z_NULL) return 1; 337 if (state->window == Z_NULL) return 1;
338 } 338 }
339 339
340 /* if window not in use yet, initialize */ 340 /* if window not in use yet, initialize */
341 if (state->wsize == 0) { 341 if (state->wsize == 0) {
342 state->wsize = 1U << state->wbits; 342 state->wsize = 1U << state->wbits;
343 state->write = 0; 343 state->write = 0;
344 state->whave = 0; 344 state->whave = 0;
345 } 345 }
346 346
347 /* copy state->wsize or less output bytes into the circular window */ 347 /* copy state->wsize or less output bytes into the circular window */
348 copy = out - strm->avail_out; 348 copy = out - strm->avail_out;
349 if (copy >= state->wsize) { 349 if (copy >= state->wsize) {
350 zmemcpy(state->window, strm->next_out - state->wsize, state->wsize); 350 zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
351 state->write = 0; 351 state->write = 0;
352 state->whave = state->wsize; 352 state->whave = state->wsize;
353 } 353 }
354 else { 354 else {
355 dist = state->wsize - state->write; 355 dist = state->wsize - state->write;
356 if (dist > copy) dist = copy; 356 if (dist > copy) dist = copy;
357 zmemcpy(state->window + state->write, strm->next_out - copy, dist); 357 zmemcpy(state->window + state->write, strm->next_out - copy, dist);
358 copy -= dist; 358 copy -= dist;
359 if (copy) { 359 if (copy) {
360 zmemcpy(state->window, strm->next_out - copy, copy); 360 zmemcpy(state->window, strm->next_out - copy, copy);
361 state->write = copy; 361 state->write = copy;
362 state->whave = state->wsize; 362 state->whave = state->wsize;
363 } 363 }
364 else { 364 else {
365 state->write += dist; 365 state->write += dist;
366 if (state->write == state->wsize) state->write = 0; 366 if (state->write == state->wsize) state->write = 0;
367 if (state->whave < state->wsize) state->whave += dist; 367 if (state->whave < state->wsize) state->whave += dist;
368 } 368 }
369 } 369 }
370 return 0; 370 return 0;
371} 371}
372 372
373/* Macros for inflate(): */ 373/* Macros for inflate(): */
374 374
375/* check function to use adler32() for zlib or crc32() for gzip */ 375/* check function to use adler32() for zlib or crc32() for gzip */
376#ifdef GUNZIP 376#ifdef GUNZIP
377# define UPDATE(check, buf, len) \ 377# define UPDATE(check, buf, len) \
378 (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) 378 (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
379#else 379#else
380# define UPDATE(check, buf, len) adler32(check, buf, len) 380# define UPDATE(check, buf, len) adler32(check, buf, len)
381#endif 381#endif
382 382
383/* check macros for header crc */ 383/* check macros for header crc */
384#ifdef GUNZIP 384#ifdef GUNZIP
385# define CRC2(check, word) \ 385# define CRC2(check, word) \
386 do { \ 386 do { \
387 hbuf[0] = (unsigned char)(word); \ 387 hbuf[0] = (unsigned char)(word); \
388 hbuf[1] = (unsigned char)((word) >> 8); \ 388 hbuf[1] = (unsigned char)((word) >> 8); \
389 check = crc32(check, hbuf, 2); \ 389 check = crc32(check, hbuf, 2); \
390 } while (0) 390 } while (0)
391 391
392# define CRC4(check, word) \ 392# define CRC4(check, word) \
393 do { \ 393 do { \
394 hbuf[0] = (unsigned char)(word); \ 394 hbuf[0] = (unsigned char)(word); \
395 hbuf[1] = (unsigned char)((word) >> 8); \ 395 hbuf[1] = (unsigned char)((word) >> 8); \
396 hbuf[2] = (unsigned char)((word) >> 16); \ 396 hbuf[2] = (unsigned char)((word) >> 16); \
397 hbuf[3] = (unsigned char)((word) >> 24); \ 397 hbuf[3] = (unsigned char)((word) >> 24); \
398 check = crc32(check, hbuf, 4); \ 398 check = crc32(check, hbuf, 4); \
399 } while (0) 399 } while (0)
400#endif 400#endif
401 401
402/* Load registers with state in inflate() for speed */ 402/* Load registers with state in inflate() for speed */
403#define LOAD() \ 403#define LOAD() \
404 do { \ 404 do { \
405 put = strm->next_out; \ 405 put = strm->next_out; \
406 left = strm->avail_out; \ 406 left = strm->avail_out; \
407 next = strm->next_in; \ 407 next = strm->next_in; \
408 have = strm->avail_in; \ 408 have = strm->avail_in; \
409 hold = state->hold; \ 409 hold = state->hold; \
410 bits = state->bits; \ 410 bits = state->bits; \
411 } while (0) 411 } while (0)
412 412
413/* Restore state from registers in inflate() */ 413/* Restore state from registers in inflate() */
414#define RESTORE() \ 414#define RESTORE() \
415 do { \ 415 do { \
416 strm->next_out = put; \ 416 strm->next_out = put; \
417 strm->avail_out = left; \ 417 strm->avail_out = left; \
418 strm->next_in = next; \ 418 strm->next_in = next; \
419 strm->avail_in = have; \ 419 strm->avail_in = have; \
420 state->hold = hold; \ 420 state->hold = hold; \
421 state->bits = bits; \ 421 state->bits = bits; \
422 } while (0) 422 } while (0)
423 423
424/* Clear the input bit accumulator */ 424/* Clear the input bit accumulator */
425#define INITBITS() \ 425#define INITBITS() \
426 do { \ 426 do { \
427 hold = 0; \ 427 hold = 0; \
428 bits = 0; \ 428 bits = 0; \
429 } while (0) 429 } while (0)
430 430
431/* Get a byte of input into the bit accumulator, or return from inflate() 431/* Get a byte of input into the bit accumulator, or return from inflate()
432 if there is no input available. */ 432 if there is no input available. */
433#define PULLBYTE() \ 433#define PULLBYTE() \
434 do { \ 434 do { \
435 if (have == 0) goto inf_leave; \ 435 if (have == 0) goto inf_leave; \
436 have--; \ 436 have--; \
437 hold += (unsigned long)(*next++) << bits; \ 437 hold += (unsigned long)(*next++) << bits; \
438 bits += 8; \ 438 bits += 8; \
439 } while (0) 439 } while (0)
440 440
441/* Assure that there are at least n bits in the bit accumulator. If there is 441/* Assure that there are at least n bits in the bit accumulator. If there is
442 not enough available input to do that, then return from inflate(). */ 442 not enough available input to do that, then return from inflate(). */
443#define NEEDBITS(n) \ 443#define NEEDBITS(n) \
444 do { \ 444 do { \
445 while (bits < (unsigned)(n)) \ 445 while (bits < (unsigned)(n)) \
446 PULLBYTE(); \ 446 PULLBYTE(); \
447 } while (0) 447 } while (0)
448 448
449/* Return the low n bits of the bit accumulator (n < 16) */ 449/* Return the low n bits of the bit accumulator (n < 16) */
450#define BITS(n) \ 450#define BITS(n) \
451 ((unsigned)hold & ((1U << (n)) - 1)) 451 ((unsigned)hold & ((1U << (n)) - 1))
452 452
453/* Remove n bits from the bit accumulator */ 453/* Remove n bits from the bit accumulator */
454#define DROPBITS(n) \ 454#define DROPBITS(n) \
455 do { \ 455 do { \
456 hold >>= (n); \ 456 hold >>= (n); \
457 bits -= (unsigned)(n); \ 457 bits -= (unsigned)(n); \
458 } while (0) 458 } while (0)
459 459
460/* Remove zero to seven bits as needed to go to a byte boundary */ 460/* Remove zero to seven bits as needed to go to a byte boundary */
461#define BYTEBITS() \ 461#define BYTEBITS() \
462 do { \ 462 do { \
463 hold >>= bits & 7; \ 463 hold >>= bits & 7; \
464 bits -= bits & 7; \ 464 bits -= bits & 7; \
465 } while (0) 465 } while (0)
466 466
467/* Reverse the bytes in a 32-bit value */ 467/* Reverse the bytes in a 32-bit value */
468#define REVERSE(q) \ 468#define REVERSE(q) \
469 ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ 469 ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
470 (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) 470 (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
471 471
472/* 472/*
473 inflate() uses a state machine to process as much input data and generate as 473 inflate() uses a state machine to process as much input data and generate as
474 much output data as possible before returning. The state machine is 474 much output data as possible before returning. The state machine is
475 structured roughly as follows: 475 structured roughly as follows:
476 476
477 for (;;) switch (state) { 477 for (;;) switch (state) {
478 ... 478 ...
479 case STATEn: 479 case STATEn:
480 if (not enough input data or output space to make progress) 480 if (not enough input data or output space to make progress)
481 return; 481 return;
482 ... make progress ... 482 ... make progress ...
483 state = STATEm; 483 state = STATEm;
484 break; 484 break;
485 ... 485 ...
486 } 486 }
487 487
488 so when inflate() is called again, the same case is attempted again, and 488 so when inflate() is called again, the same case is attempted again, and
489 if the appropriate resources are provided, the machine proceeds to the 489 if the appropriate resources are provided, the machine proceeds to the
490 next state. The NEEDBITS() macro is usually the way the state evaluates 490 next state. The NEEDBITS() macro is usually the way the state evaluates
491 whether it can proceed or should return. NEEDBITS() does the return if 491 whether it can proceed or should return. NEEDBITS() does the return if
492 the requested bits are not available. The typical use of the BITS macros 492 the requested bits are not available. The typical use of the BITS macros
493 is: 493 is:
494 494
495 NEEDBITS(n); 495 NEEDBITS(n);
496 ... do something with BITS(n) ... 496 ... do something with BITS(n) ...
497 DROPBITS(n); 497 DROPBITS(n);
498 498
499 where NEEDBITS(n) either returns from inflate() if there isn't enough 499 where NEEDBITS(n) either returns from inflate() if there isn't enough
500 input left to load n bits into the accumulator, or it continues. BITS(n) 500 input left to load n bits into the accumulator, or it continues. BITS(n)
501 gives the low n bits in the accumulator. When done, DROPBITS(n) drops 501 gives the low n bits in the accumulator. When done, DROPBITS(n) drops
502 the low n bits off the accumulator. INITBITS() clears the accumulator 502 the low n bits off the accumulator. INITBITS() clears the accumulator
503 and sets the number of available bits to zero. BYTEBITS() discards just 503 and sets the number of available bits to zero. BYTEBITS() discards just
504 enough bits to put the accumulator on a byte boundary. After BYTEBITS() 504 enough bits to put the accumulator on a byte boundary. After BYTEBITS()
505 and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. 505 and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
506 506
507 NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return 507 NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
508 if there is no input available. The decoding of variable length codes uses 508 if there is no input available. The decoding of variable length codes uses
509 PULLBYTE() directly in order to pull just enough bytes to decode the next 509 PULLBYTE() directly in order to pull just enough bytes to decode the next
510 code, and no more. 510 code, and no more.
511 511
512 Some states loop until they get enough input, making sure that enough 512 Some states loop until they get enough input, making sure that enough
513 state information is maintained to continue the loop where it left off 513 state information is maintained to continue the loop where it left off
514 if NEEDBITS() returns in the loop. For example, want, need, and keep 514 if NEEDBITS() returns in the loop. For example, want, need, and keep
515 would all have to actually be part of the saved state in case NEEDBITS() 515 would all have to actually be part of the saved state in case NEEDBITS()
516 returns: 516 returns:
517 517
518 case STATEw: 518 case STATEw:
519 while (want < need) { 519 while (want < need) {
520 NEEDBITS(n); 520 NEEDBITS(n);
521 keep[want++] = BITS(n); 521 keep[want++] = BITS(n);
522 DROPBITS(n); 522 DROPBITS(n);
523 } 523 }
524 state = STATEx; 524 state = STATEx;
525 case STATEx: 525 case STATEx:
526 526
527 As shown above, if the next state is also the next case, then the break 527 As shown above, if the next state is also the next case, then the break
528 is omitted. 528 is omitted.
529 529
530 A state may also return if there is not enough output space available to 530 A state may also return if there is not enough output space available to
531 complete that state. Those states are copying stored data, writing a 531 complete that state. Those states are copying stored data, writing a
532 literal byte, and copying a matching string. 532 literal byte, and copying a matching string.
533 533
534 When returning, a "goto inf_leave" is used to update the total counters, 534 When returning, a "goto inf_leave" is used to update the total counters,
535 update the check value, and determine whether any progress has been made 535 update the check value, and determine whether any progress has been made
536 during that inflate() call in order to return the proper return code. 536 during that inflate() call in order to return the proper return code.
537 Progress is defined as a change in either strm->avail_in or strm->avail_out. 537 Progress is defined as a change in either strm->avail_in or strm->avail_out.
538 When there is a window, goto inf_leave will update the window with the last 538 When there is a window, goto inf_leave will update the window with the last
539 output written. If a goto inf_leave occurs in the middle of decompression 539 output written. If a goto inf_leave occurs in the middle of decompression
540 and there is no window currently, goto inf_leave will create one and copy 540 and there is no window currently, goto inf_leave will create one and copy
541 output to the window for the next call of inflate(). 541 output to the window for the next call of inflate().
542 542
543 In this implementation, the flush parameter of inflate() only affects the 543 In this implementation, the flush parameter of inflate() only affects the
544 return code (per zlib.h). inflate() always writes as much as possible to 544 return code (per zlib.h). inflate() always writes as much as possible to
545 strm->next_out, given the space available and the provided input--the effect 545 strm->next_out, given the space available and the provided input--the effect
546 documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers 546 documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
547 the allocation of and copying into a sliding window until necessary, which 547 the allocation of and copying into a sliding window until necessary, which
548 provides the effect documented in zlib.h for Z_FINISH when the entire input 548 provides the effect documented in zlib.h for Z_FINISH when the entire input
549 stream available. So the only thing the flush parameter actually does is: 549 stream available. So the only thing the flush parameter actually does is:
550 when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it 550 when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
551 will return Z_BUF_ERROR if it has not reached the end of the stream. 551 will return Z_BUF_ERROR if it has not reached the end of the stream.
552 */ 552 */
553 553
554int ZEXPORT inflate(strm, flush) 554int ZEXPORT inflate(strm, flush)
555z_streamp strm; 555z_streamp strm;
556int flush; 556int flush;
557{ 557{
558 struct inflate_state FAR *state; 558 struct inflate_state FAR *state;
559 unsigned char FAR *next; /* next input */ 559 unsigned char FAR *next; /* next input */
560 unsigned char FAR *put; /* next output */ 560 unsigned char FAR *put; /* next output */
561 unsigned have, left; /* available input and output */ 561 unsigned have, left; /* available input and output */
562 unsigned long hold; /* bit buffer */ 562 unsigned long hold; /* bit buffer */
563 unsigned bits; /* bits in bit buffer */ 563 unsigned bits; /* bits in bit buffer */
564 unsigned in, out; /* save starting available input and output */ 564 unsigned in, out; /* save starting available input and output */
565 unsigned copy; /* number of stored or match bytes to copy */ 565 unsigned copy; /* number of stored or match bytes to copy */
566 unsigned char FAR *from; /* where to copy match bytes from */ 566 unsigned char FAR *from; /* where to copy match bytes from */
567 code this; /* current decoding table entry */ 567 code this; /* current decoding table entry */
568 code last; /* parent table entry */ 568 code last; /* parent table entry */
569 unsigned len; /* length to copy for repeats, bits to drop */ 569 unsigned len; /* length to copy for repeats, bits to drop */
570 int ret; /* return code */ 570 int ret; /* return code */
571#ifdef GUNZIP 571#ifdef GUNZIP
572 unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ 572 unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
573#endif 573#endif
574 static const unsigned short order[19] = /* permutation of code lengths */ 574 static const unsigned short order[19] = /* permutation of code lengths */
575 {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; 575 {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
576 576
577 if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL || 577 if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
578 (strm->next_in == Z_NULL && strm->avail_in != 0)) 578 (strm->next_in == Z_NULL && strm->avail_in != 0))
579 return Z_STREAM_ERROR; 579 return Z_STREAM_ERROR;
580 580
581 state = (struct inflate_state FAR *)strm->state; 581 state = (struct inflate_state FAR *)strm->state;
582 if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ 582 if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
583 LOAD(); 583 LOAD();
584 in = have; 584 in = have;
585 out = left; 585 out = left;
586 ret = Z_OK; 586 ret = Z_OK;
587 for (;;) 587 for (;;)
588 switch (state->mode) { 588 switch (state->mode) {
589 case HEAD: 589 case HEAD:
590 if (state->wrap == 0) { 590 if (state->wrap == 0) {
591 state->mode = TYPEDO; 591 state->mode = TYPEDO;
592 break; 592 break;
593 } 593 }
594 NEEDBITS(16); 594 NEEDBITS(16);
595#ifdef GUNZIP 595#ifdef GUNZIP
596 if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ 596 if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
597 state->check = crc32(0L, Z_NULL, 0); 597 state->check = crc32(0L, Z_NULL, 0);
598 CRC2(state->check, hold); 598 CRC2(state->check, hold);
599 INITBITS(); 599 INITBITS();
600 state->mode = FLAGS; 600 state->mode = FLAGS;
601 break; 601 break;
602 } 602 }
603 state->flags = 0; /* expect zlib header */ 603 state->flags = 0; /* expect zlib header */
604 if (state->head != Z_NULL) 604 if (state->head != Z_NULL)
605 state->head->done = -1; 605 state->head->done = -1;
606 if (!(state->wrap & 1) || /* check if zlib header allowed */ 606 if (!(state->wrap & 1) || /* check if zlib header allowed */
607#else 607#else
608 if ( 608 if (
609#endif 609#endif
610 ((BITS(8) << 8) + (hold >> 8)) % 31) { 610 ((BITS(8) << 8) + (hold >> 8)) % 31) {
611 strm->msg = (char *)"incorrect header check"; 611 strm->msg = (char *)"incorrect header check";
612 state->mode = BAD; 612 state->mode = BAD;
613 break; 613 break;
614 } 614 }
615 if (BITS(4) != Z_DEFLATED) { 615 if (BITS(4) != Z_DEFLATED) {
616 strm->msg = (char *)"unknown compression method"; 616 strm->msg = (char *)"unknown compression method";
617 state->mode = BAD; 617 state->mode = BAD;
618 break; 618 break;
619 } 619 }
620 DROPBITS(4); 620 DROPBITS(4);
621 len = BITS(4) + 8; 621 len = BITS(4) + 8;
622 if (len > state->wbits) { 622 if (len > state->wbits) {
623 strm->msg = (char *)"invalid window size"; 623 strm->msg = (char *)"invalid window size";
624 state->mode = BAD; 624 state->mode = BAD;
625 break; 625 break;
626 } 626 }
627 state->dmax = 1U << len; 627 state->dmax = 1U << len;
628 Tracev((stderr, "inflate: zlib header ok\n")); 628 Tracev((stderr, "inflate: zlib header ok\n"));
629 strm->adler = state->check = adler32(0L, Z_NULL, 0); 629 strm->adler = state->check = adler32(0L, Z_NULL, 0);
630 state->mode = hold & 0x200 ? DICTID : TYPE; 630 state->mode = hold & 0x200 ? DICTID : TYPE;
631 INITBITS(); 631 INITBITS();
632 break; 632 break;
633#ifdef GUNZIP 633#ifdef GUNZIP
634 case FLAGS: 634 case FLAGS:
635 NEEDBITS(16); 635 NEEDBITS(16);
636 state->flags = (int)(hold); 636 state->flags = (int)(hold);
637 if ((state->flags & 0xff) != Z_DEFLATED) { 637 if ((state->flags & 0xff) != Z_DEFLATED) {
638 strm->msg = (char *)"unknown compression method"; 638 strm->msg = (char *)"unknown compression method";
639 state->mode = BAD; 639 state->mode = BAD;
640 break; 640 break;
641 } 641 }
642 if (state->flags & 0xe000) { 642 if (state->flags & 0xe000) {
643 strm->msg = (char *)"unknown header flags set"; 643 strm->msg = (char *)"unknown header flags set";
644 state->mode = BAD; 644 state->mode = BAD;
645 break; 645 break;
646 } 646 }
647 if (state->head != Z_NULL) 647 if (state->head != Z_NULL)
648 state->head->text = (int)((hold >> 8) & 1); 648 state->head->text = (int)((hold >> 8) & 1);
649 if (state->flags & 0x0200) CRC2(state->check, hold); 649 if (state->flags & 0x0200) CRC2(state->check, hold);
650 INITBITS(); 650 INITBITS();
651 state->mode = TIME; 651 state->mode = TIME;
652 case TIME: 652 case TIME:
653 NEEDBITS(32); 653 NEEDBITS(32);
654 if (state->head != Z_NULL) 654 if (state->head != Z_NULL)
655 state->head->time = hold; 655 state->head->time = hold;
656 if (state->flags & 0x0200) CRC4(state->check, hold); 656 if (state->flags & 0x0200) CRC4(state->check, hold);
657 INITBITS(); 657 INITBITS();
658 state->mode = OS; 658 state->mode = OS;
659 case OS: 659 case OS:
660 NEEDBITS(16); 660 NEEDBITS(16);
661 if (state->head != Z_NULL) { 661 if (state->head != Z_NULL) {
662 state->head->xflags = (int)(hold & 0xff); 662 state->head->xflags = (int)(hold & 0xff);
663 state->head->os = (int)(hold >> 8); 663 state->head->os = (int)(hold >> 8);
664 } 664 }
665 if (state->flags & 0x0200) CRC2(state->check, hold); 665 if (state->flags & 0x0200) CRC2(state->check, hold);
666 INITBITS(); 666 INITBITS();
667 state->mode = EXLEN; 667 state->mode = EXLEN;
668 case EXLEN: 668 case EXLEN:
669 if (state->flags & 0x0400) { 669 if (state->flags & 0x0400) {
670 NEEDBITS(16); 670 NEEDBITS(16);
671 state->length = (unsigned)(hold); 671 state->length = (unsigned)(hold);
672 if (state->head != Z_NULL) 672 if (state->head != Z_NULL)
673 state->head->extra_len = (unsigned)hold; 673 state->head->extra_len = (unsigned)hold;
674 if (state->flags & 0x0200) CRC2(state->check, hold); 674 if (state->flags & 0x0200) CRC2(state->check, hold);
675 INITBITS(); 675 INITBITS();
676 } 676 }
677 else if (state->head != Z_NULL) 677 else if (state->head != Z_NULL)
678 state->head->extra = Z_NULL; 678 state->head->extra = Z_NULL;
679 state->mode = EXTRA; 679 state->mode = EXTRA;
680 case EXTRA: 680 case EXTRA:
681 if (state->flags & 0x0400) { 681 if (state->flags & 0x0400) {
682 copy = state->length; 682 copy = state->length;
683 if (copy > have) copy = have; 683 if (copy > have) copy = have;
684 if (copy) { 684 if (copy) {
685 if (state->head != Z_NULL && 685 if (state->head != Z_NULL &&
686 state->head->extra != Z_NULL) { 686 state->head->extra != Z_NULL) {
687 len = state->head->extra_len - state->length; 687 len = state->head->extra_len - state->length;
688 zmemcpy(state->head->extra + len, next, 688 zmemcpy(state->head->extra + len, next,
689 len + copy > state->head->extra_max ? 689 len + copy > state->head->extra_max ?
690 state->head->extra_max - len : copy); 690 state->head->extra_max - len : copy);
691 } 691 }
692 if (state->flags & 0x0200) 692 if (state->flags & 0x0200)
693 state->check = crc32(state->check, next, copy); 693 state->check = crc32(state->check, next, copy);
694 have -= copy; 694 have -= copy;
695 next += copy; 695 next += copy;
696 state->length -= copy; 696 state->length -= copy;
697 } 697 }
698 if (state->length) goto inf_leave; 698 if (state->length) goto inf_leave;
699 } 699 }
700 state->length = 0; 700 state->length = 0;
701 state->mode = NAME; 701 state->mode = NAME;
702 case NAME: 702 case NAME:
703 if (state->flags & 0x0800) { 703 if (state->flags & 0x0800) {
704 if (have == 0) goto inf_leave; 704 if (have == 0) goto inf_leave;
705 copy = 0; 705 copy = 0;
706 do { 706 do {
707 len = (unsigned)(next[copy++]); 707 len = (unsigned)(next[copy++]);
708 if (state->head != Z_NULL && 708 if (state->head != Z_NULL &&
709 state->head->name != Z_NULL && 709 state->head->name != Z_NULL &&
710 state->length < state->head->name_max) 710 state->length < state->head->name_max)
711 state->head->name[state->length++] = len; 711 state->head->name[state->length++] = len;
712 } while (len && copy < have); 712 } while (len && copy < have);
713 if (state->flags & 0x0200) 713 if (state->flags & 0x0200)
714 state->check = crc32(state->check, next, copy); 714 state->check = crc32(state->check, next, copy);
715 have -= copy; 715 have -= copy;
716 next += copy; 716 next += copy;
717 if (len) goto inf_leave; 717 if (len) goto inf_leave;
718 } 718 }
719 else if (state->head != Z_NULL) 719 else if (state->head != Z_NULL)
720 state->head->name = Z_NULL; 720 state->head->name = Z_NULL;
721 state->length = 0; 721 state->length = 0;
722 state->mode = COMMENT; 722 state->mode = COMMENT;
723 case COMMENT: 723 case COMMENT:
724 if (state->flags & 0x1000) { 724 if (state->flags & 0x1000) {
725 if (have == 0) goto inf_leave; 725 if (have == 0) goto inf_leave;
726 copy = 0; 726 copy = 0;
727 do { 727 do {
728 len = (unsigned)(next[copy++]); 728 len = (unsigned)(next[copy++]);
729 if (state->head != Z_NULL && 729 if (state->head != Z_NULL &&
730 state->head->comment != Z_NULL && 730 state->head->comment != Z_NULL &&
731 state->length < state->head->comm_max) 731 state->length < state->head->comm_max)
732 state->head->comment[state->length++] = len; 732 state->head->comment[state->length++] = len;
733 } while (len && copy < have); 733 } while (len && copy < have);
734 if (state->flags & 0x0200) 734 if (state->flags & 0x0200)
735 state->check = crc32(state->check, next, copy); 735 state->check = crc32(state->check, next, copy);
736 have -= copy; 736 have -= copy;
737 next += copy; 737 next += copy;
738 if (len) goto inf_leave; 738 if (len) goto inf_leave;
739 } 739 }
740 else if (state->head != Z_NULL) 740 else if (state->head != Z_NULL)
741 state->head->comment = Z_NULL; 741 state->head->comment = Z_NULL;
742 state->mode = HCRC; 742 state->mode = HCRC;
743 case HCRC: 743 case HCRC:
744 if (state->flags & 0x0200) { 744 if (state->flags & 0x0200) {
745 NEEDBITS(16); 745 NEEDBITS(16);
746 if (hold != (state->check & 0xffff)) { 746 if (hold != (state->check & 0xffff)) {
747 strm->msg = (char *)"header crc mismatch"; 747 strm->msg = (char *)"header crc mismatch";
748 state->mode = BAD; 748 state->mode = BAD;
749 break; 749 break;
750 } 750 }
751 INITBITS(); 751 INITBITS();
752 } 752 }
753 if (state->head != Z_NULL) { 753 if (state->head != Z_NULL) {
754 state->head->hcrc = (int)((state->flags >> 9) & 1); 754 state->head->hcrc = (int)((state->flags >> 9) & 1);
755 state->head->done = 1; 755 state->head->done = 1;
756 } 756 }
757 strm->adler = state->check = crc32(0L, Z_NULL, 0); 757 strm->adler = state->check = crc32(0L, Z_NULL, 0);
758 state->mode = TYPE; 758 state->mode = TYPE;
759 break; 759 break;
760#endif 760#endif
761 case DICTID: 761 case DICTID:
762 NEEDBITS(32); 762 NEEDBITS(32);
763 strm->adler = state->check = REVERSE(hold); 763 strm->adler = state->check = REVERSE(hold);
764 INITBITS(); 764 INITBITS();
765 state->mode = DICT; 765 state->mode = DICT;
766 case DICT: 766 case DICT:
767 if (state->havedict == 0) { 767 if (state->havedict == 0) {
768 RESTORE(); 768 RESTORE();
769 return Z_NEED_DICT; 769 return Z_NEED_DICT;
770 } 770 }
771 strm->adler = state->check = adler32(0L, Z_NULL, 0); 771 strm->adler = state->check = adler32(0L, Z_NULL, 0);
772 state->mode = TYPE; 772 state->mode = TYPE;
773 case TYPE: 773 case TYPE:
774 if (flush == Z_BLOCK) goto inf_leave; 774 if (flush == Z_BLOCK) goto inf_leave;
775 case TYPEDO: 775 case TYPEDO:
776 if (state->last) { 776 if (state->last) {
777 BYTEBITS(); 777 BYTEBITS();
778 state->mode = CHECK; 778 state->mode = CHECK;
779 break; 779 break;
780 } 780 }
781 NEEDBITS(3); 781 NEEDBITS(3);
782 state->last = BITS(1); 782 state->last = BITS(1);
783 DROPBITS(1); 783 DROPBITS(1);
784 switch (BITS(2)) { 784 switch (BITS(2)) {
785 case 0: /* stored block */ 785 case 0: /* stored block */
786 Tracev((stderr, "inflate: stored block%s\n", 786 Tracev((stderr, "inflate: stored block%s\n",
787 state->last ? " (last)" : "")); 787 state->last ? " (last)" : ""));
788 state->mode = STORED; 788 state->mode = STORED;
789 break; 789 break;
790 case 1: /* fixed block */ 790 case 1: /* fixed block */
791 fixedtables(state); 791 fixedtables(state);
792 Tracev((stderr, "inflate: fixed codes block%s\n", 792 Tracev((stderr, "inflate: fixed codes block%s\n",
793 state->last ? " (last)" : "")); 793 state->last ? " (last)" : ""));
794 state->mode = LEN; /* decode codes */ 794 state->mode = LEN; /* decode codes */
795 break; 795 break;
796 case 2: /* dynamic block */ 796 case 2: /* dynamic block */
797 Tracev((stderr, "inflate: dynamic codes block%s\n", 797 Tracev((stderr, "inflate: dynamic codes block%s\n",
798 state->last ? " (last)" : "")); 798 state->last ? " (last)" : ""));
799 state->mode = TABLE; 799 state->mode = TABLE;
800 break; 800 break;
801 case 3: 801 case 3:
802 strm->msg = (char *)"invalid block type"; 802 strm->msg = (char *)"invalid block type";
803 state->mode = BAD; 803 state->mode = BAD;
804 } 804 }
805 DROPBITS(2); 805 DROPBITS(2);
806 break; 806 break;
807 case STORED: 807 case STORED:
808 BYTEBITS(); /* go to byte boundary */ 808 BYTEBITS(); /* go to byte boundary */
809 NEEDBITS(32); 809 NEEDBITS(32);
810 if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { 810 if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
811 strm->msg = (char *)"invalid stored block lengths"; 811 strm->msg = (char *)"invalid stored block lengths";
812 state->mode = BAD; 812 state->mode = BAD;
813 break; 813 break;
814 } 814 }
815 state->length = (unsigned)hold & 0xffff; 815 state->length = (unsigned)hold & 0xffff;
816 Tracev((stderr, "inflate: stored length %u\n", 816 Tracev((stderr, "inflate: stored length %u\n",
817 state->length)); 817 state->length));
818 INITBITS(); 818 INITBITS();
819 state->mode = COPY; 819 state->mode = COPY;
820 case COPY: 820 case COPY:
821 copy = state->length; 821 copy = state->length;
822 if (copy) { 822 if (copy) {
823 if (copy > have) copy = have; 823 if (copy > have) copy = have;
824 if (copy > left) copy = left; 824 if (copy > left) copy = left;
825 if (copy == 0) goto inf_leave; 825 if (copy == 0) goto inf_leave;
826 zmemcpy(put, next, copy); 826 zmemcpy(put, next, copy);
827 have -= copy; 827 have -= copy;
828 next += copy; 828 next += copy;
829 left -= copy; 829 left -= copy;
830 put += copy; 830 put += copy;
831 state->length -= copy; 831 state->length -= copy;
832 break; 832 break;
833 } 833 }
834 Tracev((stderr, "inflate: stored end\n")); 834 Tracev((stderr, "inflate: stored end\n"));
835 state->mode = TYPE; 835 state->mode = TYPE;
836 break; 836 break;
837 case TABLE: 837 case TABLE:
838 NEEDBITS(14); 838 NEEDBITS(14);
839 state->nlen = BITS(5) + 257; 839 state->nlen = BITS(5) + 257;
840 DROPBITS(5); 840 DROPBITS(5);
841 state->ndist = BITS(5) + 1; 841 state->ndist = BITS(5) + 1;
842 DROPBITS(5); 842 DROPBITS(5);
843 state->ncode = BITS(4) + 4; 843 state->ncode = BITS(4) + 4;
844 DROPBITS(4); 844 DROPBITS(4);
845#ifndef PKZIP_BUG_WORKAROUND 845#ifndef PKZIP_BUG_WORKAROUND
846 if (state->nlen > 286 || state->ndist > 30) { 846 if (state->nlen > 286 || state->ndist > 30) {
847 strm->msg = (char *)"too many length or distance symbols"; 847 strm->msg = (char *)"too many length or distance symbols";
848 state->mode = BAD; 848 state->mode = BAD;
849 break; 849 break;
850 } 850 }
851#endif 851#endif
852 Tracev((stderr, "inflate: table sizes ok\n")); 852 Tracev((stderr, "inflate: table sizes ok\n"));
853 state->have = 0; 853 state->have = 0;
854 state->mode = LENLENS; 854 state->mode = LENLENS;
855 case LENLENS: 855 case LENLENS:
856 while (state->have < state->ncode) { 856 while (state->have < state->ncode) {
857 NEEDBITS(3); 857 NEEDBITS(3);
858 state->lens[order[state->have++]] = (unsigned short)BITS(3); 858 state->lens[order[state->have++]] = (unsigned short)BITS(3);
859 DROPBITS(3); 859 DROPBITS(3);
860 } 860 }
861 while (state->have < 19) 861 while (state->have < 19)
862 state->lens[order[state->have++]] = 0; 862 state->lens[order[state->have++]] = 0;
863 state->next = state->codes; 863 state->next = state->codes;
864 state->lencode = (code const FAR *)(state->next); 864 state->lencode = (code const FAR *)(state->next);
865 state->lenbits = 7; 865 state->lenbits = 7;
866 ret = inflate_table(CODES, state->lens, 19, &(state->next), 866 ret = inflate_table(CODES, state->lens, 19, &(state->next),
867 &(state->lenbits), state->work); 867 &(state->lenbits), state->work);
868 if (ret) { 868 if (ret) {
869 strm->msg = (char *)"invalid code lengths set"; 869 strm->msg = (char *)"invalid code lengths set";
870 state->mode = BAD; 870 state->mode = BAD;
871 break; 871 break;
872 } 872 }
873 Tracev((stderr, "inflate: code lengths ok\n")); 873 Tracev((stderr, "inflate: code lengths ok\n"));
874 state->have = 0; 874 state->have = 0;
875 state->mode = CODELENS; 875 state->mode = CODELENS;
876 case CODELENS: 876 case CODELENS:
877 while (state->have < state->nlen + state->ndist) { 877 while (state->have < state->nlen + state->ndist) {
878 for (;;) { 878 for (;;) {
879 this = state->lencode[BITS(state->lenbits)]; 879 this = state->lencode[BITS(state->lenbits)];
880 if ((unsigned)(this.bits) <= bits) break; 880 if ((unsigned)(this.bits) <= bits) break;
881 PULLBYTE(); 881 PULLBYTE();
882 } 882 }
883 if (this.val < 16) { 883 if (this.val < 16) {
884 NEEDBITS(this.bits); 884 NEEDBITS(this.bits);
885 DROPBITS(this.bits); 885 DROPBITS(this.bits);
886 state->lens[state->have++] = this.val; 886 state->lens[state->have++] = this.val;
887 } 887 }
888 else { 888 else {
889 if (this.val == 16) { 889 if (this.val == 16) {
890 NEEDBITS(this.bits + 2); 890 NEEDBITS(this.bits + 2);
891 DROPBITS(this.bits); 891 DROPBITS(this.bits);
892 if (state->have == 0) { 892 if (state->have == 0) {
893 strm->msg = (char *)"invalid bit length repeat"; 893 strm->msg = (char *)"invalid bit length repeat";
894 state->mode = BAD; 894 state->mode = BAD;
895 break; 895 break;
896 } 896 }
897 len = state->lens[state->have - 1]; 897 len = state->lens[state->have - 1];
898 copy = 3 + BITS(2); 898 copy = 3 + BITS(2);
899 DROPBITS(2); 899 DROPBITS(2);
900 } 900 }
901 else if (this.val == 17) { 901 else if (this.val == 17) {
902 NEEDBITS(this.bits + 3); 902 NEEDBITS(this.bits + 3);
903 DROPBITS(this.bits); 903 DROPBITS(this.bits);
904 len = 0; 904 len = 0;
905 copy = 3 + BITS(3); 905 copy = 3 + BITS(3);
906 DROPBITS(3); 906 DROPBITS(3);
907 } 907 }
908 else { 908 else {
909 NEEDBITS(this.bits + 7); 909 NEEDBITS(this.bits + 7);
910 DROPBITS(this.bits); 910 DROPBITS(this.bits);
911 len = 0; 911 len = 0;
912 copy = 11 + BITS(7); 912 copy = 11 + BITS(7);
913 DROPBITS(7); 913 DROPBITS(7);
914 } 914 }
915 if (state->have + copy > state->nlen + state->ndist) { 915 if (state->have + copy > state->nlen + state->ndist) {
916 strm->msg = (char *)"invalid bit length repeat"; 916 strm->msg = (char *)"invalid bit length repeat";
917 state->mode = BAD; 917 state->mode = BAD;
918 break; 918 break;
919 } 919 }
920 while (copy--) 920 while (copy--)
921 state->lens[state->have++] = (unsigned short)len; 921 state->lens[state->have++] = (unsigned short)len;
922 } 922 }
923 } 923 }
924 924
925 /* handle error breaks in while */ 925 /* handle error breaks in while */
926 if (state->mode == BAD) break; 926 if (state->mode == BAD) break;
927 927
928 /* build code tables */ 928 /* build code tables */
929 state->next = state->codes; 929 state->next = state->codes;
930 state->lencode = (code const FAR *)(state->next); 930 state->lencode = (code const FAR *)(state->next);
931 state->lenbits = 9; 931 state->lenbits = 9;
932 ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), 932 ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
933 &(state->lenbits), state->work); 933 &(state->lenbits), state->work);
934 if (ret) { 934 if (ret) {
935 strm->msg = (char *)"invalid literal/lengths set"; 935 strm->msg = (char *)"invalid literal/lengths set";
936 state->mode = BAD; 936 state->mode = BAD;
937 break; 937 break;
938 } 938 }
939 state->distcode = (code const FAR *)(state->next); 939 state->distcode = (code const FAR *)(state->next);
940 state->distbits = 6; 940 state->distbits = 6;
941 ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, 941 ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
942 &(state->next), &(state->distbits), state->work); 942 &(state->next), &(state->distbits), state->work);
943 if (ret) { 943 if (ret) {
944 strm->msg = (char *)"invalid distances set"; 944 strm->msg = (char *)"invalid distances set";
945 state->mode = BAD; 945 state->mode = BAD;
946 break; 946 break;
947 } 947 }
948 Tracev((stderr, "inflate: codes ok\n")); 948 Tracev((stderr, "inflate: codes ok\n"));
949 state->mode = LEN; 949 state->mode = LEN;
950 case LEN: 950 case LEN:
951 if (have >= 6 && left >= 258) { 951 if (have >= 6 && left >= 258) {
952 RESTORE(); 952 RESTORE();
953 inflate_fast(strm, out); 953 inflate_fast(strm, out);
954 LOAD(); 954 LOAD();
955 break; 955 break;
956 } 956 }
957 for (;;) { 957 for (;;) {
958 this = state->lencode[BITS(state->lenbits)]; 958 this = state->lencode[BITS(state->lenbits)];
959 if ((unsigned)(this.bits) <= bits) break; 959 if ((unsigned)(this.bits) <= bits) break;
960 PULLBYTE(); 960 PULLBYTE();
961 } 961 }
962 if (this.op && (this.op & 0xf0) == 0) { 962 if (this.op && (this.op & 0xf0) == 0) {
963 last = this; 963 last = this;
964 for (;;) { 964 for (;;) {
965 this = state->lencode[last.val + 965 this = state->lencode[last.val +
966 (BITS(last.bits + last.op) >> last.bits)]; 966 (BITS(last.bits + last.op) >> last.bits)];
967 if ((unsigned)(last.bits + this.bits) <= bits) break; 967 if ((unsigned)(last.bits + this.bits) <= bits) break;
968 PULLBYTE(); 968 PULLBYTE();
969 } 969 }
970 DROPBITS(last.bits); 970 DROPBITS(last.bits);
971 } 971 }
972 DROPBITS(this.bits); 972 DROPBITS(this.bits);
973 state->length = (unsigned)this.val; 973 state->length = (unsigned)this.val;
974 if ((int)(this.op) == 0) { 974 if ((int)(this.op) == 0) {
975 Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? 975 Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
976 "inflate: literal '%c'\n" : 976 "inflate: literal '%c'\n" :
977 "inflate: literal 0x%02x\n", this.val)); 977 "inflate: literal 0x%02x\n", this.val));
978 state->mode = LIT; 978 state->mode = LIT;
979 break; 979 break;
980 } 980 }
981 if (this.op & 32) { 981 if (this.op & 32) {
982 Tracevv((stderr, "inflate: end of block\n")); 982 Tracevv((stderr, "inflate: end of block\n"));
983 state->mode = TYPE; 983 state->mode = TYPE;
984 break; 984 break;
985 } 985 }
986 if (this.op & 64) { 986 if (this.op & 64) {
987 strm->msg = (char *)"invalid literal/length code"; 987 strm->msg = (char *)"invalid literal/length code";
988 state->mode = BAD; 988 state->mode = BAD;
989 break; 989 break;
990 } 990 }
991 state->extra = (unsigned)(this.op) & 15; 991 state->extra = (unsigned)(this.op) & 15;
992 state->mode = LENEXT; 992 state->mode = LENEXT;
993 case LENEXT: 993 case LENEXT:
994 if (state->extra) { 994 if (state->extra) {
995 NEEDBITS(state->extra); 995 NEEDBITS(state->extra);
996 state->length += BITS(state->extra); 996 state->length += BITS(state->extra);
997 DROPBITS(state->extra); 997 DROPBITS(state->extra);
998 } 998 }
999 Tracevv((stderr, "inflate: length %u\n", state->length)); 999 Tracevv((stderr, "inflate: length %u\n", state->length));
1000 state->mode = DIST; 1000 state->mode = DIST;
1001 case DIST: 1001 case DIST:
1002 for (;;) { 1002 for (;;) {
1003 this = state->distcode[BITS(state->distbits)]; 1003 this = state->distcode[BITS(state->distbits)];
1004 if ((unsigned)(this.bits) <= bits) break; 1004 if ((unsigned)(this.bits) <= bits) break;
1005 PULLBYTE(); 1005 PULLBYTE();
1006 } 1006 }
1007 if ((this.op & 0xf0) == 0) { 1007 if ((this.op & 0xf0) == 0) {
1008 last = this; 1008 last = this;
1009 for (;;) { 1009 for (;;) {
1010 this = state->distcode[last.val + 1010 this = state->distcode[last.val +
1011 (BITS(last.bits + last.op) >> last.bits)]; 1011 (BITS(last.bits + last.op) >> last.bits)];
1012 if ((unsigned)(last.bits + this.bits) <= bits) break; 1012 if ((unsigned)(last.bits + this.bits) <= bits) break;
1013 PULLBYTE(); 1013 PULLBYTE();
1014 } 1014 }
1015 DROPBITS(last.bits); 1015 DROPBITS(last.bits);
1016 } 1016 }
1017 DROPBITS(this.bits); 1017 DROPBITS(this.bits);
1018 if (this.op & 64) { 1018 if (this.op & 64) {
1019 strm->msg = (char *)"invalid distance code"; 1019 strm->msg = (char *)"invalid distance code";
1020 state->mode = BAD; 1020 state->mode = BAD;
1021 break; 1021 break;
1022 } 1022 }
1023 state->offset = (unsigned)this.val; 1023 state->offset = (unsigned)this.val;
1024 state->extra = (unsigned)(this.op) & 15; 1024 state->extra = (unsigned)(this.op) & 15;
1025 state->mode = DISTEXT; 1025 state->mode = DISTEXT;
1026 case DISTEXT: 1026 case DISTEXT:
1027 if (state->extra) { 1027 if (state->extra) {
1028 NEEDBITS(state->extra); 1028 NEEDBITS(state->extra);
1029 state->offset += BITS(state->extra); 1029 state->offset += BITS(state->extra);
1030 DROPBITS(state->extra); 1030 DROPBITS(state->extra);
1031 } 1031 }
1032#ifdef INFLATE_STRICT 1032#ifdef INFLATE_STRICT
1033 if (state->offset > state->dmax) { 1033 if (state->offset > state->dmax) {
1034 strm->msg = (char *)"invalid distance too far back"; 1034 strm->msg = (char *)"invalid distance too far back";
1035 state->mode = BAD; 1035 state->mode = BAD;
1036 break; 1036 break;
1037 } 1037 }
1038#endif 1038#endif
1039 if (state->offset > state->whave + out - left) { 1039 if (state->offset > state->whave + out - left) {
1040 strm->msg = (char *)"invalid distance too far back"; 1040 strm->msg = (char *)"invalid distance too far back";
1041 state->mode = BAD; 1041 state->mode = BAD;
1042 break; 1042 break;
1043 } 1043 }
1044 Tracevv((stderr, "inflate: distance %u\n", state->offset)); 1044 Tracevv((stderr, "inflate: distance %u\n", state->offset));
1045 state->mode = MATCH; 1045 state->mode = MATCH;
1046 case MATCH: 1046 case MATCH:
1047 if (left == 0) goto inf_leave; 1047 if (left == 0) goto inf_leave;
1048 copy = out - left; 1048 copy = out - left;
1049 if (state->offset > copy) { /* copy from window */ 1049 if (state->offset > copy) { /* copy from window */
1050 copy = state->offset - copy; 1050 copy = state->offset - copy;
1051 if (copy > state->write) { 1051 if (copy > state->write) {
1052 copy -= state->write; 1052 copy -= state->write;
1053 from = state->window + (state->wsize - copy); 1053 from = state->window + (state->wsize - copy);
1054 } 1054 }
1055 else 1055 else
1056 from = state->window + (state->write - copy); 1056 from = state->window + (state->write - copy);
1057 if (copy > state->length) copy = state->length; 1057 if (copy > state->length) copy = state->length;
1058 } 1058 }
1059 else { /* copy from output */ 1059 else { /* copy from output */
1060 from = put - state->offset; 1060 from = put - state->offset;
1061 copy = state->length; 1061 copy = state->length;
1062 } 1062 }
1063 if (copy > left) copy = left; 1063 if (copy > left) copy = left;
1064 left -= copy; 1064 left -= copy;
1065 state->length -= copy; 1065 state->length -= copy;
1066 do { 1066 do {
1067 *put++ = *from++; 1067 *put++ = *from++;
1068 } while (--copy); 1068 } while (--copy);
1069 if (state->length == 0) state->mode = LEN; 1069 if (state->length == 0) state->mode = LEN;
1070 break; 1070 break;
1071 case LIT: 1071 case LIT:
1072 if (left == 0) goto inf_leave; 1072 if (left == 0) goto inf_leave;
1073 *put++ = (unsigned char)(state->length); 1073 *put++ = (unsigned char)(state->length);
1074 left--; 1074 left--;
1075 state->mode = LEN; 1075 state->mode = LEN;
1076 break; 1076 break;
1077 case CHECK: 1077 case CHECK:
1078 if (state->wrap) { 1078 if (state->wrap) {
1079 NEEDBITS(32); 1079 NEEDBITS(32);
1080 out -= left; 1080 out -= left;
1081 strm->total_out += out; 1081 strm->total_out += out;
1082 state->total += out; 1082 state->total += out;
1083 if (out) 1083 if (out)
1084 strm->adler = state->check = 1084 strm->adler = state->check =
1085 UPDATE(state->check, put - out, out); 1085 UPDATE(state->check, put - out, out);
1086 out = left; 1086 out = left;
1087 if (( 1087 if ((
1088#ifdef GUNZIP 1088#ifdef GUNZIP
1089 state->flags ? hold : 1089 state->flags ? hold :
1090#endif 1090#endif
1091 REVERSE(hold)) != state->check) { 1091 REVERSE(hold)) != state->check) {
1092 strm->msg = (char *)"incorrect data check"; 1092 strm->msg = (char *)"incorrect data check";
1093 state->mode = BAD; 1093 state->mode = BAD;
1094 break; 1094 break;
1095 } 1095 }
1096 INITBITS(); 1096 INITBITS();
1097 Tracev((stderr, "inflate: check matches trailer\n")); 1097 Tracev((stderr, "inflate: check matches trailer\n"));
1098 } 1098 }
1099#ifdef GUNZIP 1099#ifdef GUNZIP
1100 state->mode = LENGTH; 1100 state->mode = LENGTH;
1101 case LENGTH: 1101 case LENGTH:
1102 if (state->wrap && state->flags) { 1102 if (state->wrap && state->flags) {
1103 NEEDBITS(32); 1103 NEEDBITS(32);
1104 if (hold != (state->total & 0xffffffffUL)) { 1104 if (hold != (state->total & 0xffffffffUL)) {
1105 strm->msg = (char *)"incorrect length check"; 1105 strm->msg = (char *)"incorrect length check";
1106 state->mode = BAD; 1106 state->mode = BAD;
1107 break; 1107 break;
1108 } 1108 }
1109 INITBITS(); 1109 INITBITS();
1110 Tracev((stderr, "inflate: length matches trailer\n")); 1110 Tracev((stderr, "inflate: length matches trailer\n"));
1111 } 1111 }
1112#endif 1112#endif
1113 state->mode = DONE; 1113 state->mode = DONE;
1114 case DONE: 1114 case DONE:
1115 ret = Z_STREAM_END; 1115 ret = Z_STREAM_END;
1116 goto inf_leave; 1116 goto inf_leave;
1117 case BAD: 1117 case BAD:
1118 ret = Z_DATA_ERROR; 1118 ret = Z_DATA_ERROR;
1119 goto inf_leave; 1119 goto inf_leave;
1120 case MEM: 1120 case MEM:
1121 return Z_MEM_ERROR; 1121 return Z_MEM_ERROR;
1122 case SYNC: 1122 case SYNC:
1123 default: 1123 default:
1124 return Z_STREAM_ERROR; 1124 return Z_STREAM_ERROR;
1125 } 1125 }
1126 1126
1127 /* 1127 /*
1128 Return from inflate(), updating the total counts and the check value. 1128 Return from inflate(), updating the total counts and the check value.
1129 If there was no progress during the inflate() call, return a buffer 1129 If there was no progress during the inflate() call, return a buffer
1130 error. Call updatewindow() to create and/or update the window state. 1130 error. Call updatewindow() to create and/or update the window state.
1131 Note: a memory error from inflate() is non-recoverable. 1131 Note: a memory error from inflate() is non-recoverable.
1132 */ 1132 */
1133 inf_leave: 1133 inf_leave:
1134 RESTORE(); 1134 RESTORE();
1135 if (state->wsize || (state->mode < CHECK && out != strm->avail_out)) 1135 if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
1136 if (updatewindow(strm, out)) { 1136 if (updatewindow(strm, out)) {
1137 state->mode = MEM; 1137 state->mode = MEM;
1138 return Z_MEM_ERROR; 1138 return Z_MEM_ERROR;
1139 } 1139 }
1140 in -= strm->avail_in; 1140 in -= strm->avail_in;
1141 out -= strm->avail_out; 1141 out -= strm->avail_out;
1142 strm->total_in += in; 1142 strm->total_in += in;
1143 strm->total_out += out; 1143 strm->total_out += out;
1144 state->total += out; 1144 state->total += out;
1145 if (state->wrap && out) 1145 if (state->wrap && out)
1146 strm->adler = state->check = 1146 strm->adler = state->check =
1147 UPDATE(state->check, strm->next_out - out, out); 1147 UPDATE(state->check, strm->next_out - out, out);
1148 strm->data_type = state->bits + (state->last ? 64 : 0) + 1148 strm->data_type = state->bits + (state->last ? 64 : 0) +
1149 (state->mode == TYPE ? 128 : 0); 1149 (state->mode == TYPE ? 128 : 0);
1150 if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) 1150 if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
1151 ret = Z_BUF_ERROR; 1151 ret = Z_BUF_ERROR;
1152 return ret; 1152 return ret;
1153} 1153}
1154 1154
1155int ZEXPORT inflateEnd(strm) 1155int ZEXPORT inflateEnd(strm)
1156z_streamp strm; 1156z_streamp strm;
1157{ 1157{
1158 struct inflate_state FAR *state; 1158 struct inflate_state FAR *state;
1159 if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) 1159 if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
1160 return Z_STREAM_ERROR; 1160 return Z_STREAM_ERROR;
1161 state = (struct inflate_state FAR *)strm->state; 1161 state = (struct inflate_state FAR *)strm->state;
1162 if (state->window != Z_NULL) ZFREE(strm, state->window); 1162 if (state->window != Z_NULL) ZFREE(strm, state->window);
1163 ZFREE(strm, strm->state); 1163 ZFREE(strm, strm->state);
1164 strm->state = Z_NULL; 1164 strm->state = Z_NULL;
1165 Tracev((stderr, "inflate: end\n")); 1165 Tracev((stderr, "inflate: end\n"));
1166 return Z_OK; 1166 return Z_OK;
1167} 1167}
1168 1168
1169int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) 1169int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength)
1170z_streamp strm; 1170z_streamp strm;
1171const Bytef *dictionary; 1171const Bytef *dictionary;
1172uInt dictLength; 1172uInt dictLength;
1173{ 1173{
1174 struct inflate_state FAR *state; 1174 struct inflate_state FAR *state;
1175 unsigned long id; 1175 unsigned long id;
1176 1176
1177 /* check state */ 1177 /* check state */
1178 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; 1178 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
1179 state = (struct inflate_state FAR *)strm->state; 1179 state = (struct inflate_state FAR *)strm->state;
1180 if (state->wrap != 0 && state->mode != DICT) 1180 if (state->wrap != 0 && state->mode != DICT)
1181 return Z_STREAM_ERROR; 1181 return Z_STREAM_ERROR;
1182 1182
1183 /* check for correct dictionary id */ 1183 /* check for correct dictionary id */
1184 if (state->mode == DICT) { 1184 if (state->mode == DICT) {
1185 id = adler32(0L, Z_NULL, 0); 1185 id = adler32(0L, Z_NULL, 0);
1186 id = adler32(id, dictionary, dictLength); 1186 id = adler32(id, dictionary, dictLength);
1187 if (id != state->check) 1187 if (id != state->check)
1188 return Z_DATA_ERROR; 1188 return Z_DATA_ERROR;
1189 } 1189 }
1190 1190
1191 /* copy dictionary to window */ 1191 /* copy dictionary to window */
1192 if (updatewindow(strm, strm->avail_out)) { 1192 if (updatewindow(strm, strm->avail_out)) {
1193 state->mode = MEM; 1193 state->mode = MEM;
1194 return Z_MEM_ERROR; 1194 return Z_MEM_ERROR;
1195 } 1195 }
1196 if (dictLength > state->wsize) { 1196 if (dictLength > state->wsize) {
1197 zmemcpy(state->window, dictionary + dictLength - state->wsize, 1197 zmemcpy(state->window, dictionary + dictLength - state->wsize,
1198 state->wsize); 1198 state->wsize);
1199 state->whave = state->wsize; 1199 state->whave = state->wsize;
1200 } 1200 }
1201 else { 1201 else {
1202 zmemcpy(state->window + state->wsize - dictLength, dictionary, 1202 zmemcpy(state->window + state->wsize - dictLength, dictionary,
1203 dictLength); 1203 dictLength);
1204 state->whave = dictLength; 1204 state->whave = dictLength;
1205 } 1205 }
1206 state->havedict = 1; 1206 state->havedict = 1;
1207 Tracev((stderr, "inflate: dictionary set\n")); 1207 Tracev((stderr, "inflate: dictionary set\n"));
1208 return Z_OK; 1208 return Z_OK;
1209} 1209}
1210 1210
1211int ZEXPORT inflateGetHeader(strm, head) 1211int ZEXPORT inflateGetHeader(strm, head)
1212z_streamp strm; 1212z_streamp strm;
1213gz_headerp head; 1213gz_headerp head;
1214{ 1214{
1215 struct inflate_state FAR *state; 1215 struct inflate_state FAR *state;
1216 1216
1217 /* check state */ 1217 /* check state */
1218 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; 1218 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
1219 state = (struct inflate_state FAR *)strm->state; 1219 state = (struct inflate_state FAR *)strm->state;
1220 if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; 1220 if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
1221 1221
1222 /* save header structure */ 1222 /* save header structure */
1223 state->head = head; 1223 state->head = head;
1224 head->done = 0; 1224 head->done = 0;
1225 return Z_OK; 1225 return Z_OK;
1226} 1226}
1227 1227
1228/* 1228/*
1229 Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found 1229 Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
1230 or when out of input. When called, *have is the number of pattern bytes 1230 or when out of input. When called, *have is the number of pattern bytes
1231 found in order so far, in 0..3. On return *have is updated to the new 1231 found in order so far, in 0..3. On return *have is updated to the new
1232 state. If on return *have equals four, then the pattern was found and the 1232 state. If on return *have equals four, then the pattern was found and the
1233 return value is how many bytes were read including the last byte of the 1233 return value is how many bytes were read including the last byte of the
1234 pattern. If *have is less than four, then the pattern has not been found 1234 pattern. If *have is less than four, then the pattern has not been found
1235 yet and the return value is len. In the latter case, syncsearch() can be 1235 yet and the return value is len. In the latter case, syncsearch() can be
1236 called again with more data and the *have state. *have is initialized to 1236 called again with more data and the *have state. *have is initialized to
1237 zero for the first call. 1237 zero for the first call.
1238 */ 1238 */
1239local unsigned syncsearch(have, buf, len) 1239local unsigned syncsearch(have, buf, len)
1240unsigned FAR *have; 1240unsigned FAR *have;
1241unsigned char FAR *buf; 1241unsigned char FAR *buf;
1242unsigned len; 1242unsigned len;
1243{ 1243{
1244 unsigned got; 1244 unsigned got;
1245 unsigned next; 1245 unsigned next;
1246 1246
1247 got = *have; 1247 got = *have;
1248 next = 0; 1248 next = 0;
1249 while (next < len && got < 4) { 1249 while (next < len && got < 4) {
1250 if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) 1250 if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
1251 got++; 1251 got++;
1252 else if (buf[next]) 1252 else if (buf[next])
1253 got = 0; 1253 got = 0;
1254 else 1254 else
1255 got = 4 - got; 1255 got = 4 - got;
1256 next++; 1256 next++;
1257 } 1257 }
1258 *have = got; 1258 *have = got;
1259 return next; 1259 return next;
1260} 1260}
1261 1261
1262int ZEXPORT inflateSync(strm) 1262int ZEXPORT inflateSync(strm)
1263z_streamp strm; 1263z_streamp strm;
1264{ 1264{
1265 unsigned len; /* number of bytes to look at or looked at */ 1265 unsigned len; /* number of bytes to look at or looked at */
1266 unsigned long in, out; /* temporary to save total_in and total_out */ 1266 unsigned long in, out; /* temporary to save total_in and total_out */
1267 unsigned char buf[4]; /* to restore bit buffer to byte string */ 1267 unsigned char buf[4]; /* to restore bit buffer to byte string */
1268 struct inflate_state FAR *state; 1268 struct inflate_state FAR *state;
1269 1269
1270 /* check parameters */ 1270 /* check parameters */
1271 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; 1271 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
1272 state = (struct inflate_state FAR *)strm->state; 1272 state = (struct inflate_state FAR *)strm->state;
1273 if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; 1273 if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
1274 1274
1275 /* if first time, start search in bit buffer */ 1275 /* if first time, start search in bit buffer */
1276 if (state->mode != SYNC) { 1276 if (state->mode != SYNC) {
1277 state->mode = SYNC; 1277 state->mode = SYNC;
1278 state->hold <<= state->bits & 7; 1278 state->hold <<= state->bits & 7;
1279 state->bits -= state->bits & 7; 1279 state->bits -= state->bits & 7;
1280 len = 0; 1280 len = 0;
1281 while (state->bits >= 8) { 1281 while (state->bits >= 8) {
1282 buf[len++] = (unsigned char)(state->hold); 1282 buf[len++] = (unsigned char)(state->hold);
1283 state->hold >>= 8; 1283 state->hold >>= 8;
1284 state->bits -= 8; 1284 state->bits -= 8;
1285 } 1285 }
1286 state->have = 0; 1286 state->have = 0;
1287 syncsearch(&(state->have), buf, len); 1287 syncsearch(&(state->have), buf, len);
1288 } 1288 }
1289 1289
1290 /* search available input */ 1290 /* search available input */
1291 len = syncsearch(&(state->have), strm->next_in, strm->avail_in); 1291 len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
1292 strm->avail_in -= len; 1292 strm->avail_in -= len;
1293 strm->next_in += len; 1293 strm->next_in += len;
1294 strm->total_in += len; 1294 strm->total_in += len;
1295 1295
1296 /* return no joy or set up to restart inflate() on a new block */ 1296 /* return no joy or set up to restart inflate() on a new block */
1297 if (state->have != 4) return Z_DATA_ERROR; 1297 if (state->have != 4) return Z_DATA_ERROR;
1298 in = strm->total_in; out = strm->total_out; 1298 in = strm->total_in; out = strm->total_out;
1299 inflateReset(strm); 1299 inflateReset(strm);
1300 strm->total_in = in; strm->total_out = out; 1300 strm->total_in = in; strm->total_out = out;
1301 state->mode = TYPE; 1301 state->mode = TYPE;
1302 return Z_OK; 1302 return Z_OK;
1303} 1303}
1304 1304
1305/* 1305/*
1306 Returns true if inflate is currently at the end of a block generated by 1306 Returns true if inflate is currently at the end of a block generated by
1307 Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP 1307 Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
1308 implementation to provide an additional safety check. PPP uses 1308 implementation to provide an additional safety check. PPP uses
1309 Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored 1309 Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
1310 block. When decompressing, PPP checks that at the end of input packet, 1310 block. When decompressing, PPP checks that at the end of input packet,
1311 inflate is waiting for these length bytes. 1311 inflate is waiting for these length bytes.
1312 */ 1312 */
1313int ZEXPORT inflateSyncPoint(strm) 1313int ZEXPORT inflateSyncPoint(strm)
1314z_streamp strm; 1314z_streamp strm;
1315{ 1315{
1316 struct inflate_state FAR *state; 1316 struct inflate_state FAR *state;
1317 1317
1318 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; 1318 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
1319 state = (struct inflate_state FAR *)strm->state; 1319 state = (struct inflate_state FAR *)strm->state;
1320 return state->mode == STORED && state->bits == 0; 1320 return state->mode == STORED && state->bits == 0;
1321} 1321}
1322 1322
1323int ZEXPORT inflateCopy(dest, source) 1323int ZEXPORT inflateCopy(dest, source)
1324z_streamp dest; 1324z_streamp dest;
1325z_streamp source; 1325z_streamp source;
1326{ 1326{
1327 struct inflate_state FAR *state; 1327 struct inflate_state FAR *state;
1328 struct inflate_state FAR *copy; 1328 struct inflate_state FAR *copy;
1329 unsigned char FAR *window; 1329 unsigned char FAR *window;
1330 unsigned wsize; 1330 unsigned wsize;
1331 1331
1332 /* check input */ 1332 /* check input */
1333 if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL || 1333 if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
1334 source->zalloc == (alloc_func)0 || source->zfree == (free_func)0) 1334 source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
1335 return Z_STREAM_ERROR; 1335 return Z_STREAM_ERROR;
1336 state = (struct inflate_state FAR *)source->state; 1336 state = (struct inflate_state FAR *)source->state;
1337 1337
1338 /* allocate space */ 1338 /* allocate space */
1339 copy = (struct inflate_state FAR *) 1339 copy = (struct inflate_state FAR *)
1340 ZALLOC(source, 1, sizeof(struct inflate_state)); 1340 ZALLOC(source, 1, sizeof(struct inflate_state));
1341 if (copy == Z_NULL) return Z_MEM_ERROR; 1341 if (copy == Z_NULL) return Z_MEM_ERROR;
1342 window = Z_NULL; 1342 window = Z_NULL;
1343 if (state->window != Z_NULL) { 1343 if (state->window != Z_NULL) {
1344 window = (unsigned char FAR *) 1344 window = (unsigned char FAR *)
1345 ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); 1345 ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
1346 if (window == Z_NULL) { 1346 if (window == Z_NULL) {
1347 ZFREE(source, copy); 1347 ZFREE(source, copy);
1348 return Z_MEM_ERROR; 1348 return Z_MEM_ERROR;
1349 } 1349 }
1350 } 1350 }
1351 1351
1352 /* copy state */ 1352 /* copy state */
1353 zmemcpy(dest, source, sizeof(z_stream)); 1353 zmemcpy(dest, source, sizeof(z_stream));
1354 zmemcpy(copy, state, sizeof(struct inflate_state)); 1354 zmemcpy(copy, state, sizeof(struct inflate_state));
1355 if (state->lencode >= state->codes && 1355 if (state->lencode >= state->codes &&
1356 state->lencode <= state->codes + ENOUGH - 1) { 1356 state->lencode <= state->codes + ENOUGH - 1) {
1357 copy->lencode = copy->codes + (state->lencode - state->codes); 1357 copy->lencode = copy->codes + (state->lencode - state->codes);
1358 copy->distcode = copy->codes + (state->distcode - state->codes); 1358 copy->distcode = copy->codes + (state->distcode - state->codes);
1359 } 1359 }
1360 copy->next = copy->codes + (state->next - state->codes); 1360 copy->next = copy->codes + (state->next - state->codes);
1361 if (window != Z_NULL) { 1361 if (window != Z_NULL) {
1362 wsize = 1U << state->wbits; 1362 wsize = 1U << state->wbits;
1363 zmemcpy(window, state->window, wsize); 1363 zmemcpy(window, state->window, wsize);
1364 } 1364 }
1365 copy->window = window; 1365 copy->window = window;
1366 dest->state = (struct internal_state FAR *)copy; 1366 dest->state = (struct internal_state FAR *)copy;
1367 return Z_OK; 1367 return Z_OK;
1368} 1368}
diff --git a/utils/zenutils/libraries/zlib123/zlib/inflate.h b/utils/zenutils/libraries/zlib123/zlib/inflate.h
index fbbc871432..07bd3e78a7 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/inflate.h
+++ b/utils/zenutils/libraries/zlib123/zlib/inflate.h
@@ -1,115 +1,115 @@
1/* inflate.h -- internal inflate state definition 1/* inflate.h -- internal inflate state definition
2 * Copyright (C) 1995-2004 Mark Adler 2 * Copyright (C) 1995-2004 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6/* WARNING: this file should *not* be used by applications. It is 6/* WARNING: this file should *not* be used by applications. It is
7 part of the implementation of the compression library and is 7 part of the implementation of the compression library and is
8 subject to change. Applications should only use zlib.h. 8 subject to change. Applications should only use zlib.h.
9 */ 9 */
10 10
11/* define NO_GZIP when compiling if you want to disable gzip header and 11/* define NO_GZIP when compiling if you want to disable gzip header and
12 trailer decoding by inflate(). NO_GZIP would be used to avoid linking in 12 trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
13 the crc code when it is not needed. For shared libraries, gzip decoding 13 the crc code when it is not needed. For shared libraries, gzip decoding
14 should be left enabled. */ 14 should be left enabled. */
15#ifndef NO_GZIP 15#ifndef NO_GZIP
16# define GUNZIP 16# define GUNZIP
17#endif 17#endif
18 18
19/* Possible inflate modes between inflate() calls */ 19/* Possible inflate modes between inflate() calls */
20typedef enum { 20typedef enum {
21 HEAD, /* i: waiting for magic header */ 21 HEAD, /* i: waiting for magic header */
22 FLAGS, /* i: waiting for method and flags (gzip) */ 22 FLAGS, /* i: waiting for method and flags (gzip) */
23 TIME, /* i: waiting for modification time (gzip) */ 23 TIME, /* i: waiting for modification time (gzip) */
24 OS, /* i: waiting for extra flags and operating system (gzip) */ 24 OS, /* i: waiting for extra flags and operating system (gzip) */
25 EXLEN, /* i: waiting for extra length (gzip) */ 25 EXLEN, /* i: waiting for extra length (gzip) */
26 EXTRA, /* i: waiting for extra bytes (gzip) */ 26 EXTRA, /* i: waiting for extra bytes (gzip) */
27 NAME, /* i: waiting for end of file name (gzip) */ 27 NAME, /* i: waiting for end of file name (gzip) */
28 COMMENT, /* i: waiting for end of comment (gzip) */ 28 COMMENT, /* i: waiting for end of comment (gzip) */
29 HCRC, /* i: waiting for header crc (gzip) */ 29 HCRC, /* i: waiting for header crc (gzip) */
30 DICTID, /* i: waiting for dictionary check value */ 30 DICTID, /* i: waiting for dictionary check value */
31 DICT, /* waiting for inflateSetDictionary() call */ 31 DICT, /* waiting for inflateSetDictionary() call */
32 TYPE, /* i: waiting for type bits, including last-flag bit */ 32 TYPE, /* i: waiting for type bits, including last-flag bit */
33 TYPEDO, /* i: same, but skip check to exit inflate on new block */ 33 TYPEDO, /* i: same, but skip check to exit inflate on new block */
34 STORED, /* i: waiting for stored size (length and complement) */ 34 STORED, /* i: waiting for stored size (length and complement) */
35 COPY, /* i/o: waiting for input or output to copy stored block */ 35 COPY, /* i/o: waiting for input or output to copy stored block */
36 TABLE, /* i: waiting for dynamic block table lengths */ 36 TABLE, /* i: waiting for dynamic block table lengths */
37 LENLENS, /* i: waiting for code length code lengths */ 37 LENLENS, /* i: waiting for code length code lengths */
38 CODELENS, /* i: waiting for length/lit and distance code lengths */ 38 CODELENS, /* i: waiting for length/lit and distance code lengths */
39 LEN, /* i: waiting for length/lit code */ 39 LEN, /* i: waiting for length/lit code */
40 LENEXT, /* i: waiting for length extra bits */ 40 LENEXT, /* i: waiting for length extra bits */
41 DIST, /* i: waiting for distance code */ 41 DIST, /* i: waiting for distance code */
42 DISTEXT, /* i: waiting for distance extra bits */ 42 DISTEXT, /* i: waiting for distance extra bits */
43 MATCH, /* o: waiting for output space to copy string */ 43 MATCH, /* o: waiting for output space to copy string */
44 LIT, /* o: waiting for output space to write literal */ 44 LIT, /* o: waiting for output space to write literal */
45 CHECK, /* i: waiting for 32-bit check value */ 45 CHECK, /* i: waiting for 32-bit check value */
46 LENGTH, /* i: waiting for 32-bit length (gzip) */ 46 LENGTH, /* i: waiting for 32-bit length (gzip) */
47 DONE, /* finished check, done -- remain here until reset */ 47 DONE, /* finished check, done -- remain here until reset */
48 BAD, /* got a data error -- remain here until reset */ 48 BAD, /* got a data error -- remain here until reset */
49 MEM, /* got an inflate() memory error -- remain here until reset */ 49 MEM, /* got an inflate() memory error -- remain here until reset */
50 SYNC /* looking for synchronization bytes to restart inflate() */ 50 SYNC /* looking for synchronization bytes to restart inflate() */
51} inflate_mode; 51} inflate_mode;
52 52
53/* 53/*
54 State transitions between above modes - 54 State transitions between above modes -
55 55
56 (most modes can go to the BAD or MEM mode -- not shown for clarity) 56 (most modes can go to the BAD or MEM mode -- not shown for clarity)
57 57
58 Process header: 58 Process header:
59 HEAD -> (gzip) or (zlib) 59 HEAD -> (gzip) or (zlib)
60 (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME 60 (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
61 NAME -> COMMENT -> HCRC -> TYPE 61 NAME -> COMMENT -> HCRC -> TYPE
62 (zlib) -> DICTID or TYPE 62 (zlib) -> DICTID or TYPE
63 DICTID -> DICT -> TYPE 63 DICTID -> DICT -> TYPE
64 Read deflate blocks: 64 Read deflate blocks:
65 TYPE -> STORED or TABLE or LEN or CHECK 65 TYPE -> STORED or TABLE or LEN or CHECK
66 STORED -> COPY -> TYPE 66 STORED -> COPY -> TYPE
67 TABLE -> LENLENS -> CODELENS -> LEN 67 TABLE -> LENLENS -> CODELENS -> LEN
68 Read deflate codes: 68 Read deflate codes:
69 LEN -> LENEXT or LIT or TYPE 69 LEN -> LENEXT or LIT or TYPE
70 LENEXT -> DIST -> DISTEXT -> MATCH -> LEN 70 LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
71 LIT -> LEN 71 LIT -> LEN
72 Process trailer: 72 Process trailer:
73 CHECK -> LENGTH -> DONE 73 CHECK -> LENGTH -> DONE
74 */ 74 */
75 75
76/* state maintained between inflate() calls. Approximately 7K bytes. */ 76/* state maintained between inflate() calls. Approximately 7K bytes. */
77struct inflate_state { 77struct inflate_state {
78 inflate_mode mode; /* current inflate mode */ 78 inflate_mode mode; /* current inflate mode */
79 int last; /* true if processing last block */ 79 int last; /* true if processing last block */
80 int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ 80 int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
81 int havedict; /* true if dictionary provided */ 81 int havedict; /* true if dictionary provided */
82 int flags; /* gzip header method and flags (0 if zlib) */ 82 int flags; /* gzip header method and flags (0 if zlib) */
83 unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ 83 unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
84 unsigned long check; /* protected copy of check value */ 84 unsigned long check; /* protected copy of check value */
85 unsigned long total; /* protected copy of output count */ 85 unsigned long total; /* protected copy of output count */
86 gz_headerp head; /* where to save gzip header information */ 86 gz_headerp head; /* where to save gzip header information */
87 /* sliding window */ 87 /* sliding window */
88 unsigned wbits; /* log base 2 of requested window size */ 88 unsigned wbits; /* log base 2 of requested window size */
89 unsigned wsize; /* window size or zero if not using window */ 89 unsigned wsize; /* window size or zero if not using window */
90 unsigned whave; /* valid bytes in the window */ 90 unsigned whave; /* valid bytes in the window */
91 unsigned write; /* window write index */ 91 unsigned write; /* window write index */
92 unsigned char FAR *window; /* allocated sliding window, if needed */ 92 unsigned char FAR *window; /* allocated sliding window, if needed */
93 /* bit accumulator */ 93 /* bit accumulator */
94 unsigned long hold; /* input bit accumulator */ 94 unsigned long hold; /* input bit accumulator */
95 unsigned bits; /* number of bits in "in" */ 95 unsigned bits; /* number of bits in "in" */
96 /* for string and stored block copying */ 96 /* for string and stored block copying */
97 unsigned length; /* literal or length of data to copy */ 97 unsigned length; /* literal or length of data to copy */
98 unsigned offset; /* distance back to copy string from */ 98 unsigned offset; /* distance back to copy string from */
99 /* for table and code decoding */ 99 /* for table and code decoding */
100 unsigned extra; /* extra bits needed */ 100 unsigned extra; /* extra bits needed */
101 /* fixed and dynamic code tables */ 101 /* fixed and dynamic code tables */
102 code const FAR *lencode; /* starting table for length/literal codes */ 102 code const FAR *lencode; /* starting table for length/literal codes */
103 code const FAR *distcode; /* starting table for distance codes */ 103 code const FAR *distcode; /* starting table for distance codes */
104 unsigned lenbits; /* index bits for lencode */ 104 unsigned lenbits; /* index bits for lencode */
105 unsigned distbits; /* index bits for distcode */ 105 unsigned distbits; /* index bits for distcode */
106 /* dynamic table building */ 106 /* dynamic table building */
107 unsigned ncode; /* number of code length code lengths */ 107 unsigned ncode; /* number of code length code lengths */
108 unsigned nlen; /* number of length code lengths */ 108 unsigned nlen; /* number of length code lengths */
109 unsigned ndist; /* number of distance code lengths */ 109 unsigned ndist; /* number of distance code lengths */
110 unsigned have; /* number of code lengths in lens[] */ 110 unsigned have; /* number of code lengths in lens[] */
111 code FAR *next; /* next available space in codes[] */ 111 code FAR *next; /* next available space in codes[] */
112 unsigned short lens[320]; /* temporary storage for code lengths */ 112 unsigned short lens[320]; /* temporary storage for code lengths */
113 unsigned short work[288]; /* work area for code table building */ 113 unsigned short work[288]; /* work area for code table building */
114 code codes[ENOUGH]; /* space for code tables */ 114 code codes[ENOUGH]; /* space for code tables */
115}; 115};
diff --git a/utils/zenutils/libraries/zlib123/zlib/inftrees.c b/utils/zenutils/libraries/zlib123/zlib/inftrees.c
index 38ded81c36..8a9c13ff03 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/inftrees.c
+++ b/utils/zenutils/libraries/zlib123/zlib/inftrees.c
@@ -1,329 +1,329 @@
1/* inftrees.c -- generate Huffman trees for efficient decoding 1/* inftrees.c -- generate Huffman trees for efficient decoding
2 * Copyright (C) 1995-2005 Mark Adler 2 * Copyright (C) 1995-2005 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6#include "zutil.h" 6#include "zutil.h"
7#include "inftrees.h" 7#include "inftrees.h"
8 8
9#define MAXBITS 15 9#define MAXBITS 15
10 10
11const char inflate_copyright[] = 11const char inflate_copyright[] =
12 " inflate 1.2.3 Copyright 1995-2005 Mark Adler "; 12 " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
13/* 13/*
14 If you use the zlib library in a product, an acknowledgment is welcome 14 If you use the zlib library in a product, an acknowledgment is welcome
15 in the documentation of your product. If for some reason you cannot 15 in the documentation of your product. If for some reason you cannot
16 include such an acknowledgment, I would appreciate that you keep this 16 include such an acknowledgment, I would appreciate that you keep this
17 copyright string in the executable of your product. 17 copyright string in the executable of your product.
18 */ 18 */
19 19
20/* 20/*
21 Build a set of tables to decode the provided canonical Huffman code. 21 Build a set of tables to decode the provided canonical Huffman code.
22 The code lengths are lens[0..codes-1]. The result starts at *table, 22 The code lengths are lens[0..codes-1]. The result starts at *table,
23 whose indices are 0..2^bits-1. work is a writable array of at least 23 whose indices are 0..2^bits-1. work is a writable array of at least
24 lens shorts, which is used as a work area. type is the type of code 24 lens shorts, which is used as a work area. type is the type of code
25 to be generated, CODES, LENS, or DISTS. On return, zero is success, 25 to be generated, CODES, LENS, or DISTS. On return, zero is success,
26 -1 is an invalid code, and +1 means that ENOUGH isn't enough. table 26 -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
27 on return points to the next available entry's address. bits is the 27 on return points to the next available entry's address. bits is the
28 requested root table index bits, and on return it is the actual root 28 requested root table index bits, and on return it is the actual root
29 table index bits. It will differ if the request is greater than the 29 table index bits. It will differ if the request is greater than the
30 longest code or if it is less than the shortest code. 30 longest code or if it is less than the shortest code.
31 */ 31 */
32int inflate_table(type, lens, codes, table, bits, work) 32int inflate_table(type, lens, codes, table, bits, work)
33codetype type; 33codetype type;
34unsigned short FAR *lens; 34unsigned short FAR *lens;
35unsigned codes; 35unsigned codes;
36code FAR * FAR *table; 36code FAR * FAR *table;
37unsigned FAR *bits; 37unsigned FAR *bits;
38unsigned short FAR *work; 38unsigned short FAR *work;
39{ 39{
40 unsigned len; /* a code's length in bits */ 40 unsigned len; /* a code's length in bits */
41 unsigned sym; /* index of code symbols */ 41 unsigned sym; /* index of code symbols */
42 unsigned min, max; /* minimum and maximum code lengths */ 42 unsigned min, max; /* minimum and maximum code lengths */
43 unsigned root; /* number of index bits for root table */ 43 unsigned root; /* number of index bits for root table */
44 unsigned curr; /* number of index bits for current table */ 44 unsigned curr; /* number of index bits for current table */
45 unsigned drop; /* code bits to drop for sub-table */ 45 unsigned drop; /* code bits to drop for sub-table */
46 int left; /* number of prefix codes available */ 46 int left; /* number of prefix codes available */
47 unsigned used; /* code entries in table used */ 47 unsigned used; /* code entries in table used */
48 unsigned huff; /* Huffman code */ 48 unsigned huff; /* Huffman code */
49 unsigned incr; /* for incrementing code, index */ 49 unsigned incr; /* for incrementing code, index */
50 unsigned fill; /* index for replicating entries */ 50 unsigned fill; /* index for replicating entries */
51 unsigned low; /* low bits for current root entry */ 51 unsigned low; /* low bits for current root entry */
52 unsigned mask; /* mask for low root bits */ 52 unsigned mask; /* mask for low root bits */
53 code this; /* table entry for duplication */ 53 code this; /* table entry for duplication */
54 code FAR *next; /* next available space in table */ 54 code FAR *next; /* next available space in table */
55 const unsigned short FAR *base; /* base value table to use */ 55 const unsigned short FAR *base; /* base value table to use */
56 const unsigned short FAR *extra; /* extra bits table to use */ 56 const unsigned short FAR *extra; /* extra bits table to use */
57 int end; /* use base and extra for symbol > end */ 57 int end; /* use base and extra for symbol > end */
58 unsigned short count[MAXBITS+1]; /* number of codes of each length */ 58 unsigned short count[MAXBITS+1]; /* number of codes of each length */
59 unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ 59 unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
60 static const unsigned short lbase[31] = { /* Length codes 257..285 base */ 60 static const unsigned short lbase[31] = { /* Length codes 257..285 base */
61 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 61 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
62 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; 62 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
63 static const unsigned short lext[31] = { /* Length codes 257..285 extra */ 63 static const unsigned short lext[31] = { /* Length codes 257..285 extra */
64 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 64 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
65 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196}; 65 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
66 static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ 66 static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
67 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 67 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
68 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 68 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
69 8193, 12289, 16385, 24577, 0, 0}; 69 8193, 12289, 16385, 24577, 0, 0};
70 static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ 70 static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
71 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 71 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
72 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 72 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
73 28, 28, 29, 29, 64, 64}; 73 28, 28, 29, 29, 64, 64};
74 74
75 /* 75 /*
76 Process a set of code lengths to create a canonical Huffman code. The 76 Process a set of code lengths to create a canonical Huffman code. The
77 code lengths are lens[0..codes-1]. Each length corresponds to the 77 code lengths are lens[0..codes-1]. Each length corresponds to the
78 symbols 0..codes-1. The Huffman code is generated by first sorting the 78 symbols 0..codes-1. The Huffman code is generated by first sorting the
79 symbols by length from short to long, and retaining the symbol order 79 symbols by length from short to long, and retaining the symbol order
80 for codes with equal lengths. Then the code starts with all zero bits 80 for codes with equal lengths. Then the code starts with all zero bits
81 for the first code of the shortest length, and the codes are integer 81 for the first code of the shortest length, and the codes are integer
82 increments for the same length, and zeros are appended as the length 82 increments for the same length, and zeros are appended as the length
83 increases. For the deflate format, these bits are stored backwards 83 increases. For the deflate format, these bits are stored backwards
84 from their more natural integer increment ordering, and so when the 84 from their more natural integer increment ordering, and so when the
85 decoding tables are built in the large loop below, the integer codes 85 decoding tables are built in the large loop below, the integer codes
86 are incremented backwards. 86 are incremented backwards.
87 87
88 This routine assumes, but does not check, that all of the entries in 88 This routine assumes, but does not check, that all of the entries in
89 lens[] are in the range 0..MAXBITS. The caller must assure this. 89 lens[] are in the range 0..MAXBITS. The caller must assure this.
90 1..MAXBITS is interpreted as that code length. zero means that that 90 1..MAXBITS is interpreted as that code length. zero means that that
91 symbol does not occur in this code. 91 symbol does not occur in this code.
92 92
93 The codes are sorted by computing a count of codes for each length, 93 The codes are sorted by computing a count of codes for each length,
94 creating from that a table of starting indices for each length in the 94 creating from that a table of starting indices for each length in the
95 sorted table, and then entering the symbols in order in the sorted 95 sorted table, and then entering the symbols in order in the sorted
96 table. The sorted table is work[], with that space being provided by 96 table. The sorted table is work[], with that space being provided by
97 the caller. 97 the caller.
98 98
99 The length counts are used for other purposes as well, i.e. finding 99 The length counts are used for other purposes as well, i.e. finding
100 the minimum and maximum length codes, determining if there are any 100 the minimum and maximum length codes, determining if there are any
101 codes at all, checking for a valid set of lengths, and looking ahead 101 codes at all, checking for a valid set of lengths, and looking ahead
102 at length counts to determine sub-table sizes when building the 102 at length counts to determine sub-table sizes when building the
103 decoding tables. 103 decoding tables.
104 */ 104 */
105 105
106 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ 106 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
107 for (len = 0; len <= MAXBITS; len++) 107 for (len = 0; len <= MAXBITS; len++)
108 count[len] = 0; 108 count[len] = 0;
109 for (sym = 0; sym < codes; sym++) 109 for (sym = 0; sym < codes; sym++)
110 count[lens[sym]]++; 110 count[lens[sym]]++;
111 111
112 /* bound code lengths, force root to be within code lengths */ 112 /* bound code lengths, force root to be within code lengths */
113 root = *bits; 113 root = *bits;
114 for (max = MAXBITS; max >= 1; max--) 114 for (max = MAXBITS; max >= 1; max--)
115 if (count[max] != 0) break; 115 if (count[max] != 0) break;
116 if (root > max) root = max; 116 if (root > max) root = max;
117 if (max == 0) { /* no symbols to code at all */ 117 if (max == 0) { /* no symbols to code at all */
118 this.op = (unsigned char)64; /* invalid code marker */ 118 this.op = (unsigned char)64; /* invalid code marker */
119 this.bits = (unsigned char)1; 119 this.bits = (unsigned char)1;
120 this.val = (unsigned short)0; 120 this.val = (unsigned short)0;
121 *(*table)++ = this; /* make a table to force an error */ 121 *(*table)++ = this; /* make a table to force an error */
122 *(*table)++ = this; 122 *(*table)++ = this;
123 *bits = 1; 123 *bits = 1;
124 return 0; /* no symbols, but wait for decoding to report error */ 124 return 0; /* no symbols, but wait for decoding to report error */
125 } 125 }
126 for (min = 1; min <= MAXBITS; min++) 126 for (min = 1; min <= MAXBITS; min++)
127 if (count[min] != 0) break; 127 if (count[min] != 0) break;
128 if (root < min) root = min; 128 if (root < min) root = min;
129 129
130 /* check for an over-subscribed or incomplete set of lengths */ 130 /* check for an over-subscribed or incomplete set of lengths */
131 left = 1; 131 left = 1;
132 for (len = 1; len <= MAXBITS; len++) { 132 for (len = 1; len <= MAXBITS; len++) {
133 left <<= 1; 133 left <<= 1;
134 left -= count[len]; 134 left -= count[len];
135 if (left < 0) return -1; /* over-subscribed */ 135 if (left < 0) return -1; /* over-subscribed */
136 } 136 }
137 if (left > 0 && (type == CODES || max != 1)) 137 if (left > 0 && (type == CODES || max != 1))
138 return -1; /* incomplete set */ 138 return -1; /* incomplete set */
139 139
140 /* generate offsets into symbol table for each length for sorting */ 140 /* generate offsets into symbol table for each length for sorting */
141 offs[1] = 0; 141 offs[1] = 0;
142 for (len = 1; len < MAXBITS; len++) 142 for (len = 1; len < MAXBITS; len++)
143 offs[len + 1] = offs[len] + count[len]; 143 offs[len + 1] = offs[len] + count[len];
144 144
145 /* sort symbols by length, by symbol order within each length */ 145 /* sort symbols by length, by symbol order within each length */
146 for (sym = 0; sym < codes; sym++) 146 for (sym = 0; sym < codes; sym++)
147 if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; 147 if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
148 148
149 /* 149 /*
150 Create and fill in decoding tables. In this loop, the table being 150 Create and fill in decoding tables. In this loop, the table being
151 filled is at next and has curr index bits. The code being used is huff 151 filled is at next and has curr index bits. The code being used is huff
152 with length len. That code is converted to an index by dropping drop 152 with length len. That code is converted to an index by dropping drop
153 bits off of the bottom. For codes where len is less than drop + curr, 153 bits off of the bottom. For codes where len is less than drop + curr,
154 those top drop + curr - len bits are incremented through all values to 154 those top drop + curr - len bits are incremented through all values to
155 fill the table with replicated entries. 155 fill the table with replicated entries.
156 156
157 root is the number of index bits for the root table. When len exceeds 157 root is the number of index bits for the root table. When len exceeds
158 root, sub-tables are created pointed to by the root entry with an index 158 root, sub-tables are created pointed to by the root entry with an index
159 of the low root bits of huff. This is saved in low to check for when a 159 of the low root bits of huff. This is saved in low to check for when a
160 new sub-table should be started. drop is zero when the root table is 160 new sub-table should be started. drop is zero when the root table is
161 being filled, and drop is root when sub-tables are being filled. 161 being filled, and drop is root when sub-tables are being filled.
162 162
163 When a new sub-table is needed, it is necessary to look ahead in the 163 When a new sub-table is needed, it is necessary to look ahead in the
164 code lengths to determine what size sub-table is needed. The length 164 code lengths to determine what size sub-table is needed. The length
165 counts are used for this, and so count[] is decremented as codes are 165 counts are used for this, and so count[] is decremented as codes are
166 entered in the tables. 166 entered in the tables.
167 167
168 used keeps track of how many table entries have been allocated from the 168 used keeps track of how many table entries have been allocated from the
169 provided *table space. It is checked when a LENS table is being made 169 provided *table space. It is checked when a LENS table is being made
170 against the space in *table, ENOUGH, minus the maximum space needed by 170 against the space in *table, ENOUGH, minus the maximum space needed by
171 the worst case distance code, MAXD. This should never happen, but the 171 the worst case distance code, MAXD. This should never happen, but the
172 sufficiency of ENOUGH has not been proven exhaustively, hence the check. 172 sufficiency of ENOUGH has not been proven exhaustively, hence the check.
173 This assumes that when type == LENS, bits == 9. 173 This assumes that when type == LENS, bits == 9.
174 174
175 sym increments through all symbols, and the loop terminates when 175 sym increments through all symbols, and the loop terminates when
176 all codes of length max, i.e. all codes, have been processed. This 176 all codes of length max, i.e. all codes, have been processed. This
177 routine permits incomplete codes, so another loop after this one fills 177 routine permits incomplete codes, so another loop after this one fills
178 in the rest of the decoding tables with invalid code markers. 178 in the rest of the decoding tables with invalid code markers.
179 */ 179 */
180 180
181 /* set up for code type */ 181 /* set up for code type */
182 switch (type) { 182 switch (type) {
183 case CODES: 183 case CODES:
184 base = extra = work; /* dummy value--not used */ 184 base = extra = work; /* dummy value--not used */
185 end = 19; 185 end = 19;
186 break; 186 break;
187 case LENS: 187 case LENS:
188 base = lbase; 188 base = lbase;
189 base -= 257; 189 base -= 257;
190 extra = lext; 190 extra = lext;
191 extra -= 257; 191 extra -= 257;
192 end = 256; 192 end = 256;
193 break; 193 break;
194 default: /* DISTS */ 194 default: /* DISTS */
195 base = dbase; 195 base = dbase;
196 extra = dext; 196 extra = dext;
197 end = -1; 197 end = -1;
198 } 198 }
199 199
200 /* initialize state for loop */ 200 /* initialize state for loop */
201 huff = 0; /* starting code */ 201 huff = 0; /* starting code */
202 sym = 0; /* starting code symbol */ 202 sym = 0; /* starting code symbol */
203 len = min; /* starting code length */ 203 len = min; /* starting code length */
204 next = *table; /* current table to fill in */ 204 next = *table; /* current table to fill in */
205 curr = root; /* current table index bits */ 205 curr = root; /* current table index bits */
206 drop = 0; /* current bits to drop from code for index */ 206 drop = 0; /* current bits to drop from code for index */
207 low = (unsigned)(-1); /* trigger new sub-table when len > root */ 207 low = (unsigned)(-1); /* trigger new sub-table when len > root */
208 used = 1U << root; /* use root table entries */ 208 used = 1U << root; /* use root table entries */
209 mask = used - 1; /* mask for comparing low */ 209 mask = used - 1; /* mask for comparing low */
210 210
211 /* check available table space */ 211 /* check available table space */
212 if (type == LENS && used >= ENOUGH - MAXD) 212 if (type == LENS && used >= ENOUGH - MAXD)
213 return 1; 213 return 1;
214 214
215 /* process all codes and make table entries */ 215 /* process all codes and make table entries */
216 for (;;) { 216 for (;;) {
217 /* create table entry */ 217 /* create table entry */
218 this.bits = (unsigned char)(len - drop); 218 this.bits = (unsigned char)(len - drop);
219 if ((int)(work[sym]) < end) { 219 if ((int)(work[sym]) < end) {
220 this.op = (unsigned char)0; 220 this.op = (unsigned char)0;
221 this.val = work[sym]; 221 this.val = work[sym];
222 } 222 }
223 else if ((int)(work[sym]) > end) { 223 else if ((int)(work[sym]) > end) {
224 this.op = (unsigned char)(extra[work[sym]]); 224 this.op = (unsigned char)(extra[work[sym]]);
225 this.val = base[work[sym]]; 225 this.val = base[work[sym]];
226 } 226 }
227 else { 227 else {
228 this.op = (unsigned char)(32 + 64); /* end of block */ 228 this.op = (unsigned char)(32 + 64); /* end of block */
229 this.val = 0; 229 this.val = 0;
230 } 230 }
231 231
232 /* replicate for those indices with low len bits equal to huff */ 232 /* replicate for those indices with low len bits equal to huff */
233 incr = 1U << (len - drop); 233 incr = 1U << (len - drop);
234 fill = 1U << curr; 234 fill = 1U << curr;
235 min = fill; /* save offset to next table */ 235 min = fill; /* save offset to next table */
236 do { 236 do {
237 fill -= incr; 237 fill -= incr;
238 next[(huff >> drop) + fill] = this; 238 next[(huff >> drop) + fill] = this;
239 } while (fill != 0); 239 } while (fill != 0);
240 240
241 /* backwards increment the len-bit code huff */ 241 /* backwards increment the len-bit code huff */
242 incr = 1U << (len - 1); 242 incr = 1U << (len - 1);
243 while (huff & incr) 243 while (huff & incr)
244 incr >>= 1; 244 incr >>= 1;
245 if (incr != 0) { 245 if (incr != 0) {
246 huff &= incr - 1; 246 huff &= incr - 1;
247 huff += incr; 247 huff += incr;
248 } 248 }
249 else 249 else
250 huff = 0; 250 huff = 0;
251 251
252 /* go to next symbol, update count, len */ 252 /* go to next symbol, update count, len */
253 sym++; 253 sym++;
254 if (--(count[len]) == 0) { 254 if (--(count[len]) == 0) {
255 if (len == max) break; 255 if (len == max) break;
256 len = lens[work[sym]]; 256 len = lens[work[sym]];
257 } 257 }
258 258
259 /* create new sub-table if needed */ 259 /* create new sub-table if needed */
260 if (len > root && (huff & mask) != low) { 260 if (len > root && (huff & mask) != low) {
261 /* if first time, transition to sub-tables */ 261 /* if first time, transition to sub-tables */
262 if (drop == 0) 262 if (drop == 0)
263 drop = root; 263 drop = root;
264 264
265 /* increment past last table */ 265 /* increment past last table */
266 next += min; /* here min is 1 << curr */ 266 next += min; /* here min is 1 << curr */
267 267
268 /* determine length of next table */ 268 /* determine length of next table */
269 curr = len - drop; 269 curr = len - drop;
270 left = (int)(1 << curr); 270 left = (int)(1 << curr);
271 while (curr + drop < max) { 271 while (curr + drop < max) {
272 left -= count[curr + drop]; 272 left -= count[curr + drop];
273 if (left <= 0) break; 273 if (left <= 0) break;
274 curr++; 274 curr++;
275 left <<= 1; 275 left <<= 1;
276 } 276 }
277 277
278 /* check for enough space */ 278 /* check for enough space */
279 used += 1U << curr; 279 used += 1U << curr;
280 if (type == LENS && used >= ENOUGH - MAXD) 280 if (type == LENS && used >= ENOUGH - MAXD)
281 return 1; 281 return 1;
282 282
283 /* point entry in root table to sub-table */ 283 /* point entry in root table to sub-table */
284 low = huff & mask; 284 low = huff & mask;
285 (*table)[low].op = (unsigned char)curr; 285 (*table)[low].op = (unsigned char)curr;
286 (*table)[low].bits = (unsigned char)root; 286 (*table)[low].bits = (unsigned char)root;
287 (*table)[low].val = (unsigned short)(next - *table); 287 (*table)[low].val = (unsigned short)(next - *table);
288 } 288 }
289 } 289 }
290 290
291 /* 291 /*
292 Fill in rest of table for incomplete codes. This loop is similar to the 292 Fill in rest of table for incomplete codes. This loop is similar to the
293 loop above in incrementing huff for table indices. It is assumed that 293 loop above in incrementing huff for table indices. It is assumed that
294 len is equal to curr + drop, so there is no loop needed to increment 294 len is equal to curr + drop, so there is no loop needed to increment
295 through high index bits. When the current sub-table is filled, the loop 295 through high index bits. When the current sub-table is filled, the loop
296 drops back to the root table to fill in any remaining entries there. 296 drops back to the root table to fill in any remaining entries there.
297 */ 297 */
298 this.op = (unsigned char)64; /* invalid code marker */ 298 this.op = (unsigned char)64; /* invalid code marker */
299 this.bits = (unsigned char)(len - drop); 299 this.bits = (unsigned char)(len - drop);
300 this.val = (unsigned short)0; 300 this.val = (unsigned short)0;
301 while (huff != 0) { 301 while (huff != 0) {
302 /* when done with sub-table, drop back to root table */ 302 /* when done with sub-table, drop back to root table */
303 if (drop != 0 && (huff & mask) != low) { 303 if (drop != 0 && (huff & mask) != low) {
304 drop = 0; 304 drop = 0;
305 len = root; 305 len = root;
306 next = *table; 306 next = *table;
307 this.bits = (unsigned char)len; 307 this.bits = (unsigned char)len;
308 } 308 }
309 309
310 /* put invalid code marker in table */ 310 /* put invalid code marker in table */
311 next[huff >> drop] = this; 311 next[huff >> drop] = this;
312 312
313 /* backwards increment the len-bit code huff */ 313 /* backwards increment the len-bit code huff */
314 incr = 1U << (len - 1); 314 incr = 1U << (len - 1);
315 while (huff & incr) 315 while (huff & incr)
316 incr >>= 1; 316 incr >>= 1;
317 if (incr != 0) { 317 if (incr != 0) {
318 huff &= incr - 1; 318 huff &= incr - 1;
319 huff += incr; 319 huff += incr;
320 } 320 }
321 else 321 else
322 huff = 0; 322 huff = 0;
323 } 323 }
324 324
325 /* set return parameters */ 325 /* set return parameters */
326 *table += used; 326 *table += used;
327 *bits = root; 327 *bits = root;
328 return 0; 328 return 0;
329} 329}
diff --git a/utils/zenutils/libraries/zlib123/zlib/inftrees.h b/utils/zenutils/libraries/zlib123/zlib/inftrees.h
index dc0fd567ea..b1104c87e7 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/inftrees.h
+++ b/utils/zenutils/libraries/zlib123/zlib/inftrees.h
@@ -1,55 +1,55 @@
1/* inftrees.h -- header to use inftrees.c 1/* inftrees.h -- header to use inftrees.c
2 * Copyright (C) 1995-2005 Mark Adler 2 * Copyright (C) 1995-2005 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6/* WARNING: this file should *not* be used by applications. It is 6/* WARNING: this file should *not* be used by applications. It is
7 part of the implementation of the compression library and is 7 part of the implementation of the compression library and is
8 subject to change. Applications should only use zlib.h. 8 subject to change. Applications should only use zlib.h.
9 */ 9 */
10 10
11/* Structure for decoding tables. Each entry provides either the 11/* Structure for decoding tables. Each entry provides either the
12 information needed to do the operation requested by the code that 12 information needed to do the operation requested by the code that
13 indexed that table entry, or it provides a pointer to another 13 indexed that table entry, or it provides a pointer to another
14 table that indexes more bits of the code. op indicates whether 14 table that indexes more bits of the code. op indicates whether
15 the entry is a pointer to another table, a literal, a length or 15 the entry is a pointer to another table, a literal, a length or
16 distance, an end-of-block, or an invalid code. For a table 16 distance, an end-of-block, or an invalid code. For a table
17 pointer, the low four bits of op is the number of index bits of 17 pointer, the low four bits of op is the number of index bits of
18 that table. For a length or distance, the low four bits of op 18 that table. For a length or distance, the low four bits of op
19 is the number of extra bits to get after the code. bits is 19 is the number of extra bits to get after the code. bits is
20 the number of bits in this code or part of the code to drop off 20 the number of bits in this code or part of the code to drop off
21 of the bit buffer. val is the actual byte to output in the case 21 of the bit buffer. val is the actual byte to output in the case
22 of a literal, the base length or distance, or the offset from 22 of a literal, the base length or distance, or the offset from
23 the current table to the next table. Each entry is four bytes. */ 23 the current table to the next table. Each entry is four bytes. */
24typedef struct { 24typedef struct {
25 unsigned char op; /* operation, extra bits, table bits */ 25 unsigned char op; /* operation, extra bits, table bits */
26 unsigned char bits; /* bits in this part of the code */ 26 unsigned char bits; /* bits in this part of the code */
27 unsigned short val; /* offset in table or code value */ 27 unsigned short val; /* offset in table or code value */
28} code; 28} code;
29 29
30/* op values as set by inflate_table(): 30/* op values as set by inflate_table():
31 00000000 - literal 31 00000000 - literal
32 0000tttt - table link, tttt != 0 is the number of table index bits 32 0000tttt - table link, tttt != 0 is the number of table index bits
33 0001eeee - length or distance, eeee is the number of extra bits 33 0001eeee - length or distance, eeee is the number of extra bits
34 01100000 - end of block 34 01100000 - end of block
35 01000000 - invalid code 35 01000000 - invalid code
36 */ 36 */
37 37
38/* Maximum size of dynamic tree. The maximum found in a long but non- 38/* Maximum size of dynamic tree. The maximum found in a long but non-
39 exhaustive search was 1444 code structures (852 for length/literals 39 exhaustive search was 1444 code structures (852 for length/literals
40 and 592 for distances, the latter actually the result of an 40 and 592 for distances, the latter actually the result of an
41 exhaustive search). The true maximum is not known, but the value 41 exhaustive search). The true maximum is not known, but the value
42 below is more than safe. */ 42 below is more than safe. */
43#define ENOUGH 2048 43#define ENOUGH 2048
44#define MAXD 592 44#define MAXD 592
45 45
46/* Type of code to build for inftable() */ 46/* Type of code to build for inftable() */
47typedef enum { 47typedef enum {
48 CODES, 48 CODES,
49 LENS, 49 LENS,
50 DISTS 50 DISTS
51} codetype; 51} codetype;
52 52
53extern int inflate_table OF((codetype type, unsigned short FAR *lens, 53extern int inflate_table OF((codetype type, unsigned short FAR *lens,
54 unsigned codes, code FAR * FAR *table, 54 unsigned codes, code FAR * FAR *table,
55 unsigned FAR *bits, unsigned short FAR *work)); 55 unsigned FAR *bits, unsigned short FAR *work));
diff --git a/utils/zenutils/libraries/zlib123/zlib/make_vms.com b/utils/zenutils/libraries/zlib123/zlib/make_vms.com
index 93174bbc8a..c2a1fb54b2 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/make_vms.com
+++ b/utils/zenutils/libraries/zlib123/zlib/make_vms.com
@@ -1,461 +1,461 @@
1$! make libz under VMS written by 1$! make libz under VMS written by
2$! Martin P.J. Zinser 2$! Martin P.J. Zinser
3$! <zinser@zinser.no-ip.info or zinser@sysdev.deutsche-boerse.com> 3$! <zinser@zinser.no-ip.info or zinser@sysdev.deutsche-boerse.com>
4$! 4$!
5$ on error then goto err_exit 5$ on error then goto err_exit
6$! 6$!
7$! 7$!
8$! Just some general constants... 8$! Just some general constants...
9$! 9$!
10$ true = 1 10$ true = 1
11$ false = 0 11$ false = 0
12$ tmpnam = "temp_" + f$getjpi("","pid") 12$ tmpnam = "temp_" + f$getjpi("","pid")
13$ SAY = "WRITE SYS$OUTPUT" 13$ SAY = "WRITE SYS$OUTPUT"
14$! 14$!
15$! Setup variables holding "config" information 15$! Setup variables holding "config" information
16$! 16$!
17$ Make = "" 17$ Make = ""
18$ name = "Zlib" 18$ name = "Zlib"
19$ version = "?.?.?" 19$ version = "?.?.?"
20$ v_string = "ZLIB_VERSION" 20$ v_string = "ZLIB_VERSION"
21$ v_file = "zlib.h" 21$ v_file = "zlib.h"
22$ ccopt = "" 22$ ccopt = ""
23$ lopts = "" 23$ lopts = ""
24$ linkonly = false 24$ linkonly = false
25$ optfile = name + ".opt" 25$ optfile = name + ".opt"
26$ its_decc = false 26$ its_decc = false
27$ its_vaxc = false 27$ its_vaxc = false
28$ its_gnuc = false 28$ its_gnuc = false
29$ axp = f$getsyi("HW_MODEL").ge.1024 29$ axp = f$getsyi("HW_MODEL").ge.1024
30$ s_case = false 30$ s_case = false
31$! Check for MMK/MMS 31$! Check for MMK/MMS
32$! 32$!
33$ If F$Search ("Sys$System:MMS.EXE") .nes. "" Then Make = "MMS" 33$ If F$Search ("Sys$System:MMS.EXE") .nes. "" Then Make = "MMS"
34$ If F$Type (MMK) .eqs. "STRING" Then Make = "MMK" 34$ If F$Type (MMK) .eqs. "STRING" Then Make = "MMK"
35$! 35$!
36$! 36$!
37$ gosub find_version 37$ gosub find_version
38$! 38$!
39$ gosub check_opts 39$ gosub check_opts
40$! 40$!
41$! Look for the compiler used 41$! Look for the compiler used
42$! 42$!
43$ gosub check_compiler 43$ gosub check_compiler
44$ if its_decc 44$ if its_decc
45$ then 45$ then
46$ ccopt = "/prefix=all" + ccopt 46$ ccopt = "/prefix=all" + ccopt
47$ if f$trnlnm("SYS") .eqs. "" 47$ if f$trnlnm("SYS") .eqs. ""
48$ then 48$ then
49$ if axp 49$ if axp
50$ then 50$ then
51$ define sys sys$library: 51$ define sys sys$library:
52$ else 52$ else
53$ ccopt = "/decc" + ccopt 53$ ccopt = "/decc" + ccopt
54$ define sys decc$library_include: 54$ define sys decc$library_include:
55$ endif 55$ endif
56$ endif 56$ endif
57$ endif 57$ endif
58$ if its_vaxc .or. its_gnuc 58$ if its_vaxc .or. its_gnuc
59$ then 59$ then
60$ if f$trnlnm("SYS").eqs."" then define sys sys$library: 60$ if f$trnlnm("SYS").eqs."" then define sys sys$library:
61$ endif 61$ endif
62$! 62$!
63$! Build the thing plain or with mms 63$! Build the thing plain or with mms
64$! 64$!
65$ write sys$output "Compiling Zlib sources ..." 65$ write sys$output "Compiling Zlib sources ..."
66$ if make.eqs."" 66$ if make.eqs.""
67$ then 67$ then
68$ dele example.obj;*,minigzip.obj;* 68$ dele example.obj;*,minigzip.obj;*
69$ CALL MAKE adler32.OBJ "CC ''CCOPT' adler32" - 69$ CALL MAKE adler32.OBJ "CC ''CCOPT' adler32" -
70 adler32.c zlib.h zconf.h 70 adler32.c zlib.h zconf.h
71$ CALL MAKE compress.OBJ "CC ''CCOPT' compress" - 71$ CALL MAKE compress.OBJ "CC ''CCOPT' compress" -
72 compress.c zlib.h zconf.h 72 compress.c zlib.h zconf.h
73$ CALL MAKE crc32.OBJ "CC ''CCOPT' crc32" - 73$ CALL MAKE crc32.OBJ "CC ''CCOPT' crc32" -
74 crc32.c zlib.h zconf.h 74 crc32.c zlib.h zconf.h
75$ CALL MAKE deflate.OBJ "CC ''CCOPT' deflate" - 75$ CALL MAKE deflate.OBJ "CC ''CCOPT' deflate" -
76 deflate.c deflate.h zutil.h zlib.h zconf.h 76 deflate.c deflate.h zutil.h zlib.h zconf.h
77$ CALL MAKE gzio.OBJ "CC ''CCOPT' gzio" - 77$ CALL MAKE gzio.OBJ "CC ''CCOPT' gzio" -
78 gzio.c zutil.h zlib.h zconf.h 78 gzio.c zutil.h zlib.h zconf.h
79$ CALL MAKE infback.OBJ "CC ''CCOPT' infback" - 79$ CALL MAKE infback.OBJ "CC ''CCOPT' infback" -
80 infback.c zutil.h inftrees.h inflate.h inffast.h inffixed.h 80 infback.c zutil.h inftrees.h inflate.h inffast.h inffixed.h
81$ CALL MAKE inffast.OBJ "CC ''CCOPT' inffast" - 81$ CALL MAKE inffast.OBJ "CC ''CCOPT' inffast" -
82 inffast.c zutil.h zlib.h zconf.h inffast.h 82 inffast.c zutil.h zlib.h zconf.h inffast.h
83$ CALL MAKE inflate.OBJ "CC ''CCOPT' inflate" - 83$ CALL MAKE inflate.OBJ "CC ''CCOPT' inflate" -
84 inflate.c zutil.h zlib.h zconf.h infblock.h 84 inflate.c zutil.h zlib.h zconf.h infblock.h
85$ CALL MAKE inftrees.OBJ "CC ''CCOPT' inftrees" - 85$ CALL MAKE inftrees.OBJ "CC ''CCOPT' inftrees" -
86 inftrees.c zutil.h zlib.h zconf.h inftrees.h 86 inftrees.c zutil.h zlib.h zconf.h inftrees.h
87$ CALL MAKE trees.OBJ "CC ''CCOPT' trees" - 87$ CALL MAKE trees.OBJ "CC ''CCOPT' trees" -
88 trees.c deflate.h zutil.h zlib.h zconf.h 88 trees.c deflate.h zutil.h zlib.h zconf.h
89$ CALL MAKE uncompr.OBJ "CC ''CCOPT' uncompr" - 89$ CALL MAKE uncompr.OBJ "CC ''CCOPT' uncompr" -
90 uncompr.c zlib.h zconf.h 90 uncompr.c zlib.h zconf.h
91$ CALL MAKE zutil.OBJ "CC ''CCOPT' zutil" - 91$ CALL MAKE zutil.OBJ "CC ''CCOPT' zutil" -
92 zutil.c zutil.h zlib.h zconf.h 92 zutil.c zutil.h zlib.h zconf.h
93$ write sys$output "Building Zlib ..." 93$ write sys$output "Building Zlib ..."
94$ CALL MAKE libz.OLB "lib/crea libz.olb *.obj" *.OBJ 94$ CALL MAKE libz.OLB "lib/crea libz.olb *.obj" *.OBJ
95$ write sys$output "Building example..." 95$ write sys$output "Building example..."
96$ CALL MAKE example.OBJ "CC ''CCOPT' example" - 96$ CALL MAKE example.OBJ "CC ''CCOPT' example" -
97 example.c zlib.h zconf.h 97 example.c zlib.h zconf.h
98$ call make example.exe "LINK example,libz.olb/lib" example.obj libz.olb 98$ call make example.exe "LINK example,libz.olb/lib" example.obj libz.olb
99$ if f$search("x11vms:xvmsutils.olb") .nes. "" 99$ if f$search("x11vms:xvmsutils.olb") .nes. ""
100$ then 100$ then
101$ write sys$output "Building minigzip..." 101$ write sys$output "Building minigzip..."
102$ CALL MAKE minigzip.OBJ "CC ''CCOPT' minigzip" - 102$ CALL MAKE minigzip.OBJ "CC ''CCOPT' minigzip" -
103 minigzip.c zlib.h zconf.h 103 minigzip.c zlib.h zconf.h
104$ call make minigzip.exe - 104$ call make minigzip.exe -
105 "LINK minigzip,libz.olb/lib,x11vms:xvmsutils.olb/lib" - 105 "LINK minigzip,libz.olb/lib,x11vms:xvmsutils.olb/lib" -
106 minigzip.obj libz.olb 106 minigzip.obj libz.olb
107$ endif 107$ endif
108$ else 108$ else
109$ gosub crea_mms 109$ gosub crea_mms
110$ SAY "Make ''name' ''version' with ''Make' " 110$ SAY "Make ''name' ''version' with ''Make' "
111$ 'make' 111$ 'make'
112$ endif 112$ endif
113$! 113$!
114$! Alpha gets a shareable image 114$! Alpha gets a shareable image
115$! 115$!
116$ If axp 116$ If axp
117$ Then 117$ Then
118$ gosub crea_olist 118$ gosub crea_olist
119$ write sys$output "Creating libzshr.exe" 119$ write sys$output "Creating libzshr.exe"
120$ call anal_obj_axp modules.opt _link.opt 120$ call anal_obj_axp modules.opt _link.opt
121$ if s_case 121$ if s_case
122$ then 122$ then
123$ open/append optf modules.opt 123$ open/append optf modules.opt
124$ write optf "case_sensitive=YES" 124$ write optf "case_sensitive=YES"
125$ close optf 125$ close optf
126$ endif 126$ endif
127$ LINK_'lopts'/SHARE=libzshr.exe modules.opt/opt,_link.opt/opt 127$ LINK_'lopts'/SHARE=libzshr.exe modules.opt/opt,_link.opt/opt
128$ endif 128$ endif
129$ write sys$output "Zlib build completed" 129$ write sys$output "Zlib build completed"
130$ exit 130$ exit
131$CC_ERR: 131$CC_ERR:
132$ write sys$output "C compiler required to build ''name'" 132$ write sys$output "C compiler required to build ''name'"
133$ goto err_exit 133$ goto err_exit
134$ERR_EXIT: 134$ERR_EXIT:
135$ set message/facil/ident/sever/text 135$ set message/facil/ident/sever/text
136$ write sys$output "Exiting..." 136$ write sys$output "Exiting..."
137$ exit 2 137$ exit 2
138$! 138$!
139$! 139$!
140$MAKE: SUBROUTINE !SUBROUTINE TO CHECK DEPENDENCIES 140$MAKE: SUBROUTINE !SUBROUTINE TO CHECK DEPENDENCIES
141$ V = 'F$Verify(0) 141$ V = 'F$Verify(0)
142$! P1 = What we are trying to make 142$! P1 = What we are trying to make
143$! P2 = Command to make it 143$! P2 = Command to make it
144$! P3 - P8 What it depends on 144$! P3 - P8 What it depends on
145$ 145$
146$ If F$Search(P1) .Eqs. "" Then Goto Makeit 146$ If F$Search(P1) .Eqs. "" Then Goto Makeit
147$ Time = F$CvTime(F$File(P1,"RDT")) 147$ Time = F$CvTime(F$File(P1,"RDT"))
148$arg=3 148$arg=3
149$Loop: 149$Loop:
150$ Argument = P'arg 150$ Argument = P'arg
151$ If Argument .Eqs. "" Then Goto Exit 151$ If Argument .Eqs. "" Then Goto Exit
152$ El=0 152$ El=0
153$Loop2: 153$Loop2:
154$ File = F$Element(El," ",Argument) 154$ File = F$Element(El," ",Argument)
155$ If File .Eqs. " " Then Goto Endl 155$ If File .Eqs. " " Then Goto Endl
156$ AFile = "" 156$ AFile = ""
157$Loop3: 157$Loop3:
158$ OFile = AFile 158$ OFile = AFile
159$ AFile = F$Search(File) 159$ AFile = F$Search(File)
160$ If AFile .Eqs. "" .Or. AFile .Eqs. OFile Then Goto NextEl 160$ If AFile .Eqs. "" .Or. AFile .Eqs. OFile Then Goto NextEl
161$ If F$CvTime(F$File(AFile,"RDT")) .Ges. Time Then Goto Makeit 161$ If F$CvTime(F$File(AFile,"RDT")) .Ges. Time Then Goto Makeit
162$ Goto Loop3 162$ Goto Loop3
163$NextEL: 163$NextEL:
164$ El = El + 1 164$ El = El + 1
165$ Goto Loop2 165$ Goto Loop2
166$EndL: 166$EndL:
167$ arg=arg+1 167$ arg=arg+1
168$ If arg .Le. 8 Then Goto Loop 168$ If arg .Le. 8 Then Goto Loop
169$ Goto Exit 169$ Goto Exit
170$ 170$
171$Makeit: 171$Makeit:
172$ VV=F$VERIFY(0) 172$ VV=F$VERIFY(0)
173$ write sys$output P2 173$ write sys$output P2
174$ 'P2 174$ 'P2
175$ VV='F$Verify(VV) 175$ VV='F$Verify(VV)
176$Exit: 176$Exit:
177$ If V Then Set Verify 177$ If V Then Set Verify
178$ENDSUBROUTINE 178$ENDSUBROUTINE
179$!------------------------------------------------------------------------------ 179$!------------------------------------------------------------------------------
180$! 180$!
181$! Check command line options and set symbols accordingly 181$! Check command line options and set symbols accordingly
182$! 182$!
183$ CHECK_OPTS: 183$ CHECK_OPTS:
184$ i = 1 184$ i = 1
185$ OPT_LOOP: 185$ OPT_LOOP:
186$ if i .lt. 9 186$ if i .lt. 9
187$ then 187$ then
188$ cparm = f$edit(p'i',"upcase") 188$ cparm = f$edit(p'i',"upcase")
189$ if cparm .eqs. "DEBUG" 189$ if cparm .eqs. "DEBUG"
190$ then 190$ then
191$ ccopt = ccopt + "/noopt/deb" 191$ ccopt = ccopt + "/noopt/deb"
192$ lopts = lopts + "/deb" 192$ lopts = lopts + "/deb"
193$ endif 193$ endif
194$ if f$locate("CCOPT=",cparm) .lt. f$length(cparm) 194$ if f$locate("CCOPT=",cparm) .lt. f$length(cparm)
195$ then 195$ then
196$ start = f$locate("=",cparm) + 1 196$ start = f$locate("=",cparm) + 1
197$ len = f$length(cparm) - start 197$ len = f$length(cparm) - start
198$ ccopt = ccopt + f$extract(start,len,cparm) 198$ ccopt = ccopt + f$extract(start,len,cparm)
199$ if f$locate("AS_IS",f$edit(ccopt,"UPCASE")) .lt. f$length(ccopt) - 199$ if f$locate("AS_IS",f$edit(ccopt,"UPCASE")) .lt. f$length(ccopt) -
200 then s_case = true 200 then s_case = true
201$ endif 201$ endif
202$ if cparm .eqs. "LINK" then linkonly = true 202$ if cparm .eqs. "LINK" then linkonly = true
203$ if f$locate("LOPTS=",cparm) .lt. f$length(cparm) 203$ if f$locate("LOPTS=",cparm) .lt. f$length(cparm)
204$ then 204$ then
205$ start = f$locate("=",cparm) + 1 205$ start = f$locate("=",cparm) + 1
206$ len = f$length(cparm) - start 206$ len = f$length(cparm) - start
207$ lopts = lopts + f$extract(start,len,cparm) 207$ lopts = lopts + f$extract(start,len,cparm)
208$ endif 208$ endif
209$ if f$locate("CC=",cparm) .lt. f$length(cparm) 209$ if f$locate("CC=",cparm) .lt. f$length(cparm)
210$ then 210$ then
211$ start = f$locate("=",cparm) + 1 211$ start = f$locate("=",cparm) + 1
212$ len = f$length(cparm) - start 212$ len = f$length(cparm) - start
213$ cc_com = f$extract(start,len,cparm) 213$ cc_com = f$extract(start,len,cparm)
214 if (cc_com .nes. "DECC") .and. - 214 if (cc_com .nes. "DECC") .and. -
215 (cc_com .nes. "VAXC") .and. - 215 (cc_com .nes. "VAXC") .and. -
216 (cc_com .nes. "GNUC") 216 (cc_com .nes. "GNUC")
217$ then 217$ then
218$ write sys$output "Unsupported compiler choice ''cc_com' ignored" 218$ write sys$output "Unsupported compiler choice ''cc_com' ignored"
219$ write sys$output "Use DECC, VAXC, or GNUC instead" 219$ write sys$output "Use DECC, VAXC, or GNUC instead"
220$ else 220$ else
221$ if cc_com .eqs. "DECC" then its_decc = true 221$ if cc_com .eqs. "DECC" then its_decc = true
222$ if cc_com .eqs. "VAXC" then its_vaxc = true 222$ if cc_com .eqs. "VAXC" then its_vaxc = true
223$ if cc_com .eqs. "GNUC" then its_gnuc = true 223$ if cc_com .eqs. "GNUC" then its_gnuc = true
224$ endif 224$ endif
225$ endif 225$ endif
226$ if f$locate("MAKE=",cparm) .lt. f$length(cparm) 226$ if f$locate("MAKE=",cparm) .lt. f$length(cparm)
227$ then 227$ then
228$ start = f$locate("=",cparm) + 1 228$ start = f$locate("=",cparm) + 1
229$ len = f$length(cparm) - start 229$ len = f$length(cparm) - start
230$ mmks = f$extract(start,len,cparm) 230$ mmks = f$extract(start,len,cparm)
231$ if (mmks .eqs. "MMK") .or. (mmks .eqs. "MMS") 231$ if (mmks .eqs. "MMK") .or. (mmks .eqs. "MMS")
232$ then 232$ then
233$ make = mmks 233$ make = mmks
234$ else 234$ else
235$ write sys$output "Unsupported make choice ''mmks' ignored" 235$ write sys$output "Unsupported make choice ''mmks' ignored"
236$ write sys$output "Use MMK or MMS instead" 236$ write sys$output "Use MMK or MMS instead"
237$ endif 237$ endif
238$ endif 238$ endif
239$ i = i + 1 239$ i = i + 1
240$ goto opt_loop 240$ goto opt_loop
241$ endif 241$ endif
242$ return 242$ return
243$!------------------------------------------------------------------------------ 243$!------------------------------------------------------------------------------
244$! 244$!
245$! Look for the compiler used 245$! Look for the compiler used
246$! 246$!
247$CHECK_COMPILER: 247$CHECK_COMPILER:
248$ if (.not. (its_decc .or. its_vaxc .or. its_gnuc)) 248$ if (.not. (its_decc .or. its_vaxc .or. its_gnuc))
249$ then 249$ then
250$ its_decc = (f$search("SYS$SYSTEM:DECC$COMPILER.EXE") .nes. "") 250$ its_decc = (f$search("SYS$SYSTEM:DECC$COMPILER.EXE") .nes. "")
251$ its_vaxc = .not. its_decc .and. (F$Search("SYS$System:VAXC.Exe") .nes. "") 251$ its_vaxc = .not. its_decc .and. (F$Search("SYS$System:VAXC.Exe") .nes. "")
252$ its_gnuc = .not. (its_decc .or. its_vaxc) .and. (f$trnlnm("gnu_cc") .nes. "") 252$ its_gnuc = .not. (its_decc .or. its_vaxc) .and. (f$trnlnm("gnu_cc") .nes. "")
253$ endif 253$ endif
254$! 254$!
255$! Exit if no compiler available 255$! Exit if no compiler available
256$! 256$!
257$ if (.not. (its_decc .or. its_vaxc .or. its_gnuc)) 257$ if (.not. (its_decc .or. its_vaxc .or. its_gnuc))
258$ then goto CC_ERR 258$ then goto CC_ERR
259$ else 259$ else
260$ if its_decc then write sys$output "CC compiler check ... Compaq C" 260$ if its_decc then write sys$output "CC compiler check ... Compaq C"
261$ if its_vaxc then write sys$output "CC compiler check ... VAX C" 261$ if its_vaxc then write sys$output "CC compiler check ... VAX C"
262$ if its_gnuc then write sys$output "CC compiler check ... GNU C" 262$ if its_gnuc then write sys$output "CC compiler check ... GNU C"
263$ endif 263$ endif
264$ return 264$ return
265$!------------------------------------------------------------------------------ 265$!------------------------------------------------------------------------------
266$! 266$!
267$! If MMS/MMK are available dump out the descrip.mms if required 267$! If MMS/MMK are available dump out the descrip.mms if required
268$! 268$!
269$CREA_MMS: 269$CREA_MMS:
270$ write sys$output "Creating descrip.mms..." 270$ write sys$output "Creating descrip.mms..."
271$ create descrip.mms 271$ create descrip.mms
272$ open/append out descrip.mms 272$ open/append out descrip.mms
273$ copy sys$input: out 273$ copy sys$input: out
274$ deck 274$ deck
275# descrip.mms: MMS description file for building zlib on VMS 275# descrip.mms: MMS description file for building zlib on VMS
276# written by Martin P.J. Zinser 276# written by Martin P.J. Zinser
277# <zinser@zinser.no-ip.info or zinser@sysdev.deutsche-boerse.com> 277# <zinser@zinser.no-ip.info or zinser@sysdev.deutsche-boerse.com>
278 278
279OBJS = adler32.obj, compress.obj, crc32.obj, gzio.obj, uncompr.obj, infback.obj\ 279OBJS = adler32.obj, compress.obj, crc32.obj, gzio.obj, uncompr.obj, infback.obj\
280 deflate.obj, trees.obj, zutil.obj, inflate.obj, \ 280 deflate.obj, trees.obj, zutil.obj, inflate.obj, \
281 inftrees.obj, inffast.obj 281 inftrees.obj, inffast.obj
282 282
283$ eod 283$ eod
284$ write out "CFLAGS=", ccopt 284$ write out "CFLAGS=", ccopt
285$ write out "LOPTS=", lopts 285$ write out "LOPTS=", lopts
286$ copy sys$input: out 286$ copy sys$input: out
287$ deck 287$ deck
288 288
289all : example.exe minigzip.exe libz.olb 289all : example.exe minigzip.exe libz.olb
290 @ write sys$output " Example applications available" 290 @ write sys$output " Example applications available"
291 291
292libz.olb : libz.olb($(OBJS)) 292libz.olb : libz.olb($(OBJS))
293 @ write sys$output " libz available" 293 @ write sys$output " libz available"
294 294
295example.exe : example.obj libz.olb 295example.exe : example.obj libz.olb
296 link $(LOPTS) example,libz.olb/lib 296 link $(LOPTS) example,libz.olb/lib
297 297
298minigzip.exe : minigzip.obj libz.olb 298minigzip.exe : minigzip.obj libz.olb
299 link $(LOPTS) minigzip,libz.olb/lib,x11vms:xvmsutils.olb/lib 299 link $(LOPTS) minigzip,libz.olb/lib,x11vms:xvmsutils.olb/lib
300 300
301clean : 301clean :
302 delete *.obj;*,libz.olb;*,*.opt;*,*.exe;* 302 delete *.obj;*,libz.olb;*,*.opt;*,*.exe;*
303 303
304 304
305# Other dependencies. 305# Other dependencies.
306adler32.obj : adler32.c zutil.h zlib.h zconf.h 306adler32.obj : adler32.c zutil.h zlib.h zconf.h
307compress.obj : compress.c zlib.h zconf.h 307compress.obj : compress.c zlib.h zconf.h
308crc32.obj : crc32.c zutil.h zlib.h zconf.h 308crc32.obj : crc32.c zutil.h zlib.h zconf.h
309deflate.obj : deflate.c deflate.h zutil.h zlib.h zconf.h 309deflate.obj : deflate.c deflate.h zutil.h zlib.h zconf.h
310example.obj : example.c zlib.h zconf.h 310example.obj : example.c zlib.h zconf.h
311gzio.obj : gzio.c zutil.h zlib.h zconf.h 311gzio.obj : gzio.c zutil.h zlib.h zconf.h
312inffast.obj : inffast.c zutil.h zlib.h zconf.h inftrees.h inffast.h 312inffast.obj : inffast.c zutil.h zlib.h zconf.h inftrees.h inffast.h
313inflate.obj : inflate.c zutil.h zlib.h zconf.h 313inflate.obj : inflate.c zutil.h zlib.h zconf.h
314inftrees.obj : inftrees.c zutil.h zlib.h zconf.h inftrees.h 314inftrees.obj : inftrees.c zutil.h zlib.h zconf.h inftrees.h
315minigzip.obj : minigzip.c zlib.h zconf.h 315minigzip.obj : minigzip.c zlib.h zconf.h
316trees.obj : trees.c deflate.h zutil.h zlib.h zconf.h 316trees.obj : trees.c deflate.h zutil.h zlib.h zconf.h
317uncompr.obj : uncompr.c zlib.h zconf.h 317uncompr.obj : uncompr.c zlib.h zconf.h
318zutil.obj : zutil.c zutil.h zlib.h zconf.h 318zutil.obj : zutil.c zutil.h zlib.h zconf.h
319infback.obj : infback.c zutil.h inftrees.h inflate.h inffast.h inffixed.h 319infback.obj : infback.c zutil.h inftrees.h inflate.h inffast.h inffixed.h
320$ eod 320$ eod
321$ close out 321$ close out
322$ return 322$ return
323$!------------------------------------------------------------------------------ 323$!------------------------------------------------------------------------------
324$! 324$!
325$! Read list of core library sources from makefile.in and create options 325$! Read list of core library sources from makefile.in and create options
326$! needed to build shareable image 326$! needed to build shareable image
327$! 327$!
328$CREA_OLIST: 328$CREA_OLIST:
329$ open/read min makefile.in 329$ open/read min makefile.in
330$ open/write mod modules.opt 330$ open/write mod modules.opt
331$ src_check = "OBJS =" 331$ src_check = "OBJS ="
332$MRLOOP: 332$MRLOOP:
333$ read/end=mrdone min rec 333$ read/end=mrdone min rec
334$ if (f$extract(0,6,rec) .nes. src_check) then goto mrloop 334$ if (f$extract(0,6,rec) .nes. src_check) then goto mrloop
335$ rec = rec - src_check 335$ rec = rec - src_check
336$ gosub extra_filnam 336$ gosub extra_filnam
337$ if (f$element(1,"\",rec) .eqs. "\") then goto mrdone 337$ if (f$element(1,"\",rec) .eqs. "\") then goto mrdone
338$MRSLOOP: 338$MRSLOOP:
339$ read/end=mrdone min rec 339$ read/end=mrdone min rec
340$ gosub extra_filnam 340$ gosub extra_filnam
341$ if (f$element(1,"\",rec) .nes. "\") then goto mrsloop 341$ if (f$element(1,"\",rec) .nes. "\") then goto mrsloop
342$MRDONE: 342$MRDONE:
343$ close min 343$ close min
344$ close mod 344$ close mod
345$ return 345$ return
346$!------------------------------------------------------------------------------ 346$!------------------------------------------------------------------------------
347$! 347$!
348$! Take record extracted in crea_olist and split it into single filenames 348$! Take record extracted in crea_olist and split it into single filenames
349$! 349$!
350$EXTRA_FILNAM: 350$EXTRA_FILNAM:
351$ myrec = f$edit(rec - "\", "trim,compress") 351$ myrec = f$edit(rec - "\", "trim,compress")
352$ i = 0 352$ i = 0
353$FELOOP: 353$FELOOP:
354$ srcfil = f$element(i," ", myrec) 354$ srcfil = f$element(i," ", myrec)
355$ if (srcfil .nes. " ") 355$ if (srcfil .nes. " ")
356$ then 356$ then
357$ write mod f$parse(srcfil,,,"NAME"), ".obj" 357$ write mod f$parse(srcfil,,,"NAME"), ".obj"
358$ i = i + 1 358$ i = i + 1
359$ goto feloop 359$ goto feloop
360$ endif 360$ endif
361$ return 361$ return
362$!------------------------------------------------------------------------------ 362$!------------------------------------------------------------------------------
363$! 363$!
364$! Find current Zlib version number 364$! Find current Zlib version number
365$! 365$!
366$FIND_VERSION: 366$FIND_VERSION:
367$ open/read h_in 'v_file' 367$ open/read h_in 'v_file'
368$hloop: 368$hloop:
369$ read/end=hdone h_in rec 369$ read/end=hdone h_in rec
370$ rec = f$edit(rec,"TRIM") 370$ rec = f$edit(rec,"TRIM")
371$ if (f$extract(0,1,rec) .nes. "#") then goto hloop 371$ if (f$extract(0,1,rec) .nes. "#") then goto hloop
372$ rec = f$edit(rec - "#", "TRIM") 372$ rec = f$edit(rec - "#", "TRIM")
373$ if f$element(0," ",rec) .nes. "define" then goto hloop 373$ if f$element(0," ",rec) .nes. "define" then goto hloop
374$ if f$element(1," ",rec) .eqs. v_string 374$ if f$element(1," ",rec) .eqs. v_string
375$ then 375$ then
376$ version = 'f$element(2," ",rec)' 376$ version = 'f$element(2," ",rec)'
377$ goto hdone 377$ goto hdone
378$ endif 378$ endif
379$ goto hloop 379$ goto hloop
380$hdone: 380$hdone:
381$ close h_in 381$ close h_in
382$ return 382$ return
383$!------------------------------------------------------------------------------ 383$!------------------------------------------------------------------------------
384$! 384$!
385$! Analyze Object files for OpenVMS AXP to extract Procedure and Data 385$! Analyze Object files for OpenVMS AXP to extract Procedure and Data
386$! information to build a symbol vector for a shareable image 386$! information to build a symbol vector for a shareable image
387$! All the "brains" of this logic was suggested by Hartmut Becker 387$! All the "brains" of this logic was suggested by Hartmut Becker
388$! (Hartmut.Becker@compaq.com). All the bugs were introduced by me 388$! (Hartmut.Becker@compaq.com). All the bugs were introduced by me
389$! (zinser@decus.de), so if you do have problem reports please do not 389$! (zinser@decus.de), so if you do have problem reports please do not
390$! bother Hartmut/HP, but get in touch with me 390$! bother Hartmut/HP, but get in touch with me
391$! 391$!
392$ ANAL_OBJ_AXP: Subroutine 392$ ANAL_OBJ_AXP: Subroutine
393$ V = 'F$Verify(0) 393$ V = 'F$Verify(0)
394$ SAY := "WRITE_ SYS$OUTPUT" 394$ SAY := "WRITE_ SYS$OUTPUT"
395$ 395$
396$ IF F$SEARCH("''P1'") .EQS. "" 396$ IF F$SEARCH("''P1'") .EQS. ""
397$ THEN 397$ THEN
398$ SAY "ANAL_OBJ_AXP-E-NOSUCHFILE: Error, inputfile ''p1' not available" 398$ SAY "ANAL_OBJ_AXP-E-NOSUCHFILE: Error, inputfile ''p1' not available"
399$ goto exit_aa 399$ goto exit_aa
400$ ENDIF 400$ ENDIF
401$ IF "''P2'" .EQS. "" 401$ IF "''P2'" .EQS. ""
402$ THEN 402$ THEN
403$ SAY "ANAL_OBJ_AXP: Error, no output file provided" 403$ SAY "ANAL_OBJ_AXP: Error, no output file provided"
404$ goto exit_aa 404$ goto exit_aa
405$ ENDIF 405$ ENDIF
406$ 406$
407$ open/read in 'p1 407$ open/read in 'p1
408$ create a.tmp 408$ create a.tmp
409$ open/append atmp a.tmp 409$ open/append atmp a.tmp
410$ loop: 410$ loop:
411$ read/end=end_loop in line 411$ read/end=end_loop in line
412$ f= f$search(line) 412$ f= f$search(line)
413$ if f .eqs. "" 413$ if f .eqs. ""
414$ then 414$ then
415$ write sys$output "ANAL_OBJ_AXP-w-nosuchfile, ''line'" 415$ write sys$output "ANAL_OBJ_AXP-w-nosuchfile, ''line'"
416$ goto loop 416$ goto loop
417$ endif 417$ endif
418$ define/user sys$output nl: 418$ define/user sys$output nl:
419$ define/user sys$error nl: 419$ define/user sys$error nl:
420$ anal/obj/gsd 'f /out=x.tmp 420$ anal/obj/gsd 'f /out=x.tmp
421$ open/read xtmp x.tmp 421$ open/read xtmp x.tmp
422$ XLOOP: 422$ XLOOP:
423$ read/end=end_xloop xtmp xline 423$ read/end=end_xloop xtmp xline
424$ xline = f$edit(xline,"compress") 424$ xline = f$edit(xline,"compress")
425$ write atmp xline 425$ write atmp xline
426$ goto xloop 426$ goto xloop
427$ END_XLOOP: 427$ END_XLOOP:
428$ close xtmp 428$ close xtmp
429$ goto loop 429$ goto loop
430$ end_loop: 430$ end_loop:
431$ close in 431$ close in
432$ close atmp 432$ close atmp
433$ if f$search("a.tmp") .eqs. "" - 433$ if f$search("a.tmp") .eqs. "" -
434 then $ exit 434 then $ exit
435$ ! all global definitions 435$ ! all global definitions
436$ search a.tmp "symbol:","EGSY$V_DEF 1","EGSY$V_NORM 1"/out=b.tmp 436$ search a.tmp "symbol:","EGSY$V_DEF 1","EGSY$V_NORM 1"/out=b.tmp
437$ ! all procedures 437$ ! all procedures
438$ search b.tmp "EGSY$V_NORM 1"/wind=(0,1) /out=c.tmp 438$ search b.tmp "EGSY$V_NORM 1"/wind=(0,1) /out=c.tmp
439$ search c.tmp "symbol:"/out=d.tmp 439$ search c.tmp "symbol:"/out=d.tmp
440$ define/user sys$output nl: 440$ define/user sys$output nl:
441$ edito/edt/command=sys$input d.tmp 441$ edito/edt/command=sys$input d.tmp
442sub/symbol: "/symbol_vector=(/whole 442sub/symbol: "/symbol_vector=(/whole
443sub/"/=PROCEDURE)/whole 443sub/"/=PROCEDURE)/whole
444exit 444exit
445$ ! all data 445$ ! all data
446$ search b.tmp "EGSY$V_DEF 1"/wind=(0,1) /out=e.tmp 446$ search b.tmp "EGSY$V_DEF 1"/wind=(0,1) /out=e.tmp
447$ search e.tmp "symbol:"/out=f.tmp 447$ search e.tmp "symbol:"/out=f.tmp
448$ define/user sys$output nl: 448$ define/user sys$output nl:
449$ edito/edt/command=sys$input f.tmp 449$ edito/edt/command=sys$input f.tmp
450sub/symbol: "/symbol_vector=(/whole 450sub/symbol: "/symbol_vector=(/whole
451sub/"/=DATA)/whole 451sub/"/=DATA)/whole
452exit 452exit
453$ sort/nodupl d.tmp,f.tmp 'p2' 453$ sort/nodupl d.tmp,f.tmp 'p2'
454$ delete a.tmp;*,b.tmp;*,c.tmp;*,d.tmp;*,e.tmp;*,f.tmp;* 454$ delete a.tmp;*,b.tmp;*,c.tmp;*,d.tmp;*,e.tmp;*,f.tmp;*
455$ if f$search("x.tmp") .nes. "" - 455$ if f$search("x.tmp") .nes. "" -
456 then $ delete x.tmp;* 456 then $ delete x.tmp;*
457$! 457$!
458$ EXIT_AA: 458$ EXIT_AA:
459$ if V then set verify 459$ if V then set verify
460$ endsubroutine 460$ endsubroutine
461$!------------------------------------------------------------------------------ 461$!------------------------------------------------------------------------------
diff --git a/utils/zenutils/libraries/zlib123/zlib/minigzip.c b/utils/zenutils/libraries/zlib123/zlib/minigzip.c
index 41996dbc9a..4524b96a1d 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/minigzip.c
+++ b/utils/zenutils/libraries/zlib123/zlib/minigzip.c
@@ -1,322 +1,322 @@
1/* minigzip.c -- simulate gzip using the zlib compression library 1/* minigzip.c -- simulate gzip using the zlib compression library
2 * Copyright (C) 1995-2005 Jean-loup Gailly. 2 * Copyright (C) 1995-2005 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6/* 6/*
7 * minigzip is a minimal implementation of the gzip utility. This is 7 * minigzip is a minimal implementation of the gzip utility. This is
8 * only an example of using zlib and isn't meant to replace the 8 * only an example of using zlib and isn't meant to replace the
9 * full-featured gzip. No attempt is made to deal with file systems 9 * full-featured gzip. No attempt is made to deal with file systems
10 * limiting names to 14 or 8+3 characters, etc... Error checking is 10 * limiting names to 14 or 8+3 characters, etc... Error checking is
11 * very limited. So use minigzip only for testing; use gzip for the 11 * very limited. So use minigzip only for testing; use gzip for the
12 * real thing. On MSDOS, use only on file names without extension 12 * real thing. On MSDOS, use only on file names without extension
13 * or in pipe mode. 13 * or in pipe mode.
14 */ 14 */
15 15
16/* @(#) $Id$ */ 16/* @(#) $Id$ */
17 17
18#include <stdio.h> 18#include <stdio.h>
19#include "zlib.h" 19#include "zlib.h"
20 20
21#ifdef STDC 21#ifdef STDC
22# include <string.h> 22# include <string.h>
23# include <stdlib.h> 23# include <stdlib.h>
24#endif 24#endif
25 25
26#ifdef USE_MMAP 26#ifdef USE_MMAP
27# include <sys/types.h> 27# include <sys/types.h>
28# include <sys/mman.h> 28# include <sys/mman.h>
29# include <sys/stat.h> 29# include <sys/stat.h>
30#endif 30#endif
31 31
32#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__) 32#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
33# include <fcntl.h> 33# include <fcntl.h>
34# include <io.h> 34# include <io.h>
35# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) 35# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
36#else 36#else
37# define SET_BINARY_MODE(file) 37# define SET_BINARY_MODE(file)
38#endif 38#endif
39 39
40#ifdef VMS 40#ifdef VMS
41# define unlink delete 41# define unlink delete
42# define GZ_SUFFIX "-gz" 42# define GZ_SUFFIX "-gz"
43#endif 43#endif
44#ifdef RISCOS 44#ifdef RISCOS
45# define unlink remove 45# define unlink remove
46# define GZ_SUFFIX "-gz" 46# define GZ_SUFFIX "-gz"
47# define fileno(file) file->__file 47# define fileno(file) file->__file
48#endif 48#endif
49#if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os 49#if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
50# include <unix.h> /* for fileno */ 50# include <unix.h> /* for fileno */
51#endif 51#endif
52 52
53#ifndef WIN32 /* unlink already in stdio.h for WIN32 */ 53#ifndef WIN32 /* unlink already in stdio.h for WIN32 */
54 extern int unlink OF((const char *)); 54 extern int unlink OF((const char *));
55#endif 55#endif
56 56
57#ifndef GZ_SUFFIX 57#ifndef GZ_SUFFIX
58# define GZ_SUFFIX ".gz" 58# define GZ_SUFFIX ".gz"
59#endif 59#endif
60#define SUFFIX_LEN (sizeof(GZ_SUFFIX)-1) 60#define SUFFIX_LEN (sizeof(GZ_SUFFIX)-1)
61 61
62#define BUFLEN 16384 62#define BUFLEN 16384
63#define MAX_NAME_LEN 1024 63#define MAX_NAME_LEN 1024
64 64
65#ifdef MAXSEG_64K 65#ifdef MAXSEG_64K
66# define local static 66# define local static
67 /* Needed for systems with limitation on stack size. */ 67 /* Needed for systems with limitation on stack size. */
68#else 68#else
69# define local 69# define local
70#endif 70#endif
71 71
72char *prog; 72char *prog;
73 73
74void error OF((const char *msg)); 74void error OF((const char *msg));
75void gz_compress OF((FILE *in, gzFile out)); 75void gz_compress OF((FILE *in, gzFile out));
76#ifdef USE_MMAP 76#ifdef USE_MMAP
77int gz_compress_mmap OF((FILE *in, gzFile out)); 77int gz_compress_mmap OF((FILE *in, gzFile out));
78#endif 78#endif
79void gz_uncompress OF((gzFile in, FILE *out)); 79void gz_uncompress OF((gzFile in, FILE *out));
80void file_compress OF((char *file, char *mode)); 80void file_compress OF((char *file, char *mode));
81void file_uncompress OF((char *file)); 81void file_uncompress OF((char *file));
82int main OF((int argc, char *argv[])); 82int main OF((int argc, char *argv[]));
83 83
84/* =========================================================================== 84/* ===========================================================================
85 * Display error message and exit 85 * Display error message and exit
86 */ 86 */
87void error(msg) 87void error(msg)
88 const char *msg; 88 const char *msg;
89{ 89{
90 fprintf(stderr, "%s: %s\n", prog, msg); 90 fprintf(stderr, "%s: %s\n", prog, msg);
91 exit(1); 91 exit(1);
92} 92}
93 93
94/* =========================================================================== 94/* ===========================================================================
95 * Compress input to output then close both files. 95 * Compress input to output then close both files.
96 */ 96 */
97 97
98void gz_compress(in, out) 98void gz_compress(in, out)
99 FILE *in; 99 FILE *in;
100 gzFile out; 100 gzFile out;
101{ 101{
102 local char buf[BUFLEN]; 102 local char buf[BUFLEN];
103 int len; 103 int len;
104 int err; 104 int err;
105 105
106#ifdef USE_MMAP 106#ifdef USE_MMAP
107 /* Try first compressing with mmap. If mmap fails (minigzip used in a 107 /* Try first compressing with mmap. If mmap fails (minigzip used in a
108 * pipe), use the normal fread loop. 108 * pipe), use the normal fread loop.
109 */ 109 */
110 if (gz_compress_mmap(in, out) == Z_OK) return; 110 if (gz_compress_mmap(in, out) == Z_OK) return;
111#endif 111#endif
112 for (;;) { 112 for (;;) {
113 len = (int)fread(buf, 1, sizeof(buf), in); 113 len = (int)fread(buf, 1, sizeof(buf), in);
114 if (ferror(in)) { 114 if (ferror(in)) {
115 perror("fread"); 115 perror("fread");
116 exit(1); 116 exit(1);
117 } 117 }
118 if (len == 0) break; 118 if (len == 0) break;
119 119
120 if (gzwrite(out, buf, (unsigned)len) != len) error(gzerror(out, &err)); 120 if (gzwrite(out, buf, (unsigned)len) != len) error(gzerror(out, &err));
121 } 121 }
122 fclose(in); 122 fclose(in);
123 if (gzclose(out) != Z_OK) error("failed gzclose"); 123 if (gzclose(out) != Z_OK) error("failed gzclose");
124} 124}
125 125
126#ifdef USE_MMAP /* MMAP version, Miguel Albrecht <malbrech@eso.org> */ 126#ifdef USE_MMAP /* MMAP version, Miguel Albrecht <malbrech@eso.org> */
127 127
128/* Try compressing the input file at once using mmap. Return Z_OK if 128/* Try compressing the input file at once using mmap. Return Z_OK if
129 * if success, Z_ERRNO otherwise. 129 * if success, Z_ERRNO otherwise.
130 */ 130 */
131int gz_compress_mmap(in, out) 131int gz_compress_mmap(in, out)
132 FILE *in; 132 FILE *in;
133 gzFile out; 133 gzFile out;
134{ 134{
135 int len; 135 int len;
136 int err; 136 int err;
137 int ifd = fileno(in); 137 int ifd = fileno(in);
138 caddr_t buf; /* mmap'ed buffer for the entire input file */ 138 caddr_t buf; /* mmap'ed buffer for the entire input file */
139 off_t buf_len; /* length of the input file */ 139 off_t buf_len; /* length of the input file */
140 struct stat sb; 140 struct stat sb;
141 141
142 /* Determine the size of the file, needed for mmap: */ 142 /* Determine the size of the file, needed for mmap: */
143 if (fstat(ifd, &sb) < 0) return Z_ERRNO; 143 if (fstat(ifd, &sb) < 0) return Z_ERRNO;
144 buf_len = sb.st_size; 144 buf_len = sb.st_size;
145 if (buf_len <= 0) return Z_ERRNO; 145 if (buf_len <= 0) return Z_ERRNO;
146 146
147 /* Now do the actual mmap: */ 147 /* Now do the actual mmap: */
148 buf = mmap((caddr_t) 0, buf_len, PROT_READ, MAP_SHARED, ifd, (off_t)0); 148 buf = mmap((caddr_t) 0, buf_len, PROT_READ, MAP_SHARED, ifd, (off_t)0);
149 if (buf == (caddr_t)(-1)) return Z_ERRNO; 149 if (buf == (caddr_t)(-1)) return Z_ERRNO;
150 150
151 /* Compress the whole file at once: */ 151 /* Compress the whole file at once: */
152 len = gzwrite(out, (char *)buf, (unsigned)buf_len); 152 len = gzwrite(out, (char *)buf, (unsigned)buf_len);
153 153
154 if (len != (int)buf_len) error(gzerror(out, &err)); 154 if (len != (int)buf_len) error(gzerror(out, &err));
155 155
156 munmap(buf, buf_len); 156 munmap(buf, buf_len);
157 fclose(in); 157 fclose(in);
158 if (gzclose(out) != Z_OK) error("failed gzclose"); 158 if (gzclose(out) != Z_OK) error("failed gzclose");
159 return Z_OK; 159 return Z_OK;
160} 160}
161#endif /* USE_MMAP */ 161#endif /* USE_MMAP */
162 162
163/* =========================================================================== 163/* ===========================================================================
164 * Uncompress input to output then close both files. 164 * Uncompress input to output then close both files.
165 */ 165 */
166void gz_uncompress(in, out) 166void gz_uncompress(in, out)
167 gzFile in; 167 gzFile in;
168 FILE *out; 168 FILE *out;
169{ 169{
170 local char buf[BUFLEN]; 170 local char buf[BUFLEN];
171 int len; 171 int len;
172 int err; 172 int err;
173 173
174 for (;;) { 174 for (;;) {
175 len = gzread(in, buf, sizeof(buf)); 175 len = gzread(in, buf, sizeof(buf));
176 if (len < 0) error (gzerror(in, &err)); 176 if (len < 0) error (gzerror(in, &err));
177 if (len == 0) break; 177 if (len == 0) break;
178 178
179 if ((int)fwrite(buf, 1, (unsigned)len, out) != len) { 179 if ((int)fwrite(buf, 1, (unsigned)len, out) != len) {
180 error("failed fwrite"); 180 error("failed fwrite");
181 } 181 }
182 } 182 }
183 if (fclose(out)) error("failed fclose"); 183 if (fclose(out)) error("failed fclose");
184 184
185 if (gzclose(in) != Z_OK) error("failed gzclose"); 185 if (gzclose(in) != Z_OK) error("failed gzclose");
186} 186}
187 187
188 188
189/* =========================================================================== 189/* ===========================================================================
190 * Compress the given file: create a corresponding .gz file and remove the 190 * Compress the given file: create a corresponding .gz file and remove the
191 * original. 191 * original.
192 */ 192 */
193void file_compress(file, mode) 193void file_compress(file, mode)
194 char *file; 194 char *file;
195 char *mode; 195 char *mode;
196{ 196{
197 local char outfile[MAX_NAME_LEN]; 197 local char outfile[MAX_NAME_LEN];
198 FILE *in; 198 FILE *in;
199 gzFile out; 199 gzFile out;
200 200
201 strcpy(outfile, file); 201 strcpy(outfile, file);
202 strcat(outfile, GZ_SUFFIX); 202 strcat(outfile, GZ_SUFFIX);
203 203
204 in = fopen(file, "rb"); 204 in = fopen(file, "rb");
205 if (in == NULL) { 205 if (in == NULL) {
206 perror(file); 206 perror(file);
207 exit(1); 207 exit(1);
208 } 208 }
209 out = gzopen(outfile, mode); 209 out = gzopen(outfile, mode);
210 if (out == NULL) { 210 if (out == NULL) {
211 fprintf(stderr, "%s: can't gzopen %s\n", prog, outfile); 211 fprintf(stderr, "%s: can't gzopen %s\n", prog, outfile);
212 exit(1); 212 exit(1);
213 } 213 }
214 gz_compress(in, out); 214 gz_compress(in, out);
215 215
216 unlink(file); 216 unlink(file);
217} 217}
218 218
219 219
220/* =========================================================================== 220/* ===========================================================================
221 * Uncompress the given file and remove the original. 221 * Uncompress the given file and remove the original.
222 */ 222 */
223void file_uncompress(file) 223void file_uncompress(file)
224 char *file; 224 char *file;
225{ 225{
226 local char buf[MAX_NAME_LEN]; 226 local char buf[MAX_NAME_LEN];
227 char *infile, *outfile; 227 char *infile, *outfile;
228 FILE *out; 228 FILE *out;
229 gzFile in; 229 gzFile in;
230 uInt len = (uInt)strlen(file); 230 uInt len = (uInt)strlen(file);
231 231
232 strcpy(buf, file); 232 strcpy(buf, file);
233 233
234 if (len > SUFFIX_LEN && strcmp(file+len-SUFFIX_LEN, GZ_SUFFIX) == 0) { 234 if (len > SUFFIX_LEN && strcmp(file+len-SUFFIX_LEN, GZ_SUFFIX) == 0) {
235 infile = file; 235 infile = file;
236 outfile = buf; 236 outfile = buf;
237 outfile[len-3] = '\0'; 237 outfile[len-3] = '\0';
238 } else { 238 } else {
239 outfile = file; 239 outfile = file;
240 infile = buf; 240 infile = buf;
241 strcat(infile, GZ_SUFFIX); 241 strcat(infile, GZ_SUFFIX);
242 } 242 }
243 in = gzopen(infile, "rb"); 243 in = gzopen(infile, "rb");
244 if (in == NULL) { 244 if (in == NULL) {
245 fprintf(stderr, "%s: can't gzopen %s\n", prog, infile); 245 fprintf(stderr, "%s: can't gzopen %s\n", prog, infile);
246 exit(1); 246 exit(1);
247 } 247 }
248 out = fopen(outfile, "wb"); 248 out = fopen(outfile, "wb");
249 if (out == NULL) { 249 if (out == NULL) {
250 perror(file); 250 perror(file);
251 exit(1); 251 exit(1);
252 } 252 }
253 253
254 gz_uncompress(in, out); 254 gz_uncompress(in, out);
255 255
256 unlink(infile); 256 unlink(infile);
257} 257}
258 258
259 259
260/* =========================================================================== 260/* ===========================================================================
261 * Usage: minigzip [-d] [-f] [-h] [-r] [-1 to -9] [files...] 261 * Usage: minigzip [-d] [-f] [-h] [-r] [-1 to -9] [files...]
262 * -d : decompress 262 * -d : decompress
263 * -f : compress with Z_FILTERED 263 * -f : compress with Z_FILTERED
264 * -h : compress with Z_HUFFMAN_ONLY 264 * -h : compress with Z_HUFFMAN_ONLY
265 * -r : compress with Z_RLE 265 * -r : compress with Z_RLE
266 * -1 to -9 : compression level 266 * -1 to -9 : compression level
267 */ 267 */
268 268
269int main(argc, argv) 269int main(argc, argv)
270 int argc; 270 int argc;
271 char *argv[]; 271 char *argv[];
272{ 272{
273 int uncompr = 0; 273 int uncompr = 0;
274 gzFile file; 274 gzFile file;
275 char outmode[20]; 275 char outmode[20];
276 276
277 strcpy(outmode, "wb6 "); 277 strcpy(outmode, "wb6 ");
278 278
279 prog = argv[0]; 279 prog = argv[0];
280 argc--, argv++; 280 argc--, argv++;
281 281
282 while (argc > 0) { 282 while (argc > 0) {
283 if (strcmp(*argv, "-d") == 0) 283 if (strcmp(*argv, "-d") == 0)
284 uncompr = 1; 284 uncompr = 1;
285 else if (strcmp(*argv, "-f") == 0) 285 else if (strcmp(*argv, "-f") == 0)
286 outmode[3] = 'f'; 286 outmode[3] = 'f';
287 else if (strcmp(*argv, "-h") == 0) 287 else if (strcmp(*argv, "-h") == 0)
288 outmode[3] = 'h'; 288 outmode[3] = 'h';
289 else if (strcmp(*argv, "-r") == 0) 289 else if (strcmp(*argv, "-r") == 0)
290 outmode[3] = 'R'; 290 outmode[3] = 'R';
291 else if ((*argv)[0] == '-' && (*argv)[1] >= '1' && (*argv)[1] <= '9' && 291 else if ((*argv)[0] == '-' && (*argv)[1] >= '1' && (*argv)[1] <= '9' &&
292 (*argv)[2] == 0) 292 (*argv)[2] == 0)
293 outmode[2] = (*argv)[1]; 293 outmode[2] = (*argv)[1];
294 else 294 else
295 break; 295 break;
296 argc--, argv++; 296 argc--, argv++;
297 } 297 }
298 if (outmode[3] == ' ') 298 if (outmode[3] == ' ')
299 outmode[3] = 0; 299 outmode[3] = 0;
300 if (argc == 0) { 300 if (argc == 0) {
301 SET_BINARY_MODE(stdin); 301 SET_BINARY_MODE(stdin);
302 SET_BINARY_MODE(stdout); 302 SET_BINARY_MODE(stdout);
303 if (uncompr) { 303 if (uncompr) {
304 file = gzdopen(fileno(stdin), "rb"); 304 file = gzdopen(fileno(stdin), "rb");
305 if (file == NULL) error("can't gzdopen stdin"); 305 if (file == NULL) error("can't gzdopen stdin");
306 gz_uncompress(file, stdout); 306 gz_uncompress(file, stdout);
307 } else { 307 } else {
308 file = gzdopen(fileno(stdout), outmode); 308 file = gzdopen(fileno(stdout), outmode);
309 if (file == NULL) error("can't gzdopen stdout"); 309 if (file == NULL) error("can't gzdopen stdout");
310 gz_compress(stdin, file); 310 gz_compress(stdin, file);
311 } 311 }
312 } else { 312 } else {
313 do { 313 do {
314 if (uncompr) { 314 if (uncompr) {
315 file_uncompress(*argv); 315 file_uncompress(*argv);
316 } else { 316 } else {
317 file_compress(*argv, outmode); 317 file_compress(*argv, outmode);
318 } 318 }
319 } while (argv++, --argc); 319 } while (argv++, --argc);
320 } 320 }
321 return 0; 321 return 0;
322} 322}
diff --git a/utils/zenutils/libraries/zlib123/zlib/trees.c b/utils/zenutils/libraries/zlib123/zlib/trees.c
index 7a04802862..395e4e1681 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/trees.c
+++ b/utils/zenutils/libraries/zlib123/zlib/trees.c
@@ -1,1219 +1,1219 @@
1/* trees.c -- output deflated data using Huffman coding 1/* trees.c -- output deflated data using Huffman coding
2 * Copyright (C) 1995-2005 Jean-loup Gailly 2 * Copyright (C) 1995-2005 Jean-loup Gailly
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6/* 6/*
7 * ALGORITHM 7 * ALGORITHM
8 * 8 *
9 * The "deflation" process uses several Huffman trees. The more 9 * The "deflation" process uses several Huffman trees. The more
10 * common source values are represented by shorter bit sequences. 10 * common source values are represented by shorter bit sequences.
11 * 11 *
12 * Each code tree is stored in a compressed form which is itself 12 * Each code tree is stored in a compressed form which is itself
13 * a Huffman encoding of the lengths of all the code strings (in 13 * a Huffman encoding of the lengths of all the code strings (in
14 * ascending order by source values). The actual code strings are 14 * ascending order by source values). The actual code strings are
15 * reconstructed from the lengths in the inflate process, as described 15 * reconstructed from the lengths in the inflate process, as described
16 * in the deflate specification. 16 * in the deflate specification.
17 * 17 *
18 * REFERENCES 18 * REFERENCES
19 * 19 *
20 * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". 20 * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
21 * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc 21 * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
22 * 22 *
23 * Storer, James A. 23 * Storer, James A.
24 * Data Compression: Methods and Theory, pp. 49-50. 24 * Data Compression: Methods and Theory, pp. 49-50.
25 * Computer Science Press, 1988. ISBN 0-7167-8156-5. 25 * Computer Science Press, 1988. ISBN 0-7167-8156-5.
26 * 26 *
27 * Sedgewick, R. 27 * Sedgewick, R.
28 * Algorithms, p290. 28 * Algorithms, p290.
29 * Addison-Wesley, 1983. ISBN 0-201-06672-6. 29 * Addison-Wesley, 1983. ISBN 0-201-06672-6.
30 */ 30 */
31 31
32/* @(#) $Id$ */ 32/* @(#) $Id$ */
33 33
34/* #define GEN_TREES_H */ 34/* #define GEN_TREES_H */
35 35
36#include "deflate.h" 36#include "deflate.h"
37 37
38#ifdef DEBUG 38#ifdef DEBUG
39# include <ctype.h> 39# include <ctype.h>
40#endif 40#endif
41 41
42/* =========================================================================== 42/* ===========================================================================
43 * Constants 43 * Constants
44 */ 44 */
45 45
46#define MAX_BL_BITS 7 46#define MAX_BL_BITS 7
47/* Bit length codes must not exceed MAX_BL_BITS bits */ 47/* Bit length codes must not exceed MAX_BL_BITS bits */
48 48
49#define END_BLOCK 256 49#define END_BLOCK 256
50/* end of block literal code */ 50/* end of block literal code */
51 51
52#define REP_3_6 16 52#define REP_3_6 16
53/* repeat previous bit length 3-6 times (2 bits of repeat count) */ 53/* repeat previous bit length 3-6 times (2 bits of repeat count) */
54 54
55#define REPZ_3_10 17 55#define REPZ_3_10 17
56/* repeat a zero length 3-10 times (3 bits of repeat count) */ 56/* repeat a zero length 3-10 times (3 bits of repeat count) */
57 57
58#define REPZ_11_138 18 58#define REPZ_11_138 18
59/* repeat a zero length 11-138 times (7 bits of repeat count) */ 59/* repeat a zero length 11-138 times (7 bits of repeat count) */
60 60
61local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ 61local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
62 = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; 62 = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
63 63
64local const int extra_dbits[D_CODES] /* extra bits for each distance code */ 64local const int extra_dbits[D_CODES] /* extra bits for each distance code */
65 = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; 65 = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
66 66
67local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ 67local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
68 = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; 68 = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
69 69
70local const uch bl_order[BL_CODES] 70local const uch bl_order[BL_CODES]
71 = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; 71 = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
72/* The lengths of the bit length codes are sent in order of decreasing 72/* The lengths of the bit length codes are sent in order of decreasing
73 * probability, to avoid transmitting the lengths for unused bit length codes. 73 * probability, to avoid transmitting the lengths for unused bit length codes.
74 */ 74 */
75 75
76#define Buf_size (8 * 2*sizeof(char)) 76#define Buf_size (8 * 2*sizeof(char))
77/* Number of bits used within bi_buf. (bi_buf might be implemented on 77/* Number of bits used within bi_buf. (bi_buf might be implemented on
78 * more than 16 bits on some systems.) 78 * more than 16 bits on some systems.)
79 */ 79 */
80 80
81/* =========================================================================== 81/* ===========================================================================
82 * Local data. These are initialized only once. 82 * Local data. These are initialized only once.
83 */ 83 */
84 84
85#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ 85#define DIST_CODE_LEN 512 /* see definition of array dist_code below */
86 86
87#if defined(GEN_TREES_H) || !defined(STDC) 87#if defined(GEN_TREES_H) || !defined(STDC)
88/* non ANSI compilers may not accept trees.h */ 88/* non ANSI compilers may not accept trees.h */
89 89
90local ct_data static_ltree[L_CODES+2]; 90local ct_data static_ltree[L_CODES+2];
91/* The static literal tree. Since the bit lengths are imposed, there is no 91/* The static literal tree. Since the bit lengths are imposed, there is no
92 * need for the L_CODES extra codes used during heap construction. However 92 * need for the L_CODES extra codes used during heap construction. However
93 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init 93 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
94 * below). 94 * below).
95 */ 95 */
96 96
97local ct_data static_dtree[D_CODES]; 97local ct_data static_dtree[D_CODES];
98/* The static distance tree. (Actually a trivial tree since all codes use 98/* The static distance tree. (Actually a trivial tree since all codes use
99 * 5 bits.) 99 * 5 bits.)
100 */ 100 */
101 101
102uch _dist_code[DIST_CODE_LEN]; 102uch _dist_code[DIST_CODE_LEN];
103/* Distance codes. The first 256 values correspond to the distances 103/* Distance codes. The first 256 values correspond to the distances
104 * 3 .. 258, the last 256 values correspond to the top 8 bits of 104 * 3 .. 258, the last 256 values correspond to the top 8 bits of
105 * the 15 bit distances. 105 * the 15 bit distances.
106 */ 106 */
107 107
108uch _length_code[MAX_MATCH-MIN_MATCH+1]; 108uch _length_code[MAX_MATCH-MIN_MATCH+1];
109/* length code for each normalized match length (0 == MIN_MATCH) */ 109/* length code for each normalized match length (0 == MIN_MATCH) */
110 110
111local int base_length[LENGTH_CODES]; 111local int base_length[LENGTH_CODES];
112/* First normalized length for each code (0 = MIN_MATCH) */ 112/* First normalized length for each code (0 = MIN_MATCH) */
113 113
114local int base_dist[D_CODES]; 114local int base_dist[D_CODES];
115/* First normalized distance for each code (0 = distance of 1) */ 115/* First normalized distance for each code (0 = distance of 1) */
116 116
117#else 117#else
118# include "trees.h" 118# include "trees.h"
119#endif /* GEN_TREES_H */ 119#endif /* GEN_TREES_H */
120 120
121struct static_tree_desc_s { 121struct static_tree_desc_s {
122 const ct_data *static_tree; /* static tree or NULL */ 122 const ct_data *static_tree; /* static tree or NULL */
123 const intf *extra_bits; /* extra bits for each code or NULL */ 123 const intf *extra_bits; /* extra bits for each code or NULL */
124 int extra_base; /* base index for extra_bits */ 124 int extra_base; /* base index for extra_bits */
125 int elems; /* max number of elements in the tree */ 125 int elems; /* max number of elements in the tree */
126 int max_length; /* max bit length for the codes */ 126 int max_length; /* max bit length for the codes */
127}; 127};
128 128
129local static_tree_desc static_l_desc = 129local static_tree_desc static_l_desc =
130{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; 130{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
131 131
132local static_tree_desc static_d_desc = 132local static_tree_desc static_d_desc =
133{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; 133{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
134 134
135local static_tree_desc static_bl_desc = 135local static_tree_desc static_bl_desc =
136{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; 136{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
137 137
138/* =========================================================================== 138/* ===========================================================================
139 * Local (static) routines in this file. 139 * Local (static) routines in this file.
140 */ 140 */
141 141
142local void tr_static_init OF((void)); 142local void tr_static_init OF((void));
143local void init_block OF((deflate_state *s)); 143local void init_block OF((deflate_state *s));
144local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); 144local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
145local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); 145local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
146local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); 146local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
147local void build_tree OF((deflate_state *s, tree_desc *desc)); 147local void build_tree OF((deflate_state *s, tree_desc *desc));
148local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); 148local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
149local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); 149local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
150local int build_bl_tree OF((deflate_state *s)); 150local int build_bl_tree OF((deflate_state *s));
151local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, 151local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
152 int blcodes)); 152 int blcodes));
153local void compress_block OF((deflate_state *s, ct_data *ltree, 153local void compress_block OF((deflate_state *s, ct_data *ltree,
154 ct_data *dtree)); 154 ct_data *dtree));
155local void set_data_type OF((deflate_state *s)); 155local void set_data_type OF((deflate_state *s));
156local unsigned bi_reverse OF((unsigned value, int length)); 156local unsigned bi_reverse OF((unsigned value, int length));
157local void bi_windup OF((deflate_state *s)); 157local void bi_windup OF((deflate_state *s));
158local void bi_flush OF((deflate_state *s)); 158local void bi_flush OF((deflate_state *s));
159local void copy_block OF((deflate_state *s, charf *buf, unsigned len, 159local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
160 int header)); 160 int header));
161 161
162#ifdef GEN_TREES_H 162#ifdef GEN_TREES_H
163local void gen_trees_header OF((void)); 163local void gen_trees_header OF((void));
164#endif 164#endif
165 165
166#ifndef DEBUG 166#ifndef DEBUG
167# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) 167# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
168 /* Send a code of the given tree. c and tree must not have side effects */ 168 /* Send a code of the given tree. c and tree must not have side effects */
169 169
170#else /* DEBUG */ 170#else /* DEBUG */
171# define send_code(s, c, tree) \ 171# define send_code(s, c, tree) \
172 { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ 172 { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
173 send_bits(s, tree[c].Code, tree[c].Len); } 173 send_bits(s, tree[c].Code, tree[c].Len); }
174#endif 174#endif
175 175
176/* =========================================================================== 176/* ===========================================================================
177 * Output a short LSB first on the stream. 177 * Output a short LSB first on the stream.
178 * IN assertion: there is enough room in pendingBuf. 178 * IN assertion: there is enough room in pendingBuf.
179 */ 179 */
180#define put_short(s, w) { \ 180#define put_short(s, w) { \
181 put_byte(s, (uch)((w) & 0xff)); \ 181 put_byte(s, (uch)((w) & 0xff)); \
182 put_byte(s, (uch)((ush)(w) >> 8)); \ 182 put_byte(s, (uch)((ush)(w) >> 8)); \
183} 183}
184 184
185/* =========================================================================== 185/* ===========================================================================
186 * Send a value on a given number of bits. 186 * Send a value on a given number of bits.
187 * IN assertion: length <= 16 and value fits in length bits. 187 * IN assertion: length <= 16 and value fits in length bits.
188 */ 188 */
189#ifdef DEBUG 189#ifdef DEBUG
190local void send_bits OF((deflate_state *s, int value, int length)); 190local void send_bits OF((deflate_state *s, int value, int length));
191 191
192local void send_bits(s, value, length) 192local void send_bits(s, value, length)
193 deflate_state *s; 193 deflate_state *s;
194 int value; /* value to send */ 194 int value; /* value to send */
195 int length; /* number of bits */ 195 int length; /* number of bits */
196{ 196{
197 Tracevv((stderr," l %2d v %4x ", length, value)); 197 Tracevv((stderr," l %2d v %4x ", length, value));
198 Assert(length > 0 && length <= 15, "invalid length"); 198 Assert(length > 0 && length <= 15, "invalid length");
199 s->bits_sent += (ulg)length; 199 s->bits_sent += (ulg)length;
200 200
201 /* If not enough room in bi_buf, use (valid) bits from bi_buf and 201 /* If not enough room in bi_buf, use (valid) bits from bi_buf and
202 * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) 202 * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
203 * unused bits in value. 203 * unused bits in value.
204 */ 204 */
205 if (s->bi_valid > (int)Buf_size - length) { 205 if (s->bi_valid > (int)Buf_size - length) {
206 s->bi_buf |= (value << s->bi_valid); 206 s->bi_buf |= (value << s->bi_valid);
207 put_short(s, s->bi_buf); 207 put_short(s, s->bi_buf);
208 s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); 208 s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
209 s->bi_valid += length - Buf_size; 209 s->bi_valid += length - Buf_size;
210 } else { 210 } else {
211 s->bi_buf |= value << s->bi_valid; 211 s->bi_buf |= value << s->bi_valid;
212 s->bi_valid += length; 212 s->bi_valid += length;
213 } 213 }
214} 214}
215#else /* !DEBUG */ 215#else /* !DEBUG */
216 216
217#define send_bits(s, value, length) \ 217#define send_bits(s, value, length) \
218{ int len = length;\ 218{ int len = length;\
219 if (s->bi_valid > (int)Buf_size - len) {\ 219 if (s->bi_valid > (int)Buf_size - len) {\
220 int val = value;\ 220 int val = value;\
221 s->bi_buf |= (val << s->bi_valid);\ 221 s->bi_buf |= (val << s->bi_valid);\
222 put_short(s, s->bi_buf);\ 222 put_short(s, s->bi_buf);\
223 s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ 223 s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
224 s->bi_valid += len - Buf_size;\ 224 s->bi_valid += len - Buf_size;\
225 } else {\ 225 } else {\
226 s->bi_buf |= (value) << s->bi_valid;\ 226 s->bi_buf |= (value) << s->bi_valid;\
227 s->bi_valid += len;\ 227 s->bi_valid += len;\
228 }\ 228 }\
229} 229}
230#endif /* DEBUG */ 230#endif /* DEBUG */
231 231
232 232
233/* the arguments must not have side effects */ 233/* the arguments must not have side effects */
234 234
235/* =========================================================================== 235/* ===========================================================================
236 * Initialize the various 'constant' tables. 236 * Initialize the various 'constant' tables.
237 */ 237 */
238local void tr_static_init() 238local void tr_static_init()
239{ 239{
240#if defined(GEN_TREES_H) || !defined(STDC) 240#if defined(GEN_TREES_H) || !defined(STDC)
241 static int static_init_done = 0; 241 static int static_init_done = 0;
242 int n; /* iterates over tree elements */ 242 int n; /* iterates over tree elements */
243 int bits; /* bit counter */ 243 int bits; /* bit counter */
244 int length; /* length value */ 244 int length; /* length value */
245 int code; /* code value */ 245 int code; /* code value */
246 int dist; /* distance index */ 246 int dist; /* distance index */
247 ush bl_count[MAX_BITS+1]; 247 ush bl_count[MAX_BITS+1];
248 /* number of codes at each bit length for an optimal tree */ 248 /* number of codes at each bit length for an optimal tree */
249 249
250 if (static_init_done) return; 250 if (static_init_done) return;
251 251
252 /* For some embedded targets, global variables are not initialized: */ 252 /* For some embedded targets, global variables are not initialized: */
253 static_l_desc.static_tree = static_ltree; 253 static_l_desc.static_tree = static_ltree;
254 static_l_desc.extra_bits = extra_lbits; 254 static_l_desc.extra_bits = extra_lbits;
255 static_d_desc.static_tree = static_dtree; 255 static_d_desc.static_tree = static_dtree;
256 static_d_desc.extra_bits = extra_dbits; 256 static_d_desc.extra_bits = extra_dbits;
257 static_bl_desc.extra_bits = extra_blbits; 257 static_bl_desc.extra_bits = extra_blbits;
258 258
259 /* Initialize the mapping length (0..255) -> length code (0..28) */ 259 /* Initialize the mapping length (0..255) -> length code (0..28) */
260 length = 0; 260 length = 0;
261 for (code = 0; code < LENGTH_CODES-1; code++) { 261 for (code = 0; code < LENGTH_CODES-1; code++) {
262 base_length[code] = length; 262 base_length[code] = length;
263 for (n = 0; n < (1<<extra_lbits[code]); n++) { 263 for (n = 0; n < (1<<extra_lbits[code]); n++) {
264 _length_code[length++] = (uch)code; 264 _length_code[length++] = (uch)code;
265 } 265 }
266 } 266 }
267 Assert (length == 256, "tr_static_init: length != 256"); 267 Assert (length == 256, "tr_static_init: length != 256");
268 /* Note that the length 255 (match length 258) can be represented 268 /* Note that the length 255 (match length 258) can be represented
269 * in two different ways: code 284 + 5 bits or code 285, so we 269 * in two different ways: code 284 + 5 bits or code 285, so we
270 * overwrite length_code[255] to use the best encoding: 270 * overwrite length_code[255] to use the best encoding:
271 */ 271 */
272 _length_code[length-1] = (uch)code; 272 _length_code[length-1] = (uch)code;
273 273
274 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ 274 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
275 dist = 0; 275 dist = 0;
276 for (code = 0 ; code < 16; code++) { 276 for (code = 0 ; code < 16; code++) {
277 base_dist[code] = dist; 277 base_dist[code] = dist;
278 for (n = 0; n < (1<<extra_dbits[code]); n++) { 278 for (n = 0; n < (1<<extra_dbits[code]); n++) {
279 _dist_code[dist++] = (uch)code; 279 _dist_code[dist++] = (uch)code;
280 } 280 }
281 } 281 }
282 Assert (dist == 256, "tr_static_init: dist != 256"); 282 Assert (dist == 256, "tr_static_init: dist != 256");
283 dist >>= 7; /* from now on, all distances are divided by 128 */ 283 dist >>= 7; /* from now on, all distances are divided by 128 */
284 for ( ; code < D_CODES; code++) { 284 for ( ; code < D_CODES; code++) {
285 base_dist[code] = dist << 7; 285 base_dist[code] = dist << 7;
286 for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { 286 for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
287 _dist_code[256 + dist++] = (uch)code; 287 _dist_code[256 + dist++] = (uch)code;
288 } 288 }
289 } 289 }
290 Assert (dist == 256, "tr_static_init: 256+dist != 512"); 290 Assert (dist == 256, "tr_static_init: 256+dist != 512");
291 291
292 /* Construct the codes of the static literal tree */ 292 /* Construct the codes of the static literal tree */
293 for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; 293 for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
294 n = 0; 294 n = 0;
295 while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; 295 while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
296 while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; 296 while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
297 while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; 297 while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
298 while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; 298 while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
299 /* Codes 286 and 287 do not exist, but we must include them in the 299 /* Codes 286 and 287 do not exist, but we must include them in the
300 * tree construction to get a canonical Huffman tree (longest code 300 * tree construction to get a canonical Huffman tree (longest code
301 * all ones) 301 * all ones)
302 */ 302 */
303 gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); 303 gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
304 304
305 /* The static distance tree is trivial: */ 305 /* The static distance tree is trivial: */
306 for (n = 0; n < D_CODES; n++) { 306 for (n = 0; n < D_CODES; n++) {
307 static_dtree[n].Len = 5; 307 static_dtree[n].Len = 5;
308 static_dtree[n].Code = bi_reverse((unsigned)n, 5); 308 static_dtree[n].Code = bi_reverse((unsigned)n, 5);
309 } 309 }
310 static_init_done = 1; 310 static_init_done = 1;
311 311
312# ifdef GEN_TREES_H 312# ifdef GEN_TREES_H
313 gen_trees_header(); 313 gen_trees_header();
314# endif 314# endif
315#endif /* defined(GEN_TREES_H) || !defined(STDC) */ 315#endif /* defined(GEN_TREES_H) || !defined(STDC) */
316} 316}
317 317
318/* =========================================================================== 318/* ===========================================================================
319 * Genererate the file trees.h describing the static trees. 319 * Genererate the file trees.h describing the static trees.
320 */ 320 */
321#ifdef GEN_TREES_H 321#ifdef GEN_TREES_H
322# ifndef DEBUG 322# ifndef DEBUG
323# include <stdio.h> 323# include <stdio.h>
324# endif 324# endif
325 325
326# define SEPARATOR(i, last, width) \ 326# define SEPARATOR(i, last, width) \
327 ((i) == (last)? "\n};\n\n" : \ 327 ((i) == (last)? "\n};\n\n" : \
328 ((i) % (width) == (width)-1 ? ",\n" : ", ")) 328 ((i) % (width) == (width)-1 ? ",\n" : ", "))
329 329
330void gen_trees_header() 330void gen_trees_header()
331{ 331{
332 FILE *header = fopen("trees.h", "w"); 332 FILE *header = fopen("trees.h", "w");
333 int i; 333 int i;
334 334
335 Assert (header != NULL, "Can't open trees.h"); 335 Assert (header != NULL, "Can't open trees.h");
336 fprintf(header, 336 fprintf(header,
337 "/* header created automatically with -DGEN_TREES_H */\n\n"); 337 "/* header created automatically with -DGEN_TREES_H */\n\n");
338 338
339 fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); 339 fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
340 for (i = 0; i < L_CODES+2; i++) { 340 for (i = 0; i < L_CODES+2; i++) {
341 fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, 341 fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
342 static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); 342 static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
343 } 343 }
344 344
345 fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); 345 fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
346 for (i = 0; i < D_CODES; i++) { 346 for (i = 0; i < D_CODES; i++) {
347 fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, 347 fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
348 static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); 348 static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
349 } 349 }
350 350
351 fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n"); 351 fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
352 for (i = 0; i < DIST_CODE_LEN; i++) { 352 for (i = 0; i < DIST_CODE_LEN; i++) {
353 fprintf(header, "%2u%s", _dist_code[i], 353 fprintf(header, "%2u%s", _dist_code[i],
354 SEPARATOR(i, DIST_CODE_LEN-1, 20)); 354 SEPARATOR(i, DIST_CODE_LEN-1, 20));
355 } 355 }
356 356
357 fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); 357 fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
358 for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { 358 for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
359 fprintf(header, "%2u%s", _length_code[i], 359 fprintf(header, "%2u%s", _length_code[i],
360 SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); 360 SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
361 } 361 }
362 362
363 fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); 363 fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
364 for (i = 0; i < LENGTH_CODES; i++) { 364 for (i = 0; i < LENGTH_CODES; i++) {
365 fprintf(header, "%1u%s", base_length[i], 365 fprintf(header, "%1u%s", base_length[i],
366 SEPARATOR(i, LENGTH_CODES-1, 20)); 366 SEPARATOR(i, LENGTH_CODES-1, 20));
367 } 367 }
368 368
369 fprintf(header, "local const int base_dist[D_CODES] = {\n"); 369 fprintf(header, "local const int base_dist[D_CODES] = {\n");
370 for (i = 0; i < D_CODES; i++) { 370 for (i = 0; i < D_CODES; i++) {
371 fprintf(header, "%5u%s", base_dist[i], 371 fprintf(header, "%5u%s", base_dist[i],
372 SEPARATOR(i, D_CODES-1, 10)); 372 SEPARATOR(i, D_CODES-1, 10));
373 } 373 }
374 374
375 fclose(header); 375 fclose(header);
376} 376}
377#endif /* GEN_TREES_H */ 377#endif /* GEN_TREES_H */
378 378
379/* =========================================================================== 379/* ===========================================================================
380 * Initialize the tree data structures for a new zlib stream. 380 * Initialize the tree data structures for a new zlib stream.
381 */ 381 */
382void _tr_init(s) 382void _tr_init(s)
383 deflate_state *s; 383 deflate_state *s;
384{ 384{
385 tr_static_init(); 385 tr_static_init();
386 386
387 s->l_desc.dyn_tree = s->dyn_ltree; 387 s->l_desc.dyn_tree = s->dyn_ltree;
388 s->l_desc.stat_desc = &static_l_desc; 388 s->l_desc.stat_desc = &static_l_desc;
389 389
390 s->d_desc.dyn_tree = s->dyn_dtree; 390 s->d_desc.dyn_tree = s->dyn_dtree;
391 s->d_desc.stat_desc = &static_d_desc; 391 s->d_desc.stat_desc = &static_d_desc;
392 392
393 s->bl_desc.dyn_tree = s->bl_tree; 393 s->bl_desc.dyn_tree = s->bl_tree;
394 s->bl_desc.stat_desc = &static_bl_desc; 394 s->bl_desc.stat_desc = &static_bl_desc;
395 395
396 s->bi_buf = 0; 396 s->bi_buf = 0;
397 s->bi_valid = 0; 397 s->bi_valid = 0;
398 s->last_eob_len = 8; /* enough lookahead for inflate */ 398 s->last_eob_len = 8; /* enough lookahead for inflate */
399#ifdef DEBUG 399#ifdef DEBUG
400 s->compressed_len = 0L; 400 s->compressed_len = 0L;
401 s->bits_sent = 0L; 401 s->bits_sent = 0L;
402#endif 402#endif
403 403
404 /* Initialize the first block of the first file: */ 404 /* Initialize the first block of the first file: */
405 init_block(s); 405 init_block(s);
406} 406}
407 407
408/* =========================================================================== 408/* ===========================================================================
409 * Initialize a new block. 409 * Initialize a new block.
410 */ 410 */
411local void init_block(s) 411local void init_block(s)
412 deflate_state *s; 412 deflate_state *s;
413{ 413{
414 int n; /* iterates over tree elements */ 414 int n; /* iterates over tree elements */
415 415
416 /* Initialize the trees. */ 416 /* Initialize the trees. */
417 for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; 417 for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
418 for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; 418 for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
419 for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; 419 for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
420 420
421 s->dyn_ltree[END_BLOCK].Freq = 1; 421 s->dyn_ltree[END_BLOCK].Freq = 1;
422 s->opt_len = s->static_len = 0L; 422 s->opt_len = s->static_len = 0L;
423 s->last_lit = s->matches = 0; 423 s->last_lit = s->matches = 0;
424} 424}
425 425
426#define SMALLEST 1 426#define SMALLEST 1
427/* Index within the heap array of least frequent node in the Huffman tree */ 427/* Index within the heap array of least frequent node in the Huffman tree */
428 428
429 429
430/* =========================================================================== 430/* ===========================================================================
431 * Remove the smallest element from the heap and recreate the heap with 431 * Remove the smallest element from the heap and recreate the heap with
432 * one less element. Updates heap and heap_len. 432 * one less element. Updates heap and heap_len.
433 */ 433 */
434#define pqremove(s, tree, top) \ 434#define pqremove(s, tree, top) \
435{\ 435{\
436 top = s->heap[SMALLEST]; \ 436 top = s->heap[SMALLEST]; \
437 s->heap[SMALLEST] = s->heap[s->heap_len--]; \ 437 s->heap[SMALLEST] = s->heap[s->heap_len--]; \
438 pqdownheap(s, tree, SMALLEST); \ 438 pqdownheap(s, tree, SMALLEST); \
439} 439}
440 440
441/* =========================================================================== 441/* ===========================================================================
442 * Compares to subtrees, using the tree depth as tie breaker when 442 * Compares to subtrees, using the tree depth as tie breaker when
443 * the subtrees have equal frequency. This minimizes the worst case length. 443 * the subtrees have equal frequency. This minimizes the worst case length.
444 */ 444 */
445#define smaller(tree, n, m, depth) \ 445#define smaller(tree, n, m, depth) \
446 (tree[n].Freq < tree[m].Freq || \ 446 (tree[n].Freq < tree[m].Freq || \
447 (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) 447 (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
448 448
449/* =========================================================================== 449/* ===========================================================================
450 * Restore the heap property by moving down the tree starting at node k, 450 * Restore the heap property by moving down the tree starting at node k,
451 * exchanging a node with the smallest of its two sons if necessary, stopping 451 * exchanging a node with the smallest of its two sons if necessary, stopping
452 * when the heap property is re-established (each father smaller than its 452 * when the heap property is re-established (each father smaller than its
453 * two sons). 453 * two sons).
454 */ 454 */
455local void pqdownheap(s, tree, k) 455local void pqdownheap(s, tree, k)
456 deflate_state *s; 456 deflate_state *s;
457 ct_data *tree; /* the tree to restore */ 457 ct_data *tree; /* the tree to restore */
458 int k; /* node to move down */ 458 int k; /* node to move down */
459{ 459{
460 int v = s->heap[k]; 460 int v = s->heap[k];
461 int j = k << 1; /* left son of k */ 461 int j = k << 1; /* left son of k */
462 while (j <= s->heap_len) { 462 while (j <= s->heap_len) {
463 /* Set j to the smallest of the two sons: */ 463 /* Set j to the smallest of the two sons: */
464 if (j < s->heap_len && 464 if (j < s->heap_len &&
465 smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { 465 smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
466 j++; 466 j++;
467 } 467 }
468 /* Exit if v is smaller than both sons */ 468 /* Exit if v is smaller than both sons */
469 if (smaller(tree, v, s->heap[j], s->depth)) break; 469 if (smaller(tree, v, s->heap[j], s->depth)) break;
470 470
471 /* Exchange v with the smallest son */ 471 /* Exchange v with the smallest son */
472 s->heap[k] = s->heap[j]; k = j; 472 s->heap[k] = s->heap[j]; k = j;
473 473
474 /* And continue down the tree, setting j to the left son of k */ 474 /* And continue down the tree, setting j to the left son of k */
475 j <<= 1; 475 j <<= 1;
476 } 476 }
477 s->heap[k] = v; 477 s->heap[k] = v;
478} 478}
479 479
480/* =========================================================================== 480/* ===========================================================================
481 * Compute the optimal bit lengths for a tree and update the total bit length 481 * Compute the optimal bit lengths for a tree and update the total bit length
482 * for the current block. 482 * for the current block.
483 * IN assertion: the fields freq and dad are set, heap[heap_max] and 483 * IN assertion: the fields freq and dad are set, heap[heap_max] and
484 * above are the tree nodes sorted by increasing frequency. 484 * above are the tree nodes sorted by increasing frequency.
485 * OUT assertions: the field len is set to the optimal bit length, the 485 * OUT assertions: the field len is set to the optimal bit length, the
486 * array bl_count contains the frequencies for each bit length. 486 * array bl_count contains the frequencies for each bit length.
487 * The length opt_len is updated; static_len is also updated if stree is 487 * The length opt_len is updated; static_len is also updated if stree is
488 * not null. 488 * not null.
489 */ 489 */
490local void gen_bitlen(s, desc) 490local void gen_bitlen(s, desc)
491 deflate_state *s; 491 deflate_state *s;
492 tree_desc *desc; /* the tree descriptor */ 492 tree_desc *desc; /* the tree descriptor */
493{ 493{
494 ct_data *tree = desc->dyn_tree; 494 ct_data *tree = desc->dyn_tree;
495 int max_code = desc->max_code; 495 int max_code = desc->max_code;
496 const ct_data *stree = desc->stat_desc->static_tree; 496 const ct_data *stree = desc->stat_desc->static_tree;
497 const intf *extra = desc->stat_desc->extra_bits; 497 const intf *extra = desc->stat_desc->extra_bits;
498 int base = desc->stat_desc->extra_base; 498 int base = desc->stat_desc->extra_base;
499 int max_length = desc->stat_desc->max_length; 499 int max_length = desc->stat_desc->max_length;
500 int h; /* heap index */ 500 int h; /* heap index */
501 int n, m; /* iterate over the tree elements */ 501 int n, m; /* iterate over the tree elements */
502 int bits; /* bit length */ 502 int bits; /* bit length */
503 int xbits; /* extra bits */ 503 int xbits; /* extra bits */
504 ush f; /* frequency */ 504 ush f; /* frequency */
505 int overflow = 0; /* number of elements with bit length too large */ 505 int overflow = 0; /* number of elements with bit length too large */
506 506
507 for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; 507 for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
508 508
509 /* In a first pass, compute the optimal bit lengths (which may 509 /* In a first pass, compute the optimal bit lengths (which may
510 * overflow in the case of the bit length tree). 510 * overflow in the case of the bit length tree).
511 */ 511 */
512 tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ 512 tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
513 513
514 for (h = s->heap_max+1; h < HEAP_SIZE; h++) { 514 for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
515 n = s->heap[h]; 515 n = s->heap[h];
516 bits = tree[tree[n].Dad].Len + 1; 516 bits = tree[tree[n].Dad].Len + 1;
517 if (bits > max_length) bits = max_length, overflow++; 517 if (bits > max_length) bits = max_length, overflow++;
518 tree[n].Len = (ush)bits; 518 tree[n].Len = (ush)bits;
519 /* We overwrite tree[n].Dad which is no longer needed */ 519 /* We overwrite tree[n].Dad which is no longer needed */
520 520
521 if (n > max_code) continue; /* not a leaf node */ 521 if (n > max_code) continue; /* not a leaf node */
522 522
523 s->bl_count[bits]++; 523 s->bl_count[bits]++;
524 xbits = 0; 524 xbits = 0;
525 if (n >= base) xbits = extra[n-base]; 525 if (n >= base) xbits = extra[n-base];
526 f = tree[n].Freq; 526 f = tree[n].Freq;
527 s->opt_len += (ulg)f * (bits + xbits); 527 s->opt_len += (ulg)f * (bits + xbits);
528 if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); 528 if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
529 } 529 }
530 if (overflow == 0) return; 530 if (overflow == 0) return;
531 531
532 Trace((stderr,"\nbit length overflow\n")); 532 Trace((stderr,"\nbit length overflow\n"));
533 /* This happens for example on obj2 and pic of the Calgary corpus */ 533 /* This happens for example on obj2 and pic of the Calgary corpus */
534 534
535 /* Find the first bit length which could increase: */ 535 /* Find the first bit length which could increase: */
536 do { 536 do {
537 bits = max_length-1; 537 bits = max_length-1;
538 while (s->bl_count[bits] == 0) bits--; 538 while (s->bl_count[bits] == 0) bits--;
539 s->bl_count[bits]--; /* move one leaf down the tree */ 539 s->bl_count[bits]--; /* move one leaf down the tree */
540 s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ 540 s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
541 s->bl_count[max_length]--; 541 s->bl_count[max_length]--;
542 /* The brother of the overflow item also moves one step up, 542 /* The brother of the overflow item also moves one step up,
543 * but this does not affect bl_count[max_length] 543 * but this does not affect bl_count[max_length]
544 */ 544 */
545 overflow -= 2; 545 overflow -= 2;
546 } while (overflow > 0); 546 } while (overflow > 0);
547 547
548 /* Now recompute all bit lengths, scanning in increasing frequency. 548 /* Now recompute all bit lengths, scanning in increasing frequency.
549 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all 549 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
550 * lengths instead of fixing only the wrong ones. This idea is taken 550 * lengths instead of fixing only the wrong ones. This idea is taken
551 * from 'ar' written by Haruhiko Okumura.) 551 * from 'ar' written by Haruhiko Okumura.)
552 */ 552 */
553 for (bits = max_length; bits != 0; bits--) { 553 for (bits = max_length; bits != 0; bits--) {
554 n = s->bl_count[bits]; 554 n = s->bl_count[bits];
555 while (n != 0) { 555 while (n != 0) {
556 m = s->heap[--h]; 556 m = s->heap[--h];
557 if (m > max_code) continue; 557 if (m > max_code) continue;
558 if ((unsigned) tree[m].Len != (unsigned) bits) { 558 if ((unsigned) tree[m].Len != (unsigned) bits) {
559 Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); 559 Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
560 s->opt_len += ((long)bits - (long)tree[m].Len) 560 s->opt_len += ((long)bits - (long)tree[m].Len)
561 *(long)tree[m].Freq; 561 *(long)tree[m].Freq;
562 tree[m].Len = (ush)bits; 562 tree[m].Len = (ush)bits;
563 } 563 }
564 n--; 564 n--;
565 } 565 }
566 } 566 }
567} 567}
568 568
569/* =========================================================================== 569/* ===========================================================================
570 * Generate the codes for a given tree and bit counts (which need not be 570 * Generate the codes for a given tree and bit counts (which need not be
571 * optimal). 571 * optimal).
572 * IN assertion: the array bl_count contains the bit length statistics for 572 * IN assertion: the array bl_count contains the bit length statistics for
573 * the given tree and the field len is set for all tree elements. 573 * the given tree and the field len is set for all tree elements.
574 * OUT assertion: the field code is set for all tree elements of non 574 * OUT assertion: the field code is set for all tree elements of non
575 * zero code length. 575 * zero code length.
576 */ 576 */
577local void gen_codes (tree, max_code, bl_count) 577local void gen_codes (tree, max_code, bl_count)
578 ct_data *tree; /* the tree to decorate */ 578 ct_data *tree; /* the tree to decorate */
579 int max_code; /* largest code with non zero frequency */ 579 int max_code; /* largest code with non zero frequency */
580 ushf *bl_count; /* number of codes at each bit length */ 580 ushf *bl_count; /* number of codes at each bit length */
581{ 581{
582 ush next_code[MAX_BITS+1]; /* next code value for each bit length */ 582 ush next_code[MAX_BITS+1]; /* next code value for each bit length */
583 ush code = 0; /* running code value */ 583 ush code = 0; /* running code value */
584 int bits; /* bit index */ 584 int bits; /* bit index */
585 int n; /* code index */ 585 int n; /* code index */
586 586
587 /* The distribution counts are first used to generate the code values 587 /* The distribution counts are first used to generate the code values
588 * without bit reversal. 588 * without bit reversal.
589 */ 589 */
590 for (bits = 1; bits <= MAX_BITS; bits++) { 590 for (bits = 1; bits <= MAX_BITS; bits++) {
591 next_code[bits] = code = (code + bl_count[bits-1]) << 1; 591 next_code[bits] = code = (code + bl_count[bits-1]) << 1;
592 } 592 }
593 /* Check that the bit counts in bl_count are consistent. The last code 593 /* Check that the bit counts in bl_count are consistent. The last code
594 * must be all ones. 594 * must be all ones.
595 */ 595 */
596 Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, 596 Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
597 "inconsistent bit counts"); 597 "inconsistent bit counts");
598 Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); 598 Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
599 599
600 for (n = 0; n <= max_code; n++) { 600 for (n = 0; n <= max_code; n++) {
601 int len = tree[n].Len; 601 int len = tree[n].Len;
602 if (len == 0) continue; 602 if (len == 0) continue;
603 /* Now reverse the bits */ 603 /* Now reverse the bits */
604 tree[n].Code = bi_reverse(next_code[len]++, len); 604 tree[n].Code = bi_reverse(next_code[len]++, len);
605 605
606 Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", 606 Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
607 n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); 607 n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
608 } 608 }
609} 609}
610 610
611/* =========================================================================== 611/* ===========================================================================
612 * Construct one Huffman tree and assigns the code bit strings and lengths. 612 * Construct one Huffman tree and assigns the code bit strings and lengths.
613 * Update the total bit length for the current block. 613 * Update the total bit length for the current block.
614 * IN assertion: the field freq is set for all tree elements. 614 * IN assertion: the field freq is set for all tree elements.
615 * OUT assertions: the fields len and code are set to the optimal bit length 615 * OUT assertions: the fields len and code are set to the optimal bit length
616 * and corresponding code. The length opt_len is updated; static_len is 616 * and corresponding code. The length opt_len is updated; static_len is
617 * also updated if stree is not null. The field max_code is set. 617 * also updated if stree is not null. The field max_code is set.
618 */ 618 */
619local void build_tree(s, desc) 619local void build_tree(s, desc)
620 deflate_state *s; 620 deflate_state *s;
621 tree_desc *desc; /* the tree descriptor */ 621 tree_desc *desc; /* the tree descriptor */
622{ 622{
623 ct_data *tree = desc->dyn_tree; 623 ct_data *tree = desc->dyn_tree;
624 const ct_data *stree = desc->stat_desc->static_tree; 624 const ct_data *stree = desc->stat_desc->static_tree;
625 int elems = desc->stat_desc->elems; 625 int elems = desc->stat_desc->elems;
626 int n, m; /* iterate over heap elements */ 626 int n, m; /* iterate over heap elements */
627 int max_code = -1; /* largest code with non zero frequency */ 627 int max_code = -1; /* largest code with non zero frequency */
628 int node; /* new node being created */ 628 int node; /* new node being created */
629 629
630 /* Construct the initial heap, with least frequent element in 630 /* Construct the initial heap, with least frequent element in
631 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. 631 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
632 * heap[0] is not used. 632 * heap[0] is not used.
633 */ 633 */
634 s->heap_len = 0, s->heap_max = HEAP_SIZE; 634 s->heap_len = 0, s->heap_max = HEAP_SIZE;
635 635
636 for (n = 0; n < elems; n++) { 636 for (n = 0; n < elems; n++) {
637 if (tree[n].Freq != 0) { 637 if (tree[n].Freq != 0) {
638 s->heap[++(s->heap_len)] = max_code = n; 638 s->heap[++(s->heap_len)] = max_code = n;
639 s->depth[n] = 0; 639 s->depth[n] = 0;
640 } else { 640 } else {
641 tree[n].Len = 0; 641 tree[n].Len = 0;
642 } 642 }
643 } 643 }
644 644
645 /* The pkzip format requires that at least one distance code exists, 645 /* The pkzip format requires that at least one distance code exists,
646 * and that at least one bit should be sent even if there is only one 646 * and that at least one bit should be sent even if there is only one
647 * possible code. So to avoid special checks later on we force at least 647 * possible code. So to avoid special checks later on we force at least
648 * two codes of non zero frequency. 648 * two codes of non zero frequency.
649 */ 649 */
650 while (s->heap_len < 2) { 650 while (s->heap_len < 2) {
651 node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); 651 node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
652 tree[node].Freq = 1; 652 tree[node].Freq = 1;
653 s->depth[node] = 0; 653 s->depth[node] = 0;
654 s->opt_len--; if (stree) s->static_len -= stree[node].Len; 654 s->opt_len--; if (stree) s->static_len -= stree[node].Len;
655 /* node is 0 or 1 so it does not have extra bits */ 655 /* node is 0 or 1 so it does not have extra bits */
656 } 656 }
657 desc->max_code = max_code; 657 desc->max_code = max_code;
658 658
659 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, 659 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
660 * establish sub-heaps of increasing lengths: 660 * establish sub-heaps of increasing lengths:
661 */ 661 */
662 for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); 662 for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
663 663
664 /* Construct the Huffman tree by repeatedly combining the least two 664 /* Construct the Huffman tree by repeatedly combining the least two
665 * frequent nodes. 665 * frequent nodes.
666 */ 666 */
667 node = elems; /* next internal node of the tree */ 667 node = elems; /* next internal node of the tree */
668 do { 668 do {
669 pqremove(s, tree, n); /* n = node of least frequency */ 669 pqremove(s, tree, n); /* n = node of least frequency */
670 m = s->heap[SMALLEST]; /* m = node of next least frequency */ 670 m = s->heap[SMALLEST]; /* m = node of next least frequency */
671 671
672 s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ 672 s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
673 s->heap[--(s->heap_max)] = m; 673 s->heap[--(s->heap_max)] = m;
674 674
675 /* Create a new node father of n and m */ 675 /* Create a new node father of n and m */
676 tree[node].Freq = tree[n].Freq + tree[m].Freq; 676 tree[node].Freq = tree[n].Freq + tree[m].Freq;
677 s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? 677 s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
678 s->depth[n] : s->depth[m]) + 1); 678 s->depth[n] : s->depth[m]) + 1);
679 tree[n].Dad = tree[m].Dad = (ush)node; 679 tree[n].Dad = tree[m].Dad = (ush)node;
680#ifdef DUMP_BL_TREE 680#ifdef DUMP_BL_TREE
681 if (tree == s->bl_tree) { 681 if (tree == s->bl_tree) {
682 fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", 682 fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
683 node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); 683 node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
684 } 684 }
685#endif 685#endif
686 /* and insert the new node in the heap */ 686 /* and insert the new node in the heap */
687 s->heap[SMALLEST] = node++; 687 s->heap[SMALLEST] = node++;
688 pqdownheap(s, tree, SMALLEST); 688 pqdownheap(s, tree, SMALLEST);
689 689
690 } while (s->heap_len >= 2); 690 } while (s->heap_len >= 2);
691 691
692 s->heap[--(s->heap_max)] = s->heap[SMALLEST]; 692 s->heap[--(s->heap_max)] = s->heap[SMALLEST];
693 693
694 /* At this point, the fields freq and dad are set. We can now 694 /* At this point, the fields freq and dad are set. We can now
695 * generate the bit lengths. 695 * generate the bit lengths.
696 */ 696 */
697 gen_bitlen(s, (tree_desc *)desc); 697 gen_bitlen(s, (tree_desc *)desc);
698 698
699 /* The field len is now set, we can generate the bit codes */ 699 /* The field len is now set, we can generate the bit codes */
700 gen_codes ((ct_data *)tree, max_code, s->bl_count); 700 gen_codes ((ct_data *)tree, max_code, s->bl_count);
701} 701}
702 702
703/* =========================================================================== 703/* ===========================================================================
704 * Scan a literal or distance tree to determine the frequencies of the codes 704 * Scan a literal or distance tree to determine the frequencies of the codes
705 * in the bit length tree. 705 * in the bit length tree.
706 */ 706 */
707local void scan_tree (s, tree, max_code) 707local void scan_tree (s, tree, max_code)
708 deflate_state *s; 708 deflate_state *s;
709 ct_data *tree; /* the tree to be scanned */ 709 ct_data *tree; /* the tree to be scanned */
710 int max_code; /* and its largest code of non zero frequency */ 710 int max_code; /* and its largest code of non zero frequency */
711{ 711{
712 int n; /* iterates over all tree elements */ 712 int n; /* iterates over all tree elements */
713 int prevlen = -1; /* last emitted length */ 713 int prevlen = -1; /* last emitted length */
714 int curlen; /* length of current code */ 714 int curlen; /* length of current code */
715 int nextlen = tree[0].Len; /* length of next code */ 715 int nextlen = tree[0].Len; /* length of next code */
716 int count = 0; /* repeat count of the current code */ 716 int count = 0; /* repeat count of the current code */
717 int max_count = 7; /* max repeat count */ 717 int max_count = 7; /* max repeat count */
718 int min_count = 4; /* min repeat count */ 718 int min_count = 4; /* min repeat count */
719 719
720 if (nextlen == 0) max_count = 138, min_count = 3; 720 if (nextlen == 0) max_count = 138, min_count = 3;
721 tree[max_code+1].Len = (ush)0xffff; /* guard */ 721 tree[max_code+1].Len = (ush)0xffff; /* guard */
722 722
723 for (n = 0; n <= max_code; n++) { 723 for (n = 0; n <= max_code; n++) {
724 curlen = nextlen; nextlen = tree[n+1].Len; 724 curlen = nextlen; nextlen = tree[n+1].Len;
725 if (++count < max_count && curlen == nextlen) { 725 if (++count < max_count && curlen == nextlen) {
726 continue; 726 continue;
727 } else if (count < min_count) { 727 } else if (count < min_count) {
728 s->bl_tree[curlen].Freq += count; 728 s->bl_tree[curlen].Freq += count;
729 } else if (curlen != 0) { 729 } else if (curlen != 0) {
730 if (curlen != prevlen) s->bl_tree[curlen].Freq++; 730 if (curlen != prevlen) s->bl_tree[curlen].Freq++;
731 s->bl_tree[REP_3_6].Freq++; 731 s->bl_tree[REP_3_6].Freq++;
732 } else if (count <= 10) { 732 } else if (count <= 10) {
733 s->bl_tree[REPZ_3_10].Freq++; 733 s->bl_tree[REPZ_3_10].Freq++;
734 } else { 734 } else {
735 s->bl_tree[REPZ_11_138].Freq++; 735 s->bl_tree[REPZ_11_138].Freq++;
736 } 736 }
737 count = 0; prevlen = curlen; 737 count = 0; prevlen = curlen;
738 if (nextlen == 0) { 738 if (nextlen == 0) {
739 max_count = 138, min_count = 3; 739 max_count = 138, min_count = 3;
740 } else if (curlen == nextlen) { 740 } else if (curlen == nextlen) {
741 max_count = 6, min_count = 3; 741 max_count = 6, min_count = 3;
742 } else { 742 } else {
743 max_count = 7, min_count = 4; 743 max_count = 7, min_count = 4;
744 } 744 }
745 } 745 }
746} 746}
747 747
748/* =========================================================================== 748/* ===========================================================================
749 * Send a literal or distance tree in compressed form, using the codes in 749 * Send a literal or distance tree in compressed form, using the codes in
750 * bl_tree. 750 * bl_tree.
751 */ 751 */
752local void send_tree (s, tree, max_code) 752local void send_tree (s, tree, max_code)
753 deflate_state *s; 753 deflate_state *s;
754 ct_data *tree; /* the tree to be scanned */ 754 ct_data *tree; /* the tree to be scanned */
755 int max_code; /* and its largest code of non zero frequency */ 755 int max_code; /* and its largest code of non zero frequency */
756{ 756{
757 int n; /* iterates over all tree elements */ 757 int n; /* iterates over all tree elements */
758 int prevlen = -1; /* last emitted length */ 758 int prevlen = -1; /* last emitted length */
759 int curlen; /* length of current code */ 759 int curlen; /* length of current code */
760 int nextlen = tree[0].Len; /* length of next code */ 760 int nextlen = tree[0].Len; /* length of next code */
761 int count = 0; /* repeat count of the current code */ 761 int count = 0; /* repeat count of the current code */
762 int max_count = 7; /* max repeat count */ 762 int max_count = 7; /* max repeat count */
763 int min_count = 4; /* min repeat count */ 763 int min_count = 4; /* min repeat count */
764 764
765 /* tree[max_code+1].Len = -1; */ /* guard already set */ 765 /* tree[max_code+1].Len = -1; */ /* guard already set */
766 if (nextlen == 0) max_count = 138, min_count = 3; 766 if (nextlen == 0) max_count = 138, min_count = 3;
767 767
768 for (n = 0; n <= max_code; n++) { 768 for (n = 0; n <= max_code; n++) {
769 curlen = nextlen; nextlen = tree[n+1].Len; 769 curlen = nextlen; nextlen = tree[n+1].Len;
770 if (++count < max_count && curlen == nextlen) { 770 if (++count < max_count && curlen == nextlen) {
771 continue; 771 continue;
772 } else if (count < min_count) { 772 } else if (count < min_count) {
773 do { send_code(s, curlen, s->bl_tree); } while (--count != 0); 773 do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
774 774
775 } else if (curlen != 0) { 775 } else if (curlen != 0) {
776 if (curlen != prevlen) { 776 if (curlen != prevlen) {
777 send_code(s, curlen, s->bl_tree); count--; 777 send_code(s, curlen, s->bl_tree); count--;
778 } 778 }
779 Assert(count >= 3 && count <= 6, " 3_6?"); 779 Assert(count >= 3 && count <= 6, " 3_6?");
780 send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); 780 send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
781 781
782 } else if (count <= 10) { 782 } else if (count <= 10) {
783 send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); 783 send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
784 784
785 } else { 785 } else {
786 send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); 786 send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
787 } 787 }
788 count = 0; prevlen = curlen; 788 count = 0; prevlen = curlen;
789 if (nextlen == 0) { 789 if (nextlen == 0) {
790 max_count = 138, min_count = 3; 790 max_count = 138, min_count = 3;
791 } else if (curlen == nextlen) { 791 } else if (curlen == nextlen) {
792 max_count = 6, min_count = 3; 792 max_count = 6, min_count = 3;
793 } else { 793 } else {
794 max_count = 7, min_count = 4; 794 max_count = 7, min_count = 4;
795 } 795 }
796 } 796 }
797} 797}
798 798
799/* =========================================================================== 799/* ===========================================================================
800 * Construct the Huffman tree for the bit lengths and return the index in 800 * Construct the Huffman tree for the bit lengths and return the index in
801 * bl_order of the last bit length code to send. 801 * bl_order of the last bit length code to send.
802 */ 802 */
803local int build_bl_tree(s) 803local int build_bl_tree(s)
804 deflate_state *s; 804 deflate_state *s;
805{ 805{
806 int max_blindex; /* index of last bit length code of non zero freq */ 806 int max_blindex; /* index of last bit length code of non zero freq */
807 807
808 /* Determine the bit length frequencies for literal and distance trees */ 808 /* Determine the bit length frequencies for literal and distance trees */
809 scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); 809 scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
810 scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); 810 scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
811 811
812 /* Build the bit length tree: */ 812 /* Build the bit length tree: */
813 build_tree(s, (tree_desc *)(&(s->bl_desc))); 813 build_tree(s, (tree_desc *)(&(s->bl_desc)));
814 /* opt_len now includes the length of the tree representations, except 814 /* opt_len now includes the length of the tree representations, except
815 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. 815 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
816 */ 816 */
817 817
818 /* Determine the number of bit length codes to send. The pkzip format 818 /* Determine the number of bit length codes to send. The pkzip format
819 * requires that at least 4 bit length codes be sent. (appnote.txt says 819 * requires that at least 4 bit length codes be sent. (appnote.txt says
820 * 3 but the actual value used is 4.) 820 * 3 but the actual value used is 4.)
821 */ 821 */
822 for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { 822 for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
823 if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; 823 if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
824 } 824 }
825 /* Update opt_len to include the bit length tree and counts */ 825 /* Update opt_len to include the bit length tree and counts */
826 s->opt_len += 3*(max_blindex+1) + 5+5+4; 826 s->opt_len += 3*(max_blindex+1) + 5+5+4;
827 Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", 827 Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
828 s->opt_len, s->static_len)); 828 s->opt_len, s->static_len));
829 829
830 return max_blindex; 830 return max_blindex;
831} 831}
832 832
833/* =========================================================================== 833/* ===========================================================================
834 * Send the header for a block using dynamic Huffman trees: the counts, the 834 * Send the header for a block using dynamic Huffman trees: the counts, the
835 * lengths of the bit length codes, the literal tree and the distance tree. 835 * lengths of the bit length codes, the literal tree and the distance tree.
836 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. 836 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
837 */ 837 */
838local void send_all_trees(s, lcodes, dcodes, blcodes) 838local void send_all_trees(s, lcodes, dcodes, blcodes)
839 deflate_state *s; 839 deflate_state *s;
840 int lcodes, dcodes, blcodes; /* number of codes for each tree */ 840 int lcodes, dcodes, blcodes; /* number of codes for each tree */
841{ 841{
842 int rank; /* index in bl_order */ 842 int rank; /* index in bl_order */
843 843
844 Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); 844 Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
845 Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, 845 Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
846 "too many codes"); 846 "too many codes");
847 Tracev((stderr, "\nbl counts: ")); 847 Tracev((stderr, "\nbl counts: "));
848 send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ 848 send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
849 send_bits(s, dcodes-1, 5); 849 send_bits(s, dcodes-1, 5);
850 send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ 850 send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
851 for (rank = 0; rank < blcodes; rank++) { 851 for (rank = 0; rank < blcodes; rank++) {
852 Tracev((stderr, "\nbl code %2d ", bl_order[rank])); 852 Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
853 send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); 853 send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
854 } 854 }
855 Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); 855 Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
856 856
857 send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ 857 send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
858 Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); 858 Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
859 859
860 send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ 860 send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
861 Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); 861 Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
862} 862}
863 863
864/* =========================================================================== 864/* ===========================================================================
865 * Send a stored block 865 * Send a stored block
866 */ 866 */
867void _tr_stored_block(s, buf, stored_len, eof) 867void _tr_stored_block(s, buf, stored_len, eof)
868 deflate_state *s; 868 deflate_state *s;
869 charf *buf; /* input block */ 869 charf *buf; /* input block */
870 ulg stored_len; /* length of input block */ 870 ulg stored_len; /* length of input block */
871 int eof; /* true if this is the last block for a file */ 871 int eof; /* true if this is the last block for a file */
872{ 872{
873 send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */ 873 send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
874#ifdef DEBUG 874#ifdef DEBUG
875 s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; 875 s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
876 s->compressed_len += (stored_len + 4) << 3; 876 s->compressed_len += (stored_len + 4) << 3;
877#endif 877#endif
878 copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ 878 copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
879} 879}
880 880
881/* =========================================================================== 881/* ===========================================================================
882 * Send one empty static block to give enough lookahead for inflate. 882 * Send one empty static block to give enough lookahead for inflate.
883 * This takes 10 bits, of which 7 may remain in the bit buffer. 883 * This takes 10 bits, of which 7 may remain in the bit buffer.
884 * The current inflate code requires 9 bits of lookahead. If the 884 * The current inflate code requires 9 bits of lookahead. If the
885 * last two codes for the previous block (real code plus EOB) were coded 885 * last two codes for the previous block (real code plus EOB) were coded
886 * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode 886 * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
887 * the last real code. In this case we send two empty static blocks instead 887 * the last real code. In this case we send two empty static blocks instead
888 * of one. (There are no problems if the previous block is stored or fixed.) 888 * of one. (There are no problems if the previous block is stored or fixed.)
889 * To simplify the code, we assume the worst case of last real code encoded 889 * To simplify the code, we assume the worst case of last real code encoded
890 * on one bit only. 890 * on one bit only.
891 */ 891 */
892void _tr_align(s) 892void _tr_align(s)
893 deflate_state *s; 893 deflate_state *s;
894{ 894{
895 send_bits(s, STATIC_TREES<<1, 3); 895 send_bits(s, STATIC_TREES<<1, 3);
896 send_code(s, END_BLOCK, static_ltree); 896 send_code(s, END_BLOCK, static_ltree);
897#ifdef DEBUG 897#ifdef DEBUG
898 s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ 898 s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
899#endif 899#endif
900 bi_flush(s); 900 bi_flush(s);
901 /* Of the 10 bits for the empty block, we have already sent 901 /* Of the 10 bits for the empty block, we have already sent
902 * (10 - bi_valid) bits. The lookahead for the last real code (before 902 * (10 - bi_valid) bits. The lookahead for the last real code (before
903 * the EOB of the previous block) was thus at least one plus the length 903 * the EOB of the previous block) was thus at least one plus the length
904 * of the EOB plus what we have just sent of the empty static block. 904 * of the EOB plus what we have just sent of the empty static block.
905 */ 905 */
906 if (1 + s->last_eob_len + 10 - s->bi_valid < 9) { 906 if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
907 send_bits(s, STATIC_TREES<<1, 3); 907 send_bits(s, STATIC_TREES<<1, 3);
908 send_code(s, END_BLOCK, static_ltree); 908 send_code(s, END_BLOCK, static_ltree);
909#ifdef DEBUG 909#ifdef DEBUG
910 s->compressed_len += 10L; 910 s->compressed_len += 10L;
911#endif 911#endif
912 bi_flush(s); 912 bi_flush(s);
913 } 913 }
914 s->last_eob_len = 7; 914 s->last_eob_len = 7;
915} 915}
916 916
917/* =========================================================================== 917/* ===========================================================================
918 * Determine the best encoding for the current block: dynamic trees, static 918 * Determine the best encoding for the current block: dynamic trees, static
919 * trees or store, and output the encoded block to the zip file. 919 * trees or store, and output the encoded block to the zip file.
920 */ 920 */
921void _tr_flush_block(s, buf, stored_len, eof) 921void _tr_flush_block(s, buf, stored_len, eof)
922 deflate_state *s; 922 deflate_state *s;
923 charf *buf; /* input block, or NULL if too old */ 923 charf *buf; /* input block, or NULL if too old */
924 ulg stored_len; /* length of input block */ 924 ulg stored_len; /* length of input block */
925 int eof; /* true if this is the last block for a file */ 925 int eof; /* true if this is the last block for a file */
926{ 926{
927 ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ 927 ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
928 int max_blindex = 0; /* index of last bit length code of non zero freq */ 928 int max_blindex = 0; /* index of last bit length code of non zero freq */
929 929
930 /* Build the Huffman trees unless a stored block is forced */ 930 /* Build the Huffman trees unless a stored block is forced */
931 if (s->level > 0) { 931 if (s->level > 0) {
932 932
933 /* Check if the file is binary or text */ 933 /* Check if the file is binary or text */
934 if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN) 934 if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
935 set_data_type(s); 935 set_data_type(s);
936 936
937 /* Construct the literal and distance trees */ 937 /* Construct the literal and distance trees */
938 build_tree(s, (tree_desc *)(&(s->l_desc))); 938 build_tree(s, (tree_desc *)(&(s->l_desc)));
939 Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, 939 Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
940 s->static_len)); 940 s->static_len));
941 941
942 build_tree(s, (tree_desc *)(&(s->d_desc))); 942 build_tree(s, (tree_desc *)(&(s->d_desc)));
943 Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, 943 Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
944 s->static_len)); 944 s->static_len));
945 /* At this point, opt_len and static_len are the total bit lengths of 945 /* At this point, opt_len and static_len are the total bit lengths of
946 * the compressed block data, excluding the tree representations. 946 * the compressed block data, excluding the tree representations.
947 */ 947 */
948 948
949 /* Build the bit length tree for the above two trees, and get the index 949 /* Build the bit length tree for the above two trees, and get the index
950 * in bl_order of the last bit length code to send. 950 * in bl_order of the last bit length code to send.
951 */ 951 */
952 max_blindex = build_bl_tree(s); 952 max_blindex = build_bl_tree(s);
953 953
954 /* Determine the best encoding. Compute the block lengths in bytes. */ 954 /* Determine the best encoding. Compute the block lengths in bytes. */
955 opt_lenb = (s->opt_len+3+7)>>3; 955 opt_lenb = (s->opt_len+3+7)>>3;
956 static_lenb = (s->static_len+3+7)>>3; 956 static_lenb = (s->static_len+3+7)>>3;
957 957
958 Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", 958 Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
959 opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, 959 opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
960 s->last_lit)); 960 s->last_lit));
961 961
962 if (static_lenb <= opt_lenb) opt_lenb = static_lenb; 962 if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
963 963
964 } else { 964 } else {
965 Assert(buf != (char*)0, "lost buf"); 965 Assert(buf != (char*)0, "lost buf");
966 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ 966 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
967 } 967 }
968 968
969#ifdef FORCE_STORED 969#ifdef FORCE_STORED
970 if (buf != (char*)0) { /* force stored block */ 970 if (buf != (char*)0) { /* force stored block */
971#else 971#else
972 if (stored_len+4 <= opt_lenb && buf != (char*)0) { 972 if (stored_len+4 <= opt_lenb && buf != (char*)0) {
973 /* 4: two words for the lengths */ 973 /* 4: two words for the lengths */
974#endif 974#endif
975 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. 975 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
976 * Otherwise we can't have processed more than WSIZE input bytes since 976 * Otherwise we can't have processed more than WSIZE input bytes since
977 * the last block flush, because compression would have been 977 * the last block flush, because compression would have been
978 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to 978 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
979 * transform a block into a stored block. 979 * transform a block into a stored block.
980 */ 980 */
981 _tr_stored_block(s, buf, stored_len, eof); 981 _tr_stored_block(s, buf, stored_len, eof);
982 982
983#ifdef FORCE_STATIC 983#ifdef FORCE_STATIC
984 } else if (static_lenb >= 0) { /* force static trees */ 984 } else if (static_lenb >= 0) { /* force static trees */
985#else 985#else
986 } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { 986 } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
987#endif 987#endif
988 send_bits(s, (STATIC_TREES<<1)+eof, 3); 988 send_bits(s, (STATIC_TREES<<1)+eof, 3);
989 compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree); 989 compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
990#ifdef DEBUG 990#ifdef DEBUG
991 s->compressed_len += 3 + s->static_len; 991 s->compressed_len += 3 + s->static_len;
992#endif 992#endif
993 } else { 993 } else {
994 send_bits(s, (DYN_TREES<<1)+eof, 3); 994 send_bits(s, (DYN_TREES<<1)+eof, 3);
995 send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, 995 send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
996 max_blindex+1); 996 max_blindex+1);
997 compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree); 997 compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
998#ifdef DEBUG 998#ifdef DEBUG
999 s->compressed_len += 3 + s->opt_len; 999 s->compressed_len += 3 + s->opt_len;
1000#endif 1000#endif
1001 } 1001 }
1002 Assert (s->compressed_len == s->bits_sent, "bad compressed size"); 1002 Assert (s->compressed_len == s->bits_sent, "bad compressed size");
1003 /* The above check is made mod 2^32, for files larger than 512 MB 1003 /* The above check is made mod 2^32, for files larger than 512 MB
1004 * and uLong implemented on 32 bits. 1004 * and uLong implemented on 32 bits.
1005 */ 1005 */
1006 init_block(s); 1006 init_block(s);
1007 1007
1008 if (eof) { 1008 if (eof) {
1009 bi_windup(s); 1009 bi_windup(s);
1010#ifdef DEBUG 1010#ifdef DEBUG
1011 s->compressed_len += 7; /* align on byte boundary */ 1011 s->compressed_len += 7; /* align on byte boundary */
1012#endif 1012#endif
1013 } 1013 }
1014 Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, 1014 Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
1015 s->compressed_len-7*eof)); 1015 s->compressed_len-7*eof));
1016} 1016}
1017 1017
1018/* =========================================================================== 1018/* ===========================================================================
1019 * Save the match info and tally the frequency counts. Return true if 1019 * Save the match info and tally the frequency counts. Return true if
1020 * the current block must be flushed. 1020 * the current block must be flushed.
1021 */ 1021 */
1022int _tr_tally (s, dist, lc) 1022int _tr_tally (s, dist, lc)
1023 deflate_state *s; 1023 deflate_state *s;
1024 unsigned dist; /* distance of matched string */ 1024 unsigned dist; /* distance of matched string */
1025 unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ 1025 unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
1026{ 1026{
1027 s->d_buf[s->last_lit] = (ush)dist; 1027 s->d_buf[s->last_lit] = (ush)dist;
1028 s->l_buf[s->last_lit++] = (uch)lc; 1028 s->l_buf[s->last_lit++] = (uch)lc;
1029 if (dist == 0) { 1029 if (dist == 0) {
1030 /* lc is the unmatched char */ 1030 /* lc is the unmatched char */
1031 s->dyn_ltree[lc].Freq++; 1031 s->dyn_ltree[lc].Freq++;
1032 } else { 1032 } else {
1033 s->matches++; 1033 s->matches++;
1034 /* Here, lc is the match length - MIN_MATCH */ 1034 /* Here, lc is the match length - MIN_MATCH */
1035 dist--; /* dist = match distance - 1 */ 1035 dist--; /* dist = match distance - 1 */
1036 Assert((ush)dist < (ush)MAX_DIST(s) && 1036 Assert((ush)dist < (ush)MAX_DIST(s) &&
1037 (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && 1037 (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
1038 (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); 1038 (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
1039 1039
1040 s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; 1040 s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
1041 s->dyn_dtree[d_code(dist)].Freq++; 1041 s->dyn_dtree[d_code(dist)].Freq++;
1042 } 1042 }
1043 1043
1044#ifdef TRUNCATE_BLOCK 1044#ifdef TRUNCATE_BLOCK
1045 /* Try to guess if it is profitable to stop the current block here */ 1045 /* Try to guess if it is profitable to stop the current block here */
1046 if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { 1046 if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
1047 /* Compute an upper bound for the compressed length */ 1047 /* Compute an upper bound for the compressed length */
1048 ulg out_length = (ulg)s->last_lit*8L; 1048 ulg out_length = (ulg)s->last_lit*8L;
1049 ulg in_length = (ulg)((long)s->strstart - s->block_start); 1049 ulg in_length = (ulg)((long)s->strstart - s->block_start);
1050 int dcode; 1050 int dcode;
1051 for (dcode = 0; dcode < D_CODES; dcode++) { 1051 for (dcode = 0; dcode < D_CODES; dcode++) {
1052 out_length += (ulg)s->dyn_dtree[dcode].Freq * 1052 out_length += (ulg)s->dyn_dtree[dcode].Freq *
1053 (5L+extra_dbits[dcode]); 1053 (5L+extra_dbits[dcode]);
1054 } 1054 }
1055 out_length >>= 3; 1055 out_length >>= 3;
1056 Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", 1056 Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
1057 s->last_lit, in_length, out_length, 1057 s->last_lit, in_length, out_length,
1058 100L - out_length*100L/in_length)); 1058 100L - out_length*100L/in_length));
1059 if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; 1059 if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
1060 } 1060 }
1061#endif 1061#endif
1062 return (s->last_lit == s->lit_bufsize-1); 1062 return (s->last_lit == s->lit_bufsize-1);
1063 /* We avoid equality with lit_bufsize because of wraparound at 64K 1063 /* We avoid equality with lit_bufsize because of wraparound at 64K
1064 * on 16 bit machines and because stored blocks are restricted to 1064 * on 16 bit machines and because stored blocks are restricted to
1065 * 64K-1 bytes. 1065 * 64K-1 bytes.
1066 */ 1066 */
1067} 1067}
1068 1068
1069/* =========================================================================== 1069/* ===========================================================================
1070 * Send the block data compressed using the given Huffman trees 1070 * Send the block data compressed using the given Huffman trees
1071 */ 1071 */
1072local void compress_block(s, ltree, dtree) 1072local void compress_block(s, ltree, dtree)
1073 deflate_state *s; 1073 deflate_state *s;
1074 ct_data *ltree; /* literal tree */ 1074 ct_data *ltree; /* literal tree */
1075 ct_data *dtree; /* distance tree */ 1075 ct_data *dtree; /* distance tree */
1076{ 1076{
1077 unsigned dist; /* distance of matched string */ 1077 unsigned dist; /* distance of matched string */
1078 int lc; /* match length or unmatched char (if dist == 0) */ 1078 int lc; /* match length or unmatched char (if dist == 0) */
1079 unsigned lx = 0; /* running index in l_buf */ 1079 unsigned lx = 0; /* running index in l_buf */
1080 unsigned code; /* the code to send */ 1080 unsigned code; /* the code to send */
1081 int extra; /* number of extra bits to send */ 1081 int extra; /* number of extra bits to send */
1082 1082
1083 if (s->last_lit != 0) do { 1083 if (s->last_lit != 0) do {
1084 dist = s->d_buf[lx]; 1084 dist = s->d_buf[lx];
1085 lc = s->l_buf[lx++]; 1085 lc = s->l_buf[lx++];
1086 if (dist == 0) { 1086 if (dist == 0) {
1087 send_code(s, lc, ltree); /* send a literal byte */ 1087 send_code(s, lc, ltree); /* send a literal byte */
1088 Tracecv(isgraph(lc), (stderr," '%c' ", lc)); 1088 Tracecv(isgraph(lc), (stderr," '%c' ", lc));
1089 } else { 1089 } else {
1090 /* Here, lc is the match length - MIN_MATCH */ 1090 /* Here, lc is the match length - MIN_MATCH */
1091 code = _length_code[lc]; 1091 code = _length_code[lc];
1092 send_code(s, code+LITERALS+1, ltree); /* send the length code */ 1092 send_code(s, code+LITERALS+1, ltree); /* send the length code */
1093 extra = extra_lbits[code]; 1093 extra = extra_lbits[code];
1094 if (extra != 0) { 1094 if (extra != 0) {
1095 lc -= base_length[code]; 1095 lc -= base_length[code];
1096 send_bits(s, lc, extra); /* send the extra length bits */ 1096 send_bits(s, lc, extra); /* send the extra length bits */
1097 } 1097 }
1098 dist--; /* dist is now the match distance - 1 */ 1098 dist--; /* dist is now the match distance - 1 */
1099 code = d_code(dist); 1099 code = d_code(dist);
1100 Assert (code < D_CODES, "bad d_code"); 1100 Assert (code < D_CODES, "bad d_code");
1101 1101
1102 send_code(s, code, dtree); /* send the distance code */ 1102 send_code(s, code, dtree); /* send the distance code */
1103 extra = extra_dbits[code]; 1103 extra = extra_dbits[code];
1104 if (extra != 0) { 1104 if (extra != 0) {
1105 dist -= base_dist[code]; 1105 dist -= base_dist[code];
1106 send_bits(s, dist, extra); /* send the extra distance bits */ 1106 send_bits(s, dist, extra); /* send the extra distance bits */
1107 } 1107 }
1108 } /* literal or match pair ? */ 1108 } /* literal or match pair ? */
1109 1109
1110 /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ 1110 /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
1111 Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, 1111 Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
1112 "pendingBuf overflow"); 1112 "pendingBuf overflow");
1113 1113
1114 } while (lx < s->last_lit); 1114 } while (lx < s->last_lit);
1115 1115
1116 send_code(s, END_BLOCK, ltree); 1116 send_code(s, END_BLOCK, ltree);
1117 s->last_eob_len = ltree[END_BLOCK].Len; 1117 s->last_eob_len = ltree[END_BLOCK].Len;
1118} 1118}
1119 1119
1120/* =========================================================================== 1120/* ===========================================================================
1121 * Set the data type to BINARY or TEXT, using a crude approximation: 1121 * Set the data type to BINARY or TEXT, using a crude approximation:
1122 * set it to Z_TEXT if all symbols are either printable characters (33 to 255) 1122 * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
1123 * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise. 1123 * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
1124 * IN assertion: the fields Freq of dyn_ltree are set. 1124 * IN assertion: the fields Freq of dyn_ltree are set.
1125 */ 1125 */
1126local void set_data_type(s) 1126local void set_data_type(s)
1127 deflate_state *s; 1127 deflate_state *s;
1128{ 1128{
1129 int n; 1129 int n;
1130 1130
1131 for (n = 0; n < 9; n++) 1131 for (n = 0; n < 9; n++)
1132 if (s->dyn_ltree[n].Freq != 0) 1132 if (s->dyn_ltree[n].Freq != 0)
1133 break; 1133 break;
1134 if (n == 9) 1134 if (n == 9)
1135 for (n = 14; n < 32; n++) 1135 for (n = 14; n < 32; n++)
1136 if (s->dyn_ltree[n].Freq != 0) 1136 if (s->dyn_ltree[n].Freq != 0)
1137 break; 1137 break;
1138 s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY; 1138 s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
1139} 1139}
1140 1140
1141/* =========================================================================== 1141/* ===========================================================================
1142 * Reverse the first len bits of a code, using straightforward code (a faster 1142 * Reverse the first len bits of a code, using straightforward code (a faster
1143 * method would use a table) 1143 * method would use a table)
1144 * IN assertion: 1 <= len <= 15 1144 * IN assertion: 1 <= len <= 15
1145 */ 1145 */
1146local unsigned bi_reverse(code, len) 1146local unsigned bi_reverse(code, len)
1147 unsigned code; /* the value to invert */ 1147 unsigned code; /* the value to invert */
1148 int len; /* its bit length */ 1148 int len; /* its bit length */
1149{ 1149{
1150 register unsigned res = 0; 1150 register unsigned res = 0;
1151 do { 1151 do {
1152 res |= code & 1; 1152 res |= code & 1;
1153 code >>= 1, res <<= 1; 1153 code >>= 1, res <<= 1;
1154 } while (--len > 0); 1154 } while (--len > 0);
1155 return res >> 1; 1155 return res >> 1;
1156} 1156}
1157 1157
1158/* =========================================================================== 1158/* ===========================================================================
1159 * Flush the bit buffer, keeping at most 7 bits in it. 1159 * Flush the bit buffer, keeping at most 7 bits in it.
1160 */ 1160 */
1161local void bi_flush(s) 1161local void bi_flush(s)
1162 deflate_state *s; 1162 deflate_state *s;
1163{ 1163{
1164 if (s->bi_valid == 16) { 1164 if (s->bi_valid == 16) {
1165 put_short(s, s->bi_buf); 1165 put_short(s, s->bi_buf);
1166 s->bi_buf = 0; 1166 s->bi_buf = 0;
1167 s->bi_valid = 0; 1167 s->bi_valid = 0;
1168 } else if (s->bi_valid >= 8) { 1168 } else if (s->bi_valid >= 8) {
1169 put_byte(s, (Byte)s->bi_buf); 1169 put_byte(s, (Byte)s->bi_buf);
1170 s->bi_buf >>= 8; 1170 s->bi_buf >>= 8;
1171 s->bi_valid -= 8; 1171 s->bi_valid -= 8;
1172 } 1172 }
1173} 1173}
1174 1174
1175/* =========================================================================== 1175/* ===========================================================================
1176 * Flush the bit buffer and align the output on a byte boundary 1176 * Flush the bit buffer and align the output on a byte boundary
1177 */ 1177 */
1178local void bi_windup(s) 1178local void bi_windup(s)
1179 deflate_state *s; 1179 deflate_state *s;
1180{ 1180{
1181 if (s->bi_valid > 8) { 1181 if (s->bi_valid > 8) {
1182 put_short(s, s->bi_buf); 1182 put_short(s, s->bi_buf);
1183 } else if (s->bi_valid > 0) { 1183 } else if (s->bi_valid > 0) {
1184 put_byte(s, (Byte)s->bi_buf); 1184 put_byte(s, (Byte)s->bi_buf);
1185 } 1185 }
1186 s->bi_buf = 0; 1186 s->bi_buf = 0;
1187 s->bi_valid = 0; 1187 s->bi_valid = 0;
1188#ifdef DEBUG 1188#ifdef DEBUG
1189 s->bits_sent = (s->bits_sent+7) & ~7; 1189 s->bits_sent = (s->bits_sent+7) & ~7;
1190#endif 1190#endif
1191} 1191}
1192 1192
1193/* =========================================================================== 1193/* ===========================================================================
1194 * Copy a stored block, storing first the length and its 1194 * Copy a stored block, storing first the length and its
1195 * one's complement if requested. 1195 * one's complement if requested.
1196 */ 1196 */
1197local void copy_block(s, buf, len, header) 1197local void copy_block(s, buf, len, header)
1198 deflate_state *s; 1198 deflate_state *s;
1199 charf *buf; /* the input data */ 1199 charf *buf; /* the input data */
1200 unsigned len; /* its length */ 1200 unsigned len; /* its length */
1201 int header; /* true if block header must be written */ 1201 int header; /* true if block header must be written */
1202{ 1202{
1203 bi_windup(s); /* align on byte boundary */ 1203 bi_windup(s); /* align on byte boundary */
1204 s->last_eob_len = 8; /* enough lookahead for inflate */ 1204 s->last_eob_len = 8; /* enough lookahead for inflate */
1205 1205
1206 if (header) { 1206 if (header) {
1207 put_short(s, (ush)len); 1207 put_short(s, (ush)len);
1208 put_short(s, (ush)~len); 1208 put_short(s, (ush)~len);
1209#ifdef DEBUG 1209#ifdef DEBUG
1210 s->bits_sent += 2*16; 1210 s->bits_sent += 2*16;
1211#endif 1211#endif
1212 } 1212 }
1213#ifdef DEBUG 1213#ifdef DEBUG
1214 s->bits_sent += (ulg)len<<3; 1214 s->bits_sent += (ulg)len<<3;
1215#endif 1215#endif
1216 while (len--) { 1216 while (len--) {
1217 put_byte(s, *buf++); 1217 put_byte(s, *buf++);
1218 } 1218 }
1219} 1219}
diff --git a/utils/zenutils/libraries/zlib123/zlib/trees.h b/utils/zenutils/libraries/zlib123/zlib/trees.h
index 1ca868b848..72facf900f 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/trees.h
+++ b/utils/zenutils/libraries/zlib123/zlib/trees.h
@@ -1,128 +1,128 @@
1/* header created automatically with -DGEN_TREES_H */ 1/* header created automatically with -DGEN_TREES_H */
2 2
3local const ct_data static_ltree[L_CODES+2] = { 3local const ct_data static_ltree[L_CODES+2] = {
4{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, 4{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
5{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, 5{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
6{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, 6{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
7{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, 7{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
8{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, 8{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
9{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, 9{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
10{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, 10{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
11{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, 11{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
12{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, 12{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
13{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, 13{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
14{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, 14{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
15{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, 15{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
16{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, 16{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
17{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, 17{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
18{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, 18{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
19{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, 19{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
20{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, 20{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
21{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, 21{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
22{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, 22{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
23{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, 23{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
24{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, 24{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
25{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, 25{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
26{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, 26{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
27{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, 27{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
28{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, 28{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
29{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, 29{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
30{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, 30{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
31{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, 31{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
32{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, 32{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
33{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, 33{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
34{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, 34{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
35{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, 35{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
36{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, 36{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
37{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, 37{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
38{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, 38{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
39{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, 39{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
40{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, 40{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
41{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, 41{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
42{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, 42{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
43{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, 43{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
44{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, 44{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
45{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, 45{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
46{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, 46{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
47{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, 47{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
48{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, 48{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
49{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, 49{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
50{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, 50{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
51{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, 51{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
52{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, 52{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
53{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, 53{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
54{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, 54{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
55{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, 55{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
56{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, 56{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
57{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, 57{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
58{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, 58{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
59{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, 59{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
60{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, 60{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
61{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} 61{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
62}; 62};
63 63
64local const ct_data static_dtree[D_CODES] = { 64local const ct_data static_dtree[D_CODES] = {
65{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, 65{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
66{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, 66{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
67{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, 67{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
68{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, 68{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
69{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, 69{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
70{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} 70{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
71}; 71};
72 72
73const uch _dist_code[DIST_CODE_LEN] = { 73const uch _dist_code[DIST_CODE_LEN] = {
74 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 74 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
75 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 75 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
7610, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 7610, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
7711, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 7711, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
7812, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 7812, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
7913, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 7913, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
8013, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 8013, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
8114, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 8114, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
8214, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 8214, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
8314, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 8314, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
8415, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 8415, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
8515, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 8515, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
8615, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 8615, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
8718, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 8718, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
8823, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 8823, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
8924, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 8924, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
9026, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 9026, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
9126, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 9126, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
9227, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9227, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
9327, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 9327, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
9428, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 9428, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
9528, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 9528, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
9628, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 9628, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
9729, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 9729, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
9829, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 9829, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
9929, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 9929, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
100}; 100};
101 101
102const uch _length_code[MAX_MATCH-MIN_MATCH+1]= { 102const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
103 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 103 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
10413, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 10413, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
10517, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 10517, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
10619, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 10619, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
10721, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 10721, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
10822, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 10822, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
10923, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 10923, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
11024, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 11024, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
11125, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 11125, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
11225, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 11225, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
11326, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 11326, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
11426, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 11426, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
11527, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 11527, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
116}; 116};
117 117
118local const int base_length[LENGTH_CODES] = { 118local const int base_length[LENGTH_CODES] = {
1190, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 1190, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
12064, 80, 96, 112, 128, 160, 192, 224, 0 12064, 80, 96, 112, 128, 160, 192, 224, 0
121}; 121};
122 122
123local const int base_dist[D_CODES] = { 123local const int base_dist[D_CODES] = {
124 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 124 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
125 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 125 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
126 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 126 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
127}; 127};
128 128
diff --git a/utils/zenutils/libraries/zlib123/zlib/uncompr.c b/utils/zenutils/libraries/zlib123/zlib/uncompr.c
index ad6db0a67c..b59e3d0def 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/uncompr.c
+++ b/utils/zenutils/libraries/zlib123/zlib/uncompr.c
@@ -1,61 +1,61 @@
1/* uncompr.c -- decompress a memory buffer 1/* uncompr.c -- decompress a memory buffer
2 * Copyright (C) 1995-2003 Jean-loup Gailly. 2 * Copyright (C) 1995-2003 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6/* @(#) $Id$ */ 6/* @(#) $Id$ */
7 7
8#define ZLIB_INTERNAL 8#define ZLIB_INTERNAL
9#include "zlib.h" 9#include "zlib.h"
10 10
11/* =========================================================================== 11/* ===========================================================================
12 Decompresses the source buffer into the destination buffer. sourceLen is 12 Decompresses the source buffer into the destination buffer. sourceLen is
13 the byte length of the source buffer. Upon entry, destLen is the total 13 the byte length of the source buffer. Upon entry, destLen is the total
14 size of the destination buffer, which must be large enough to hold the 14 size of the destination buffer, which must be large enough to hold the
15 entire uncompressed data. (The size of the uncompressed data must have 15 entire uncompressed data. (The size of the uncompressed data must have
16 been saved previously by the compressor and transmitted to the decompressor 16 been saved previously by the compressor and transmitted to the decompressor
17 by some mechanism outside the scope of this compression library.) 17 by some mechanism outside the scope of this compression library.)
18 Upon exit, destLen is the actual size of the compressed buffer. 18 Upon exit, destLen is the actual size of the compressed buffer.
19 This function can be used to decompress a whole file at once if the 19 This function can be used to decompress a whole file at once if the
20 input file is mmap'ed. 20 input file is mmap'ed.
21 21
22 uncompress returns Z_OK if success, Z_MEM_ERROR if there was not 22 uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
23 enough memory, Z_BUF_ERROR if there was not enough room in the output 23 enough memory, Z_BUF_ERROR if there was not enough room in the output
24 buffer, or Z_DATA_ERROR if the input data was corrupted. 24 buffer, or Z_DATA_ERROR if the input data was corrupted.
25*/ 25*/
26int ZEXPORT uncompress (dest, destLen, source, sourceLen) 26int ZEXPORT uncompress (dest, destLen, source, sourceLen)
27 Bytef *dest; 27 Bytef *dest;
28 uLongf *destLen; 28 uLongf *destLen;
29 const Bytef *source; 29 const Bytef *source;
30 uLong sourceLen; 30 uLong sourceLen;
31{ 31{
32 z_stream stream; 32 z_stream stream;
33 int err; 33 int err;
34 34
35 stream.next_in = (Bytef*)source; 35 stream.next_in = (Bytef*)source;
36 stream.avail_in = (uInt)sourceLen; 36 stream.avail_in = (uInt)sourceLen;
37 /* Check for source > 64K on 16-bit machine: */ 37 /* Check for source > 64K on 16-bit machine: */
38 if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; 38 if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
39 39
40 stream.next_out = dest; 40 stream.next_out = dest;
41 stream.avail_out = (uInt)*destLen; 41 stream.avail_out = (uInt)*destLen;
42 if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; 42 if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
43 43
44 stream.zalloc = (alloc_func)0; 44 stream.zalloc = (alloc_func)0;
45 stream.zfree = (free_func)0; 45 stream.zfree = (free_func)0;
46 46
47 err = inflateInit(&stream); 47 err = inflateInit(&stream);
48 if (err != Z_OK) return err; 48 if (err != Z_OK) return err;
49 49
50 err = inflate(&stream, Z_FINISH); 50 err = inflate(&stream, Z_FINISH);
51 if (err != Z_STREAM_END) { 51 if (err != Z_STREAM_END) {
52 inflateEnd(&stream); 52 inflateEnd(&stream);
53 if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) 53 if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0))
54 return Z_DATA_ERROR; 54 return Z_DATA_ERROR;
55 return err; 55 return err;
56 } 56 }
57 *destLen = stream.total_out; 57 *destLen = stream.total_out;
58 58
59 err = inflateEnd(&stream); 59 err = inflateEnd(&stream);
60 return err; 60 return err;
61} 61}
diff --git a/utils/zenutils/libraries/zlib123/zlib/zconf.h b/utils/zenutils/libraries/zlib123/zlib/zconf.h
index e3b0c962e3..03a9431c8b 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/zconf.h
+++ b/utils/zenutils/libraries/zlib123/zlib/zconf.h
@@ -1,332 +1,332 @@
1/* zconf.h -- configuration of the zlib compression library 1/* zconf.h -- configuration of the zlib compression library
2 * Copyright (C) 1995-2005 Jean-loup Gailly. 2 * Copyright (C) 1995-2005 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6/* @(#) $Id$ */ 6/* @(#) $Id$ */
7 7
8#ifndef ZCONF_H 8#ifndef ZCONF_H
9#define ZCONF_H 9#define ZCONF_H
10 10
11/* 11/*
12 * If you *really* need a unique prefix for all types and library functions, 12 * If you *really* need a unique prefix for all types and library functions,
13 * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. 13 * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
14 */ 14 */
15#ifdef Z_PREFIX 15#ifdef Z_PREFIX
16# define deflateInit_ z_deflateInit_ 16# define deflateInit_ z_deflateInit_
17# define deflate z_deflate 17# define deflate z_deflate
18# define deflateEnd z_deflateEnd 18# define deflateEnd z_deflateEnd
19# define inflateInit_ z_inflateInit_ 19# define inflateInit_ z_inflateInit_
20# define inflate z_inflate 20# define inflate z_inflate
21# define inflateEnd z_inflateEnd 21# define inflateEnd z_inflateEnd
22# define deflateInit2_ z_deflateInit2_ 22# define deflateInit2_ z_deflateInit2_
23# define deflateSetDictionary z_deflateSetDictionary 23# define deflateSetDictionary z_deflateSetDictionary
24# define deflateCopy z_deflateCopy 24# define deflateCopy z_deflateCopy
25# define deflateReset z_deflateReset 25# define deflateReset z_deflateReset
26# define deflateParams z_deflateParams 26# define deflateParams z_deflateParams
27# define deflateBound z_deflateBound 27# define deflateBound z_deflateBound
28# define deflatePrime z_deflatePrime 28# define deflatePrime z_deflatePrime
29# define inflateInit2_ z_inflateInit2_ 29# define inflateInit2_ z_inflateInit2_
30# define inflateSetDictionary z_inflateSetDictionary 30# define inflateSetDictionary z_inflateSetDictionary
31# define inflateSync z_inflateSync 31# define inflateSync z_inflateSync
32# define inflateSyncPoint z_inflateSyncPoint 32# define inflateSyncPoint z_inflateSyncPoint
33# define inflateCopy z_inflateCopy 33# define inflateCopy z_inflateCopy
34# define inflateReset z_inflateReset 34# define inflateReset z_inflateReset
35# define inflateBack z_inflateBack 35# define inflateBack z_inflateBack
36# define inflateBackEnd z_inflateBackEnd 36# define inflateBackEnd z_inflateBackEnd
37# define compress z_compress 37# define compress z_compress
38# define compress2 z_compress2 38# define compress2 z_compress2
39# define compressBound z_compressBound 39# define compressBound z_compressBound
40# define uncompress z_uncompress 40# define uncompress z_uncompress
41# define adler32 z_adler32 41# define adler32 z_adler32
42# define crc32 z_crc32 42# define crc32 z_crc32
43# define get_crc_table z_get_crc_table 43# define get_crc_table z_get_crc_table
44# define zError z_zError 44# define zError z_zError
45 45
46# define alloc_func z_alloc_func 46# define alloc_func z_alloc_func
47# define free_func z_free_func 47# define free_func z_free_func
48# define in_func z_in_func 48# define in_func z_in_func
49# define out_func z_out_func 49# define out_func z_out_func
50# define Byte z_Byte 50# define Byte z_Byte
51# define uInt z_uInt 51# define uInt z_uInt
52# define uLong z_uLong 52# define uLong z_uLong
53# define Bytef z_Bytef 53# define Bytef z_Bytef
54# define charf z_charf 54# define charf z_charf
55# define intf z_intf 55# define intf z_intf
56# define uIntf z_uIntf 56# define uIntf z_uIntf
57# define uLongf z_uLongf 57# define uLongf z_uLongf
58# define voidpf z_voidpf 58# define voidpf z_voidpf
59# define voidp z_voidp 59# define voidp z_voidp
60#endif 60#endif
61 61
62#if defined(__MSDOS__) && !defined(MSDOS) 62#if defined(__MSDOS__) && !defined(MSDOS)
63# define MSDOS 63# define MSDOS
64#endif 64#endif
65#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) 65#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
66# define OS2 66# define OS2
67#endif 67#endif
68#if defined(_WINDOWS) && !defined(WINDOWS) 68#if defined(_WINDOWS) && !defined(WINDOWS)
69# define WINDOWS 69# define WINDOWS
70#endif 70#endif
71#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) 71#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
72# ifndef WIN32 72# ifndef WIN32
73# define WIN32 73# define WIN32
74# endif 74# endif
75#endif 75#endif
76#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) 76#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
77# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) 77# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
78# ifndef SYS16BIT 78# ifndef SYS16BIT
79# define SYS16BIT 79# define SYS16BIT
80# endif 80# endif
81# endif 81# endif
82#endif 82#endif
83 83
84/* 84/*
85 * Compile with -DMAXSEG_64K if the alloc function cannot allocate more 85 * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
86 * than 64k bytes at a time (needed on systems with 16-bit int). 86 * than 64k bytes at a time (needed on systems with 16-bit int).
87 */ 87 */
88#ifdef SYS16BIT 88#ifdef SYS16BIT
89# define MAXSEG_64K 89# define MAXSEG_64K
90#endif 90#endif
91#ifdef MSDOS 91#ifdef MSDOS
92# define UNALIGNED_OK 92# define UNALIGNED_OK
93#endif 93#endif
94 94
95#ifdef __STDC_VERSION__ 95#ifdef __STDC_VERSION__
96# ifndef STDC 96# ifndef STDC
97# define STDC 97# define STDC
98# endif 98# endif
99# if __STDC_VERSION__ >= 199901L 99# if __STDC_VERSION__ >= 199901L
100# ifndef STDC99 100# ifndef STDC99
101# define STDC99 101# define STDC99
102# endif 102# endif
103# endif 103# endif
104#endif 104#endif
105#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) 105#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
106# define STDC 106# define STDC
107#endif 107#endif
108#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) 108#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
109# define STDC 109# define STDC
110#endif 110#endif
111#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) 111#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
112# define STDC 112# define STDC
113#endif 113#endif
114#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) 114#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
115# define STDC 115# define STDC
116#endif 116#endif
117 117
118#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ 118#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
119# define STDC 119# define STDC
120#endif 120#endif
121 121
122#ifndef STDC 122#ifndef STDC
123# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ 123# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
124# define const /* note: need a more gentle solution here */ 124# define const /* note: need a more gentle solution here */
125# endif 125# endif
126#endif 126#endif
127 127
128/* Some Mac compilers merge all .h files incorrectly: */ 128/* Some Mac compilers merge all .h files incorrectly: */
129#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) 129#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
130# define NO_DUMMY_DECL 130# define NO_DUMMY_DECL
131#endif 131#endif
132 132
133/* Maximum value for memLevel in deflateInit2 */ 133/* Maximum value for memLevel in deflateInit2 */
134#ifndef MAX_MEM_LEVEL 134#ifndef MAX_MEM_LEVEL
135# ifdef MAXSEG_64K 135# ifdef MAXSEG_64K
136# define MAX_MEM_LEVEL 8 136# define MAX_MEM_LEVEL 8
137# else 137# else
138# define MAX_MEM_LEVEL 9 138# define MAX_MEM_LEVEL 9
139# endif 139# endif
140#endif 140#endif
141 141
142/* Maximum value for windowBits in deflateInit2 and inflateInit2. 142/* Maximum value for windowBits in deflateInit2 and inflateInit2.
143 * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files 143 * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
144 * created by gzip. (Files created by minigzip can still be extracted by 144 * created by gzip. (Files created by minigzip can still be extracted by
145 * gzip.) 145 * gzip.)
146 */ 146 */
147#ifndef MAX_WBITS 147#ifndef MAX_WBITS
148# define MAX_WBITS 15 /* 32K LZ77 window */ 148# define MAX_WBITS 15 /* 32K LZ77 window */
149#endif 149#endif
150 150
151/* The memory requirements for deflate are (in bytes): 151/* The memory requirements for deflate are (in bytes):
152 (1 << (windowBits+2)) + (1 << (memLevel+9)) 152 (1 << (windowBits+2)) + (1 << (memLevel+9))
153 that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) 153 that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
154 plus a few kilobytes for small objects. For example, if you want to reduce 154 plus a few kilobytes for small objects. For example, if you want to reduce
155 the default memory requirements from 256K to 128K, compile with 155 the default memory requirements from 256K to 128K, compile with
156 make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" 156 make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
157 Of course this will generally degrade compression (there's no free lunch). 157 Of course this will generally degrade compression (there's no free lunch).
158 158
159 The memory requirements for inflate are (in bytes) 1 << windowBits 159 The memory requirements for inflate are (in bytes) 1 << windowBits
160 that is, 32K for windowBits=15 (default value) plus a few kilobytes 160 that is, 32K for windowBits=15 (default value) plus a few kilobytes
161 for small objects. 161 for small objects.
162*/ 162*/
163 163
164 /* Type declarations */ 164 /* Type declarations */
165 165
166#ifndef OF /* function prototypes */ 166#ifndef OF /* function prototypes */
167# ifdef STDC 167# ifdef STDC
168# define OF(args) args 168# define OF(args) args
169# else 169# else
170# define OF(args) () 170# define OF(args) ()
171# endif 171# endif
172#endif 172#endif
173 173
174/* The following definitions for FAR are needed only for MSDOS mixed 174/* The following definitions for FAR are needed only for MSDOS mixed
175 * model programming (small or medium model with some far allocations). 175 * model programming (small or medium model with some far allocations).
176 * This was tested only with MSC; for other MSDOS compilers you may have 176 * This was tested only with MSC; for other MSDOS compilers you may have
177 * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, 177 * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
178 * just define FAR to be empty. 178 * just define FAR to be empty.
179 */ 179 */
180#ifdef SYS16BIT 180#ifdef SYS16BIT
181# if defined(M_I86SM) || defined(M_I86MM) 181# if defined(M_I86SM) || defined(M_I86MM)
182 /* MSC small or medium model */ 182 /* MSC small or medium model */
183# define SMALL_MEDIUM 183# define SMALL_MEDIUM
184# ifdef _MSC_VER 184# ifdef _MSC_VER
185# define FAR _far 185# define FAR _far
186# else 186# else
187# define FAR far 187# define FAR far
188# endif 188# endif
189# endif 189# endif
190# if (defined(__SMALL__) || defined(__MEDIUM__)) 190# if (defined(__SMALL__) || defined(__MEDIUM__))
191 /* Turbo C small or medium model */ 191 /* Turbo C small or medium model */
192# define SMALL_MEDIUM 192# define SMALL_MEDIUM
193# ifdef __BORLANDC__ 193# ifdef __BORLANDC__
194# define FAR _far 194# define FAR _far
195# else 195# else
196# define FAR far 196# define FAR far
197# endif 197# endif
198# endif 198# endif
199#endif 199#endif
200 200
201#if defined(WINDOWS) || defined(WIN32) 201#if defined(WINDOWS) || defined(WIN32)
202 /* If building or using zlib as a DLL, define ZLIB_DLL. 202 /* If building or using zlib as a DLL, define ZLIB_DLL.
203 * This is not mandatory, but it offers a little performance increase. 203 * This is not mandatory, but it offers a little performance increase.
204 */ 204 */
205# ifdef ZLIB_DLL 205# ifdef ZLIB_DLL
206# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) 206# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
207# ifdef ZLIB_INTERNAL 207# ifdef ZLIB_INTERNAL
208# define ZEXTERN extern __declspec(dllexport) 208# define ZEXTERN extern __declspec(dllexport)
209# else 209# else
210# define ZEXTERN extern __declspec(dllimport) 210# define ZEXTERN extern __declspec(dllimport)
211# endif 211# endif
212# endif 212# endif
213# endif /* ZLIB_DLL */ 213# endif /* ZLIB_DLL */
214 /* If building or using zlib with the WINAPI/WINAPIV calling convention, 214 /* If building or using zlib with the WINAPI/WINAPIV calling convention,
215 * define ZLIB_WINAPI. 215 * define ZLIB_WINAPI.
216 * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. 216 * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
217 */ 217 */
218# ifdef ZLIB_WINAPI 218# ifdef ZLIB_WINAPI
219# ifdef FAR 219# ifdef FAR
220# undef FAR 220# undef FAR
221# endif 221# endif
222# include <windows.h> 222# include <windows.h>
223 /* No need for _export, use ZLIB.DEF instead. */ 223 /* No need for _export, use ZLIB.DEF instead. */
224 /* For complete Windows compatibility, use WINAPI, not __stdcall. */ 224 /* For complete Windows compatibility, use WINAPI, not __stdcall. */
225# define ZEXPORT WINAPI 225# define ZEXPORT WINAPI
226# ifdef WIN32 226# ifdef WIN32
227# define ZEXPORTVA WINAPIV 227# define ZEXPORTVA WINAPIV
228# else 228# else
229# define ZEXPORTVA FAR CDECL 229# define ZEXPORTVA FAR CDECL
230# endif 230# endif
231# endif 231# endif
232#endif 232#endif
233 233
234#if defined (__BEOS__) 234#if defined (__BEOS__)
235# ifdef ZLIB_DLL 235# ifdef ZLIB_DLL
236# ifdef ZLIB_INTERNAL 236# ifdef ZLIB_INTERNAL
237# define ZEXPORT __declspec(dllexport) 237# define ZEXPORT __declspec(dllexport)
238# define ZEXPORTVA __declspec(dllexport) 238# define ZEXPORTVA __declspec(dllexport)
239# else 239# else
240# define ZEXPORT __declspec(dllimport) 240# define ZEXPORT __declspec(dllimport)
241# define ZEXPORTVA __declspec(dllimport) 241# define ZEXPORTVA __declspec(dllimport)
242# endif 242# endif
243# endif 243# endif
244#endif 244#endif
245 245
246#ifndef ZEXTERN 246#ifndef ZEXTERN
247# define ZEXTERN extern 247# define ZEXTERN extern
248#endif 248#endif
249#ifndef ZEXPORT 249#ifndef ZEXPORT
250# define ZEXPORT 250# define ZEXPORT
251#endif 251#endif
252#ifndef ZEXPORTVA 252#ifndef ZEXPORTVA
253# define ZEXPORTVA 253# define ZEXPORTVA
254#endif 254#endif
255 255
256#ifndef FAR 256#ifndef FAR
257# define FAR 257# define FAR
258#endif 258#endif
259 259
260#if !defined(__MACTYPES__) 260#if !defined(__MACTYPES__)
261typedef unsigned char Byte; /* 8 bits */ 261typedef unsigned char Byte; /* 8 bits */
262#endif 262#endif
263typedef unsigned int uInt; /* 16 bits or more */ 263typedef unsigned int uInt; /* 16 bits or more */
264typedef unsigned long uLong; /* 32 bits or more */ 264typedef unsigned long uLong; /* 32 bits or more */
265 265
266#ifdef SMALL_MEDIUM 266#ifdef SMALL_MEDIUM
267 /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ 267 /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
268# define Bytef Byte FAR 268# define Bytef Byte FAR
269#else 269#else
270 typedef Byte FAR Bytef; 270 typedef Byte FAR Bytef;
271#endif 271#endif
272typedef char FAR charf; 272typedef char FAR charf;
273typedef int FAR intf; 273typedef int FAR intf;
274typedef uInt FAR uIntf; 274typedef uInt FAR uIntf;
275typedef uLong FAR uLongf; 275typedef uLong FAR uLongf;
276 276
277#ifdef STDC 277#ifdef STDC
278 typedef void const *voidpc; 278 typedef void const *voidpc;
279 typedef void FAR *voidpf; 279 typedef void FAR *voidpf;
280 typedef void *voidp; 280 typedef void *voidp;
281#else 281#else
282 typedef Byte const *voidpc; 282 typedef Byte const *voidpc;
283 typedef Byte FAR *voidpf; 283 typedef Byte FAR *voidpf;
284 typedef Byte *voidp; 284 typedef Byte *voidp;
285#endif 285#endif
286 286
287#if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */ 287#if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
288# include <sys/types.h> /* for off_t */ 288# include <sys/types.h> /* for off_t */
289# include <unistd.h> /* for SEEK_* and off_t */ 289# include <unistd.h> /* for SEEK_* and off_t */
290# ifdef VMS 290# ifdef VMS
291# include <unixio.h> /* for off_t */ 291# include <unixio.h> /* for off_t */
292# endif 292# endif
293# define z_off_t off_t 293# define z_off_t off_t
294#endif 294#endif
295#ifndef SEEK_SET 295#ifndef SEEK_SET
296# define SEEK_SET 0 /* Seek from beginning of file. */ 296# define SEEK_SET 0 /* Seek from beginning of file. */
297# define SEEK_CUR 1 /* Seek from current position. */ 297# define SEEK_CUR 1 /* Seek from current position. */
298# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ 298# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
299#endif 299#endif
300#ifndef z_off_t 300#ifndef z_off_t
301# define z_off_t long 301# define z_off_t long
302#endif 302#endif
303 303
304#if defined(__OS400__) 304#if defined(__OS400__)
305# define NO_vsnprintf 305# define NO_vsnprintf
306#endif 306#endif
307 307
308#if defined(__MVS__) 308#if defined(__MVS__)
309# define NO_vsnprintf 309# define NO_vsnprintf
310# ifdef FAR 310# ifdef FAR
311# undef FAR 311# undef FAR
312# endif 312# endif
313#endif 313#endif
314 314
315/* MVS linker does not support external names larger than 8 bytes */ 315/* MVS linker does not support external names larger than 8 bytes */
316#if defined(__MVS__) 316#if defined(__MVS__)
317# pragma map(deflateInit_,"DEIN") 317# pragma map(deflateInit_,"DEIN")
318# pragma map(deflateInit2_,"DEIN2") 318# pragma map(deflateInit2_,"DEIN2")
319# pragma map(deflateEnd,"DEEND") 319# pragma map(deflateEnd,"DEEND")
320# pragma map(deflateBound,"DEBND") 320# pragma map(deflateBound,"DEBND")
321# pragma map(inflateInit_,"ININ") 321# pragma map(inflateInit_,"ININ")
322# pragma map(inflateInit2_,"ININ2") 322# pragma map(inflateInit2_,"ININ2")
323# pragma map(inflateEnd,"INEND") 323# pragma map(inflateEnd,"INEND")
324# pragma map(inflateSync,"INSY") 324# pragma map(inflateSync,"INSY")
325# pragma map(inflateSetDictionary,"INSEDI") 325# pragma map(inflateSetDictionary,"INSEDI")
326# pragma map(compressBound,"CMBND") 326# pragma map(compressBound,"CMBND")
327# pragma map(inflate_table,"INTABL") 327# pragma map(inflate_table,"INTABL")
328# pragma map(inflate_fast,"INFA") 328# pragma map(inflate_fast,"INFA")
329# pragma map(inflate_copyright,"INCOPY") 329# pragma map(inflate_copyright,"INCOPY")
330#endif 330#endif
331 331
332#endif /* ZCONF_H */ 332#endif /* ZCONF_H */
diff --git a/utils/zenutils/libraries/zlib123/zlib/zconf.in.h b/utils/zenutils/libraries/zlib123/zlib/zconf.in.h
index e3b0c962e3..03a9431c8b 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/zconf.in.h
+++ b/utils/zenutils/libraries/zlib123/zlib/zconf.in.h
@@ -1,332 +1,332 @@
1/* zconf.h -- configuration of the zlib compression library 1/* zconf.h -- configuration of the zlib compression library
2 * Copyright (C) 1995-2005 Jean-loup Gailly. 2 * Copyright (C) 1995-2005 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6/* @(#) $Id$ */ 6/* @(#) $Id$ */
7 7
8#ifndef ZCONF_H 8#ifndef ZCONF_H
9#define ZCONF_H 9#define ZCONF_H
10 10
11/* 11/*
12 * If you *really* need a unique prefix for all types and library functions, 12 * If you *really* need a unique prefix for all types and library functions,
13 * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. 13 * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
14 */ 14 */
15#ifdef Z_PREFIX 15#ifdef Z_PREFIX
16# define deflateInit_ z_deflateInit_ 16# define deflateInit_ z_deflateInit_
17# define deflate z_deflate 17# define deflate z_deflate
18# define deflateEnd z_deflateEnd 18# define deflateEnd z_deflateEnd
19# define inflateInit_ z_inflateInit_ 19# define inflateInit_ z_inflateInit_
20# define inflate z_inflate 20# define inflate z_inflate
21# define inflateEnd z_inflateEnd 21# define inflateEnd z_inflateEnd
22# define deflateInit2_ z_deflateInit2_ 22# define deflateInit2_ z_deflateInit2_
23# define deflateSetDictionary z_deflateSetDictionary 23# define deflateSetDictionary z_deflateSetDictionary
24# define deflateCopy z_deflateCopy 24# define deflateCopy z_deflateCopy
25# define deflateReset z_deflateReset 25# define deflateReset z_deflateReset
26# define deflateParams z_deflateParams 26# define deflateParams z_deflateParams
27# define deflateBound z_deflateBound 27# define deflateBound z_deflateBound
28# define deflatePrime z_deflatePrime 28# define deflatePrime z_deflatePrime
29# define inflateInit2_ z_inflateInit2_ 29# define inflateInit2_ z_inflateInit2_
30# define inflateSetDictionary z_inflateSetDictionary 30# define inflateSetDictionary z_inflateSetDictionary
31# define inflateSync z_inflateSync 31# define inflateSync z_inflateSync
32# define inflateSyncPoint z_inflateSyncPoint 32# define inflateSyncPoint z_inflateSyncPoint
33# define inflateCopy z_inflateCopy 33# define inflateCopy z_inflateCopy
34# define inflateReset z_inflateReset 34# define inflateReset z_inflateReset
35# define inflateBack z_inflateBack 35# define inflateBack z_inflateBack
36# define inflateBackEnd z_inflateBackEnd 36# define inflateBackEnd z_inflateBackEnd
37# define compress z_compress 37# define compress z_compress
38# define compress2 z_compress2 38# define compress2 z_compress2
39# define compressBound z_compressBound 39# define compressBound z_compressBound
40# define uncompress z_uncompress 40# define uncompress z_uncompress
41# define adler32 z_adler32 41# define adler32 z_adler32
42# define crc32 z_crc32 42# define crc32 z_crc32
43# define get_crc_table z_get_crc_table 43# define get_crc_table z_get_crc_table
44# define zError z_zError 44# define zError z_zError
45 45
46# define alloc_func z_alloc_func 46# define alloc_func z_alloc_func
47# define free_func z_free_func 47# define free_func z_free_func
48# define in_func z_in_func 48# define in_func z_in_func
49# define out_func z_out_func 49# define out_func z_out_func
50# define Byte z_Byte 50# define Byte z_Byte
51# define uInt z_uInt 51# define uInt z_uInt
52# define uLong z_uLong 52# define uLong z_uLong
53# define Bytef z_Bytef 53# define Bytef z_Bytef
54# define charf z_charf 54# define charf z_charf
55# define intf z_intf 55# define intf z_intf
56# define uIntf z_uIntf 56# define uIntf z_uIntf
57# define uLongf z_uLongf 57# define uLongf z_uLongf
58# define voidpf z_voidpf 58# define voidpf z_voidpf
59# define voidp z_voidp 59# define voidp z_voidp
60#endif 60#endif
61 61
62#if defined(__MSDOS__) && !defined(MSDOS) 62#if defined(__MSDOS__) && !defined(MSDOS)
63# define MSDOS 63# define MSDOS
64#endif 64#endif
65#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) 65#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
66# define OS2 66# define OS2
67#endif 67#endif
68#if defined(_WINDOWS) && !defined(WINDOWS) 68#if defined(_WINDOWS) && !defined(WINDOWS)
69# define WINDOWS 69# define WINDOWS
70#endif 70#endif
71#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) 71#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
72# ifndef WIN32 72# ifndef WIN32
73# define WIN32 73# define WIN32
74# endif 74# endif
75#endif 75#endif
76#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) 76#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
77# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) 77# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
78# ifndef SYS16BIT 78# ifndef SYS16BIT
79# define SYS16BIT 79# define SYS16BIT
80# endif 80# endif
81# endif 81# endif
82#endif 82#endif
83 83
84/* 84/*
85 * Compile with -DMAXSEG_64K if the alloc function cannot allocate more 85 * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
86 * than 64k bytes at a time (needed on systems with 16-bit int). 86 * than 64k bytes at a time (needed on systems with 16-bit int).
87 */ 87 */
88#ifdef SYS16BIT 88#ifdef SYS16BIT
89# define MAXSEG_64K 89# define MAXSEG_64K
90#endif 90#endif
91#ifdef MSDOS 91#ifdef MSDOS
92# define UNALIGNED_OK 92# define UNALIGNED_OK
93#endif 93#endif
94 94
95#ifdef __STDC_VERSION__ 95#ifdef __STDC_VERSION__
96# ifndef STDC 96# ifndef STDC
97# define STDC 97# define STDC
98# endif 98# endif
99# if __STDC_VERSION__ >= 199901L 99# if __STDC_VERSION__ >= 199901L
100# ifndef STDC99 100# ifndef STDC99
101# define STDC99 101# define STDC99
102# endif 102# endif
103# endif 103# endif
104#endif 104#endif
105#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) 105#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
106# define STDC 106# define STDC
107#endif 107#endif
108#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) 108#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
109# define STDC 109# define STDC
110#endif 110#endif
111#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) 111#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
112# define STDC 112# define STDC
113#endif 113#endif
114#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) 114#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
115# define STDC 115# define STDC
116#endif 116#endif
117 117
118#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ 118#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
119# define STDC 119# define STDC
120#endif 120#endif
121 121
122#ifndef STDC 122#ifndef STDC
123# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ 123# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
124# define const /* note: need a more gentle solution here */ 124# define const /* note: need a more gentle solution here */
125# endif 125# endif
126#endif 126#endif
127 127
128/* Some Mac compilers merge all .h files incorrectly: */ 128/* Some Mac compilers merge all .h files incorrectly: */
129#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) 129#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
130# define NO_DUMMY_DECL 130# define NO_DUMMY_DECL
131#endif 131#endif
132 132
133/* Maximum value for memLevel in deflateInit2 */ 133/* Maximum value for memLevel in deflateInit2 */
134#ifndef MAX_MEM_LEVEL 134#ifndef MAX_MEM_LEVEL
135# ifdef MAXSEG_64K 135# ifdef MAXSEG_64K
136# define MAX_MEM_LEVEL 8 136# define MAX_MEM_LEVEL 8
137# else 137# else
138# define MAX_MEM_LEVEL 9 138# define MAX_MEM_LEVEL 9
139# endif 139# endif
140#endif 140#endif
141 141
142/* Maximum value for windowBits in deflateInit2 and inflateInit2. 142/* Maximum value for windowBits in deflateInit2 and inflateInit2.
143 * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files 143 * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
144 * created by gzip. (Files created by minigzip can still be extracted by 144 * created by gzip. (Files created by minigzip can still be extracted by
145 * gzip.) 145 * gzip.)
146 */ 146 */
147#ifndef MAX_WBITS 147#ifndef MAX_WBITS
148# define MAX_WBITS 15 /* 32K LZ77 window */ 148# define MAX_WBITS 15 /* 32K LZ77 window */
149#endif 149#endif
150 150
151/* The memory requirements for deflate are (in bytes): 151/* The memory requirements for deflate are (in bytes):
152 (1 << (windowBits+2)) + (1 << (memLevel+9)) 152 (1 << (windowBits+2)) + (1 << (memLevel+9))
153 that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) 153 that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
154 plus a few kilobytes for small objects. For example, if you want to reduce 154 plus a few kilobytes for small objects. For example, if you want to reduce
155 the default memory requirements from 256K to 128K, compile with 155 the default memory requirements from 256K to 128K, compile with
156 make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" 156 make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
157 Of course this will generally degrade compression (there's no free lunch). 157 Of course this will generally degrade compression (there's no free lunch).
158 158
159 The memory requirements for inflate are (in bytes) 1 << windowBits 159 The memory requirements for inflate are (in bytes) 1 << windowBits
160 that is, 32K for windowBits=15 (default value) plus a few kilobytes 160 that is, 32K for windowBits=15 (default value) plus a few kilobytes
161 for small objects. 161 for small objects.
162*/ 162*/
163 163
164 /* Type declarations */ 164 /* Type declarations */
165 165
166#ifndef OF /* function prototypes */ 166#ifndef OF /* function prototypes */
167# ifdef STDC 167# ifdef STDC
168# define OF(args) args 168# define OF(args) args
169# else 169# else
170# define OF(args) () 170# define OF(args) ()
171# endif 171# endif
172#endif 172#endif
173 173
174/* The following definitions for FAR are needed only for MSDOS mixed 174/* The following definitions for FAR are needed only for MSDOS mixed
175 * model programming (small or medium model with some far allocations). 175 * model programming (small or medium model with some far allocations).
176 * This was tested only with MSC; for other MSDOS compilers you may have 176 * This was tested only with MSC; for other MSDOS compilers you may have
177 * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, 177 * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
178 * just define FAR to be empty. 178 * just define FAR to be empty.
179 */ 179 */
180#ifdef SYS16BIT 180#ifdef SYS16BIT
181# if defined(M_I86SM) || defined(M_I86MM) 181# if defined(M_I86SM) || defined(M_I86MM)
182 /* MSC small or medium model */ 182 /* MSC small or medium model */
183# define SMALL_MEDIUM 183# define SMALL_MEDIUM
184# ifdef _MSC_VER 184# ifdef _MSC_VER
185# define FAR _far 185# define FAR _far
186# else 186# else
187# define FAR far 187# define FAR far
188# endif 188# endif
189# endif 189# endif
190# if (defined(__SMALL__) || defined(__MEDIUM__)) 190# if (defined(__SMALL__) || defined(__MEDIUM__))
191 /* Turbo C small or medium model */ 191 /* Turbo C small or medium model */
192# define SMALL_MEDIUM 192# define SMALL_MEDIUM
193# ifdef __BORLANDC__ 193# ifdef __BORLANDC__
194# define FAR _far 194# define FAR _far
195# else 195# else
196# define FAR far 196# define FAR far
197# endif 197# endif
198# endif 198# endif
199#endif 199#endif
200 200
201#if defined(WINDOWS) || defined(WIN32) 201#if defined(WINDOWS) || defined(WIN32)
202 /* If building or using zlib as a DLL, define ZLIB_DLL. 202 /* If building or using zlib as a DLL, define ZLIB_DLL.
203 * This is not mandatory, but it offers a little performance increase. 203 * This is not mandatory, but it offers a little performance increase.
204 */ 204 */
205# ifdef ZLIB_DLL 205# ifdef ZLIB_DLL
206# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) 206# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
207# ifdef ZLIB_INTERNAL 207# ifdef ZLIB_INTERNAL
208# define ZEXTERN extern __declspec(dllexport) 208# define ZEXTERN extern __declspec(dllexport)
209# else 209# else
210# define ZEXTERN extern __declspec(dllimport) 210# define ZEXTERN extern __declspec(dllimport)
211# endif 211# endif
212# endif 212# endif
213# endif /* ZLIB_DLL */ 213# endif /* ZLIB_DLL */
214 /* If building or using zlib with the WINAPI/WINAPIV calling convention, 214 /* If building or using zlib with the WINAPI/WINAPIV calling convention,
215 * define ZLIB_WINAPI. 215 * define ZLIB_WINAPI.
216 * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. 216 * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
217 */ 217 */
218# ifdef ZLIB_WINAPI 218# ifdef ZLIB_WINAPI
219# ifdef FAR 219# ifdef FAR
220# undef FAR 220# undef FAR
221# endif 221# endif
222# include <windows.h> 222# include <windows.h>
223 /* No need for _export, use ZLIB.DEF instead. */ 223 /* No need for _export, use ZLIB.DEF instead. */
224 /* For complete Windows compatibility, use WINAPI, not __stdcall. */ 224 /* For complete Windows compatibility, use WINAPI, not __stdcall. */
225# define ZEXPORT WINAPI 225# define ZEXPORT WINAPI
226# ifdef WIN32 226# ifdef WIN32
227# define ZEXPORTVA WINAPIV 227# define ZEXPORTVA WINAPIV
228# else 228# else
229# define ZEXPORTVA FAR CDECL 229# define ZEXPORTVA FAR CDECL
230# endif 230# endif
231# endif 231# endif
232#endif 232#endif
233 233
234#if defined (__BEOS__) 234#if defined (__BEOS__)
235# ifdef ZLIB_DLL 235# ifdef ZLIB_DLL
236# ifdef ZLIB_INTERNAL 236# ifdef ZLIB_INTERNAL
237# define ZEXPORT __declspec(dllexport) 237# define ZEXPORT __declspec(dllexport)
238# define ZEXPORTVA __declspec(dllexport) 238# define ZEXPORTVA __declspec(dllexport)
239# else 239# else
240# define ZEXPORT __declspec(dllimport) 240# define ZEXPORT __declspec(dllimport)
241# define ZEXPORTVA __declspec(dllimport) 241# define ZEXPORTVA __declspec(dllimport)
242# endif 242# endif
243# endif 243# endif
244#endif 244#endif
245 245
246#ifndef ZEXTERN 246#ifndef ZEXTERN
247# define ZEXTERN extern 247# define ZEXTERN extern
248#endif 248#endif
249#ifndef ZEXPORT 249#ifndef ZEXPORT
250# define ZEXPORT 250# define ZEXPORT
251#endif 251#endif
252#ifndef ZEXPORTVA 252#ifndef ZEXPORTVA
253# define ZEXPORTVA 253# define ZEXPORTVA
254#endif 254#endif
255 255
256#ifndef FAR 256#ifndef FAR
257# define FAR 257# define FAR
258#endif 258#endif
259 259
260#if !defined(__MACTYPES__) 260#if !defined(__MACTYPES__)
261typedef unsigned char Byte; /* 8 bits */ 261typedef unsigned char Byte; /* 8 bits */
262#endif 262#endif
263typedef unsigned int uInt; /* 16 bits or more */ 263typedef unsigned int uInt; /* 16 bits or more */
264typedef unsigned long uLong; /* 32 bits or more */ 264typedef unsigned long uLong; /* 32 bits or more */
265 265
266#ifdef SMALL_MEDIUM 266#ifdef SMALL_MEDIUM
267 /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ 267 /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
268# define Bytef Byte FAR 268# define Bytef Byte FAR
269#else 269#else
270 typedef Byte FAR Bytef; 270 typedef Byte FAR Bytef;
271#endif 271#endif
272typedef char FAR charf; 272typedef char FAR charf;
273typedef int FAR intf; 273typedef int FAR intf;
274typedef uInt FAR uIntf; 274typedef uInt FAR uIntf;
275typedef uLong FAR uLongf; 275typedef uLong FAR uLongf;
276 276
277#ifdef STDC 277#ifdef STDC
278 typedef void const *voidpc; 278 typedef void const *voidpc;
279 typedef void FAR *voidpf; 279 typedef void FAR *voidpf;
280 typedef void *voidp; 280 typedef void *voidp;
281#else 281#else
282 typedef Byte const *voidpc; 282 typedef Byte const *voidpc;
283 typedef Byte FAR *voidpf; 283 typedef Byte FAR *voidpf;
284 typedef Byte *voidp; 284 typedef Byte *voidp;
285#endif 285#endif
286 286
287#if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */ 287#if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
288# include <sys/types.h> /* for off_t */ 288# include <sys/types.h> /* for off_t */
289# include <unistd.h> /* for SEEK_* and off_t */ 289# include <unistd.h> /* for SEEK_* and off_t */
290# ifdef VMS 290# ifdef VMS
291# include <unixio.h> /* for off_t */ 291# include <unixio.h> /* for off_t */
292# endif 292# endif
293# define z_off_t off_t 293# define z_off_t off_t
294#endif 294#endif
295#ifndef SEEK_SET 295#ifndef SEEK_SET
296# define SEEK_SET 0 /* Seek from beginning of file. */ 296# define SEEK_SET 0 /* Seek from beginning of file. */
297# define SEEK_CUR 1 /* Seek from current position. */ 297# define SEEK_CUR 1 /* Seek from current position. */
298# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ 298# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
299#endif 299#endif
300#ifndef z_off_t 300#ifndef z_off_t
301# define z_off_t long 301# define z_off_t long
302#endif 302#endif
303 303
304#if defined(__OS400__) 304#if defined(__OS400__)
305# define NO_vsnprintf 305# define NO_vsnprintf
306#endif 306#endif
307 307
308#if defined(__MVS__) 308#if defined(__MVS__)
309# define NO_vsnprintf 309# define NO_vsnprintf
310# ifdef FAR 310# ifdef FAR
311# undef FAR 311# undef FAR
312# endif 312# endif
313#endif 313#endif
314 314
315/* MVS linker does not support external names larger than 8 bytes */ 315/* MVS linker does not support external names larger than 8 bytes */
316#if defined(__MVS__) 316#if defined(__MVS__)
317# pragma map(deflateInit_,"DEIN") 317# pragma map(deflateInit_,"DEIN")
318# pragma map(deflateInit2_,"DEIN2") 318# pragma map(deflateInit2_,"DEIN2")
319# pragma map(deflateEnd,"DEEND") 319# pragma map(deflateEnd,"DEEND")
320# pragma map(deflateBound,"DEBND") 320# pragma map(deflateBound,"DEBND")
321# pragma map(inflateInit_,"ININ") 321# pragma map(inflateInit_,"ININ")
322# pragma map(inflateInit2_,"ININ2") 322# pragma map(inflateInit2_,"ININ2")
323# pragma map(inflateEnd,"INEND") 323# pragma map(inflateEnd,"INEND")
324# pragma map(inflateSync,"INSY") 324# pragma map(inflateSync,"INSY")
325# pragma map(inflateSetDictionary,"INSEDI") 325# pragma map(inflateSetDictionary,"INSEDI")
326# pragma map(compressBound,"CMBND") 326# pragma map(compressBound,"CMBND")
327# pragma map(inflate_table,"INTABL") 327# pragma map(inflate_table,"INTABL")
328# pragma map(inflate_fast,"INFA") 328# pragma map(inflate_fast,"INFA")
329# pragma map(inflate_copyright,"INCOPY") 329# pragma map(inflate_copyright,"INCOPY")
330#endif 330#endif
331 331
332#endif /* ZCONF_H */ 332#endif /* ZCONF_H */
diff --git a/utils/zenutils/libraries/zlib123/zlib/zlib.3 b/utils/zenutils/libraries/zlib123/zlib/zlib.3
index f6b0da1176..90b8162870 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/zlib.3
+++ b/utils/zenutils/libraries/zlib123/zlib/zlib.3
@@ -1,159 +1,159 @@
1.TH ZLIB 3 "18 July 2005" 1.TH ZLIB 3 "18 July 2005"
2.SH NAME 2.SH NAME
3zlib \- compression/decompression library 3zlib \- compression/decompression library
4.SH SYNOPSIS 4.SH SYNOPSIS
5[see 5[see
6.I zlib.h 6.I zlib.h
7for full description] 7for full description]
8.SH DESCRIPTION 8.SH DESCRIPTION
9The 9The
10.I zlib 10.I zlib
11library is a general purpose data compression library. 11library is a general purpose data compression library.
12The code is thread safe. 12The code is thread safe.
13It provides in-memory compression and decompression functions, 13It provides in-memory compression and decompression functions,
14including integrity checks of the uncompressed data. 14including integrity checks of the uncompressed data.
15This version of the library supports only one compression method (deflation) 15This version of the library supports only one compression method (deflation)
16but other algorithms will be added later 16but other algorithms will be added later
17and will have the same stream interface. 17and will have the same stream interface.
18.LP 18.LP
19Compression can be done in a single step if the buffers are large enough 19Compression can be done in a single step if the buffers are large enough
20(for example if an input file is mmap'ed), 20(for example if an input file is mmap'ed),
21or can be done by repeated calls of the compression function. 21or can be done by repeated calls of the compression function.
22In the latter case, 22In the latter case,
23the application must provide more input and/or consume the output 23the application must provide more input and/or consume the output
24(providing more output space) before each call. 24(providing more output space) before each call.
25.LP 25.LP
26The library also supports reading and writing files in 26The library also supports reading and writing files in
27.IR gzip (1) 27.IR gzip (1)
28(.gz) format 28(.gz) format
29with an interface similar to that of stdio. 29with an interface similar to that of stdio.
30.LP 30.LP
31The library does not install any signal handler. 31The library does not install any signal handler.
32The decoder checks the consistency of the compressed data, 32The decoder checks the consistency of the compressed data,
33so the library should never crash even in case of corrupted input. 33so the library should never crash even in case of corrupted input.
34.LP 34.LP
35All functions of the compression library are documented in the file 35All functions of the compression library are documented in the file
36.IR zlib.h . 36.IR zlib.h .
37The distribution source includes examples of use of the library 37The distribution source includes examples of use of the library
38in the files 38in the files
39.I example.c 39.I example.c
40and 40and
41.IR minigzip.c . 41.IR minigzip.c .
42.LP 42.LP
43Changes to this version are documented in the file 43Changes to this version are documented in the file
44.I ChangeLog 44.I ChangeLog
45that accompanies the source, 45that accompanies the source,
46and are concerned primarily with bug fixes and portability enhancements. 46and are concerned primarily with bug fixes and portability enhancements.
47.LP 47.LP
48A Java implementation of 48A Java implementation of
49.I zlib 49.I zlib
50is available in the Java Development Kit 1.1: 50is available in the Java Development Kit 1.1:
51.IP 51.IP
52http://www.javasoft.com/products/JDK/1.1/docs/api/Package-java.util.zip.html 52http://www.javasoft.com/products/JDK/1.1/docs/api/Package-java.util.zip.html
53.LP 53.LP
54A Perl interface to 54A Perl interface to
55.IR zlib , 55.IR zlib ,
56written by Paul Marquess (pmqs@cpan.org), 56written by Paul Marquess (pmqs@cpan.org),
57is available at CPAN (Comprehensive Perl Archive Network) sites, 57is available at CPAN (Comprehensive Perl Archive Network) sites,
58including: 58including:
59.IP 59.IP
60http://www.cpan.org/modules/by-module/Compress/ 60http://www.cpan.org/modules/by-module/Compress/
61.LP 61.LP
62A Python interface to 62A Python interface to
63.IR zlib , 63.IR zlib ,
64written by A.M. Kuchling (amk@magnet.com), 64written by A.M. Kuchling (amk@magnet.com),
65is available in Python 1.5 and later versions: 65is available in Python 1.5 and later versions:
66.IP 66.IP
67http://www.python.org/doc/lib/module-zlib.html 67http://www.python.org/doc/lib/module-zlib.html
68.LP 68.LP
69A 69A
70.I zlib 70.I zlib
71binding for 71binding for
72.IR tcl (1), 72.IR tcl (1),
73written by Andreas Kupries (a.kupries@westend.com), 73written by Andreas Kupries (a.kupries@westend.com),
74is availlable at: 74is availlable at:
75.IP 75.IP
76http://www.westend.com/~kupries/doc/trf/man/man.html 76http://www.westend.com/~kupries/doc/trf/man/man.html
77.LP 77.LP
78An experimental package to read and write files in .zip format, 78An experimental package to read and write files in .zip format,
79written on top of 79written on top of
80.I zlib 80.I zlib
81by Gilles Vollant (info@winimage.com), 81by Gilles Vollant (info@winimage.com),
82is available at: 82is available at:
83.IP 83.IP
84http://www.winimage.com/zLibDll/unzip.html 84http://www.winimage.com/zLibDll/unzip.html
85and also in the 85and also in the
86.I contrib/minizip 86.I contrib/minizip
87directory of the main 87directory of the main
88.I zlib 88.I zlib
89web site. 89web site.
90.SH "SEE ALSO" 90.SH "SEE ALSO"
91The 91The
92.I zlib 92.I zlib
93web site can be found at either of these locations: 93web site can be found at either of these locations:
94.IP 94.IP
95http://www.zlib.org 95http://www.zlib.org
96.br 96.br
97http://www.gzip.org/zlib/ 97http://www.gzip.org/zlib/
98.LP 98.LP
99The data format used by the zlib library is described by RFC 99The data format used by the zlib library is described by RFC
100(Request for Comments) 1950 to 1952 in the files: 100(Request for Comments) 1950 to 1952 in the files:
101.IP 101.IP
102http://www.ietf.org/rfc/rfc1950.txt (concerning zlib format) 102http://www.ietf.org/rfc/rfc1950.txt (concerning zlib format)
103.br 103.br
104http://www.ietf.org/rfc/rfc1951.txt (concerning deflate format) 104http://www.ietf.org/rfc/rfc1951.txt (concerning deflate format)
105.br 105.br
106http://www.ietf.org/rfc/rfc1952.txt (concerning gzip format) 106http://www.ietf.org/rfc/rfc1952.txt (concerning gzip format)
107.LP 107.LP
108These documents are also available in other formats from: 108These documents are also available in other formats from:
109.IP 109.IP
110ftp://ftp.uu.net/graphics/png/documents/zlib/zdoc-index.html 110ftp://ftp.uu.net/graphics/png/documents/zlib/zdoc-index.html
111.LP 111.LP
112Mark Nelson (markn@ieee.org) wrote an article about 112Mark Nelson (markn@ieee.org) wrote an article about
113.I zlib 113.I zlib
114for the Jan. 1997 issue of Dr. Dobb's Journal; 114for the Jan. 1997 issue of Dr. Dobb's Journal;
115a copy of the article is available at: 115a copy of the article is available at:
116.IP 116.IP
117http://dogma.net/markn/articles/zlibtool/zlibtool.htm 117http://dogma.net/markn/articles/zlibtool/zlibtool.htm
118.SH "REPORTING PROBLEMS" 118.SH "REPORTING PROBLEMS"
119Before reporting a problem, 119Before reporting a problem,
120please check the 120please check the
121.I zlib 121.I zlib
122web site to verify that you have the latest version of 122web site to verify that you have the latest version of
123.IR zlib ; 123.IR zlib ;
124otherwise, 124otherwise,
125obtain the latest version and see if the problem still exists. 125obtain the latest version and see if the problem still exists.
126Please read the 126Please read the
127.I zlib 127.I zlib
128FAQ at: 128FAQ at:
129.IP 129.IP
130http://www.gzip.org/zlib/zlib_faq.html 130http://www.gzip.org/zlib/zlib_faq.html
131.LP 131.LP
132before asking for help. 132before asking for help.
133Send questions and/or comments to zlib@gzip.org, 133Send questions and/or comments to zlib@gzip.org,
134or (for the Windows DLL version) to Gilles Vollant (info@winimage.com). 134or (for the Windows DLL version) to Gilles Vollant (info@winimage.com).
135.SH AUTHORS 135.SH AUTHORS
136Version 1.2.3 136Version 1.2.3
137Copyright (C) 1995-2005 Jean-loup Gailly (jloup@gzip.org) 137Copyright (C) 1995-2005 Jean-loup Gailly (jloup@gzip.org)
138and Mark Adler (madler@alumni.caltech.edu). 138and Mark Adler (madler@alumni.caltech.edu).
139.LP 139.LP
140This software is provided "as-is," 140This software is provided "as-is,"
141without any express or implied warranty. 141without any express or implied warranty.
142In no event will the authors be held liable for any damages 142In no event will the authors be held liable for any damages
143arising from the use of this software. 143arising from the use of this software.
144See the distribution directory with respect to requirements 144See the distribution directory with respect to requirements
145governing redistribution. 145governing redistribution.
146The deflate format used by 146The deflate format used by
147.I zlib 147.I zlib
148was defined by Phil Katz. 148was defined by Phil Katz.
149The deflate and 149The deflate and
150.I zlib 150.I zlib
151specifications were written by L. Peter Deutsch. 151specifications were written by L. Peter Deutsch.
152Thanks to all the people who reported problems and suggested various 152Thanks to all the people who reported problems and suggested various
153improvements in 153improvements in
154.IR zlib ; 154.IR zlib ;
155who are too numerous to cite here. 155who are too numerous to cite here.
156.LP 156.LP
157UNIX manual page by R. P. C. Rodgers, 157UNIX manual page by R. P. C. Rodgers,
158U.S. National Library of Medicine (rodgers@nlm.nih.gov). 158U.S. National Library of Medicine (rodgers@nlm.nih.gov).
159.\" end of man page 159.\" end of man page
diff --git a/utils/zenutils/libraries/zlib123/zlib/zlib.h b/utils/zenutils/libraries/zlib123/zlib/zlib.h
index 62d0e4675b..022817927c 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/zlib.h
+++ b/utils/zenutils/libraries/zlib123/zlib/zlib.h
@@ -1,1357 +1,1357 @@
1/* zlib.h -- interface of the 'zlib' general purpose compression library 1/* zlib.h -- interface of the 'zlib' general purpose compression library
2 version 1.2.3, July 18th, 2005 2 version 1.2.3, July 18th, 2005
3 3
4 Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler 4 Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler
5 5
6 This software is provided 'as-is', without any express or implied 6 This software is provided 'as-is', without any express or implied
7 warranty. In no event will the authors be held liable for any damages 7 warranty. In no event will the authors be held liable for any damages
8 arising from the use of this software. 8 arising from the use of this software.
9 9
10 Permission is granted to anyone to use this software for any purpose, 10 Permission is granted to anyone to use this software for any purpose,
11 including commercial applications, and to alter it and redistribute it 11 including commercial applications, and to alter it and redistribute it
12 freely, subject to the following restrictions: 12 freely, subject to the following restrictions:
13 13
14 1. The origin of this software must not be misrepresented; you must not 14 1. The origin of this software must not be misrepresented; you must not
15 claim that you wrote the original software. If you use this software 15 claim that you wrote the original software. If you use this software
16 in a product, an acknowledgment in the product documentation would be 16 in a product, an acknowledgment in the product documentation would be
17 appreciated but is not required. 17 appreciated but is not required.
18 2. Altered source versions must be plainly marked as such, and must not be 18 2. Altered source versions must be plainly marked as such, and must not be
19 misrepresented as being the original software. 19 misrepresented as being the original software.
20 3. This notice may not be removed or altered from any source distribution. 20 3. This notice may not be removed or altered from any source distribution.
21 21
22 Jean-loup Gailly Mark Adler 22 Jean-loup Gailly Mark Adler
23 jloup@gzip.org madler@alumni.caltech.edu 23 jloup@gzip.org madler@alumni.caltech.edu
24 24
25 25
26 The data format used by the zlib library is described by RFCs (Request for 26 The data format used by the zlib library is described by RFCs (Request for
27 Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt 27 Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt
28 (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). 28 (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
29*/ 29*/
30 30
31#ifndef ZLIB_H 31#ifndef ZLIB_H
32#define ZLIB_H 32#define ZLIB_H
33 33
34#include "zconf.h" 34#include "zconf.h"
35 35
36#ifdef __cplusplus 36#ifdef __cplusplus
37extern "C" { 37extern "C" {
38#endif 38#endif
39 39
40#define ZLIB_VERSION "1.2.3" 40#define ZLIB_VERSION "1.2.3"
41#define ZLIB_VERNUM 0x1230 41#define ZLIB_VERNUM 0x1230
42 42
43/* 43/*
44 The 'zlib' compression library provides in-memory compression and 44 The 'zlib' compression library provides in-memory compression and
45 decompression functions, including integrity checks of the uncompressed 45 decompression functions, including integrity checks of the uncompressed
46 data. This version of the library supports only one compression method 46 data. This version of the library supports only one compression method
47 (deflation) but other algorithms will be added later and will have the same 47 (deflation) but other algorithms will be added later and will have the same
48 stream interface. 48 stream interface.
49 49
50 Compression can be done in a single step if the buffers are large 50 Compression can be done in a single step if the buffers are large
51 enough (for example if an input file is mmap'ed), or can be done by 51 enough (for example if an input file is mmap'ed), or can be done by
52 repeated calls of the compression function. In the latter case, the 52 repeated calls of the compression function. In the latter case, the
53 application must provide more input and/or consume the output 53 application must provide more input and/or consume the output
54 (providing more output space) before each call. 54 (providing more output space) before each call.
55 55
56 The compressed data format used by default by the in-memory functions is 56 The compressed data format used by default by the in-memory functions is
57 the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped 57 the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
58 around a deflate stream, which is itself documented in RFC 1951. 58 around a deflate stream, which is itself documented in RFC 1951.
59 59
60 The library also supports reading and writing files in gzip (.gz) format 60 The library also supports reading and writing files in gzip (.gz) format
61 with an interface similar to that of stdio using the functions that start 61 with an interface similar to that of stdio using the functions that start
62 with "gz". The gzip format is different from the zlib format. gzip is a 62 with "gz". The gzip format is different from the zlib format. gzip is a
63 gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. 63 gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
64 64
65 This library can optionally read and write gzip streams in memory as well. 65 This library can optionally read and write gzip streams in memory as well.
66 66
67 The zlib format was designed to be compact and fast for use in memory 67 The zlib format was designed to be compact and fast for use in memory
68 and on communications channels. The gzip format was designed for single- 68 and on communications channels. The gzip format was designed for single-
69 file compression on file systems, has a larger header than zlib to maintain 69 file compression on file systems, has a larger header than zlib to maintain
70 directory information, and uses a different, slower check method than zlib. 70 directory information, and uses a different, slower check method than zlib.
71 71
72 The library does not install any signal handler. The decoder checks 72 The library does not install any signal handler. The decoder checks
73 the consistency of the compressed data, so the library should never 73 the consistency of the compressed data, so the library should never
74 crash even in case of corrupted input. 74 crash even in case of corrupted input.
75*/ 75*/
76 76
77typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); 77typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
78typedef void (*free_func) OF((voidpf opaque, voidpf address)); 78typedef void (*free_func) OF((voidpf opaque, voidpf address));
79 79
80struct internal_state; 80struct internal_state;
81 81
82typedef struct z_stream_s { 82typedef struct z_stream_s {
83 Bytef *next_in; /* next input byte */ 83 Bytef *next_in; /* next input byte */
84 uInt avail_in; /* number of bytes available at next_in */ 84 uInt avail_in; /* number of bytes available at next_in */
85 uLong total_in; /* total nb of input bytes read so far */ 85 uLong total_in; /* total nb of input bytes read so far */
86 86
87 Bytef *next_out; /* next output byte should be put there */ 87 Bytef *next_out; /* next output byte should be put there */
88 uInt avail_out; /* remaining free space at next_out */ 88 uInt avail_out; /* remaining free space at next_out */
89 uLong total_out; /* total nb of bytes output so far */ 89 uLong total_out; /* total nb of bytes output so far */
90 90
91 char *msg; /* last error message, NULL if no error */ 91 char *msg; /* last error message, NULL if no error */
92 struct internal_state FAR *state; /* not visible by applications */ 92 struct internal_state FAR *state; /* not visible by applications */
93 93
94 alloc_func zalloc; /* used to allocate the internal state */ 94 alloc_func zalloc; /* used to allocate the internal state */
95 free_func zfree; /* used to free the internal state */ 95 free_func zfree; /* used to free the internal state */
96 voidpf opaque; /* private data object passed to zalloc and zfree */ 96 voidpf opaque; /* private data object passed to zalloc and zfree */
97 97
98 int data_type; /* best guess about the data type: binary or text */ 98 int data_type; /* best guess about the data type: binary or text */
99 uLong adler; /* adler32 value of the uncompressed data */ 99 uLong adler; /* adler32 value of the uncompressed data */
100 uLong reserved; /* reserved for future use */ 100 uLong reserved; /* reserved for future use */
101} z_stream; 101} z_stream;
102 102
103typedef z_stream FAR *z_streamp; 103typedef z_stream FAR *z_streamp;
104 104
105/* 105/*
106 gzip header information passed to and from zlib routines. See RFC 1952 106 gzip header information passed to and from zlib routines. See RFC 1952
107 for more details on the meanings of these fields. 107 for more details on the meanings of these fields.
108*/ 108*/
109typedef struct gz_header_s { 109typedef struct gz_header_s {
110 int text; /* true if compressed data believed to be text */ 110 int text; /* true if compressed data believed to be text */
111 uLong time; /* modification time */ 111 uLong time; /* modification time */
112 int xflags; /* extra flags (not used when writing a gzip file) */ 112 int xflags; /* extra flags (not used when writing a gzip file) */
113 int os; /* operating system */ 113 int os; /* operating system */
114 Bytef *extra; /* pointer to extra field or Z_NULL if none */ 114 Bytef *extra; /* pointer to extra field or Z_NULL if none */
115 uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ 115 uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
116 uInt extra_max; /* space at extra (only when reading header) */ 116 uInt extra_max; /* space at extra (only when reading header) */
117 Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ 117 Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
118 uInt name_max; /* space at name (only when reading header) */ 118 uInt name_max; /* space at name (only when reading header) */
119 Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ 119 Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
120 uInt comm_max; /* space at comment (only when reading header) */ 120 uInt comm_max; /* space at comment (only when reading header) */
121 int hcrc; /* true if there was or will be a header crc */ 121 int hcrc; /* true if there was or will be a header crc */
122 int done; /* true when done reading gzip header (not used 122 int done; /* true when done reading gzip header (not used
123 when writing a gzip file) */ 123 when writing a gzip file) */
124} gz_header; 124} gz_header;
125 125
126typedef gz_header FAR *gz_headerp; 126typedef gz_header FAR *gz_headerp;
127 127
128/* 128/*
129 The application must update next_in and avail_in when avail_in has 129 The application must update next_in and avail_in when avail_in has
130 dropped to zero. It must update next_out and avail_out when avail_out 130 dropped to zero. It must update next_out and avail_out when avail_out
131 has dropped to zero. The application must initialize zalloc, zfree and 131 has dropped to zero. The application must initialize zalloc, zfree and
132 opaque before calling the init function. All other fields are set by the 132 opaque before calling the init function. All other fields are set by the
133 compression library and must not be updated by the application. 133 compression library and must not be updated by the application.
134 134
135 The opaque value provided by the application will be passed as the first 135 The opaque value provided by the application will be passed as the first
136 parameter for calls of zalloc and zfree. This can be useful for custom 136 parameter for calls of zalloc and zfree. This can be useful for custom
137 memory management. The compression library attaches no meaning to the 137 memory management. The compression library attaches no meaning to the
138 opaque value. 138 opaque value.
139 139
140 zalloc must return Z_NULL if there is not enough memory for the object. 140 zalloc must return Z_NULL if there is not enough memory for the object.
141 If zlib is used in a multi-threaded application, zalloc and zfree must be 141 If zlib is used in a multi-threaded application, zalloc and zfree must be
142 thread safe. 142 thread safe.
143 143
144 On 16-bit systems, the functions zalloc and zfree must be able to allocate 144 On 16-bit systems, the functions zalloc and zfree must be able to allocate
145 exactly 65536 bytes, but will not be required to allocate more than this 145 exactly 65536 bytes, but will not be required to allocate more than this
146 if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, 146 if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
147 pointers returned by zalloc for objects of exactly 65536 bytes *must* 147 pointers returned by zalloc for objects of exactly 65536 bytes *must*
148 have their offset normalized to zero. The default allocation function 148 have their offset normalized to zero. The default allocation function
149 provided by this library ensures this (see zutil.c). To reduce memory 149 provided by this library ensures this (see zutil.c). To reduce memory
150 requirements and avoid any allocation of 64K objects, at the expense of 150 requirements and avoid any allocation of 64K objects, at the expense of
151 compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). 151 compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
152 152
153 The fields total_in and total_out can be used for statistics or 153 The fields total_in and total_out can be used for statistics or
154 progress reports. After compression, total_in holds the total size of 154 progress reports. After compression, total_in holds the total size of
155 the uncompressed data and may be saved for use in the decompressor 155 the uncompressed data and may be saved for use in the decompressor
156 (particularly if the decompressor wants to decompress everything in 156 (particularly if the decompressor wants to decompress everything in
157 a single step). 157 a single step).
158*/ 158*/
159 159
160 /* constants */ 160 /* constants */
161 161
162#define Z_NO_FLUSH 0 162#define Z_NO_FLUSH 0
163#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */ 163#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
164#define Z_SYNC_FLUSH 2 164#define Z_SYNC_FLUSH 2
165#define Z_FULL_FLUSH 3 165#define Z_FULL_FLUSH 3
166#define Z_FINISH 4 166#define Z_FINISH 4
167#define Z_BLOCK 5 167#define Z_BLOCK 5
168/* Allowed flush values; see deflate() and inflate() below for details */ 168/* Allowed flush values; see deflate() and inflate() below for details */
169 169
170#define Z_OK 0 170#define Z_OK 0
171#define Z_STREAM_END 1 171#define Z_STREAM_END 1
172#define Z_NEED_DICT 2 172#define Z_NEED_DICT 2
173#define Z_ERRNO (-1) 173#define Z_ERRNO (-1)
174#define Z_STREAM_ERROR (-2) 174#define Z_STREAM_ERROR (-2)
175#define Z_DATA_ERROR (-3) 175#define Z_DATA_ERROR (-3)
176#define Z_MEM_ERROR (-4) 176#define Z_MEM_ERROR (-4)
177#define Z_BUF_ERROR (-5) 177#define Z_BUF_ERROR (-5)
178#define Z_VERSION_ERROR (-6) 178#define Z_VERSION_ERROR (-6)
179/* Return codes for the compression/decompression functions. Negative 179/* Return codes for the compression/decompression functions. Negative
180 * values are errors, positive values are used for special but normal events. 180 * values are errors, positive values are used for special but normal events.
181 */ 181 */
182 182
183#define Z_NO_COMPRESSION 0 183#define Z_NO_COMPRESSION 0
184#define Z_BEST_SPEED 1 184#define Z_BEST_SPEED 1
185#define Z_BEST_COMPRESSION 9 185#define Z_BEST_COMPRESSION 9
186#define Z_DEFAULT_COMPRESSION (-1) 186#define Z_DEFAULT_COMPRESSION (-1)
187/* compression levels */ 187/* compression levels */
188 188
189#define Z_FILTERED 1 189#define Z_FILTERED 1
190#define Z_HUFFMAN_ONLY 2 190#define Z_HUFFMAN_ONLY 2
191#define Z_RLE 3 191#define Z_RLE 3
192#define Z_FIXED 4 192#define Z_FIXED 4
193#define Z_DEFAULT_STRATEGY 0 193#define Z_DEFAULT_STRATEGY 0
194/* compression strategy; see deflateInit2() below for details */ 194/* compression strategy; see deflateInit2() below for details */
195 195
196#define Z_BINARY 0 196#define Z_BINARY 0
197#define Z_TEXT 1 197#define Z_TEXT 1
198#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ 198#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
199#define Z_UNKNOWN 2 199#define Z_UNKNOWN 2
200/* Possible values of the data_type field (though see inflate()) */ 200/* Possible values of the data_type field (though see inflate()) */
201 201
202#define Z_DEFLATED 8 202#define Z_DEFLATED 8
203/* The deflate compression method (the only one supported in this version) */ 203/* The deflate compression method (the only one supported in this version) */
204 204
205#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ 205#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
206 206
207#define zlib_version zlibVersion() 207#define zlib_version zlibVersion()
208/* for compatibility with versions < 1.0.2 */ 208/* for compatibility with versions < 1.0.2 */
209 209
210 /* basic functions */ 210 /* basic functions */
211 211
212ZEXTERN const char * ZEXPORT zlibVersion OF((void)); 212ZEXTERN const char * ZEXPORT zlibVersion OF((void));
213/* The application can compare zlibVersion and ZLIB_VERSION for consistency. 213/* The application can compare zlibVersion and ZLIB_VERSION for consistency.
214 If the first character differs, the library code actually used is 214 If the first character differs, the library code actually used is
215 not compatible with the zlib.h header file used by the application. 215 not compatible with the zlib.h header file used by the application.
216 This check is automatically made by deflateInit and inflateInit. 216 This check is automatically made by deflateInit and inflateInit.
217 */ 217 */
218 218
219/* 219/*
220ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); 220ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
221 221
222 Initializes the internal stream state for compression. The fields 222 Initializes the internal stream state for compression. The fields
223 zalloc, zfree and opaque must be initialized before by the caller. 223 zalloc, zfree and opaque must be initialized before by the caller.
224 If zalloc and zfree are set to Z_NULL, deflateInit updates them to 224 If zalloc and zfree are set to Z_NULL, deflateInit updates them to
225 use default allocation functions. 225 use default allocation functions.
226 226
227 The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: 227 The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
228 1 gives best speed, 9 gives best compression, 0 gives no compression at 228 1 gives best speed, 9 gives best compression, 0 gives no compression at
229 all (the input data is simply copied a block at a time). 229 all (the input data is simply copied a block at a time).
230 Z_DEFAULT_COMPRESSION requests a default compromise between speed and 230 Z_DEFAULT_COMPRESSION requests a default compromise between speed and
231 compression (currently equivalent to level 6). 231 compression (currently equivalent to level 6).
232 232
233 deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not 233 deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
234 enough memory, Z_STREAM_ERROR if level is not a valid compression level, 234 enough memory, Z_STREAM_ERROR if level is not a valid compression level,
235 Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible 235 Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
236 with the version assumed by the caller (ZLIB_VERSION). 236 with the version assumed by the caller (ZLIB_VERSION).
237 msg is set to null if there is no error message. deflateInit does not 237 msg is set to null if there is no error message. deflateInit does not
238 perform any compression: this will be done by deflate(). 238 perform any compression: this will be done by deflate().
239*/ 239*/
240 240
241 241
242ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); 242ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
243/* 243/*
244 deflate compresses as much data as possible, and stops when the input 244 deflate compresses as much data as possible, and stops when the input
245 buffer becomes empty or the output buffer becomes full. It may introduce some 245 buffer becomes empty or the output buffer becomes full. It may introduce some
246 output latency (reading input without producing any output) except when 246 output latency (reading input without producing any output) except when
247 forced to flush. 247 forced to flush.
248 248
249 The detailed semantics are as follows. deflate performs one or both of the 249 The detailed semantics are as follows. deflate performs one or both of the
250 following actions: 250 following actions:
251 251
252 - Compress more input starting at next_in and update next_in and avail_in 252 - Compress more input starting at next_in and update next_in and avail_in
253 accordingly. If not all input can be processed (because there is not 253 accordingly. If not all input can be processed (because there is not
254 enough room in the output buffer), next_in and avail_in are updated and 254 enough room in the output buffer), next_in and avail_in are updated and
255 processing will resume at this point for the next call of deflate(). 255 processing will resume at this point for the next call of deflate().
256 256
257 - Provide more output starting at next_out and update next_out and avail_out 257 - Provide more output starting at next_out and update next_out and avail_out
258 accordingly. This action is forced if the parameter flush is non zero. 258 accordingly. This action is forced if the parameter flush is non zero.
259 Forcing flush frequently degrades the compression ratio, so this parameter 259 Forcing flush frequently degrades the compression ratio, so this parameter
260 should be set only when necessary (in interactive applications). 260 should be set only when necessary (in interactive applications).
261 Some output may be provided even if flush is not set. 261 Some output may be provided even if flush is not set.
262 262
263 Before the call of deflate(), the application should ensure that at least 263 Before the call of deflate(), the application should ensure that at least
264 one of the actions is possible, by providing more input and/or consuming 264 one of the actions is possible, by providing more input and/or consuming
265 more output, and updating avail_in or avail_out accordingly; avail_out 265 more output, and updating avail_in or avail_out accordingly; avail_out
266 should never be zero before the call. The application can consume the 266 should never be zero before the call. The application can consume the
267 compressed output when it wants, for example when the output buffer is full 267 compressed output when it wants, for example when the output buffer is full
268 (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK 268 (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
269 and with zero avail_out, it must be called again after making room in the 269 and with zero avail_out, it must be called again after making room in the
270 output buffer because there might be more output pending. 270 output buffer because there might be more output pending.
271 271
272 Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to 272 Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
273 decide how much data to accumualte before producing output, in order to 273 decide how much data to accumualte before producing output, in order to
274 maximize compression. 274 maximize compression.
275 275
276 If the parameter flush is set to Z_SYNC_FLUSH, all pending output is 276 If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
277 flushed to the output buffer and the output is aligned on a byte boundary, so 277 flushed to the output buffer and the output is aligned on a byte boundary, so
278 that the decompressor can get all input data available so far. (In particular 278 that the decompressor can get all input data available so far. (In particular
279 avail_in is zero after the call if enough output space has been provided 279 avail_in is zero after the call if enough output space has been provided
280 before the call.) Flushing may degrade compression for some compression 280 before the call.) Flushing may degrade compression for some compression
281 algorithms and so it should be used only when necessary. 281 algorithms and so it should be used only when necessary.
282 282
283 If flush is set to Z_FULL_FLUSH, all output is flushed as with 283 If flush is set to Z_FULL_FLUSH, all output is flushed as with
284 Z_SYNC_FLUSH, and the compression state is reset so that decompression can 284 Z_SYNC_FLUSH, and the compression state is reset so that decompression can
285 restart from this point if previous compressed data has been damaged or if 285 restart from this point if previous compressed data has been damaged or if
286 random access is desired. Using Z_FULL_FLUSH too often can seriously degrade 286 random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
287 compression. 287 compression.
288 288
289 If deflate returns with avail_out == 0, this function must be called again 289 If deflate returns with avail_out == 0, this function must be called again
290 with the same value of the flush parameter and more output space (updated 290 with the same value of the flush parameter and more output space (updated
291 avail_out), until the flush is complete (deflate returns with non-zero 291 avail_out), until the flush is complete (deflate returns with non-zero
292 avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that 292 avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
293 avail_out is greater than six to avoid repeated flush markers due to 293 avail_out is greater than six to avoid repeated flush markers due to
294 avail_out == 0 on return. 294 avail_out == 0 on return.
295 295
296 If the parameter flush is set to Z_FINISH, pending input is processed, 296 If the parameter flush is set to Z_FINISH, pending input is processed,
297 pending output is flushed and deflate returns with Z_STREAM_END if there 297 pending output is flushed and deflate returns with Z_STREAM_END if there
298 was enough output space; if deflate returns with Z_OK, this function must be 298 was enough output space; if deflate returns with Z_OK, this function must be
299 called again with Z_FINISH and more output space (updated avail_out) but no 299 called again with Z_FINISH and more output space (updated avail_out) but no
300 more input data, until it returns with Z_STREAM_END or an error. After 300 more input data, until it returns with Z_STREAM_END or an error. After
301 deflate has returned Z_STREAM_END, the only possible operations on the 301 deflate has returned Z_STREAM_END, the only possible operations on the
302 stream are deflateReset or deflateEnd. 302 stream are deflateReset or deflateEnd.
303 303
304 Z_FINISH can be used immediately after deflateInit if all the compression 304 Z_FINISH can be used immediately after deflateInit if all the compression
305 is to be done in a single step. In this case, avail_out must be at least 305 is to be done in a single step. In this case, avail_out must be at least
306 the value returned by deflateBound (see below). If deflate does not return 306 the value returned by deflateBound (see below). If deflate does not return
307 Z_STREAM_END, then it must be called again as described above. 307 Z_STREAM_END, then it must be called again as described above.
308 308
309 deflate() sets strm->adler to the adler32 checksum of all input read 309 deflate() sets strm->adler to the adler32 checksum of all input read
310 so far (that is, total_in bytes). 310 so far (that is, total_in bytes).
311 311
312 deflate() may update strm->data_type if it can make a good guess about 312 deflate() may update strm->data_type if it can make a good guess about
313 the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered 313 the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
314 binary. This field is only for information purposes and does not affect 314 binary. This field is only for information purposes and does not affect
315 the compression algorithm in any manner. 315 the compression algorithm in any manner.
316 316
317 deflate() returns Z_OK if some progress has been made (more input 317 deflate() returns Z_OK if some progress has been made (more input
318 processed or more output produced), Z_STREAM_END if all input has been 318 processed or more output produced), Z_STREAM_END if all input has been
319 consumed and all output has been produced (only when flush is set to 319 consumed and all output has been produced (only when flush is set to
320 Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example 320 Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
321 if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible 321 if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
322 (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not 322 (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
323 fatal, and deflate() can be called again with more input and more output 323 fatal, and deflate() can be called again with more input and more output
324 space to continue compressing. 324 space to continue compressing.
325*/ 325*/
326 326
327 327
328ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); 328ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
329/* 329/*
330 All dynamically allocated data structures for this stream are freed. 330 All dynamically allocated data structures for this stream are freed.
331 This function discards any unprocessed input and does not flush any 331 This function discards any unprocessed input and does not flush any
332 pending output. 332 pending output.
333 333
334 deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the 334 deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
335 stream state was inconsistent, Z_DATA_ERROR if the stream was freed 335 stream state was inconsistent, Z_DATA_ERROR if the stream was freed
336 prematurely (some input or output was discarded). In the error case, 336 prematurely (some input or output was discarded). In the error case,
337 msg may be set but then points to a static string (which must not be 337 msg may be set but then points to a static string (which must not be
338 deallocated). 338 deallocated).
339*/ 339*/
340 340
341 341
342/* 342/*
343ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); 343ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
344 344
345 Initializes the internal stream state for decompression. The fields 345 Initializes the internal stream state for decompression. The fields
346 next_in, avail_in, zalloc, zfree and opaque must be initialized before by 346 next_in, avail_in, zalloc, zfree and opaque must be initialized before by
347 the caller. If next_in is not Z_NULL and avail_in is large enough (the exact 347 the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
348 value depends on the compression method), inflateInit determines the 348 value depends on the compression method), inflateInit determines the
349 compression method from the zlib header and allocates all data structures 349 compression method from the zlib header and allocates all data structures
350 accordingly; otherwise the allocation will be deferred to the first call of 350 accordingly; otherwise the allocation will be deferred to the first call of
351 inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to 351 inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
352 use default allocation functions. 352 use default allocation functions.
353 353
354 inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough 354 inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
355 memory, Z_VERSION_ERROR if the zlib library version is incompatible with the 355 memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
356 version assumed by the caller. msg is set to null if there is no error 356 version assumed by the caller. msg is set to null if there is no error
357 message. inflateInit does not perform any decompression apart from reading 357 message. inflateInit does not perform any decompression apart from reading
358 the zlib header if present: this will be done by inflate(). (So next_in and 358 the zlib header if present: this will be done by inflate(). (So next_in and
359 avail_in may be modified, but next_out and avail_out are unchanged.) 359 avail_in may be modified, but next_out and avail_out are unchanged.)
360*/ 360*/
361 361
362 362
363ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); 363ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
364/* 364/*
365 inflate decompresses as much data as possible, and stops when the input 365 inflate decompresses as much data as possible, and stops when the input
366 buffer becomes empty or the output buffer becomes full. It may introduce 366 buffer becomes empty or the output buffer becomes full. It may introduce
367 some output latency (reading input without producing any output) except when 367 some output latency (reading input without producing any output) except when
368 forced to flush. 368 forced to flush.
369 369
370 The detailed semantics are as follows. inflate performs one or both of the 370 The detailed semantics are as follows. inflate performs one or both of the
371 following actions: 371 following actions:
372 372
373 - Decompress more input starting at next_in and update next_in and avail_in 373 - Decompress more input starting at next_in and update next_in and avail_in
374 accordingly. If not all input can be processed (because there is not 374 accordingly. If not all input can be processed (because there is not
375 enough room in the output buffer), next_in is updated and processing 375 enough room in the output buffer), next_in is updated and processing
376 will resume at this point for the next call of inflate(). 376 will resume at this point for the next call of inflate().
377 377
378 - Provide more output starting at next_out and update next_out and avail_out 378 - Provide more output starting at next_out and update next_out and avail_out
379 accordingly. inflate() provides as much output as possible, until there 379 accordingly. inflate() provides as much output as possible, until there
380 is no more input data or no more space in the output buffer (see below 380 is no more input data or no more space in the output buffer (see below
381 about the flush parameter). 381 about the flush parameter).
382 382
383 Before the call of inflate(), the application should ensure that at least 383 Before the call of inflate(), the application should ensure that at least
384 one of the actions is possible, by providing more input and/or consuming 384 one of the actions is possible, by providing more input and/or consuming
385 more output, and updating the next_* and avail_* values accordingly. 385 more output, and updating the next_* and avail_* values accordingly.
386 The application can consume the uncompressed output when it wants, for 386 The application can consume the uncompressed output when it wants, for
387 example when the output buffer is full (avail_out == 0), or after each 387 example when the output buffer is full (avail_out == 0), or after each
388 call of inflate(). If inflate returns Z_OK and with zero avail_out, it 388 call of inflate(). If inflate returns Z_OK and with zero avail_out, it
389 must be called again after making room in the output buffer because there 389 must be called again after making room in the output buffer because there
390 might be more output pending. 390 might be more output pending.
391 391
392 The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, 392 The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
393 Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much 393 Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
394 output as possible to the output buffer. Z_BLOCK requests that inflate() stop 394 output as possible to the output buffer. Z_BLOCK requests that inflate() stop
395 if and when it gets to the next deflate block boundary. When decoding the 395 if and when it gets to the next deflate block boundary. When decoding the
396 zlib or gzip format, this will cause inflate() to return immediately after 396 zlib or gzip format, this will cause inflate() to return immediately after
397 the header and before the first block. When doing a raw inflate, inflate() 397 the header and before the first block. When doing a raw inflate, inflate()
398 will go ahead and process the first block, and will return when it gets to 398 will go ahead and process the first block, and will return when it gets to
399 the end of that block, or when it runs out of data. 399 the end of that block, or when it runs out of data.
400 400
401 The Z_BLOCK option assists in appending to or combining deflate streams. 401 The Z_BLOCK option assists in appending to or combining deflate streams.
402 Also to assist in this, on return inflate() will set strm->data_type to the 402 Also to assist in this, on return inflate() will set strm->data_type to the
403 number of unused bits in the last byte taken from strm->next_in, plus 64 403 number of unused bits in the last byte taken from strm->next_in, plus 64
404 if inflate() is currently decoding the last block in the deflate stream, 404 if inflate() is currently decoding the last block in the deflate stream,
405 plus 128 if inflate() returned immediately after decoding an end-of-block 405 plus 128 if inflate() returned immediately after decoding an end-of-block
406 code or decoding the complete header up to just before the first byte of the 406 code or decoding the complete header up to just before the first byte of the
407 deflate stream. The end-of-block will not be indicated until all of the 407 deflate stream. The end-of-block will not be indicated until all of the
408 uncompressed data from that block has been written to strm->next_out. The 408 uncompressed data from that block has been written to strm->next_out. The
409 number of unused bits may in general be greater than seven, except when 409 number of unused bits may in general be greater than seven, except when
410 bit 7 of data_type is set, in which case the number of unused bits will be 410 bit 7 of data_type is set, in which case the number of unused bits will be
411 less than eight. 411 less than eight.
412 412
413 inflate() should normally be called until it returns Z_STREAM_END or an 413 inflate() should normally be called until it returns Z_STREAM_END or an
414 error. However if all decompression is to be performed in a single step 414 error. However if all decompression is to be performed in a single step
415 (a single call of inflate), the parameter flush should be set to 415 (a single call of inflate), the parameter flush should be set to
416 Z_FINISH. In this case all pending input is processed and all pending 416 Z_FINISH. In this case all pending input is processed and all pending
417 output is flushed; avail_out must be large enough to hold all the 417 output is flushed; avail_out must be large enough to hold all the
418 uncompressed data. (The size of the uncompressed data may have been saved 418 uncompressed data. (The size of the uncompressed data may have been saved
419 by the compressor for this purpose.) The next operation on this stream must 419 by the compressor for this purpose.) The next operation on this stream must
420 be inflateEnd to deallocate the decompression state. The use of Z_FINISH 420 be inflateEnd to deallocate the decompression state. The use of Z_FINISH
421 is never required, but can be used to inform inflate that a faster approach 421 is never required, but can be used to inform inflate that a faster approach
422 may be used for the single inflate() call. 422 may be used for the single inflate() call.
423 423
424 In this implementation, inflate() always flushes as much output as 424 In this implementation, inflate() always flushes as much output as
425 possible to the output buffer, and always uses the faster approach on the 425 possible to the output buffer, and always uses the faster approach on the
426 first call. So the only effect of the flush parameter in this implementation 426 first call. So the only effect of the flush parameter in this implementation
427 is on the return value of inflate(), as noted below, or when it returns early 427 is on the return value of inflate(), as noted below, or when it returns early
428 because Z_BLOCK is used. 428 because Z_BLOCK is used.
429 429
430 If a preset dictionary is needed after this call (see inflateSetDictionary 430 If a preset dictionary is needed after this call (see inflateSetDictionary
431 below), inflate sets strm->adler to the adler32 checksum of the dictionary 431 below), inflate sets strm->adler to the adler32 checksum of the dictionary
432 chosen by the compressor and returns Z_NEED_DICT; otherwise it sets 432 chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
433 strm->adler to the adler32 checksum of all output produced so far (that is, 433 strm->adler to the adler32 checksum of all output produced so far (that is,
434 total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described 434 total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
435 below. At the end of the stream, inflate() checks that its computed adler32 435 below. At the end of the stream, inflate() checks that its computed adler32
436 checksum is equal to that saved by the compressor and returns Z_STREAM_END 436 checksum is equal to that saved by the compressor and returns Z_STREAM_END
437 only if the checksum is correct. 437 only if the checksum is correct.
438 438
439 inflate() will decompress and check either zlib-wrapped or gzip-wrapped 439 inflate() will decompress and check either zlib-wrapped or gzip-wrapped
440 deflate data. The header type is detected automatically. Any information 440 deflate data. The header type is detected automatically. Any information
441 contained in the gzip header is not retained, so applications that need that 441 contained in the gzip header is not retained, so applications that need that
442 information should instead use raw inflate, see inflateInit2() below, or 442 information should instead use raw inflate, see inflateInit2() below, or
443 inflateBack() and perform their own processing of the gzip header and 443 inflateBack() and perform their own processing of the gzip header and
444 trailer. 444 trailer.
445 445
446 inflate() returns Z_OK if some progress has been made (more input processed 446 inflate() returns Z_OK if some progress has been made (more input processed
447 or more output produced), Z_STREAM_END if the end of the compressed data has 447 or more output produced), Z_STREAM_END if the end of the compressed data has
448 been reached and all uncompressed output has been produced, Z_NEED_DICT if a 448 been reached and all uncompressed output has been produced, Z_NEED_DICT if a
449 preset dictionary is needed at this point, Z_DATA_ERROR if the input data was 449 preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
450 corrupted (input stream not conforming to the zlib format or incorrect check 450 corrupted (input stream not conforming to the zlib format or incorrect check
451 value), Z_STREAM_ERROR if the stream structure was inconsistent (for example 451 value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
452 if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory, 452 if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
453 Z_BUF_ERROR if no progress is possible or if there was not enough room in the 453 Z_BUF_ERROR if no progress is possible or if there was not enough room in the
454 output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and 454 output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
455 inflate() can be called again with more input and more output space to 455 inflate() can be called again with more input and more output space to
456 continue decompressing. If Z_DATA_ERROR is returned, the application may then 456 continue decompressing. If Z_DATA_ERROR is returned, the application may then
457 call inflateSync() to look for a good compression block if a partial recovery 457 call inflateSync() to look for a good compression block if a partial recovery
458 of the data is desired. 458 of the data is desired.
459*/ 459*/
460 460
461 461
462ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); 462ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
463/* 463/*
464 All dynamically allocated data structures for this stream are freed. 464 All dynamically allocated data structures for this stream are freed.
465 This function discards any unprocessed input and does not flush any 465 This function discards any unprocessed input and does not flush any
466 pending output. 466 pending output.
467 467
468 inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state 468 inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
469 was inconsistent. In the error case, msg may be set but then points to a 469 was inconsistent. In the error case, msg may be set but then points to a
470 static string (which must not be deallocated). 470 static string (which must not be deallocated).
471*/ 471*/
472 472
473 /* Advanced functions */ 473 /* Advanced functions */
474 474
475/* 475/*
476 The following functions are needed only in some special applications. 476 The following functions are needed only in some special applications.
477*/ 477*/
478 478
479/* 479/*
480ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, 480ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
481 int level, 481 int level,
482 int method, 482 int method,
483 int windowBits, 483 int windowBits,
484 int memLevel, 484 int memLevel,
485 int strategy)); 485 int strategy));
486 486
487 This is another version of deflateInit with more compression options. The 487 This is another version of deflateInit with more compression options. The
488 fields next_in, zalloc, zfree and opaque must be initialized before by 488 fields next_in, zalloc, zfree and opaque must be initialized before by
489 the caller. 489 the caller.
490 490
491 The method parameter is the compression method. It must be Z_DEFLATED in 491 The method parameter is the compression method. It must be Z_DEFLATED in
492 this version of the library. 492 this version of the library.
493 493
494 The windowBits parameter is the base two logarithm of the window size 494 The windowBits parameter is the base two logarithm of the window size
495 (the size of the history buffer). It should be in the range 8..15 for this 495 (the size of the history buffer). It should be in the range 8..15 for this
496 version of the library. Larger values of this parameter result in better 496 version of the library. Larger values of this parameter result in better
497 compression at the expense of memory usage. The default value is 15 if 497 compression at the expense of memory usage. The default value is 15 if
498 deflateInit is used instead. 498 deflateInit is used instead.
499 499
500 windowBits can also be -8..-15 for raw deflate. In this case, -windowBits 500 windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
501 determines the window size. deflate() will then generate raw deflate data 501 determines the window size. deflate() will then generate raw deflate data
502 with no zlib header or trailer, and will not compute an adler32 check value. 502 with no zlib header or trailer, and will not compute an adler32 check value.
503 503
504 windowBits can also be greater than 15 for optional gzip encoding. Add 504 windowBits can also be greater than 15 for optional gzip encoding. Add
505 16 to windowBits to write a simple gzip header and trailer around the 505 16 to windowBits to write a simple gzip header and trailer around the
506 compressed data instead of a zlib wrapper. The gzip header will have no 506 compressed data instead of a zlib wrapper. The gzip header will have no
507 file name, no extra data, no comment, no modification time (set to zero), 507 file name, no extra data, no comment, no modification time (set to zero),
508 no header crc, and the operating system will be set to 255 (unknown). If a 508 no header crc, and the operating system will be set to 255 (unknown). If a
509 gzip stream is being written, strm->adler is a crc32 instead of an adler32. 509 gzip stream is being written, strm->adler is a crc32 instead of an adler32.
510 510
511 The memLevel parameter specifies how much memory should be allocated 511 The memLevel parameter specifies how much memory should be allocated
512 for the internal compression state. memLevel=1 uses minimum memory but 512 for the internal compression state. memLevel=1 uses minimum memory but
513 is slow and reduces compression ratio; memLevel=9 uses maximum memory 513 is slow and reduces compression ratio; memLevel=9 uses maximum memory
514 for optimal speed. The default value is 8. See zconf.h for total memory 514 for optimal speed. The default value is 8. See zconf.h for total memory
515 usage as a function of windowBits and memLevel. 515 usage as a function of windowBits and memLevel.
516 516
517 The strategy parameter is used to tune the compression algorithm. Use the 517 The strategy parameter is used to tune the compression algorithm. Use the
518 value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a 518 value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
519 filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no 519 filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
520 string match), or Z_RLE to limit match distances to one (run-length 520 string match), or Z_RLE to limit match distances to one (run-length
521 encoding). Filtered data consists mostly of small values with a somewhat 521 encoding). Filtered data consists mostly of small values with a somewhat
522 random distribution. In this case, the compression algorithm is tuned to 522 random distribution. In this case, the compression algorithm is tuned to
523 compress them better. The effect of Z_FILTERED is to force more Huffman 523 compress them better. The effect of Z_FILTERED is to force more Huffman
524 coding and less string matching; it is somewhat intermediate between 524 coding and less string matching; it is somewhat intermediate between
525 Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as 525 Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
526 Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy 526 Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
527 parameter only affects the compression ratio but not the correctness of the 527 parameter only affects the compression ratio but not the correctness of the
528 compressed output even if it is not set appropriately. Z_FIXED prevents the 528 compressed output even if it is not set appropriately. Z_FIXED prevents the
529 use of dynamic Huffman codes, allowing for a simpler decoder for special 529 use of dynamic Huffman codes, allowing for a simpler decoder for special
530 applications. 530 applications.
531 531
532 deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough 532 deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
533 memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid 533 memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
534 method). msg is set to null if there is no error message. deflateInit2 does 534 method). msg is set to null if there is no error message. deflateInit2 does
535 not perform any compression: this will be done by deflate(). 535 not perform any compression: this will be done by deflate().
536*/ 536*/
537 537
538ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, 538ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
539 const Bytef *dictionary, 539 const Bytef *dictionary,
540 uInt dictLength)); 540 uInt dictLength));
541/* 541/*
542 Initializes the compression dictionary from the given byte sequence 542 Initializes the compression dictionary from the given byte sequence
543 without producing any compressed output. This function must be called 543 without producing any compressed output. This function must be called
544 immediately after deflateInit, deflateInit2 or deflateReset, before any 544 immediately after deflateInit, deflateInit2 or deflateReset, before any
545 call of deflate. The compressor and decompressor must use exactly the same 545 call of deflate. The compressor and decompressor must use exactly the same
546 dictionary (see inflateSetDictionary). 546 dictionary (see inflateSetDictionary).
547 547
548 The dictionary should consist of strings (byte sequences) that are likely 548 The dictionary should consist of strings (byte sequences) that are likely
549 to be encountered later in the data to be compressed, with the most commonly 549 to be encountered later in the data to be compressed, with the most commonly
550 used strings preferably put towards the end of the dictionary. Using a 550 used strings preferably put towards the end of the dictionary. Using a
551 dictionary is most useful when the data to be compressed is short and can be 551 dictionary is most useful when the data to be compressed is short and can be
552 predicted with good accuracy; the data can then be compressed better than 552 predicted with good accuracy; the data can then be compressed better than
553 with the default empty dictionary. 553 with the default empty dictionary.
554 554
555 Depending on the size of the compression data structures selected by 555 Depending on the size of the compression data structures selected by
556 deflateInit or deflateInit2, a part of the dictionary may in effect be 556 deflateInit or deflateInit2, a part of the dictionary may in effect be
557 discarded, for example if the dictionary is larger than the window size in 557 discarded, for example if the dictionary is larger than the window size in
558 deflate or deflate2. Thus the strings most likely to be useful should be 558 deflate or deflate2. Thus the strings most likely to be useful should be
559 put at the end of the dictionary, not at the front. In addition, the 559 put at the end of the dictionary, not at the front. In addition, the
560 current implementation of deflate will use at most the window size minus 560 current implementation of deflate will use at most the window size minus
561 262 bytes of the provided dictionary. 561 262 bytes of the provided dictionary.
562 562
563 Upon return of this function, strm->adler is set to the adler32 value 563 Upon return of this function, strm->adler is set to the adler32 value
564 of the dictionary; the decompressor may later use this value to determine 564 of the dictionary; the decompressor may later use this value to determine
565 which dictionary has been used by the compressor. (The adler32 value 565 which dictionary has been used by the compressor. (The adler32 value
566 applies to the whole dictionary even if only a subset of the dictionary is 566 applies to the whole dictionary even if only a subset of the dictionary is
567 actually used by the compressor.) If a raw deflate was requested, then the 567 actually used by the compressor.) If a raw deflate was requested, then the
568 adler32 value is not computed and strm->adler is not set. 568 adler32 value is not computed and strm->adler is not set.
569 569
570 deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a 570 deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
571 parameter is invalid (such as NULL dictionary) or the stream state is 571 parameter is invalid (such as NULL dictionary) or the stream state is
572 inconsistent (for example if deflate has already been called for this stream 572 inconsistent (for example if deflate has already been called for this stream
573 or if the compression method is bsort). deflateSetDictionary does not 573 or if the compression method is bsort). deflateSetDictionary does not
574 perform any compression: this will be done by deflate(). 574 perform any compression: this will be done by deflate().
575*/ 575*/
576 576
577ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, 577ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
578 z_streamp source)); 578 z_streamp source));
579/* 579/*
580 Sets the destination stream as a complete copy of the source stream. 580 Sets the destination stream as a complete copy of the source stream.
581 581
582 This function can be useful when several compression strategies will be 582 This function can be useful when several compression strategies will be
583 tried, for example when there are several ways of pre-processing the input 583 tried, for example when there are several ways of pre-processing the input
584 data with a filter. The streams that will be discarded should then be freed 584 data with a filter. The streams that will be discarded should then be freed
585 by calling deflateEnd. Note that deflateCopy duplicates the internal 585 by calling deflateEnd. Note that deflateCopy duplicates the internal
586 compression state which can be quite large, so this strategy is slow and 586 compression state which can be quite large, so this strategy is slow and
587 can consume lots of memory. 587 can consume lots of memory.
588 588
589 deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not 589 deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
590 enough memory, Z_STREAM_ERROR if the source stream state was inconsistent 590 enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
591 (such as zalloc being NULL). msg is left unchanged in both source and 591 (such as zalloc being NULL). msg is left unchanged in both source and
592 destination. 592 destination.
593*/ 593*/
594 594
595ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); 595ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
596/* 596/*
597 This function is equivalent to deflateEnd followed by deflateInit, 597 This function is equivalent to deflateEnd followed by deflateInit,
598 but does not free and reallocate all the internal compression state. 598 but does not free and reallocate all the internal compression state.
599 The stream will keep the same compression level and any other attributes 599 The stream will keep the same compression level and any other attributes
600 that may have been set by deflateInit2. 600 that may have been set by deflateInit2.
601 601
602 deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source 602 deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
603 stream state was inconsistent (such as zalloc or state being NULL). 603 stream state was inconsistent (such as zalloc or state being NULL).
604*/ 604*/
605 605
606ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, 606ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
607 int level, 607 int level,
608 int strategy)); 608 int strategy));
609/* 609/*
610 Dynamically update the compression level and compression strategy. The 610 Dynamically update the compression level and compression strategy. The
611 interpretation of level and strategy is as in deflateInit2. This can be 611 interpretation of level and strategy is as in deflateInit2. This can be
612 used to switch between compression and straight copy of the input data, or 612 used to switch between compression and straight copy of the input data, or
613 to switch to a different kind of input data requiring a different 613 to switch to a different kind of input data requiring a different
614 strategy. If the compression level is changed, the input available so far 614 strategy. If the compression level is changed, the input available so far
615 is compressed with the old level (and may be flushed); the new level will 615 is compressed with the old level (and may be flushed); the new level will
616 take effect only at the next call of deflate(). 616 take effect only at the next call of deflate().
617 617
618 Before the call of deflateParams, the stream state must be set as for 618 Before the call of deflateParams, the stream state must be set as for
619 a call of deflate(), since the currently available input may have to 619 a call of deflate(), since the currently available input may have to
620 be compressed and flushed. In particular, strm->avail_out must be non-zero. 620 be compressed and flushed. In particular, strm->avail_out must be non-zero.
621 621
622 deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source 622 deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
623 stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR 623 stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
624 if strm->avail_out was zero. 624 if strm->avail_out was zero.
625*/ 625*/
626 626
627ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, 627ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
628 int good_length, 628 int good_length,
629 int max_lazy, 629 int max_lazy,
630 int nice_length, 630 int nice_length,
631 int max_chain)); 631 int max_chain));
632/* 632/*
633 Fine tune deflate's internal compression parameters. This should only be 633 Fine tune deflate's internal compression parameters. This should only be
634 used by someone who understands the algorithm used by zlib's deflate for 634 used by someone who understands the algorithm used by zlib's deflate for
635 searching for the best matching string, and even then only by the most 635 searching for the best matching string, and even then only by the most
636 fanatic optimizer trying to squeeze out the last compressed bit for their 636 fanatic optimizer trying to squeeze out the last compressed bit for their
637 specific input data. Read the deflate.c source code for the meaning of the 637 specific input data. Read the deflate.c source code for the meaning of the
638 max_lazy, good_length, nice_length, and max_chain parameters. 638 max_lazy, good_length, nice_length, and max_chain parameters.
639 639
640 deflateTune() can be called after deflateInit() or deflateInit2(), and 640 deflateTune() can be called after deflateInit() or deflateInit2(), and
641 returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. 641 returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
642 */ 642 */
643 643
644ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, 644ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
645 uLong sourceLen)); 645 uLong sourceLen));
646/* 646/*
647 deflateBound() returns an upper bound on the compressed size after 647 deflateBound() returns an upper bound on the compressed size after
648 deflation of sourceLen bytes. It must be called after deflateInit() 648 deflation of sourceLen bytes. It must be called after deflateInit()
649 or deflateInit2(). This would be used to allocate an output buffer 649 or deflateInit2(). This would be used to allocate an output buffer
650 for deflation in a single pass, and so would be called before deflate(). 650 for deflation in a single pass, and so would be called before deflate().
651*/ 651*/
652 652
653ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, 653ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
654 int bits, 654 int bits,
655 int value)); 655 int value));
656/* 656/*
657 deflatePrime() inserts bits in the deflate output stream. The intent 657 deflatePrime() inserts bits in the deflate output stream. The intent
658 is that this function is used to start off the deflate output with the 658 is that this function is used to start off the deflate output with the
659 bits leftover from a previous deflate stream when appending to it. As such, 659 bits leftover from a previous deflate stream when appending to it. As such,
660 this function can only be used for raw deflate, and must be used before the 660 this function can only be used for raw deflate, and must be used before the
661 first deflate() call after a deflateInit2() or deflateReset(). bits must be 661 first deflate() call after a deflateInit2() or deflateReset(). bits must be
662 less than or equal to 16, and that many of the least significant bits of 662 less than or equal to 16, and that many of the least significant bits of
663 value will be inserted in the output. 663 value will be inserted in the output.
664 664
665 deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source 665 deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
666 stream state was inconsistent. 666 stream state was inconsistent.
667*/ 667*/
668 668
669ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, 669ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
670 gz_headerp head)); 670 gz_headerp head));
671/* 671/*
672 deflateSetHeader() provides gzip header information for when a gzip 672 deflateSetHeader() provides gzip header information for when a gzip
673 stream is requested by deflateInit2(). deflateSetHeader() may be called 673 stream is requested by deflateInit2(). deflateSetHeader() may be called
674 after deflateInit2() or deflateReset() and before the first call of 674 after deflateInit2() or deflateReset() and before the first call of
675 deflate(). The text, time, os, extra field, name, and comment information 675 deflate(). The text, time, os, extra field, name, and comment information
676 in the provided gz_header structure are written to the gzip header (xflag is 676 in the provided gz_header structure are written to the gzip header (xflag is
677 ignored -- the extra flags are set according to the compression level). The 677 ignored -- the extra flags are set according to the compression level). The
678 caller must assure that, if not Z_NULL, name and comment are terminated with 678 caller must assure that, if not Z_NULL, name and comment are terminated with
679 a zero byte, and that if extra is not Z_NULL, that extra_len bytes are 679 a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
680 available there. If hcrc is true, a gzip header crc is included. Note that 680 available there. If hcrc is true, a gzip header crc is included. Note that
681 the current versions of the command-line version of gzip (up through version 681 the current versions of the command-line version of gzip (up through version
682 1.3.x) do not support header crc's, and will report that it is a "multi-part 682 1.3.x) do not support header crc's, and will report that it is a "multi-part
683 gzip file" and give up. 683 gzip file" and give up.
684 684
685 If deflateSetHeader is not used, the default gzip header has text false, 685 If deflateSetHeader is not used, the default gzip header has text false,
686 the time set to zero, and os set to 255, with no extra, name, or comment 686 the time set to zero, and os set to 255, with no extra, name, or comment
687 fields. The gzip header is returned to the default state by deflateReset(). 687 fields. The gzip header is returned to the default state by deflateReset().
688 688
689 deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source 689 deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
690 stream state was inconsistent. 690 stream state was inconsistent.
691*/ 691*/
692 692
693/* 693/*
694ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, 694ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
695 int windowBits)); 695 int windowBits));
696 696
697 This is another version of inflateInit with an extra parameter. The 697 This is another version of inflateInit with an extra parameter. The
698 fields next_in, avail_in, zalloc, zfree and opaque must be initialized 698 fields next_in, avail_in, zalloc, zfree and opaque must be initialized
699 before by the caller. 699 before by the caller.
700 700
701 The windowBits parameter is the base two logarithm of the maximum window 701 The windowBits parameter is the base two logarithm of the maximum window
702 size (the size of the history buffer). It should be in the range 8..15 for 702 size (the size of the history buffer). It should be in the range 8..15 for
703 this version of the library. The default value is 15 if inflateInit is used 703 this version of the library. The default value is 15 if inflateInit is used
704 instead. windowBits must be greater than or equal to the windowBits value 704 instead. windowBits must be greater than or equal to the windowBits value
705 provided to deflateInit2() while compressing, or it must be equal to 15 if 705 provided to deflateInit2() while compressing, or it must be equal to 15 if
706 deflateInit2() was not used. If a compressed stream with a larger window 706 deflateInit2() was not used. If a compressed stream with a larger window
707 size is given as input, inflate() will return with the error code 707 size is given as input, inflate() will return with the error code
708 Z_DATA_ERROR instead of trying to allocate a larger window. 708 Z_DATA_ERROR instead of trying to allocate a larger window.
709 709
710 windowBits can also be -8..-15 for raw inflate. In this case, -windowBits 710 windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
711 determines the window size. inflate() will then process raw deflate data, 711 determines the window size. inflate() will then process raw deflate data,
712 not looking for a zlib or gzip header, not generating a check value, and not 712 not looking for a zlib or gzip header, not generating a check value, and not
713 looking for any check values for comparison at the end of the stream. This 713 looking for any check values for comparison at the end of the stream. This
714 is for use with other formats that use the deflate compressed data format 714 is for use with other formats that use the deflate compressed data format
715 such as zip. Those formats provide their own check values. If a custom 715 such as zip. Those formats provide their own check values. If a custom
716 format is developed using the raw deflate format for compressed data, it is 716 format is developed using the raw deflate format for compressed data, it is
717 recommended that a check value such as an adler32 or a crc32 be applied to 717 recommended that a check value such as an adler32 or a crc32 be applied to
718 the uncompressed data as is done in the zlib, gzip, and zip formats. For 718 the uncompressed data as is done in the zlib, gzip, and zip formats. For
719 most applications, the zlib format should be used as is. Note that comments 719 most applications, the zlib format should be used as is. Note that comments
720 above on the use in deflateInit2() applies to the magnitude of windowBits. 720 above on the use in deflateInit2() applies to the magnitude of windowBits.
721 721
722 windowBits can also be greater than 15 for optional gzip decoding. Add 722 windowBits can also be greater than 15 for optional gzip decoding. Add
723 32 to windowBits to enable zlib and gzip decoding with automatic header 723 32 to windowBits to enable zlib and gzip decoding with automatic header
724 detection, or add 16 to decode only the gzip format (the zlib format will 724 detection, or add 16 to decode only the gzip format (the zlib format will
725 return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is 725 return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
726 a crc32 instead of an adler32. 726 a crc32 instead of an adler32.
727 727
728 inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough 728 inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
729 memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg 729 memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
730 is set to null if there is no error message. inflateInit2 does not perform 730 is set to null if there is no error message. inflateInit2 does not perform
731 any decompression apart from reading the zlib header if present: this will 731 any decompression apart from reading the zlib header if present: this will
732 be done by inflate(). (So next_in and avail_in may be modified, but next_out 732 be done by inflate(). (So next_in and avail_in may be modified, but next_out
733 and avail_out are unchanged.) 733 and avail_out are unchanged.)
734*/ 734*/
735 735
736ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, 736ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
737 const Bytef *dictionary, 737 const Bytef *dictionary,
738 uInt dictLength)); 738 uInt dictLength));
739/* 739/*
740 Initializes the decompression dictionary from the given uncompressed byte 740 Initializes the decompression dictionary from the given uncompressed byte
741 sequence. This function must be called immediately after a call of inflate, 741 sequence. This function must be called immediately after a call of inflate,
742 if that call returned Z_NEED_DICT. The dictionary chosen by the compressor 742 if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
743 can be determined from the adler32 value returned by that call of inflate. 743 can be determined from the adler32 value returned by that call of inflate.
744 The compressor and decompressor must use exactly the same dictionary (see 744 The compressor and decompressor must use exactly the same dictionary (see
745 deflateSetDictionary). For raw inflate, this function can be called 745 deflateSetDictionary). For raw inflate, this function can be called
746 immediately after inflateInit2() or inflateReset() and before any call of 746 immediately after inflateInit2() or inflateReset() and before any call of
747 inflate() to set the dictionary. The application must insure that the 747 inflate() to set the dictionary. The application must insure that the
748 dictionary that was used for compression is provided. 748 dictionary that was used for compression is provided.
749 749
750 inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a 750 inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
751 parameter is invalid (such as NULL dictionary) or the stream state is 751 parameter is invalid (such as NULL dictionary) or the stream state is
752 inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the 752 inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
753 expected one (incorrect adler32 value). inflateSetDictionary does not 753 expected one (incorrect adler32 value). inflateSetDictionary does not
754 perform any decompression: this will be done by subsequent calls of 754 perform any decompression: this will be done by subsequent calls of
755 inflate(). 755 inflate().
756*/ 756*/
757 757
758ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); 758ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
759/* 759/*
760 Skips invalid compressed data until a full flush point (see above the 760 Skips invalid compressed data until a full flush point (see above the
761 description of deflate with Z_FULL_FLUSH) can be found, or until all 761 description of deflate with Z_FULL_FLUSH) can be found, or until all
762 available input is skipped. No output is provided. 762 available input is skipped. No output is provided.
763 763
764 inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR 764 inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
765 if no more input was provided, Z_DATA_ERROR if no flush point has been found, 765 if no more input was provided, Z_DATA_ERROR if no flush point has been found,
766 or Z_STREAM_ERROR if the stream structure was inconsistent. In the success 766 or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
767 case, the application may save the current current value of total_in which 767 case, the application may save the current current value of total_in which
768 indicates where valid compressed data was found. In the error case, the 768 indicates where valid compressed data was found. In the error case, the
769 application may repeatedly call inflateSync, providing more input each time, 769 application may repeatedly call inflateSync, providing more input each time,
770 until success or end of the input data. 770 until success or end of the input data.
771*/ 771*/
772 772
773ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, 773ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
774 z_streamp source)); 774 z_streamp source));
775/* 775/*
776 Sets the destination stream as a complete copy of the source stream. 776 Sets the destination stream as a complete copy of the source stream.
777 777
778 This function can be useful when randomly accessing a large stream. The 778 This function can be useful when randomly accessing a large stream. The
779 first pass through the stream can periodically record the inflate state, 779 first pass through the stream can periodically record the inflate state,
780 allowing restarting inflate at those points when randomly accessing the 780 allowing restarting inflate at those points when randomly accessing the
781 stream. 781 stream.
782 782
783 inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not 783 inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
784 enough memory, Z_STREAM_ERROR if the source stream state was inconsistent 784 enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
785 (such as zalloc being NULL). msg is left unchanged in both source and 785 (such as zalloc being NULL). msg is left unchanged in both source and
786 destination. 786 destination.
787*/ 787*/
788 788
789ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); 789ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
790/* 790/*
791 This function is equivalent to inflateEnd followed by inflateInit, 791 This function is equivalent to inflateEnd followed by inflateInit,
792 but does not free and reallocate all the internal decompression state. 792 but does not free and reallocate all the internal decompression state.
793 The stream will keep attributes that may have been set by inflateInit2. 793 The stream will keep attributes that may have been set by inflateInit2.
794 794
795 inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source 795 inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
796 stream state was inconsistent (such as zalloc or state being NULL). 796 stream state was inconsistent (such as zalloc or state being NULL).
797*/ 797*/
798 798
799ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, 799ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
800 int bits, 800 int bits,
801 int value)); 801 int value));
802/* 802/*
803 This function inserts bits in the inflate input stream. The intent is 803 This function inserts bits in the inflate input stream. The intent is
804 that this function is used to start inflating at a bit position in the 804 that this function is used to start inflating at a bit position in the
805 middle of a byte. The provided bits will be used before any bytes are used 805 middle of a byte. The provided bits will be used before any bytes are used
806 from next_in. This function should only be used with raw inflate, and 806 from next_in. This function should only be used with raw inflate, and
807 should be used before the first inflate() call after inflateInit2() or 807 should be used before the first inflate() call after inflateInit2() or
808 inflateReset(). bits must be less than or equal to 16, and that many of the 808 inflateReset(). bits must be less than or equal to 16, and that many of the
809 least significant bits of value will be inserted in the input. 809 least significant bits of value will be inserted in the input.
810 810
811 inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source 811 inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
812 stream state was inconsistent. 812 stream state was inconsistent.
813*/ 813*/
814 814
815ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, 815ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
816 gz_headerp head)); 816 gz_headerp head));
817/* 817/*
818 inflateGetHeader() requests that gzip header information be stored in the 818 inflateGetHeader() requests that gzip header information be stored in the
819 provided gz_header structure. inflateGetHeader() may be called after 819 provided gz_header structure. inflateGetHeader() may be called after
820 inflateInit2() or inflateReset(), and before the first call of inflate(). 820 inflateInit2() or inflateReset(), and before the first call of inflate().
821 As inflate() processes the gzip stream, head->done is zero until the header 821 As inflate() processes the gzip stream, head->done is zero until the header
822 is completed, at which time head->done is set to one. If a zlib stream is 822 is completed, at which time head->done is set to one. If a zlib stream is
823 being decoded, then head->done is set to -1 to indicate that there will be 823 being decoded, then head->done is set to -1 to indicate that there will be
824 no gzip header information forthcoming. Note that Z_BLOCK can be used to 824 no gzip header information forthcoming. Note that Z_BLOCK can be used to
825 force inflate() to return immediately after header processing is complete 825 force inflate() to return immediately after header processing is complete
826 and before any actual data is decompressed. 826 and before any actual data is decompressed.
827 827
828 The text, time, xflags, and os fields are filled in with the gzip header 828 The text, time, xflags, and os fields are filled in with the gzip header
829 contents. hcrc is set to true if there is a header CRC. (The header CRC 829 contents. hcrc is set to true if there is a header CRC. (The header CRC
830 was valid if done is set to one.) If extra is not Z_NULL, then extra_max 830 was valid if done is set to one.) If extra is not Z_NULL, then extra_max
831 contains the maximum number of bytes to write to extra. Once done is true, 831 contains the maximum number of bytes to write to extra. Once done is true,
832 extra_len contains the actual extra field length, and extra contains the 832 extra_len contains the actual extra field length, and extra contains the
833 extra field, or that field truncated if extra_max is less than extra_len. 833 extra field, or that field truncated if extra_max is less than extra_len.
834 If name is not Z_NULL, then up to name_max characters are written there, 834 If name is not Z_NULL, then up to name_max characters are written there,
835 terminated with a zero unless the length is greater than name_max. If 835 terminated with a zero unless the length is greater than name_max. If
836 comment is not Z_NULL, then up to comm_max characters are written there, 836 comment is not Z_NULL, then up to comm_max characters are written there,
837 terminated with a zero unless the length is greater than comm_max. When 837 terminated with a zero unless the length is greater than comm_max. When
838 any of extra, name, or comment are not Z_NULL and the respective field is 838 any of extra, name, or comment are not Z_NULL and the respective field is
839 not present in the header, then that field is set to Z_NULL to signal its 839 not present in the header, then that field is set to Z_NULL to signal its
840 absence. This allows the use of deflateSetHeader() with the returned 840 absence. This allows the use of deflateSetHeader() with the returned
841 structure to duplicate the header. However if those fields are set to 841 structure to duplicate the header. However if those fields are set to
842 allocated memory, then the application will need to save those pointers 842 allocated memory, then the application will need to save those pointers
843 elsewhere so that they can be eventually freed. 843 elsewhere so that they can be eventually freed.
844 844
845 If inflateGetHeader is not used, then the header information is simply 845 If inflateGetHeader is not used, then the header information is simply
846 discarded. The header is always checked for validity, including the header 846 discarded. The header is always checked for validity, including the header
847 CRC if present. inflateReset() will reset the process to discard the header 847 CRC if present. inflateReset() will reset the process to discard the header
848 information. The application would need to call inflateGetHeader() again to 848 information. The application would need to call inflateGetHeader() again to
849 retrieve the header from the next gzip stream. 849 retrieve the header from the next gzip stream.
850 850
851 inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source 851 inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
852 stream state was inconsistent. 852 stream state was inconsistent.
853*/ 853*/
854 854
855/* 855/*
856ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, 856ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
857 unsigned char FAR *window)); 857 unsigned char FAR *window));
858 858
859 Initialize the internal stream state for decompression using inflateBack() 859 Initialize the internal stream state for decompression using inflateBack()
860 calls. The fields zalloc, zfree and opaque in strm must be initialized 860 calls. The fields zalloc, zfree and opaque in strm must be initialized
861 before the call. If zalloc and zfree are Z_NULL, then the default library- 861 before the call. If zalloc and zfree are Z_NULL, then the default library-
862 derived memory allocation routines are used. windowBits is the base two 862 derived memory allocation routines are used. windowBits is the base two
863 logarithm of the window size, in the range 8..15. window is a caller 863 logarithm of the window size, in the range 8..15. window is a caller
864 supplied buffer of that size. Except for special applications where it is 864 supplied buffer of that size. Except for special applications where it is
865 assured that deflate was used with small window sizes, windowBits must be 15 865 assured that deflate was used with small window sizes, windowBits must be 15
866 and a 32K byte window must be supplied to be able to decompress general 866 and a 32K byte window must be supplied to be able to decompress general
867 deflate streams. 867 deflate streams.
868 868
869 See inflateBack() for the usage of these routines. 869 See inflateBack() for the usage of these routines.
870 870
871 inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of 871 inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
872 the paramaters are invalid, Z_MEM_ERROR if the internal state could not 872 the paramaters are invalid, Z_MEM_ERROR if the internal state could not
873 be allocated, or Z_VERSION_ERROR if the version of the library does not 873 be allocated, or Z_VERSION_ERROR if the version of the library does not
874 match the version of the header file. 874 match the version of the header file.
875*/ 875*/
876 876
877typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); 877typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
878typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); 878typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
879 879
880ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, 880ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
881 in_func in, void FAR *in_desc, 881 in_func in, void FAR *in_desc,
882 out_func out, void FAR *out_desc)); 882 out_func out, void FAR *out_desc));
883/* 883/*
884 inflateBack() does a raw inflate with a single call using a call-back 884 inflateBack() does a raw inflate with a single call using a call-back
885 interface for input and output. This is more efficient than inflate() for 885 interface for input and output. This is more efficient than inflate() for
886 file i/o applications in that it avoids copying between the output and the 886 file i/o applications in that it avoids copying between the output and the
887 sliding window by simply making the window itself the output buffer. This 887 sliding window by simply making the window itself the output buffer. This
888 function trusts the application to not change the output buffer passed by 888 function trusts the application to not change the output buffer passed by
889 the output function, at least until inflateBack() returns. 889 the output function, at least until inflateBack() returns.
890 890
891 inflateBackInit() must be called first to allocate the internal state 891 inflateBackInit() must be called first to allocate the internal state
892 and to initialize the state with the user-provided window buffer. 892 and to initialize the state with the user-provided window buffer.
893 inflateBack() may then be used multiple times to inflate a complete, raw 893 inflateBack() may then be used multiple times to inflate a complete, raw
894 deflate stream with each call. inflateBackEnd() is then called to free 894 deflate stream with each call. inflateBackEnd() is then called to free
895 the allocated state. 895 the allocated state.
896 896
897 A raw deflate stream is one with no zlib or gzip header or trailer. 897 A raw deflate stream is one with no zlib or gzip header or trailer.
898 This routine would normally be used in a utility that reads zip or gzip 898 This routine would normally be used in a utility that reads zip or gzip
899 files and writes out uncompressed files. The utility would decode the 899 files and writes out uncompressed files. The utility would decode the
900 header and process the trailer on its own, hence this routine expects 900 header and process the trailer on its own, hence this routine expects
901 only the raw deflate stream to decompress. This is different from the 901 only the raw deflate stream to decompress. This is different from the
902 normal behavior of inflate(), which expects either a zlib or gzip header and 902 normal behavior of inflate(), which expects either a zlib or gzip header and
903 trailer around the deflate stream. 903 trailer around the deflate stream.
904 904
905 inflateBack() uses two subroutines supplied by the caller that are then 905 inflateBack() uses two subroutines supplied by the caller that are then
906 called by inflateBack() for input and output. inflateBack() calls those 906 called by inflateBack() for input and output. inflateBack() calls those
907 routines until it reads a complete deflate stream and writes out all of the 907 routines until it reads a complete deflate stream and writes out all of the
908 uncompressed data, or until it encounters an error. The function's 908 uncompressed data, or until it encounters an error. The function's
909 parameters and return types are defined above in the in_func and out_func 909 parameters and return types are defined above in the in_func and out_func
910 typedefs. inflateBack() will call in(in_desc, &buf) which should return the 910 typedefs. inflateBack() will call in(in_desc, &buf) which should return the
911 number of bytes of provided input, and a pointer to that input in buf. If 911 number of bytes of provided input, and a pointer to that input in buf. If
912 there is no input available, in() must return zero--buf is ignored in that 912 there is no input available, in() must return zero--buf is ignored in that
913 case--and inflateBack() will return a buffer error. inflateBack() will call 913 case--and inflateBack() will return a buffer error. inflateBack() will call
914 out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() 914 out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
915 should return zero on success, or non-zero on failure. If out() returns 915 should return zero on success, or non-zero on failure. If out() returns
916 non-zero, inflateBack() will return with an error. Neither in() nor out() 916 non-zero, inflateBack() will return with an error. Neither in() nor out()
917 are permitted to change the contents of the window provided to 917 are permitted to change the contents of the window provided to
918 inflateBackInit(), which is also the buffer that out() uses to write from. 918 inflateBackInit(), which is also the buffer that out() uses to write from.
919 The length written by out() will be at most the window size. Any non-zero 919 The length written by out() will be at most the window size. Any non-zero
920 amount of input may be provided by in(). 920 amount of input may be provided by in().
921 921
922 For convenience, inflateBack() can be provided input on the first call by 922 For convenience, inflateBack() can be provided input on the first call by
923 setting strm->next_in and strm->avail_in. If that input is exhausted, then 923 setting strm->next_in and strm->avail_in. If that input is exhausted, then
924 in() will be called. Therefore strm->next_in must be initialized before 924 in() will be called. Therefore strm->next_in must be initialized before
925 calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called 925 calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
926 immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in 926 immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
927 must also be initialized, and then if strm->avail_in is not zero, input will 927 must also be initialized, and then if strm->avail_in is not zero, input will
928 initially be taken from strm->next_in[0 .. strm->avail_in - 1]. 928 initially be taken from strm->next_in[0 .. strm->avail_in - 1].
929 929
930 The in_desc and out_desc parameters of inflateBack() is passed as the 930 The in_desc and out_desc parameters of inflateBack() is passed as the
931 first parameter of in() and out() respectively when they are called. These 931 first parameter of in() and out() respectively when they are called. These
932 descriptors can be optionally used to pass any information that the caller- 932 descriptors can be optionally used to pass any information that the caller-
933 supplied in() and out() functions need to do their job. 933 supplied in() and out() functions need to do their job.
934 934
935 On return, inflateBack() will set strm->next_in and strm->avail_in to 935 On return, inflateBack() will set strm->next_in and strm->avail_in to
936 pass back any unused input that was provided by the last in() call. The 936 pass back any unused input that was provided by the last in() call. The
937 return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR 937 return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
938 if in() or out() returned an error, Z_DATA_ERROR if there was a format 938 if in() or out() returned an error, Z_DATA_ERROR if there was a format
939 error in the deflate stream (in which case strm->msg is set to indicate the 939 error in the deflate stream (in which case strm->msg is set to indicate the
940 nature of the error), or Z_STREAM_ERROR if the stream was not properly 940 nature of the error), or Z_STREAM_ERROR if the stream was not properly
941 initialized. In the case of Z_BUF_ERROR, an input or output error can be 941 initialized. In the case of Z_BUF_ERROR, an input or output error can be
942 distinguished using strm->next_in which will be Z_NULL only if in() returned 942 distinguished using strm->next_in which will be Z_NULL only if in() returned
943 an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to 943 an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
944 out() returning non-zero. (in() will always be called before out(), so 944 out() returning non-zero. (in() will always be called before out(), so
945 strm->next_in is assured to be defined if out() returns non-zero.) Note 945 strm->next_in is assured to be defined if out() returns non-zero.) Note
946 that inflateBack() cannot return Z_OK. 946 that inflateBack() cannot return Z_OK.
947*/ 947*/
948 948
949ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); 949ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
950/* 950/*
951 All memory allocated by inflateBackInit() is freed. 951 All memory allocated by inflateBackInit() is freed.
952 952
953 inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream 953 inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
954 state was inconsistent. 954 state was inconsistent.
955*/ 955*/
956 956
957ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); 957ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
958/* Return flags indicating compile-time options. 958/* Return flags indicating compile-time options.
959 959
960 Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: 960 Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
961 1.0: size of uInt 961 1.0: size of uInt
962 3.2: size of uLong 962 3.2: size of uLong
963 5.4: size of voidpf (pointer) 963 5.4: size of voidpf (pointer)
964 7.6: size of z_off_t 964 7.6: size of z_off_t
965 965
966 Compiler, assembler, and debug options: 966 Compiler, assembler, and debug options:
967 8: DEBUG 967 8: DEBUG
968 9: ASMV or ASMINF -- use ASM code 968 9: ASMV or ASMINF -- use ASM code
969 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention 969 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
970 11: 0 (reserved) 970 11: 0 (reserved)
971 971
972 One-time table building (smaller code, but not thread-safe if true): 972 One-time table building (smaller code, but not thread-safe if true):
973 12: BUILDFIXED -- build static block decoding tables when needed 973 12: BUILDFIXED -- build static block decoding tables when needed
974 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed 974 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
975 14,15: 0 (reserved) 975 14,15: 0 (reserved)
976 976
977 Library content (indicates missing functionality): 977 Library content (indicates missing functionality):
978 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking 978 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
979 deflate code when not needed) 979 deflate code when not needed)
980 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect 980 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
981 and decode gzip streams (to avoid linking crc code) 981 and decode gzip streams (to avoid linking crc code)
982 18-19: 0 (reserved) 982 18-19: 0 (reserved)
983 983
984 Operation variations (changes in library functionality): 984 Operation variations (changes in library functionality):
985 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate 985 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
986 21: FASTEST -- deflate algorithm with only one, lowest compression level 986 21: FASTEST -- deflate algorithm with only one, lowest compression level
987 22,23: 0 (reserved) 987 22,23: 0 (reserved)
988 988
989 The sprintf variant used by gzprintf (zero is best): 989 The sprintf variant used by gzprintf (zero is best):
990 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format 990 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
991 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! 991 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
992 26: 0 = returns value, 1 = void -- 1 means inferred string length returned 992 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
993 993
994 Remainder: 994 Remainder:
995 27-31: 0 (reserved) 995 27-31: 0 (reserved)
996 */ 996 */
997 997
998 998
999 /* utility functions */ 999 /* utility functions */
1000 1000
1001/* 1001/*
1002 The following utility functions are implemented on top of the 1002 The following utility functions are implemented on top of the
1003 basic stream-oriented functions. To simplify the interface, some 1003 basic stream-oriented functions. To simplify the interface, some
1004 default options are assumed (compression level and memory usage, 1004 default options are assumed (compression level and memory usage,
1005 standard memory allocation functions). The source code of these 1005 standard memory allocation functions). The source code of these
1006 utility functions can easily be modified if you need special options. 1006 utility functions can easily be modified if you need special options.
1007*/ 1007*/
1008 1008
1009ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, 1009ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
1010 const Bytef *source, uLong sourceLen)); 1010 const Bytef *source, uLong sourceLen));
1011/* 1011/*
1012 Compresses the source buffer into the destination buffer. sourceLen is 1012 Compresses the source buffer into the destination buffer. sourceLen is
1013 the byte length of the source buffer. Upon entry, destLen is the total 1013 the byte length of the source buffer. Upon entry, destLen is the total
1014 size of the destination buffer, which must be at least the value returned 1014 size of the destination buffer, which must be at least the value returned
1015 by compressBound(sourceLen). Upon exit, destLen is the actual size of the 1015 by compressBound(sourceLen). Upon exit, destLen is the actual size of the
1016 compressed buffer. 1016 compressed buffer.
1017 This function can be used to compress a whole file at once if the 1017 This function can be used to compress a whole file at once if the
1018 input file is mmap'ed. 1018 input file is mmap'ed.
1019 compress returns Z_OK if success, Z_MEM_ERROR if there was not 1019 compress returns Z_OK if success, Z_MEM_ERROR if there was not
1020 enough memory, Z_BUF_ERROR if there was not enough room in the output 1020 enough memory, Z_BUF_ERROR if there was not enough room in the output
1021 buffer. 1021 buffer.
1022*/ 1022*/
1023 1023
1024ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, 1024ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
1025 const Bytef *source, uLong sourceLen, 1025 const Bytef *source, uLong sourceLen,
1026 int level)); 1026 int level));
1027/* 1027/*
1028 Compresses the source buffer into the destination buffer. The level 1028 Compresses the source buffer into the destination buffer. The level
1029 parameter has the same meaning as in deflateInit. sourceLen is the byte 1029 parameter has the same meaning as in deflateInit. sourceLen is the byte
1030 length of the source buffer. Upon entry, destLen is the total size of the 1030 length of the source buffer. Upon entry, destLen is the total size of the
1031 destination buffer, which must be at least the value returned by 1031 destination buffer, which must be at least the value returned by
1032 compressBound(sourceLen). Upon exit, destLen is the actual size of the 1032 compressBound(sourceLen). Upon exit, destLen is the actual size of the
1033 compressed buffer. 1033 compressed buffer.
1034 1034
1035 compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough 1035 compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
1036 memory, Z_BUF_ERROR if there was not enough room in the output buffer, 1036 memory, Z_BUF_ERROR if there was not enough room in the output buffer,
1037 Z_STREAM_ERROR if the level parameter is invalid. 1037 Z_STREAM_ERROR if the level parameter is invalid.
1038*/ 1038*/
1039 1039
1040ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); 1040ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
1041/* 1041/*
1042 compressBound() returns an upper bound on the compressed size after 1042 compressBound() returns an upper bound on the compressed size after
1043 compress() or compress2() on sourceLen bytes. It would be used before 1043 compress() or compress2() on sourceLen bytes. It would be used before
1044 a compress() or compress2() call to allocate the destination buffer. 1044 a compress() or compress2() call to allocate the destination buffer.
1045*/ 1045*/
1046 1046
1047ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, 1047ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
1048 const Bytef *source, uLong sourceLen)); 1048 const Bytef *source, uLong sourceLen));
1049/* 1049/*
1050 Decompresses the source buffer into the destination buffer. sourceLen is 1050 Decompresses the source buffer into the destination buffer. sourceLen is
1051 the byte length of the source buffer. Upon entry, destLen is the total 1051 the byte length of the source buffer. Upon entry, destLen is the total
1052 size of the destination buffer, which must be large enough to hold the 1052 size of the destination buffer, which must be large enough to hold the
1053 entire uncompressed data. (The size of the uncompressed data must have 1053 entire uncompressed data. (The size of the uncompressed data must have
1054 been saved previously by the compressor and transmitted to the decompressor 1054 been saved previously by the compressor and transmitted to the decompressor
1055 by some mechanism outside the scope of this compression library.) 1055 by some mechanism outside the scope of this compression library.)
1056 Upon exit, destLen is the actual size of the compressed buffer. 1056 Upon exit, destLen is the actual size of the compressed buffer.
1057 This function can be used to decompress a whole file at once if the 1057 This function can be used to decompress a whole file at once if the
1058 input file is mmap'ed. 1058 input file is mmap'ed.
1059 1059
1060 uncompress returns Z_OK if success, Z_MEM_ERROR if there was not 1060 uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
1061 enough memory, Z_BUF_ERROR if there was not enough room in the output 1061 enough memory, Z_BUF_ERROR if there was not enough room in the output
1062 buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. 1062 buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
1063*/ 1063*/
1064 1064
1065 1065
1066typedef voidp gzFile; 1066typedef voidp gzFile;
1067 1067
1068ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); 1068ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
1069/* 1069/*
1070 Opens a gzip (.gz) file for reading or writing. The mode parameter 1070 Opens a gzip (.gz) file for reading or writing. The mode parameter
1071 is as in fopen ("rb" or "wb") but can also include a compression level 1071 is as in fopen ("rb" or "wb") but can also include a compression level
1072 ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for 1072 ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
1073 Huffman only compression as in "wb1h", or 'R' for run-length encoding 1073 Huffman only compression as in "wb1h", or 'R' for run-length encoding
1074 as in "wb1R". (See the description of deflateInit2 for more information 1074 as in "wb1R". (See the description of deflateInit2 for more information
1075 about the strategy parameter.) 1075 about the strategy parameter.)
1076 1076
1077 gzopen can be used to read a file which is not in gzip format; in this 1077 gzopen can be used to read a file which is not in gzip format; in this
1078 case gzread will directly read from the file without decompression. 1078 case gzread will directly read from the file without decompression.
1079 1079
1080 gzopen returns NULL if the file could not be opened or if there was 1080 gzopen returns NULL if the file could not be opened or if there was
1081 insufficient memory to allocate the (de)compression state; errno 1081 insufficient memory to allocate the (de)compression state; errno
1082 can be checked to distinguish the two cases (if errno is zero, the 1082 can be checked to distinguish the two cases (if errno is zero, the
1083 zlib error is Z_MEM_ERROR). */ 1083 zlib error is Z_MEM_ERROR). */
1084 1084
1085ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); 1085ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
1086/* 1086/*
1087 gzdopen() associates a gzFile with the file descriptor fd. File 1087 gzdopen() associates a gzFile with the file descriptor fd. File
1088 descriptors are obtained from calls like open, dup, creat, pipe or 1088 descriptors are obtained from calls like open, dup, creat, pipe or
1089 fileno (in the file has been previously opened with fopen). 1089 fileno (in the file has been previously opened with fopen).
1090 The mode parameter is as in gzopen. 1090 The mode parameter is as in gzopen.
1091 The next call of gzclose on the returned gzFile will also close the 1091 The next call of gzclose on the returned gzFile will also close the
1092 file descriptor fd, just like fclose(fdopen(fd), mode) closes the file 1092 file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
1093 descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode). 1093 descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
1094 gzdopen returns NULL if there was insufficient memory to allocate 1094 gzdopen returns NULL if there was insufficient memory to allocate
1095 the (de)compression state. 1095 the (de)compression state.
1096*/ 1096*/
1097 1097
1098ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); 1098ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
1099/* 1099/*
1100 Dynamically update the compression level or strategy. See the description 1100 Dynamically update the compression level or strategy. See the description
1101 of deflateInit2 for the meaning of these parameters. 1101 of deflateInit2 for the meaning of these parameters.
1102 gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not 1102 gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
1103 opened for writing. 1103 opened for writing.
1104*/ 1104*/
1105 1105
1106ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); 1106ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
1107/* 1107/*
1108 Reads the given number of uncompressed bytes from the compressed file. 1108 Reads the given number of uncompressed bytes from the compressed file.
1109 If the input file was not in gzip format, gzread copies the given number 1109 If the input file was not in gzip format, gzread copies the given number
1110 of bytes into the buffer. 1110 of bytes into the buffer.
1111 gzread returns the number of uncompressed bytes actually read (0 for 1111 gzread returns the number of uncompressed bytes actually read (0 for
1112 end of file, -1 for error). */ 1112 end of file, -1 for error). */
1113 1113
1114ZEXTERN int ZEXPORT gzwrite OF((gzFile file, 1114ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
1115 voidpc buf, unsigned len)); 1115 voidpc buf, unsigned len));
1116/* 1116/*
1117 Writes the given number of uncompressed bytes into the compressed file. 1117 Writes the given number of uncompressed bytes into the compressed file.
1118 gzwrite returns the number of uncompressed bytes actually written 1118 gzwrite returns the number of uncompressed bytes actually written
1119 (0 in case of error). 1119 (0 in case of error).
1120*/ 1120*/
1121 1121
1122ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); 1122ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
1123/* 1123/*
1124 Converts, formats, and writes the args to the compressed file under 1124 Converts, formats, and writes the args to the compressed file under
1125 control of the format string, as in fprintf. gzprintf returns the number of 1125 control of the format string, as in fprintf. gzprintf returns the number of
1126 uncompressed bytes actually written (0 in case of error). The number of 1126 uncompressed bytes actually written (0 in case of error). The number of
1127 uncompressed bytes written is limited to 4095. The caller should assure that 1127 uncompressed bytes written is limited to 4095. The caller should assure that
1128 this limit is not exceeded. If it is exceeded, then gzprintf() will return 1128 this limit is not exceeded. If it is exceeded, then gzprintf() will return
1129 return an error (0) with nothing written. In this case, there may also be a 1129 return an error (0) with nothing written. In this case, there may also be a
1130 buffer overflow with unpredictable consequences, which is possible only if 1130 buffer overflow with unpredictable consequences, which is possible only if
1131 zlib was compiled with the insecure functions sprintf() or vsprintf() 1131 zlib was compiled with the insecure functions sprintf() or vsprintf()
1132 because the secure snprintf() or vsnprintf() functions were not available. 1132 because the secure snprintf() or vsnprintf() functions were not available.
1133*/ 1133*/
1134 1134
1135ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); 1135ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
1136/* 1136/*
1137 Writes the given null-terminated string to the compressed file, excluding 1137 Writes the given null-terminated string to the compressed file, excluding
1138 the terminating null character. 1138 the terminating null character.
1139 gzputs returns the number of characters written, or -1 in case of error. 1139 gzputs returns the number of characters written, or -1 in case of error.
1140*/ 1140*/
1141 1141
1142ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); 1142ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
1143/* 1143/*
1144 Reads bytes from the compressed file until len-1 characters are read, or 1144 Reads bytes from the compressed file until len-1 characters are read, or
1145 a newline character is read and transferred to buf, or an end-of-file 1145 a newline character is read and transferred to buf, or an end-of-file
1146 condition is encountered. The string is then terminated with a null 1146 condition is encountered. The string is then terminated with a null
1147 character. 1147 character.
1148 gzgets returns buf, or Z_NULL in case of error. 1148 gzgets returns buf, or Z_NULL in case of error.
1149*/ 1149*/
1150 1150
1151ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); 1151ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
1152/* 1152/*
1153 Writes c, converted to an unsigned char, into the compressed file. 1153 Writes c, converted to an unsigned char, into the compressed file.
1154 gzputc returns the value that was written, or -1 in case of error. 1154 gzputc returns the value that was written, or -1 in case of error.
1155*/ 1155*/
1156 1156
1157ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); 1157ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
1158/* 1158/*
1159 Reads one byte from the compressed file. gzgetc returns this byte 1159 Reads one byte from the compressed file. gzgetc returns this byte
1160 or -1 in case of end of file or error. 1160 or -1 in case of end of file or error.
1161*/ 1161*/
1162 1162
1163ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); 1163ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
1164/* 1164/*
1165 Push one character back onto the stream to be read again later. 1165 Push one character back onto the stream to be read again later.
1166 Only one character of push-back is allowed. gzungetc() returns the 1166 Only one character of push-back is allowed. gzungetc() returns the
1167 character pushed, or -1 on failure. gzungetc() will fail if a 1167 character pushed, or -1 on failure. gzungetc() will fail if a
1168 character has been pushed but not read yet, or if c is -1. The pushed 1168 character has been pushed but not read yet, or if c is -1. The pushed
1169 character will be discarded if the stream is repositioned with gzseek() 1169 character will be discarded if the stream is repositioned with gzseek()
1170 or gzrewind(). 1170 or gzrewind().
1171*/ 1171*/
1172 1172
1173ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); 1173ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
1174/* 1174/*
1175 Flushes all pending output into the compressed file. The parameter 1175 Flushes all pending output into the compressed file. The parameter
1176 flush is as in the deflate() function. The return value is the zlib 1176 flush is as in the deflate() function. The return value is the zlib
1177 error number (see function gzerror below). gzflush returns Z_OK if 1177 error number (see function gzerror below). gzflush returns Z_OK if
1178 the flush parameter is Z_FINISH and all output could be flushed. 1178 the flush parameter is Z_FINISH and all output could be flushed.
1179 gzflush should be called only when strictly necessary because it can 1179 gzflush should be called only when strictly necessary because it can
1180 degrade compression. 1180 degrade compression.
1181*/ 1181*/
1182 1182
1183ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, 1183ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
1184 z_off_t offset, int whence)); 1184 z_off_t offset, int whence));
1185/* 1185/*
1186 Sets the starting position for the next gzread or gzwrite on the 1186 Sets the starting position for the next gzread or gzwrite on the
1187 given compressed file. The offset represents a number of bytes in the 1187 given compressed file. The offset represents a number of bytes in the
1188 uncompressed data stream. The whence parameter is defined as in lseek(2); 1188 uncompressed data stream. The whence parameter is defined as in lseek(2);
1189 the value SEEK_END is not supported. 1189 the value SEEK_END is not supported.
1190 If the file is opened for reading, this function is emulated but can be 1190 If the file is opened for reading, this function is emulated but can be
1191 extremely slow. If the file is opened for writing, only forward seeks are 1191 extremely slow. If the file is opened for writing, only forward seeks are
1192 supported; gzseek then compresses a sequence of zeroes up to the new 1192 supported; gzseek then compresses a sequence of zeroes up to the new
1193 starting position. 1193 starting position.
1194 1194
1195 gzseek returns the resulting offset location as measured in bytes from 1195 gzseek returns the resulting offset location as measured in bytes from
1196 the beginning of the uncompressed stream, or -1 in case of error, in 1196 the beginning of the uncompressed stream, or -1 in case of error, in
1197 particular if the file is opened for writing and the new starting position 1197 particular if the file is opened for writing and the new starting position
1198 would be before the current position. 1198 would be before the current position.
1199*/ 1199*/
1200 1200
1201ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); 1201ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
1202/* 1202/*
1203 Rewinds the given file. This function is supported only for reading. 1203 Rewinds the given file. This function is supported only for reading.
1204 1204
1205 gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) 1205 gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
1206*/ 1206*/
1207 1207
1208ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); 1208ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
1209/* 1209/*
1210 Returns the starting position for the next gzread or gzwrite on the 1210 Returns the starting position for the next gzread or gzwrite on the
1211 given compressed file. This position represents a number of bytes in the 1211 given compressed file. This position represents a number of bytes in the
1212 uncompressed data stream. 1212 uncompressed data stream.
1213 1213
1214 gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) 1214 gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
1215*/ 1215*/
1216 1216
1217ZEXTERN int ZEXPORT gzeof OF((gzFile file)); 1217ZEXTERN int ZEXPORT gzeof OF((gzFile file));
1218/* 1218/*
1219 Returns 1 when EOF has previously been detected reading the given 1219 Returns 1 when EOF has previously been detected reading the given
1220 input stream, otherwise zero. 1220 input stream, otherwise zero.
1221*/ 1221*/
1222 1222
1223ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); 1223ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
1224/* 1224/*
1225 Returns 1 if file is being read directly without decompression, otherwise 1225 Returns 1 if file is being read directly without decompression, otherwise
1226 zero. 1226 zero.
1227*/ 1227*/
1228 1228
1229ZEXTERN int ZEXPORT gzclose OF((gzFile file)); 1229ZEXTERN int ZEXPORT gzclose OF((gzFile file));
1230/* 1230/*
1231 Flushes all pending output if necessary, closes the compressed file 1231 Flushes all pending output if necessary, closes the compressed file
1232 and deallocates all the (de)compression state. The return value is the zlib 1232 and deallocates all the (de)compression state. The return value is the zlib
1233 error number (see function gzerror below). 1233 error number (see function gzerror below).
1234*/ 1234*/
1235 1235
1236ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); 1236ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
1237/* 1237/*
1238 Returns the error message for the last error which occurred on the 1238 Returns the error message for the last error which occurred on the
1239 given compressed file. errnum is set to zlib error number. If an 1239 given compressed file. errnum is set to zlib error number. If an
1240 error occurred in the file system and not in the compression library, 1240 error occurred in the file system and not in the compression library,
1241 errnum is set to Z_ERRNO and the application may consult errno 1241 errnum is set to Z_ERRNO and the application may consult errno
1242 to get the exact error code. 1242 to get the exact error code.
1243*/ 1243*/
1244 1244
1245ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); 1245ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
1246/* 1246/*
1247 Clears the error and end-of-file flags for file. This is analogous to the 1247 Clears the error and end-of-file flags for file. This is analogous to the
1248 clearerr() function in stdio. This is useful for continuing to read a gzip 1248 clearerr() function in stdio. This is useful for continuing to read a gzip
1249 file that is being written concurrently. 1249 file that is being written concurrently.
1250*/ 1250*/
1251 1251
1252 /* checksum functions */ 1252 /* checksum functions */
1253 1253
1254/* 1254/*
1255 These functions are not related to compression but are exported 1255 These functions are not related to compression but are exported
1256 anyway because they might be useful in applications using the 1256 anyway because they might be useful in applications using the
1257 compression library. 1257 compression library.
1258*/ 1258*/
1259 1259
1260ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); 1260ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
1261/* 1261/*
1262 Update a running Adler-32 checksum with the bytes buf[0..len-1] and 1262 Update a running Adler-32 checksum with the bytes buf[0..len-1] and
1263 return the updated checksum. If buf is NULL, this function returns 1263 return the updated checksum. If buf is NULL, this function returns
1264 the required initial value for the checksum. 1264 the required initial value for the checksum.
1265 An Adler-32 checksum is almost as reliable as a CRC32 but can be computed 1265 An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
1266 much faster. Usage example: 1266 much faster. Usage example:
1267 1267
1268 uLong adler = adler32(0L, Z_NULL, 0); 1268 uLong adler = adler32(0L, Z_NULL, 0);
1269 1269
1270 while (read_buffer(buffer, length) != EOF) { 1270 while (read_buffer(buffer, length) != EOF) {
1271 adler = adler32(adler, buffer, length); 1271 adler = adler32(adler, buffer, length);
1272 } 1272 }
1273 if (adler != original_adler) error(); 1273 if (adler != original_adler) error();
1274*/ 1274*/
1275 1275
1276ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, 1276ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
1277 z_off_t len2)); 1277 z_off_t len2));
1278/* 1278/*
1279 Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 1279 Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
1280 and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for 1280 and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
1281 each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of 1281 each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
1282 seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. 1282 seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
1283*/ 1283*/
1284 1284
1285ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); 1285ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
1286/* 1286/*
1287 Update a running CRC-32 with the bytes buf[0..len-1] and return the 1287 Update a running CRC-32 with the bytes buf[0..len-1] and return the
1288 updated CRC-32. If buf is NULL, this function returns the required initial 1288 updated CRC-32. If buf is NULL, this function returns the required initial
1289 value for the for the crc. Pre- and post-conditioning (one's complement) is 1289 value for the for the crc. Pre- and post-conditioning (one's complement) is
1290 performed within this function so it shouldn't be done by the application. 1290 performed within this function so it shouldn't be done by the application.
1291 Usage example: 1291 Usage example:
1292 1292
1293 uLong crc = crc32(0L, Z_NULL, 0); 1293 uLong crc = crc32(0L, Z_NULL, 0);
1294 1294
1295 while (read_buffer(buffer, length) != EOF) { 1295 while (read_buffer(buffer, length) != EOF) {
1296 crc = crc32(crc, buffer, length); 1296 crc = crc32(crc, buffer, length);
1297 } 1297 }
1298 if (crc != original_crc) error(); 1298 if (crc != original_crc) error();
1299*/ 1299*/
1300 1300
1301ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); 1301ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
1302 1302
1303/* 1303/*
1304 Combine two CRC-32 check values into one. For two sequences of bytes, 1304 Combine two CRC-32 check values into one. For two sequences of bytes,
1305 seq1 and seq2 with lengths len1 and len2, CRC-32 check values were 1305 seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
1306 calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 1306 calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
1307 check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and 1307 check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
1308 len2. 1308 len2.
1309*/ 1309*/
1310 1310
1311 1311
1312 /* various hacks, don't look :) */ 1312 /* various hacks, don't look :) */
1313 1313
1314/* deflateInit and inflateInit are macros to allow checking the zlib version 1314/* deflateInit and inflateInit are macros to allow checking the zlib version
1315 * and the compiler's view of z_stream: 1315 * and the compiler's view of z_stream:
1316 */ 1316 */
1317ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, 1317ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
1318 const char *version, int stream_size)); 1318 const char *version, int stream_size));
1319ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, 1319ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
1320 const char *version, int stream_size)); 1320 const char *version, int stream_size));
1321ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, 1321ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
1322 int windowBits, int memLevel, 1322 int windowBits, int memLevel,
1323 int strategy, const char *version, 1323 int strategy, const char *version,
1324 int stream_size)); 1324 int stream_size));
1325ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, 1325ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
1326 const char *version, int stream_size)); 1326 const char *version, int stream_size));
1327ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, 1327ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
1328 unsigned char FAR *window, 1328 unsigned char FAR *window,
1329 const char *version, 1329 const char *version,
1330 int stream_size)); 1330 int stream_size));
1331#define deflateInit(strm, level) \ 1331#define deflateInit(strm, level) \
1332 deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) 1332 deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
1333#define inflateInit(strm) \ 1333#define inflateInit(strm) \
1334 inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) 1334 inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
1335#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ 1335#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
1336 deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ 1336 deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
1337 (strategy), ZLIB_VERSION, sizeof(z_stream)) 1337 (strategy), ZLIB_VERSION, sizeof(z_stream))
1338#define inflateInit2(strm, windowBits) \ 1338#define inflateInit2(strm, windowBits) \
1339 inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) 1339 inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
1340#define inflateBackInit(strm, windowBits, window) \ 1340#define inflateBackInit(strm, windowBits, window) \
1341 inflateBackInit_((strm), (windowBits), (window), \ 1341 inflateBackInit_((strm), (windowBits), (window), \
1342 ZLIB_VERSION, sizeof(z_stream)) 1342 ZLIB_VERSION, sizeof(z_stream))
1343 1343
1344 1344
1345#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) 1345#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
1346 struct internal_state {int dummy;}; /* hack for buggy compilers */ 1346 struct internal_state {int dummy;}; /* hack for buggy compilers */
1347#endif 1347#endif
1348 1348
1349ZEXTERN const char * ZEXPORT zError OF((int)); 1349ZEXTERN const char * ZEXPORT zError OF((int));
1350ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z)); 1350ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
1351ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); 1351ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
1352 1352
1353#ifdef __cplusplus 1353#ifdef __cplusplus
1354} 1354}
1355#endif 1355#endif
1356 1356
1357#endif /* ZLIB_H */ 1357#endif /* ZLIB_H */
diff --git a/utils/zenutils/libraries/zlib123/zlib/zutil.c b/utils/zenutils/libraries/zlib123/zlib/zutil.c
index 0f4bd7871d..d55f5948a3 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/zutil.c
+++ b/utils/zenutils/libraries/zlib123/zlib/zutil.c
@@ -1,318 +1,318 @@
1/* zutil.c -- target dependent utility functions for the compression library 1/* zutil.c -- target dependent utility functions for the compression library
2 * Copyright (C) 1995-2005 Jean-loup Gailly. 2 * Copyright (C) 1995-2005 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6/* @(#) $Id$ */ 6/* @(#) $Id$ */
7 7
8#include "zutil.h" 8#include "zutil.h"
9 9
10#ifndef NO_DUMMY_DECL 10#ifndef NO_DUMMY_DECL
11struct internal_state {int dummy;}; /* for buggy compilers */ 11struct internal_state {int dummy;}; /* for buggy compilers */
12#endif 12#endif
13 13
14const char * const z_errmsg[10] = { 14const char * const z_errmsg[10] = {
15"need dictionary", /* Z_NEED_DICT 2 */ 15"need dictionary", /* Z_NEED_DICT 2 */
16"stream end", /* Z_STREAM_END 1 */ 16"stream end", /* Z_STREAM_END 1 */
17"", /* Z_OK 0 */ 17"", /* Z_OK 0 */
18"file error", /* Z_ERRNO (-1) */ 18"file error", /* Z_ERRNO (-1) */
19"stream error", /* Z_STREAM_ERROR (-2) */ 19"stream error", /* Z_STREAM_ERROR (-2) */
20"data error", /* Z_DATA_ERROR (-3) */ 20"data error", /* Z_DATA_ERROR (-3) */
21"insufficient memory", /* Z_MEM_ERROR (-4) */ 21"insufficient memory", /* Z_MEM_ERROR (-4) */
22"buffer error", /* Z_BUF_ERROR (-5) */ 22"buffer error", /* Z_BUF_ERROR (-5) */
23"incompatible version",/* Z_VERSION_ERROR (-6) */ 23"incompatible version",/* Z_VERSION_ERROR (-6) */
24""}; 24""};
25 25
26 26
27const char * ZEXPORT zlibVersion() 27const char * ZEXPORT zlibVersion()
28{ 28{
29 return ZLIB_VERSION; 29 return ZLIB_VERSION;
30} 30}
31 31
32uLong ZEXPORT zlibCompileFlags() 32uLong ZEXPORT zlibCompileFlags()
33{ 33{
34 uLong flags; 34 uLong flags;
35 35
36 flags = 0; 36 flags = 0;
37 switch (sizeof(uInt)) { 37 switch (sizeof(uInt)) {
38 case 2: break; 38 case 2: break;
39 case 4: flags += 1; break; 39 case 4: flags += 1; break;
40 case 8: flags += 2; break; 40 case 8: flags += 2; break;
41 default: flags += 3; 41 default: flags += 3;
42 } 42 }
43 switch (sizeof(uLong)) { 43 switch (sizeof(uLong)) {
44 case 2: break; 44 case 2: break;
45 case 4: flags += 1 << 2; break; 45 case 4: flags += 1 << 2; break;
46 case 8: flags += 2 << 2; break; 46 case 8: flags += 2 << 2; break;
47 default: flags += 3 << 2; 47 default: flags += 3 << 2;
48 } 48 }
49 switch (sizeof(voidpf)) { 49 switch (sizeof(voidpf)) {
50 case 2: break; 50 case 2: break;
51 case 4: flags += 1 << 4; break; 51 case 4: flags += 1 << 4; break;
52 case 8: flags += 2 << 4; break; 52 case 8: flags += 2 << 4; break;
53 default: flags += 3 << 4; 53 default: flags += 3 << 4;
54 } 54 }
55 switch (sizeof(z_off_t)) { 55 switch (sizeof(z_off_t)) {
56 case 2: break; 56 case 2: break;
57 case 4: flags += 1 << 6; break; 57 case 4: flags += 1 << 6; break;
58 case 8: flags += 2 << 6; break; 58 case 8: flags += 2 << 6; break;
59 default: flags += 3 << 6; 59 default: flags += 3 << 6;
60 } 60 }
61#ifdef DEBUG 61#ifdef DEBUG
62 flags += 1 << 8; 62 flags += 1 << 8;
63#endif 63#endif
64#if defined(ASMV) || defined(ASMINF) 64#if defined(ASMV) || defined(ASMINF)
65 flags += 1 << 9; 65 flags += 1 << 9;
66#endif 66#endif
67#ifdef ZLIB_WINAPI 67#ifdef ZLIB_WINAPI
68 flags += 1 << 10; 68 flags += 1 << 10;
69#endif 69#endif
70#ifdef BUILDFIXED 70#ifdef BUILDFIXED
71 flags += 1 << 12; 71 flags += 1 << 12;
72#endif 72#endif
73#ifdef DYNAMIC_CRC_TABLE 73#ifdef DYNAMIC_CRC_TABLE
74 flags += 1 << 13; 74 flags += 1 << 13;
75#endif 75#endif
76#ifdef NO_GZCOMPRESS 76#ifdef NO_GZCOMPRESS
77 flags += 1L << 16; 77 flags += 1L << 16;
78#endif 78#endif
79#ifdef NO_GZIP 79#ifdef NO_GZIP
80 flags += 1L << 17; 80 flags += 1L << 17;
81#endif 81#endif
82#ifdef PKZIP_BUG_WORKAROUND 82#ifdef PKZIP_BUG_WORKAROUND
83 flags += 1L << 20; 83 flags += 1L << 20;
84#endif 84#endif
85#ifdef FASTEST 85#ifdef FASTEST
86 flags += 1L << 21; 86 flags += 1L << 21;
87#endif 87#endif
88#ifdef STDC 88#ifdef STDC
89# ifdef NO_vsnprintf 89# ifdef NO_vsnprintf
90 flags += 1L << 25; 90 flags += 1L << 25;
91# ifdef HAS_vsprintf_void 91# ifdef HAS_vsprintf_void
92 flags += 1L << 26; 92 flags += 1L << 26;
93# endif 93# endif
94# else 94# else
95# ifdef HAS_vsnprintf_void 95# ifdef HAS_vsnprintf_void
96 flags += 1L << 26; 96 flags += 1L << 26;
97# endif 97# endif
98# endif 98# endif
99#else 99#else
100 flags += 1L << 24; 100 flags += 1L << 24;
101# ifdef NO_snprintf 101# ifdef NO_snprintf
102 flags += 1L << 25; 102 flags += 1L << 25;
103# ifdef HAS_sprintf_void 103# ifdef HAS_sprintf_void
104 flags += 1L << 26; 104 flags += 1L << 26;
105# endif 105# endif
106# else 106# else
107# ifdef HAS_snprintf_void 107# ifdef HAS_snprintf_void
108 flags += 1L << 26; 108 flags += 1L << 26;
109# endif 109# endif
110# endif 110# endif
111#endif 111#endif
112 return flags; 112 return flags;
113} 113}
114 114
115#ifdef DEBUG 115#ifdef DEBUG
116 116
117# ifndef verbose 117# ifndef verbose
118# define verbose 0 118# define verbose 0
119# endif 119# endif
120int z_verbose = verbose; 120int z_verbose = verbose;
121 121
122void z_error (m) 122void z_error (m)
123 char *m; 123 char *m;
124{ 124{
125 fprintf(stderr, "%s\n", m); 125 fprintf(stderr, "%s\n", m);
126 exit(1); 126 exit(1);
127} 127}
128#endif 128#endif
129 129
130/* exported to allow conversion of error code to string for compress() and 130/* exported to allow conversion of error code to string for compress() and
131 * uncompress() 131 * uncompress()
132 */ 132 */
133const char * ZEXPORT zError(err) 133const char * ZEXPORT zError(err)
134 int err; 134 int err;
135{ 135{
136 return ERR_MSG(err); 136 return ERR_MSG(err);
137} 137}
138 138
139#if defined(_WIN32_WCE) 139#if defined(_WIN32_WCE)
140 /* The Microsoft C Run-Time Library for Windows CE doesn't have 140 /* The Microsoft C Run-Time Library for Windows CE doesn't have
141 * errno. We define it as a global variable to simplify porting. 141 * errno. We define it as a global variable to simplify porting.
142 * Its value is always 0 and should not be used. 142 * Its value is always 0 and should not be used.
143 */ 143 */
144 int errno = 0; 144 int errno = 0;
145#endif 145#endif
146 146
147#ifndef HAVE_MEMCPY 147#ifndef HAVE_MEMCPY
148 148
149void zmemcpy(dest, source, len) 149void zmemcpy(dest, source, len)
150 Bytef* dest; 150 Bytef* dest;
151 const Bytef* source; 151 const Bytef* source;
152 uInt len; 152 uInt len;
153{ 153{
154 if (len == 0) return; 154 if (len == 0) return;
155 do { 155 do {
156 *dest++ = *source++; /* ??? to be unrolled */ 156 *dest++ = *source++; /* ??? to be unrolled */
157 } while (--len != 0); 157 } while (--len != 0);
158} 158}
159 159
160int zmemcmp(s1, s2, len) 160int zmemcmp(s1, s2, len)
161 const Bytef* s1; 161 const Bytef* s1;
162 const Bytef* s2; 162 const Bytef* s2;
163 uInt len; 163 uInt len;
164{ 164{
165 uInt j; 165 uInt j;
166 166
167 for (j = 0; j < len; j++) { 167 for (j = 0; j < len; j++) {
168 if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; 168 if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
169 } 169 }
170 return 0; 170 return 0;
171} 171}
172 172
173void zmemzero(dest, len) 173void zmemzero(dest, len)
174 Bytef* dest; 174 Bytef* dest;
175 uInt len; 175 uInt len;
176{ 176{
177 if (len == 0) return; 177 if (len == 0) return;
178 do { 178 do {
179 *dest++ = 0; /* ??? to be unrolled */ 179 *dest++ = 0; /* ??? to be unrolled */
180 } while (--len != 0); 180 } while (--len != 0);
181} 181}
182#endif 182#endif
183 183
184 184
185#ifdef SYS16BIT 185#ifdef SYS16BIT
186 186
187#ifdef __TURBOC__ 187#ifdef __TURBOC__
188/* Turbo C in 16-bit mode */ 188/* Turbo C in 16-bit mode */
189 189
190# define MY_ZCALLOC 190# define MY_ZCALLOC
191 191
192/* Turbo C malloc() does not allow dynamic allocation of 64K bytes 192/* Turbo C malloc() does not allow dynamic allocation of 64K bytes
193 * and farmalloc(64K) returns a pointer with an offset of 8, so we 193 * and farmalloc(64K) returns a pointer with an offset of 8, so we
194 * must fix the pointer. Warning: the pointer must be put back to its 194 * must fix the pointer. Warning: the pointer must be put back to its
195 * original form in order to free it, use zcfree(). 195 * original form in order to free it, use zcfree().
196 */ 196 */
197 197
198#define MAX_PTR 10 198#define MAX_PTR 10
199/* 10*64K = 640K */ 199/* 10*64K = 640K */
200 200
201local int next_ptr = 0; 201local int next_ptr = 0;
202 202
203typedef struct ptr_table_s { 203typedef struct ptr_table_s {
204 voidpf org_ptr; 204 voidpf org_ptr;
205 voidpf new_ptr; 205 voidpf new_ptr;
206} ptr_table; 206} ptr_table;
207 207
208local ptr_table table[MAX_PTR]; 208local ptr_table table[MAX_PTR];
209/* This table is used to remember the original form of pointers 209/* This table is used to remember the original form of pointers
210 * to large buffers (64K). Such pointers are normalized with a zero offset. 210 * to large buffers (64K). Such pointers are normalized with a zero offset.
211 * Since MSDOS is not a preemptive multitasking OS, this table is not 211 * Since MSDOS is not a preemptive multitasking OS, this table is not
212 * protected from concurrent access. This hack doesn't work anyway on 212 * protected from concurrent access. This hack doesn't work anyway on
213 * a protected system like OS/2. Use Microsoft C instead. 213 * a protected system like OS/2. Use Microsoft C instead.
214 */ 214 */
215 215
216voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) 216voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
217{ 217{
218 voidpf buf = opaque; /* just to make some compilers happy */ 218 voidpf buf = opaque; /* just to make some compilers happy */
219 ulg bsize = (ulg)items*size; 219 ulg bsize = (ulg)items*size;
220 220
221 /* If we allocate less than 65520 bytes, we assume that farmalloc 221 /* If we allocate less than 65520 bytes, we assume that farmalloc
222 * will return a usable pointer which doesn't have to be normalized. 222 * will return a usable pointer which doesn't have to be normalized.
223 */ 223 */
224 if (bsize < 65520L) { 224 if (bsize < 65520L) {
225 buf = farmalloc(bsize); 225 buf = farmalloc(bsize);
226 if (*(ush*)&buf != 0) return buf; 226 if (*(ush*)&buf != 0) return buf;
227 } else { 227 } else {
228 buf = farmalloc(bsize + 16L); 228 buf = farmalloc(bsize + 16L);
229 } 229 }
230 if (buf == NULL || next_ptr >= MAX_PTR) return NULL; 230 if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
231 table[next_ptr].org_ptr = buf; 231 table[next_ptr].org_ptr = buf;
232 232
233 /* Normalize the pointer to seg:0 */ 233 /* Normalize the pointer to seg:0 */
234 *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; 234 *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
235 *(ush*)&buf = 0; 235 *(ush*)&buf = 0;
236 table[next_ptr++].new_ptr = buf; 236 table[next_ptr++].new_ptr = buf;
237 return buf; 237 return buf;
238} 238}
239 239
240void zcfree (voidpf opaque, voidpf ptr) 240void zcfree (voidpf opaque, voidpf ptr)
241{ 241{
242 int n; 242 int n;
243 if (*(ush*)&ptr != 0) { /* object < 64K */ 243 if (*(ush*)&ptr != 0) { /* object < 64K */
244 farfree(ptr); 244 farfree(ptr);
245 return; 245 return;
246 } 246 }
247 /* Find the original pointer */ 247 /* Find the original pointer */
248 for (n = 0; n < next_ptr; n++) { 248 for (n = 0; n < next_ptr; n++) {
249 if (ptr != table[n].new_ptr) continue; 249 if (ptr != table[n].new_ptr) continue;
250 250
251 farfree(table[n].org_ptr); 251 farfree(table[n].org_ptr);
252 while (++n < next_ptr) { 252 while (++n < next_ptr) {
253 table[n-1] = table[n]; 253 table[n-1] = table[n];
254 } 254 }
255 next_ptr--; 255 next_ptr--;
256 return; 256 return;
257 } 257 }
258 ptr = opaque; /* just to make some compilers happy */ 258 ptr = opaque; /* just to make some compilers happy */
259 Assert(0, "zcfree: ptr not found"); 259 Assert(0, "zcfree: ptr not found");
260} 260}
261 261
262#endif /* __TURBOC__ */ 262#endif /* __TURBOC__ */
263 263
264 264
265#ifdef M_I86 265#ifdef M_I86
266/* Microsoft C in 16-bit mode */ 266/* Microsoft C in 16-bit mode */
267 267
268# define MY_ZCALLOC 268# define MY_ZCALLOC
269 269
270#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) 270#if (!defined(_MSC_VER) || (_MSC_VER <= 600))
271# define _halloc halloc 271# define _halloc halloc
272# define _hfree hfree 272# define _hfree hfree
273#endif 273#endif
274 274
275voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) 275voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
276{ 276{
277 if (opaque) opaque = 0; /* to make compiler happy */ 277 if (opaque) opaque = 0; /* to make compiler happy */
278 return _halloc((long)items, size); 278 return _halloc((long)items, size);
279} 279}
280 280
281void zcfree (voidpf opaque, voidpf ptr) 281void zcfree (voidpf opaque, voidpf ptr)
282{ 282{
283 if (opaque) opaque = 0; /* to make compiler happy */ 283 if (opaque) opaque = 0; /* to make compiler happy */
284 _hfree(ptr); 284 _hfree(ptr);
285} 285}
286 286
287#endif /* M_I86 */ 287#endif /* M_I86 */
288 288
289#endif /* SYS16BIT */ 289#endif /* SYS16BIT */
290 290
291 291
292#ifndef MY_ZCALLOC /* Any system without a special alloc function */ 292#ifndef MY_ZCALLOC /* Any system without a special alloc function */
293 293
294#ifndef STDC 294#ifndef STDC
295extern voidp malloc OF((uInt size)); 295extern voidp malloc OF((uInt size));
296extern voidp calloc OF((uInt items, uInt size)); 296extern voidp calloc OF((uInt items, uInt size));
297extern void free OF((voidpf ptr)); 297extern void free OF((voidpf ptr));
298#endif 298#endif
299 299
300voidpf zcalloc (opaque, items, size) 300voidpf zcalloc (opaque, items, size)
301 voidpf opaque; 301 voidpf opaque;
302 unsigned items; 302 unsigned items;
303 unsigned size; 303 unsigned size;
304{ 304{
305 if (opaque) items += size - size; /* make compiler happy */ 305 if (opaque) items += size - size; /* make compiler happy */
306 return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : 306 return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
307 (voidpf)calloc(items, size); 307 (voidpf)calloc(items, size);
308} 308}
309 309
310void zcfree (opaque, ptr) 310void zcfree (opaque, ptr)
311 voidpf opaque; 311 voidpf opaque;
312 voidpf ptr; 312 voidpf ptr;
313{ 313{
314 free(ptr); 314 free(ptr);
315 if (opaque) return; /* make compiler happy */ 315 if (opaque) return; /* make compiler happy */
316} 316}
317 317
318#endif /* MY_ZCALLOC */ 318#endif /* MY_ZCALLOC */
diff --git a/utils/zenutils/libraries/zlib123/zlib/zutil.h b/utils/zenutils/libraries/zlib123/zlib/zutil.h
index 0ba6e02087..b7d5eff81b 100755..100644
--- a/utils/zenutils/libraries/zlib123/zlib/zutil.h
+++ b/utils/zenutils/libraries/zlib123/zlib/zutil.h
@@ -1,269 +1,269 @@
1/* zutil.h -- internal interface and configuration of the compression library 1/* zutil.h -- internal interface and configuration of the compression library
2 * Copyright (C) 1995-2005 Jean-loup Gailly. 2 * Copyright (C) 1995-2005 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h 3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */ 4 */
5 5
6/* WARNING: this file should *not* be used by applications. It is 6/* WARNING: this file should *not* be used by applications. It is
7 part of the implementation of the compression library and is 7 part of the implementation of the compression library and is
8 subject to change. Applications should only use zlib.h. 8 subject to change. Applications should only use zlib.h.
9 */ 9 */
10 10
11/* @(#) $Id$ */ 11/* @(#) $Id$ */
12 12
13#ifndef ZUTIL_H 13#ifndef ZUTIL_H
14#define ZUTIL_H 14#define ZUTIL_H
15 15
16#define ZLIB_INTERNAL 16#define ZLIB_INTERNAL
17#include "zlib.h" 17#include "zlib.h"
18 18
19#ifdef STDC 19#ifdef STDC
20# ifndef _WIN32_WCE 20# ifndef _WIN32_WCE
21# include <stddef.h> 21# include <stddef.h>
22# endif 22# endif
23# include <string.h> 23# include <string.h>
24# include <stdlib.h> 24# include <stdlib.h>
25#endif 25#endif
26#ifdef NO_ERRNO_H 26#ifdef NO_ERRNO_H
27# ifdef _WIN32_WCE 27# ifdef _WIN32_WCE
28 /* The Microsoft C Run-Time Library for Windows CE doesn't have 28 /* The Microsoft C Run-Time Library for Windows CE doesn't have
29 * errno. We define it as a global variable to simplify porting. 29 * errno. We define it as a global variable to simplify porting.
30 * Its value is always 0 and should not be used. We rename it to 30 * Its value is always 0 and should not be used. We rename it to
31 * avoid conflict with other libraries that use the same workaround. 31 * avoid conflict with other libraries that use the same workaround.
32 */ 32 */
33# define errno z_errno 33# define errno z_errno
34# endif 34# endif
35 extern int errno; 35 extern int errno;
36#else 36#else
37# ifndef _WIN32_WCE 37# ifndef _WIN32_WCE
38# include <errno.h> 38# include <errno.h>
39# endif 39# endif
40#endif 40#endif
41 41
42#ifndef local 42#ifndef local
43# define local static 43# define local static
44#endif 44#endif
45/* compile with -Dlocal if your debugger can't find static symbols */ 45/* compile with -Dlocal if your debugger can't find static symbols */
46 46
47typedef unsigned char uch; 47typedef unsigned char uch;
48typedef uch FAR uchf; 48typedef uch FAR uchf;
49typedef unsigned short ush; 49typedef unsigned short ush;
50typedef ush FAR ushf; 50typedef ush FAR ushf;
51typedef unsigned long ulg; 51typedef unsigned long ulg;
52 52
53extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ 53extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
54/* (size given to avoid silly warnings with Visual C++) */ 54/* (size given to avoid silly warnings with Visual C++) */
55 55
56#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] 56#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
57 57
58#define ERR_RETURN(strm,err) \ 58#define ERR_RETURN(strm,err) \
59 return (strm->msg = (char*)ERR_MSG(err), (err)) 59 return (strm->msg = (char*)ERR_MSG(err), (err))
60/* To be used only when the state is known to be valid */ 60/* To be used only when the state is known to be valid */
61 61
62 /* common constants */ 62 /* common constants */
63 63
64#ifndef DEF_WBITS 64#ifndef DEF_WBITS
65# define DEF_WBITS MAX_WBITS 65# define DEF_WBITS MAX_WBITS
66#endif 66#endif
67/* default windowBits for decompression. MAX_WBITS is for compression only */ 67/* default windowBits for decompression. MAX_WBITS is for compression only */
68 68
69#if MAX_MEM_LEVEL >= 8 69#if MAX_MEM_LEVEL >= 8
70# define DEF_MEM_LEVEL 8 70# define DEF_MEM_LEVEL 8
71#else 71#else
72# define DEF_MEM_LEVEL MAX_MEM_LEVEL 72# define DEF_MEM_LEVEL MAX_MEM_LEVEL
73#endif 73#endif
74/* default memLevel */ 74/* default memLevel */
75 75
76#define STORED_BLOCK 0 76#define STORED_BLOCK 0
77#define STATIC_TREES 1 77#define STATIC_TREES 1
78#define DYN_TREES 2 78#define DYN_TREES 2
79/* The three kinds of block type */ 79/* The three kinds of block type */
80 80
81#define MIN_MATCH 3 81#define MIN_MATCH 3
82#define MAX_MATCH 258 82#define MAX_MATCH 258
83/* The minimum and maximum match lengths */ 83/* The minimum and maximum match lengths */
84 84
85#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ 85#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
86 86
87 /* target dependencies */ 87 /* target dependencies */
88 88
89#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) 89#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
90# define OS_CODE 0x00 90# define OS_CODE 0x00
91# if defined(__TURBOC__) || defined(__BORLANDC__) 91# if defined(__TURBOC__) || defined(__BORLANDC__)
92# if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) 92# if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
93 /* Allow compilation with ANSI keywords only enabled */ 93 /* Allow compilation with ANSI keywords only enabled */
94 void _Cdecl farfree( void *block ); 94 void _Cdecl farfree( void *block );
95 void *_Cdecl farmalloc( unsigned long nbytes ); 95 void *_Cdecl farmalloc( unsigned long nbytes );
96# else 96# else
97# include <alloc.h> 97# include <alloc.h>
98# endif 98# endif
99# else /* MSC or DJGPP */ 99# else /* MSC or DJGPP */
100# include <malloc.h> 100# include <malloc.h>
101# endif 101# endif
102#endif 102#endif
103 103
104#ifdef AMIGA 104#ifdef AMIGA
105# define OS_CODE 0x01 105# define OS_CODE 0x01
106#endif 106#endif
107 107
108#if defined(VAXC) || defined(VMS) 108#if defined(VAXC) || defined(VMS)
109# define OS_CODE 0x02 109# define OS_CODE 0x02
110# define F_OPEN(name, mode) \ 110# define F_OPEN(name, mode) \
111 fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") 111 fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
112#endif 112#endif
113 113
114#if defined(ATARI) || defined(atarist) 114#if defined(ATARI) || defined(atarist)
115# define OS_CODE 0x05 115# define OS_CODE 0x05
116#endif 116#endif
117 117
118#ifdef OS2 118#ifdef OS2
119# define OS_CODE 0x06 119# define OS_CODE 0x06
120# ifdef M_I86 120# ifdef M_I86
121 #include <malloc.h> 121 #include <malloc.h>
122# endif 122# endif
123#endif 123#endif
124 124
125#if defined(MACOS) || defined(TARGET_OS_MAC) 125#if defined(MACOS) || defined(TARGET_OS_MAC)
126# define OS_CODE 0x07 126# define OS_CODE 0x07
127# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os 127# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
128# include <unix.h> /* for fdopen */ 128# include <unix.h> /* for fdopen */
129# else 129# else
130# ifndef fdopen 130# ifndef fdopen
131# define fdopen(fd,mode) NULL /* No fdopen() */ 131# define fdopen(fd,mode) NULL /* No fdopen() */
132# endif 132# endif
133# endif 133# endif
134#endif 134#endif
135 135
136#ifdef TOPS20 136#ifdef TOPS20
137# define OS_CODE 0x0a 137# define OS_CODE 0x0a
138#endif 138#endif
139 139
140#ifdef WIN32 140#ifdef WIN32
141# ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */ 141# ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
142# define OS_CODE 0x0b 142# define OS_CODE 0x0b
143# endif 143# endif
144#endif 144#endif
145 145
146#ifdef __50SERIES /* Prime/PRIMOS */ 146#ifdef __50SERIES /* Prime/PRIMOS */
147# define OS_CODE 0x0f 147# define OS_CODE 0x0f
148#endif 148#endif
149 149
150#if defined(_BEOS_) || defined(RISCOS) 150#if defined(_BEOS_) || defined(RISCOS)
151# define fdopen(fd,mode) NULL /* No fdopen() */ 151# define fdopen(fd,mode) NULL /* No fdopen() */
152#endif 152#endif
153 153
154#if (defined(_MSC_VER) && (_MSC_VER > 600)) 154#if (defined(_MSC_VER) && (_MSC_VER > 600))
155# if defined(_WIN32_WCE) 155# if defined(_WIN32_WCE)
156# define fdopen(fd,mode) NULL /* No fdopen() */ 156# define fdopen(fd,mode) NULL /* No fdopen() */
157# ifndef _PTRDIFF_T_DEFINED 157# ifndef _PTRDIFF_T_DEFINED
158 typedef int ptrdiff_t; 158 typedef int ptrdiff_t;
159# define _PTRDIFF_T_DEFINED 159# define _PTRDIFF_T_DEFINED
160# endif 160# endif
161# else 161# else
162# define fdopen(fd,type) _fdopen(fd,type) 162# define fdopen(fd,type) _fdopen(fd,type)
163# endif 163# endif
164#endif 164#endif
165 165
166 /* common defaults */ 166 /* common defaults */
167 167
168#ifndef OS_CODE 168#ifndef OS_CODE
169# define OS_CODE 0x03 /* assume Unix */ 169# define OS_CODE 0x03 /* assume Unix */
170#endif 170#endif
171 171
172#ifndef F_OPEN 172#ifndef F_OPEN
173# define F_OPEN(name, mode) fopen((name), (mode)) 173# define F_OPEN(name, mode) fopen((name), (mode))
174#endif 174#endif
175 175
176 /* functions */ 176 /* functions */
177 177
178#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) 178#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
179# ifndef HAVE_VSNPRINTF 179# ifndef HAVE_VSNPRINTF
180# define HAVE_VSNPRINTF 180# define HAVE_VSNPRINTF
181# endif 181# endif
182#endif 182#endif
183#if defined(__CYGWIN__) 183#if defined(__CYGWIN__)
184# ifndef HAVE_VSNPRINTF 184# ifndef HAVE_VSNPRINTF
185# define HAVE_VSNPRINTF 185# define HAVE_VSNPRINTF
186# endif 186# endif
187#endif 187#endif
188#ifndef HAVE_VSNPRINTF 188#ifndef HAVE_VSNPRINTF
189# ifdef MSDOS 189# ifdef MSDOS
190 /* vsnprintf may exist on some MS-DOS compilers (DJGPP?), 190 /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
191 but for now we just assume it doesn't. */ 191 but for now we just assume it doesn't. */
192# define NO_vsnprintf 192# define NO_vsnprintf
193# endif 193# endif
194# ifdef __TURBOC__ 194# ifdef __TURBOC__
195# define NO_vsnprintf 195# define NO_vsnprintf
196# endif 196# endif
197# ifdef WIN32 197# ifdef WIN32
198 /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ 198 /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
199# if !defined(vsnprintf) && !defined(NO_vsnprintf) 199# if !defined(vsnprintf) && !defined(NO_vsnprintf)
200# define vsnprintf _vsnprintf 200# define vsnprintf _vsnprintf
201# endif 201# endif
202# endif 202# endif
203# ifdef __SASC 203# ifdef __SASC
204# define NO_vsnprintf 204# define NO_vsnprintf
205# endif 205# endif
206#endif 206#endif
207#ifdef VMS 207#ifdef VMS
208# define NO_vsnprintf 208# define NO_vsnprintf
209#endif 209#endif
210 210
211#if defined(pyr) 211#if defined(pyr)
212# define NO_MEMCPY 212# define NO_MEMCPY
213#endif 213#endif
214#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) 214#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
215 /* Use our own functions for small and medium model with MSC <= 5.0. 215 /* Use our own functions for small and medium model with MSC <= 5.0.
216 * You may have to use the same strategy for Borland C (untested). 216 * You may have to use the same strategy for Borland C (untested).
217 * The __SC__ check is for Symantec. 217 * The __SC__ check is for Symantec.
218 */ 218 */
219# define NO_MEMCPY 219# define NO_MEMCPY
220#endif 220#endif
221#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) 221#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
222# define HAVE_MEMCPY 222# define HAVE_MEMCPY
223#endif 223#endif
224#ifdef HAVE_MEMCPY 224#ifdef HAVE_MEMCPY
225# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ 225# ifdef SMALL_MEDIUM /* MSDOS small or medium model */
226# define zmemcpy _fmemcpy 226# define zmemcpy _fmemcpy
227# define zmemcmp _fmemcmp 227# define zmemcmp _fmemcmp
228# define zmemzero(dest, len) _fmemset(dest, 0, len) 228# define zmemzero(dest, len) _fmemset(dest, 0, len)
229# else 229# else
230# define zmemcpy memcpy 230# define zmemcpy memcpy
231# define zmemcmp memcmp 231# define zmemcmp memcmp
232# define zmemzero(dest, len) memset(dest, 0, len) 232# define zmemzero(dest, len) memset(dest, 0, len)
233# endif 233# endif
234#else 234#else
235 extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); 235 extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
236 extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); 236 extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
237 extern void zmemzero OF((Bytef* dest, uInt len)); 237 extern void zmemzero OF((Bytef* dest, uInt len));
238#endif 238#endif
239 239
240/* Diagnostic functions */ 240/* Diagnostic functions */
241#ifdef DEBUG 241#ifdef DEBUG
242# include <stdio.h> 242# include <stdio.h>
243 extern int z_verbose; 243 extern int z_verbose;
244 extern void z_error OF((char *m)); 244 extern void z_error OF((char *m));
245# define Assert(cond,msg) {if(!(cond)) z_error(msg);} 245# define Assert(cond,msg) {if(!(cond)) z_error(msg);}
246# define Trace(x) {if (z_verbose>=0) fprintf x ;} 246# define Trace(x) {if (z_verbose>=0) fprintf x ;}
247# define Tracev(x) {if (z_verbose>0) fprintf x ;} 247# define Tracev(x) {if (z_verbose>0) fprintf x ;}
248# define Tracevv(x) {if (z_verbose>1) fprintf x ;} 248# define Tracevv(x) {if (z_verbose>1) fprintf x ;}
249# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} 249# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
250# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} 250# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
251#else 251#else
252# define Assert(cond,msg) 252# define Assert(cond,msg)
253# define Trace(x) 253# define Trace(x)
254# define Tracev(x) 254# define Tracev(x)
255# define Tracevv(x) 255# define Tracevv(x)
256# define Tracec(c,x) 256# define Tracec(c,x)
257# define Tracecv(c,x) 257# define Tracecv(c,x)
258#endif 258#endif
259 259
260 260
261voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size)); 261voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
262void zcfree OF((voidpf opaque, voidpf ptr)); 262void zcfree OF((voidpf opaque, voidpf ptr));
263 263
264#define ZALLOC(strm, items, size) \ 264#define ZALLOC(strm, items, size) \
265 (*((strm)->zalloc))((strm)->opaque, (items), (size)) 265 (*((strm)->zalloc))((strm)->opaque, (items), (size))
266#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) 266#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
267#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} 267#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
268 268
269#endif /* ZUTIL_H */ 269#endif /* ZUTIL_H */
diff --git a/utils/zenutils/notes.txt b/utils/zenutils/notes.txt
index 0848718ac2..0006bd2e71 100755..100644
--- a/utils/zenutils/notes.txt
+++ b/utils/zenutils/notes.txt
@@ -1,77 +1,77 @@
1zenutils is a collection of utilities for working with firmwares of the Creative Zen range. 1zenutils is a collection of utilities for working with firmwares of the Creative Zen range.
2 2
3The utilities are split into 3 categories: 3The utilities are split into 3 categories:
41) update_* 41) update_*
5 Operates on the Creative firmware updater executable. 5 Operates on the Creative firmware updater executable.
62) firmware_* 62) firmware_*
7 Operates on the Creative firmware archive. 7 Operates on the Creative firmware archive.
83) zen_crypt 83) zen_crypt
9 Operates on the parts of the firmware archive which requires cryptography. 9 Operates on the parts of the firmware archive which requires cryptography.
10 10
11 11
12General usage: 12General usage:
13-------------- 13--------------
14A typical use scenario would be: download the firmware updater and run 14A typical use scenario would be: download the firmware updater and run
15 update_extract on it to obtain the firmware archive which it contains. 15 update_extract on it to obtain the firmware archive which it contains.
16Run firmware_extract on the firmware archive to obtain the files 16Run firmware_extract on the firmware archive to obtain the files
17 which the firmware archive contains and a make file that can later be used 17 which the firmware archive contains and a make file that can later be used
18 to create a new firmware archive. Edit* the extracted files of 18 to create a new firmware archive. Edit* the extracted files of
19 interest and optionally the associated make file. Create a new firmware 19 interest and optionally the associated make file. Create a new firmware
20 archive by running firmware_make. If a NULL entry is present in the firmware 20 archive by running firmware_make. If a NULL entry is present in the firmware
21 then it's signature has to be updated running zen_crypt. If on windows, you 21 then it's signature has to be updated running zen_crypt. If on windows, you
22 can use update_patch to write your newly created firmware archive to the 22 can use update_patch to write your newly created firmware archive to the
23 updater executable which you originally extracted it from. The new updater 23 updater executable which you originally extracted it from. The new updater
24 will update your player with the modifications you've made. 24 will update your player with the modifications you've made.
25 25
26* If you're creating or editing executable code, such as the CENC or ©TL entries, 26* If you're creating or editing executable code, such as the CENC or ©TL entries,
27you'll need to use zen_crypt to decrypt and/or encrypt them. 27you'll need to use zen_crypt to decrypt and/or encrypt them.
28In addition, executable code on some players that use the ©TL entries also needs 28In addition, executable code on some players that use the ©TL entries also needs
29 to be signed using zen_crypt, prior to encrypting them. 29 to be signed using zen_crypt, prior to encrypting them.
30Encrypting FBOOT and FRESC is not supported, as these contain the executable 30Encrypting FBOOT and FRESC is not supported, as these contain the executable
31 code that makes up the critical Rescue Mode software, contained in flash. 31 code that makes up the critical Rescue Mode software, contained in flash.
32As opposed to CENC and ©TL which ultimately ends up being stored in the players 32As opposed to CENC and ©TL which ultimately ends up being stored in the players
33 filesystem as a file named Jukebox2.jrm. 33 filesystem as a file named Jukebox2.jrm.
34 34
35 35
36Important: 36Important:
37---------- 37----------
38The only entries required in a firmware archive is CINF and if present, NULL. 38The only entries required in a firmware archive is CINF and if present, NULL.
39Including either FBOOT, FRESC or EXT0 in your firmware archive is not advised, 39Including either FBOOT, FRESC or EXT0 in your firmware archive is not advised,
40 the first two are required for the Rescue Mode software operation and EXT0 is 40 the first two are required for the Rescue Mode software operation and EXT0 is
41 unknown, but given that it's contents is sent to an internal device named mcu0, 41 unknown, but given that it's contents is sent to an internal device named mcu0,
42 the consequences of failure could be fatal to your player. 42 the consequences of failure could be fatal to your player.
43 43
44 44
45Supported players: 45Supported players:
46------------------ 46------------------
47zen_crypt supports signing, verification, decryption and encryption on the 47zen_crypt supports signing, verification, decryption and encryption on the
48 following Creative Zen players: 48 following Creative Zen players:
49 Vision:M (default if no player is specified) 49 Vision:M (default if no player is specified)
50 Vision W 50 Vision W
51 Micro 51 Micro
52 MicroPhoto 52 MicroPhoto
53 Sleek 53 Sleek
54 SleekPhoto 54 SleekPhoto
55 Touch 55 Touch
56 Xtra 56 Xtra
57 57
58The other utilities are not player specific and may work on players not listed. 58The other utilities are not player specific and may work on players not listed.
59Although the Vision:M is the only player I've fully tested. 59Although the Vision:M is the only player I've fully tested.
60 60
61 61
62Building the sources: 62Building the sources:
63--------------------- 63---------------------
64The source code uses the CMake (www.cmake.org) build system. 64The source code uses the CMake (www.cmake.org) build system.
65Once you've installed CMake, you'll need to run it to produce make files for 65Once you've installed CMake, you'll need to run it to produce make files for
66 your system. I would recommend producing the make files within in the 'build' 66 your system. I would recommend producing the make files within in the 'build'
67 directory of this package. Which can be done by typing: 67 directory of this package. Which can be done by typing:
68 zenutils\build\>cmake -g "Visual Studio 8 2005" .. 68 zenutils\build\>cmake -g "Visual Studio 8 2005" ..
69 (for msvc8 on windows) 69 (for msvc8 on windows)
70 or: 70 or:
71 ~zenutils/build/$ cmake -g "Unix Makefiles" .. 71 ~zenutils/build/$ cmake -g "Unix Makefiles" ..
72 (for various 'nixes) 72 (for various 'nixes)
73The windows example will produce a solution file for msvc8. 73The windows example will produce a solution file for msvc8.
74The 'nix example will produce a makefile which can be built using make. 74The 'nix example will produce a makefile which can be built using make.
75 75
76The executables will be placed within the 'bin' directory, once built. 76The executables will be placed within the 'bin' directory, once built.
77 77
diff --git a/utils/zenutils/source/CMakeLists.txt b/utils/zenutils/source/CMakeLists.txt
index e3d44fd036..e7a4bcf63b 100755..100644
--- a/utils/zenutils/source/CMakeLists.txt
+++ b/utils/zenutils/source/CMakeLists.txt
@@ -1,6 +1,6 @@
1ADD_SUBDIRECTORY(firmware_extract) 1ADD_SUBDIRECTORY(firmware_extract)
2ADD_SUBDIRECTORY(firmware_make) 2ADD_SUBDIRECTORY(firmware_make)
3ADD_SUBDIRECTORY(shared) 3ADD_SUBDIRECTORY(shared)
4ADD_SUBDIRECTORY(update_extract) 4ADD_SUBDIRECTORY(update_extract)
5ADD_SUBDIRECTORY(update_patch) 5ADD_SUBDIRECTORY(update_patch)
6ADD_SUBDIRECTORY(zen_crypt) 6ADD_SUBDIRECTORY(zen_crypt)
diff --git a/utils/zenutils/source/firmware_extract/CMakeLists.txt b/utils/zenutils/source/firmware_extract/CMakeLists.txt
index 3814f03612..43af3e3235 100755..100644
--- a/utils/zenutils/source/firmware_extract/CMakeLists.txt
+++ b/utils/zenutils/source/firmware_extract/CMakeLists.txt
@@ -1,3 +1,3 @@
1ADD_EXECUTABLE(firmware_extract main.cpp) 1ADD_EXECUTABLE(firmware_extract main.cpp)
2 2
3TARGET_LINK_LIBRARIES(firmware_extract shared) 3TARGET_LINK_LIBRARIES(firmware_extract shared)
diff --git a/utils/zenutils/source/firmware_extract/main.cpp b/utils/zenutils/source/firmware_extract/main.cpp
index c677a91a75..bcd77afdfc 100755..100644
--- a/utils/zenutils/source/firmware_extract/main.cpp
+++ b/utils/zenutils/source/firmware_extract/main.cpp
@@ -1,243 +1,243 @@
1/* zenutils - Utilities for working with creative firmwares. 1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com> 2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 * 3 *
4 * This program is free software; you can redistribute it and/or modify 4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by 5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or 6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. 7 * (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software 15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */ 17 */
18 18
19#include <iostream> 19#include <iostream>
20#include <ctime> 20#include <ctime>
21#include <getpot/getpot.hpp> 21#include <getpot/getpot.hpp>
22#include <utils.h> 22#include <utils.h>
23#include <firmware.h> 23#include <firmware.h>
24 24
25 25
26static const char VERSION[] = "0.1"; 26static const char VERSION[] = "0.1";
27 27
28 28
29void print_version() 29void print_version()
30{ 30{
31 std::cout 31 std::cout
32 << "firmware_extract - Extracts files from a Creative firmware." 32 << "firmware_extract - Extracts files from a Creative firmware."
33 << std::endl 33 << std::endl
34 << "Version " << VERSION << std::endl 34 << "Version " << VERSION << std::endl
35 << "Copyright (c) 2007 Rasmus Ry" << std::endl; 35 << "Copyright (c) 2007 Rasmus Ry" << std::endl;
36} 36}
37 37
38void print_help() 38void print_help()
39{ 39{
40 print_version(); 40 print_version();
41 std::cout 41 std::cout
42 << "Usage: firmware_extract [command] [options]" << std::endl 42 << "Usage: firmware_extract [command] [options]" << std::endl
43 << std::endl 43 << std::endl
44 << " Commands:" << std::endl 44 << " Commands:" << std::endl
45 << " -h,--help" << std::endl 45 << " -h,--help" << std::endl
46 << " prints this message." << std::endl 46 << " prints this message." << std::endl
47 << " -f,--firmware [file]" << std::endl 47 << " -f,--firmware [file]" << std::endl
48 << " specifies the firmware arhive file name." << std::endl 48 << " specifies the firmware arhive file name." << std::endl
49 << std::endl 49 << std::endl
50 << " Options:" << std::endl 50 << " Options:" << std::endl
51 << " -V,--verbose" << std::endl 51 << " -V,--verbose" << std::endl
52 << " prints verbose messages." << std::endl 52 << " prints verbose messages." << std::endl
53 << " -p,--prefix [prefix]" << std::endl 53 << " -p,--prefix [prefix]" << std::endl
54 << " specifies a file name prefix for the extracted files." << std::endl 54 << " specifies a file name prefix for the extracted files." << std::endl
55 << std::endl 55 << std::endl
56 ; 56 ;
57} 57}
58 58
59 59
60struct save_entry_functor 60struct save_entry_functor
61{ 61{
62 save_entry_functor(const std::string& fileprefix) 62 save_entry_functor(const std::string& fileprefix)
63 : _fileprefix(fileprefix) {} 63 : _fileprefix(fileprefix) {}
64 64
65 bool operator()(const zen::firmware_entry& entry) 65 bool operator()(const zen::firmware_entry& entry)
66 { 66 {
67 std::string filename = _fileprefix + entry.get_content_name(); 67 std::string filename = _fileprefix + entry.get_content_name();
68 std::ofstream ofs; 68 std::ofstream ofs;
69 ofs.open(filename.c_str(), std::ios::binary); 69 ofs.open(filename.c_str(), std::ios::binary);
70 if (!ofs) 70 if (!ofs)
71 false; 71 false;
72 72
73 size_t off = entry.get_content_offset(); 73 size_t off = entry.get_content_offset();
74 std::streamsize size = entry.get_bytes().size() - off; 74 std::streamsize size = entry.get_bytes().size() - off;
75 ofs.write((const char*)&entry.get_bytes()[off], size); 75 ofs.write((const char*)&entry.get_bytes()[off], size);
76 76
77 return ofs.good(); 77 return ofs.good();
78 } 78 }
79 79
80 const std::string& _fileprefix; 80 const std::string& _fileprefix;
81}; //struct save_entry_functor 81}; //struct save_entry_functor
82 82
83struct print_entry_functor 83struct print_entry_functor
84{ 84{
85 print_entry_functor(std::ostream& os, const std::string& fileprefix) 85 print_entry_functor(std::ostream& os, const std::string& fileprefix)
86 : _os(os), _fileprefix(fileprefix), num(0) {} 86 : _os(os), _fileprefix(fileprefix), num(0) {}
87 87
88 bool operator()(const zen::firmware_entry& entry) 88 bool operator()(const zen::firmware_entry& entry)
89 { 89 {
90 std::string filename = _fileprefix + entry.get_content_name(); 90 std::string filename = _fileprefix + entry.get_content_name();
91 if (!num) 91 if (!num)
92 _os << "[./" << num++ << "]" << std::endl; 92 _os << "[./" << num++ << "]" << std::endl;
93 else 93 else
94 _os << "[../" << num++ << "]" << std::endl; 94 _os << "[../" << num++ << "]" << std::endl;
95 _os << "tag = " << entry.get_name() << std::endl; 95 _os << "tag = " << entry.get_name() << std::endl;
96 96
97 if (entry.get_content_offset()) 97 if (entry.get_content_offset())
98 _os << "name = " << entry.get_content_name() << std::endl; 98 _os << "name = " << entry.get_content_name() << std::endl;
99 99
100 _os << "file = \'" << shared::double_quote(filename) << "\'" 100 _os << "file = \'" << shared::double_quote(filename) << "\'"
101 << std::endl; 101 << std::endl;
102 102
103 return _os.good(); 103 return _os.good();
104 } 104 }
105 105
106 std::ostream& _os; 106 std::ostream& _os;
107 const std::string& _fileprefix; 107 const std::string& _fileprefix;
108 int num; 108 int num;
109}; //struct print_entry_functor 109}; //struct print_entry_functor
110 110
111 111
112int process_arguments(int argc, char* argv[]) 112int process_arguments(int argc, char* argv[])
113{ 113{
114 //-------------------------------------------------------------------- 114 //--------------------------------------------------------------------
115 // Parse input variables. 115 // Parse input variables.
116 //-------------------------------------------------------------------- 116 //--------------------------------------------------------------------
117 117
118 GetPot cl(argc, argv); 118 GetPot cl(argc, argv);
119 if (cl.size() == 1 || cl.search(2, "-h", "--help")) 119 if (cl.size() == 1 || cl.search(2, "-h", "--help"))
120 { 120 {
121 print_help(); 121 print_help();
122 return 1; 122 return 1;
123 } 123 }
124 124
125 std::string firmwarename; 125 std::string firmwarename;
126 if (cl.search("-f") || cl.search("--firmware")) 126 if (cl.search("-f") || cl.search("--firmware"))
127 firmwarename = cl.next(""); 127 firmwarename = cl.next("");
128 if (firmwarename.empty()) 128 if (firmwarename.empty())
129 { 129 {
130 std::cerr << "Firmware archive must be specified." << std::endl; 130 std::cerr << "Firmware archive must be specified." << std::endl;
131 return 2; 131 return 2;
132 } 132 }
133 133
134 bool verbose = false; 134 bool verbose = false;
135 if (cl.search("-V") || cl.search("--verbose")) 135 if (cl.search("-V") || cl.search("--verbose"))
136 verbose = true; 136 verbose = true;
137 137
138 std::string prefixname = shared::remove_extension(firmwarename) + "_"; 138 std::string prefixname = shared::remove_extension(firmwarename) + "_";
139 if (cl.search("-p") || cl.search("--prefix")) 139 if (cl.search("-p") || cl.search("--prefix"))
140 prefixname = cl.next(prefixname.c_str()); 140 prefixname = cl.next(prefixname.c_str());
141 141
142 142
143 //-------------------------------------------------------------------- 143 //--------------------------------------------------------------------
144 // Read the firmware archive. 144 // Read the firmware archive.
145 //-------------------------------------------------------------------- 145 //--------------------------------------------------------------------
146 146
147 if (verbose) 147 if (verbose)
148 std::cout << "[*] Reading firmware archive..." << std::endl; 148 std::cout << "[*] Reading firmware archive..." << std::endl;
149 149
150 zen::firmware_archive archive(false); 150 zen::firmware_archive archive(false);
151 std::ifstream ifs; 151 std::ifstream ifs;
152 ifs.open(firmwarename.c_str(), std::ios::binary); 152 ifs.open(firmwarename.c_str(), std::ios::binary);
153 if (!ifs) 153 if (!ifs)
154 { 154 {
155 std::cerr << "Failed to open the firmware archive." << std::endl; 155 std::cerr << "Failed to open the firmware archive." << std::endl;
156 return 3; 156 return 3;
157 } 157 }
158 158
159 if (!archive.read(ifs)) 159 if (!archive.read(ifs))
160 { 160 {
161 std::cerr << "Failed to read the firmware archive." << std::endl; 161 std::cerr << "Failed to read the firmware archive." << std::endl;
162 return 4; 162 return 4;
163 } 163 }
164 164
165 165
166 //-------------------------------------------------------------------- 166 //--------------------------------------------------------------------
167 // Generate a make file for the extracted firmware archive. 167 // Generate a make file for the extracted firmware archive.
168 //-------------------------------------------------------------------- 168 //--------------------------------------------------------------------
169 169
170 // Get make filename for the given input file. 170 // Get make filename for the given input file.
171 std::string makefile = shared::replace_extension(firmwarename, ".mk"); 171 std::string makefile = shared::replace_extension(firmwarename, ".mk");
172 172
173 if (verbose) 173 if (verbose)
174 std::cout << "[*] Producing make file..." << std::endl; 174 std::cout << "[*] Producing make file..." << std::endl;
175 175
176 176
177 // Produce make file for the given input file. 177 // Produce make file for the given input file.
178 std::ofstream ofs; 178 std::ofstream ofs;
179 ofs.open(makefile.c_str(), std::ios::binary); 179 ofs.open(makefile.c_str(), std::ios::binary);
180 if (!ofs) 180 if (!ofs)
181 { 181 {
182 std::cerr << "Failed to create firmware archive make file." 182 std::cerr << "Failed to create firmware archive make file."
183 << std::endl; 183 << std::endl;
184 return 5; 184 return 5;
185 } 185 }
186 186
187 time_t timeval = time(NULL); 187 time_t timeval = time(NULL);
188 ofs << "# Make file generated at: " << ctime(&timeval); 188 ofs << "# Make file generated at: " << ctime(&timeval);
189 ofs << "endian = " << (archive.is_big_endian() ? "big" : "little") 189 ofs << "endian = " << (archive.is_big_endian() ? "big" : "little")
190 << std::endl; 190 << std::endl;
191 ofs << "signed = " << (archive.is_signed() ? "true" : "false") 191 ofs << "signed = " << (archive.is_signed() ? "true" : "false")
192 << std::endl; 192 << std::endl;
193 193
194 ofs << "[children]" << std::endl; 194 ofs << "[children]" << std::endl;
195 ofs << "count = " << archive.get_children().size() << std::endl; 195 ofs << "count = " << archive.get_children().size() << std::endl;
196 196
197 std::for_each(archive.get_children().begin(), 197 std::for_each(archive.get_children().begin(),
198 archive.get_children().end(), 198 archive.get_children().end(),
199 print_entry_functor(ofs, prefixname)); 199 print_entry_functor(ofs, prefixname));
200 200
201 ofs << "[neighbours]" << std::endl; 201 ofs << "[neighbours]" << std::endl;
202 ofs << "count = " << archive.get_neighbours().size() << std::endl; 202 ofs << "count = " << archive.get_neighbours().size() << std::endl;
203 std::for_each(archive.get_neighbours().begin(), 203 std::for_each(archive.get_neighbours().begin(),
204 archive.get_neighbours().end(), 204 archive.get_neighbours().end(),
205 print_entry_functor(ofs, prefixname)); 205 print_entry_functor(ofs, prefixname));
206 206
207 207
208 //-------------------------------------------------------------------- 208 //--------------------------------------------------------------------
209 // Save firmware entries. 209 // Save firmware entries.
210 //-------------------------------------------------------------------- 210 //--------------------------------------------------------------------
211 211
212 if (verbose) 212 if (verbose)
213 std::cout << "[*] Saving firmware entries..." << std::endl; 213 std::cout << "[*] Saving firmware entries..." << std::endl;
214 214
215 std::for_each(archive.get_children().begin(), 215 std::for_each(archive.get_children().begin(),
216 archive.get_children().end(), 216 archive.get_children().end(),
217 save_entry_functor(prefixname)); 217 save_entry_functor(prefixname));
218 218
219 std::for_each(archive.get_neighbours().begin(), 219 std::for_each(archive.get_neighbours().begin(),
220 archive.get_neighbours().end(), 220 archive.get_neighbours().end(),
221 save_entry_functor(prefixname)); 221 save_entry_functor(prefixname));
222 222
223 return 0; 223 return 0;
224} 224}
225 225
226int main(int argc, char* argv[]) 226int main(int argc, char* argv[])
227{ 227{
228 try 228 try
229 { 229 {
230 return process_arguments(argc, argv); 230 return process_arguments(argc, argv);
231 } 231 }
232 catch (const std::exception& xcpt) 232 catch (const std::exception& xcpt)
233 { 233 {
234 std::cerr << "Exception caught: " << xcpt.what() << std::endl; 234 std::cerr << "Exception caught: " << xcpt.what() << std::endl;
235 return -1; 235 return -1;
236 } 236 }
237 catch (...) 237 catch (...)
238 { 238 {
239 std::cerr << "Unknown exception caught." << std::endl; 239 std::cerr << "Unknown exception caught." << std::endl;
240 return -2; 240 return -2;
241 } 241 }
242 return -3; 242 return -3;
243} 243}
diff --git a/utils/zenutils/source/firmware_make/CMakeLists.txt b/utils/zenutils/source/firmware_make/CMakeLists.txt
index 518a008730..39197e2f07 100755..100644
--- a/utils/zenutils/source/firmware_make/CMakeLists.txt
+++ b/utils/zenutils/source/firmware_make/CMakeLists.txt
@@ -1,3 +1,3 @@
1ADD_EXECUTABLE(firmware_make main.cpp) 1ADD_EXECUTABLE(firmware_make main.cpp)
2 2
3TARGET_LINK_LIBRARIES (firmware_make shared) 3TARGET_LINK_LIBRARIES (firmware_make shared)
diff --git a/utils/zenutils/source/firmware_make/main.cpp b/utils/zenutils/source/firmware_make/main.cpp
index b0602b6ffe..35d036e601 100755..100644
--- a/utils/zenutils/source/firmware_make/main.cpp
+++ b/utils/zenutils/source/firmware_make/main.cpp
@@ -1,261 +1,261 @@
1/* zenutils - Utilities for working with creative firmwares. 1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com> 2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 * 3 *
4 * This program is free software; you can redistribute it and/or modify 4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by 5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or 6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. 7 * (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software 15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */ 17 */
18 18
19#include <iostream> 19#include <iostream>
20#include <sstream> 20#include <sstream>
21#include <getpot/getpot.hpp> 21#include <getpot/getpot.hpp>
22#include <file.h> 22#include <file.h>
23#include <firmware.h> 23#include <firmware.h>
24#include <utils.h> 24#include <utils.h>
25 25
26 26
27static const char VERSION[] = "0.1"; 27static const char VERSION[] = "0.1";
28 28
29void print_version() 29void print_version()
30{ 30{
31 std::cout 31 std::cout
32 << "firmware_make - Creates a Creative firmware archive." << std::endl 32 << "firmware_make - Creates a Creative firmware archive." << std::endl
33 << "Version " << VERSION << std::endl 33 << "Version " << VERSION << std::endl
34 << "Copyright (c) 2007 Rasmus Ry" << std::endl; 34 << "Copyright (c) 2007 Rasmus Ry" << std::endl;
35} 35}
36 36
37void print_help() 37void print_help()
38{ 38{
39 print_version(); 39 print_version();
40 std::cout << std::endl 40 std::cout << std::endl
41 << "Usage: firmware_make [command] [options]" << std::endl 41 << "Usage: firmware_make [command] [options]" << std::endl
42 << std::endl 42 << std::endl
43 << " Commands:" << std::endl 43 << " Commands:" << std::endl
44 << " -h,--help" << std::endl 44 << " -h,--help" << std::endl
45 << " prints this message." << std::endl 45 << " prints this message." << std::endl
46 << " -m,--makefile [file]" << std::endl 46 << " -m,--makefile [file]" << std::endl
47 << " specifies the .mk file to build the firmware archive from." 47 << " specifies the .mk file to build the firmware archive from."
48 << std::endl << std::endl 48 << std::endl << std::endl
49 << " Options:" << std::endl 49 << " Options:" << std::endl
50 << " -V,--verbose" << std::endl 50 << " -V,--verbose" << std::endl
51 << " prints verbose messages." << std::endl 51 << " prints verbose messages." << std::endl
52 << " -f,--firmware [file]" << std::endl 52 << " -f,--firmware [file]" << std::endl
53 << " specifies the output firmware file name" << std::endl 53 << " specifies the output firmware file name" << std::endl
54 << std::endl 54 << std::endl
55 ; 55 ;
56} 56}
57 57
58dword get_tag_value(std::string tag) 58dword get_tag_value(std::string tag)
59{ 59{
60 if (tag[0] == '0' && tag[1] == 'x') 60 if (tag[0] == '0' && tag[1] == 'x')
61 { 61 {
62 dword val = 0; 62 dword val = 0;
63 if (sscanf(tag.c_str(), "0x%08X", &val) == 1) 63 if (sscanf(tag.c_str(), "0x%08X", &val) == 1)
64 return val; 64 return val;
65 if (sscanf(tag.c_str(), "0x%08x", &val) == 1) 65 if (sscanf(tag.c_str(), "0x%08x", &val) == 1)
66 return val; 66 return val;
67 } 67 }
68 else 68 else
69 { 69 {
70 return shared::swap(*(dword*)&tag[0]); 70 return shared::swap(*(dword*)&tag[0]);
71 } 71 }
72 return 0; 72 return 0;
73} 73}
74 74
75bool process_child(const GetPot& mkfile, const std::string& root, int index, 75bool process_child(const GetPot& mkfile, const std::string& root, int index,
76 zen::firmware_entry& entry) 76 zen::firmware_entry& entry)
77{ 77{
78 std::stringstream sstm; 78 std::stringstream sstm;
79 sstm << root << "/" << index; 79 sstm << root << "/" << index;
80 std::string var = sstm.str() + "/tag"; 80 std::string var = sstm.str() + "/tag";
81 std::string tag = mkfile(var.c_str(), ""); 81 std::string tag = mkfile(var.c_str(), "");
82 var = sstm.str() + "/name"; 82 var = sstm.str() + "/name";
83 std::string name = mkfile(var.c_str(), ""); 83 std::string name = mkfile(var.c_str(), "");
84 var = sstm.str() + "/file"; 84 var = sstm.str() + "/file";
85 std::string file = mkfile(var.c_str(), ""); 85 std::string file = mkfile(var.c_str(), "");
86 86
87 if (file.empty() || tag.empty()) 87 if (file.empty() || tag.empty())
88 { 88 {
89 std::cerr << "Invalid file or tag for var: " << sstm.str() 89 std::cerr << "Invalid file or tag for var: " << sstm.str()
90 << std::endl; 90 << std::endl;
91 return false; 91 return false;
92 } 92 }
93 93
94 shared::bytes buffer; 94 shared::bytes buffer;
95 if (!shared::read_file(file, buffer)) 95 if (!shared::read_file(file, buffer))
96 { 96 {
97 std::cerr << "Failed to read the file: " << file << std::endl; 97 std::cerr << "Failed to read the file: " << file << std::endl;
98 return false; 98 return false;
99 } 99 }
100 100
101 entry.get_bytes().clear(); 101 entry.get_bytes().clear();
102 entry.get_header().tag = get_tag_value(tag); 102 entry.get_header().tag = get_tag_value(tag);
103 size_t contoff = entry.get_content_offset(); 103 size_t contoff = entry.get_content_offset();
104 if (contoff) 104 if (contoff)
105 { 105 {
106 entry.get_bytes().resize(contoff, 0); 106 entry.get_bytes().resize(contoff, 0);
107 if (!name.empty()) 107 if (!name.empty())
108 { 108 {
109 size_t endoff = entry.is_big_endian() ? 1 : 0; 109 size_t endoff = entry.is_big_endian() ? 1 : 0;
110 for (int i = 0; i < name.size(); ++i) 110 for (int i = 0; i < name.size(); ++i)
111 entry.get_bytes()[i * 2 + endoff] = name[i]; 111 entry.get_bytes()[i * 2 + endoff] = name[i];
112 } 112 }
113 } 113 }
114 entry.get_bytes().insert(entry.get_bytes().end(), buffer.begin(), 114 entry.get_bytes().insert(entry.get_bytes().end(), buffer.begin(),
115 buffer.end()); 115 buffer.end());
116 116
117 entry.get_header().size = entry.get_bytes().size(); 117 entry.get_header().size = entry.get_bytes().size();
118 118
119 return true; 119 return true;
120} 120}
121 121
122int process_arguments(int argc, char* argv[]) 122int process_arguments(int argc, char* argv[])
123{ 123{
124 //-------------------------------------------------------------------- 124 //--------------------------------------------------------------------
125 // Parse input variables. 125 // Parse input variables.
126 //-------------------------------------------------------------------- 126 //--------------------------------------------------------------------
127 127
128 GetPot cl(argc, argv); 128 GetPot cl(argc, argv);
129 if (cl.size() == 1 || cl.search(2, "-h", "--help")) 129 if (cl.size() == 1 || cl.search(2, "-h", "--help"))
130 { 130 {
131 print_help(); 131 print_help();
132 return 1; 132 return 1;
133 } 133 }
134 134
135 std::string makefile; 135 std::string makefile;
136 if (cl.search("-m") || cl.search("--makefile")) 136 if (cl.search("-m") || cl.search("--makefile"))
137 makefile = cl.next(""); 137 makefile = cl.next("");
138 if (makefile.empty()) 138 if (makefile.empty())
139 { 139 {
140 std::cerr << "Makefile must be specified." << std::endl; 140 std::cerr << "Makefile must be specified." << std::endl;
141 return 2; 141 return 2;
142 } 142 }
143 143
144 std::string firmware; 144 std::string firmware;
145 if (cl.search("-f") || cl.search("--firmware")) 145 if (cl.search("-f") || cl.search("--firmware"))
146 firmware = cl.next(""); 146 firmware = cl.next("");
147 if (firmware.empty()) 147 if (firmware.empty())
148 { 148 {
149 std::cerr << "Firmware must be specified." << std::endl; 149 std::cerr << "Firmware must be specified." << std::endl;
150 return 3; 150 return 3;
151 } 151 }
152 152
153 bool verbose = false; 153 bool verbose = false;
154 if (cl.search("-V") || cl.search("--verbose")) 154 if (cl.search("-V") || cl.search("--verbose"))
155 verbose = true; 155 verbose = true;
156 156
157 GetPot mkfile(makefile.c_str()); 157 GetPot mkfile(makefile.c_str());
158 if (verbose) 158 if (verbose)
159 mkfile.print(); 159 mkfile.print();
160 160
161 bool big_endian; 161 bool big_endian;
162 std::string endian = mkfile("endian", "little"); 162 std::string endian = mkfile("endian", "little");
163 if (endian == "little") 163 if (endian == "little")
164 { 164 {
165 big_endian = false; 165 big_endian = false;
166 } 166 }
167 else if (endian == "big") 167 else if (endian == "big")
168 { 168 {
169 big_endian = true; 169 big_endian = true;
170 } 170 }
171 else 171 else
172 { 172 {
173 std::cerr << "Invalid value of 'endian'" << std::endl; 173 std::cerr << "Invalid value of 'endian'" << std::endl;
174 return 4; 174 return 4;
175 } 175 }
176 176
177 zen::firmware_archive archive(big_endian); 177 zen::firmware_archive archive(big_endian);
178 int childcount = mkfile("children/count", 0); 178 int childcount = mkfile("children/count", 0);
179 if (!childcount) 179 if (!childcount)
180 { 180 {
181 std::cerr << "A firmware archive must have at least one child entry." 181 std::cerr << "A firmware archive must have at least one child entry."
182 << std::endl; 182 << std::endl;
183 return 5; 183 return 5;
184 } 184 }
185 185
186 for (int i = 0; i < childcount; i++) 186 for (int i = 0; i < childcount; i++)
187 { 187 {
188 zen::firmware_entry entry(big_endian); 188 zen::firmware_entry entry(big_endian);
189 if (!process_child(mkfile, "children", i, entry)) 189 if (!process_child(mkfile, "children", i, entry))
190 { 190 {
191 return 6; 191 return 6;
192 } 192 }
193 archive.get_children().push_back(entry); 193 archive.get_children().push_back(entry);
194 } 194 }
195 195
196 int neighbourcount = mkfile("neighbours/count", 0); 196 int neighbourcount = mkfile("neighbours/count", 0);
197 for (int i = 0; i < neighbourcount; i++) 197 for (int i = 0; i < neighbourcount; i++)
198 { 198 {
199 zen::firmware_entry entry(big_endian); 199 zen::firmware_entry entry(big_endian);
200 if (!process_child(mkfile, "neighbours", i, entry)) 200 if (!process_child(mkfile, "neighbours", i, entry))
201 { 201 {
202 return 7; 202 return 7;
203 } 203 }
204 archive.get_neighbours().push_back(entry); 204 archive.get_neighbours().push_back(entry);
205 } 205 }
206 206
207 std::ofstream ofs; 207 std::ofstream ofs;
208 ofs.open(firmware.c_str(), std::ios::out|std::ios::binary|std::ios::trunc); 208 ofs.open(firmware.c_str(), std::ios::out|std::ios::binary|std::ios::trunc);
209 if (!ofs) 209 if (!ofs)
210 { 210 {
211 std::cerr << "Failed to create the firmware file." << std::endl; 211 std::cerr << "Failed to create the firmware file." << std::endl;
212 return 8; 212 return 8;
213 } 213 }
214 214
215 if (!archive.write(ofs)) 215 if (!archive.write(ofs))
216 { 216 {
217 std::cerr << "Failed to save the firmware archive." << std::endl; 217 std::cerr << "Failed to save the firmware archive." << std::endl;
218 return 9; 218 return 9;
219 } 219 }
220 ofs.close(); 220 ofs.close();
221 221
222 size_t length = archive.calc_size(); 222 size_t length = archive.calc_size();
223 if (!length) 223 if (!length)
224 { 224 {
225 std::cerr << "Failed to determine the size of the firmware archive." 225 std::cerr << "Failed to determine the size of the firmware archive."
226 << std::endl; 226 << std::endl;
227 return 10; 227 return 10;
228 } 228 }
229 229
230 int align = length % 4; 230 int align = length % 4;
231 if (align) 231 if (align)
232 { 232 {
233 shared::bytes padding(4 - align, 0); 233 shared::bytes padding(4 - align, 0);
234 if (!shared::write_file(firmware, padding, false, length)) 234 if (!shared::write_file(firmware, padding, false, length))
235 { 235 {
236 std::cerr << "Failed to write padding data." << std::endl; 236 std::cerr << "Failed to write padding data." << std::endl;
237 return 11; 237 return 11;
238 } 238 }
239 } 239 }
240 240
241 return 0; 241 return 0;
242} 242}
243 243
244int main(int argc, char* argv[]) 244int main(int argc, char* argv[])
245{ 245{
246 try 246 try
247 { 247 {
248 return process_arguments(argc, argv); 248 return process_arguments(argc, argv);
249 } 249 }
250 catch (const std::exception& xcpt) 250 catch (const std::exception& xcpt)
251 { 251 {
252 std::cerr << "Exception caught: " << xcpt.what() << std::endl; 252 std::cerr << "Exception caught: " << xcpt.what() << std::endl;
253 return -1; 253 return -1;
254 } 254 }
255 catch (...) 255 catch (...)
256 { 256 {
257 std::cerr << "Unknown exception caught." << std::endl; 257 std::cerr << "Unknown exception caught." << std::endl;
258 return -2; 258 return -2;
259 } 259 }
260 return -3; 260 return -3;
261} 261}
diff --git a/utils/zenutils/source/shared/CMakeLists.txt b/utils/zenutils/source/shared/CMakeLists.txt
index 2e42dbbe74..751257f64f 100755..100644
--- a/utils/zenutils/source/shared/CMakeLists.txt
+++ b/utils/zenutils/source/shared/CMakeLists.txt
@@ -1,16 +1,16 @@
1PROJECT(shared) 1PROJECT(shared)
2 2
3# source files for shared 3# source files for shared
4SET(shared_srcs 4SET(shared_srcs
5 cenc.cpp 5 cenc.cpp
6 crypt.cpp 6 crypt.cpp
7 file.cpp 7 file.cpp
8 firmware.cpp 8 firmware.cpp
9 pe.cpp 9 pe.cpp
10 updater.cpp 10 updater.cpp
11 utils.cpp 11 utils.cpp
12) 12)
13 13
14ADD_LIBRARY(shared ${shared_srcs}) 14ADD_LIBRARY(shared ${shared_srcs})
15TARGET_LINK_LIBRARIES(shared pelib) 15TARGET_LINK_LIBRARIES(shared pelib)
16TARGET_LINK_LIBRARIES(shared zlib) 16TARGET_LINK_LIBRARIES(shared zlib)
diff --git a/utils/zenutils/source/shared/cenc.cpp b/utils/zenutils/source/shared/cenc.cpp
index 932bee4625..929a59b64d 100755..100644
--- a/utils/zenutils/source/shared/cenc.cpp
+++ b/utils/zenutils/source/shared/cenc.cpp
@@ -1,333 +1,333 @@
1/* zenutils - Utilities for working with creative firmwares. 1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com> 2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 * 3 *
4 * This program is free software; you can redistribute it and/or modify 4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by 5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or 6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. 7 * (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software 15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */ 17 */
18 18
19#include "cenc.h" 19#include "cenc.h"
20#include <firmware.h> 20#include <firmware.h>
21#include <stdexcept> 21#include <stdexcept>
22 22
23 23
24namespace { 24namespace {
25const byte CODE_MASK = 0xC0; 25const byte CODE_MASK = 0xC0;
26const byte ARGS_MASK = 0x3F; 26const byte ARGS_MASK = 0x3F;
27 27
28const byte REPEAT_CODE = 0x00; 28const byte REPEAT_CODE = 0x00;
29const byte BLOCK_CODE = 0x40; 29const byte BLOCK_CODE = 0x40;
30const byte LONG_RUN_CODE = 0x80; 30const byte LONG_RUN_CODE = 0x80;
31const byte SHORT_RUN_CODE = 0xC0; 31const byte SHORT_RUN_CODE = 0xC0;
32 32
33const byte BLOCK_ARGS = 0x1F; 33const byte BLOCK_ARGS = 0x1F;
34const byte BLOCK_MODE = 0x20; 34const byte BLOCK_MODE = 0x20;
35 35
36 36
37void decode_run(byte* dst, word len, byte val, 37void decode_run(byte* dst, word len, byte val,
38 int& dstidx) 38 int& dstidx)
39{ 39{
40 memset(dst + dstidx, val, len); 40 memset(dst + dstidx, val, len);
41 dstidx += len; 41 dstidx += len;
42} 42}
43 43
44void decode_pattern(byte* src, byte* dst, 44void decode_pattern(byte* src, byte* dst,
45 word len, int& srcidx, int& dstidx, 45 word len, int& srcidx, int& dstidx,
46 bool bdecode, int npasses) 46 bool bdecode, int npasses)
47{ 47{
48 for (int i = 0; i < npasses; i++) 48 for (int i = 0; i < npasses; i++)
49 { 49 {
50 if (bdecode) 50 if (bdecode)
51 { 51 {
52 for (int j = 0; j < len; j++) 52 for (int j = 0; j < len; j++)
53 { 53 {
54 word c, d; 54 word c, d;
55 c = src[srcidx + j]; 55 c = src[srcidx + j];
56 d = (c >> 5) & 7; 56 d = (c >> 5) & 7;
57 c = (c << 3) & 0xF8; 57 c = (c << 3) & 0xF8;
58 src[srcidx + j] = static_cast<byte>(c | d); 58 src[srcidx + j] = static_cast<byte>(c | d);
59 } 59 }
60 bdecode = false; 60 bdecode = false;
61 } 61 }
62 memcpy(dst + dstidx, src + srcidx, len); 62 memcpy(dst + dstidx, src + srcidx, len);
63 dstidx += len; 63 dstidx += len;
64 } 64 }
65 srcidx += len; 65 srcidx += len;
66} 66}
67}; //namespace 67}; //namespace
68 68
69int zen::cenc_decode(byte* src, int srclen, byte* dst, int dstlen) 69int zen::cenc_decode(byte* src, int srclen, byte* dst, int dstlen)
70{ 70{
71 if (!src || !srclen || !dst || !dstlen) 71 if (!src || !srclen || !dst || !dstlen)
72 { 72 {
73 throw std::invalid_argument("Invalid argument(s)."); 73 throw std::invalid_argument("Invalid argument(s).");
74 } 74 }
75 75
76 int i = 0, j = 0; 76 int i = 0, j = 0;
77 do 77 do
78 { 78 {
79 word c, d, e; 79 word c, d, e;
80 c = src[i++]; 80 c = src[i++];
81 switch (c & CODE_MASK) 81 switch (c & CODE_MASK)
82 { 82 {
83 case REPEAT_CODE: // 2 bytes 83 case REPEAT_CODE: // 2 bytes
84 d = src[i++]; 84 d = src[i++];
85 d = d + 2; 85 d = d + 2;
86 86
87 e = (c & ARGS_MASK) + 2; 87 e = (c & ARGS_MASK) + 2;
88 88
89 decode_pattern(src, dst, e, i, j, false, d); 89 decode_pattern(src, dst, e, i, j, false, d);
90 break; 90 break;
91 91
92 case BLOCK_CODE: // 1/2/3 bytes 92 case BLOCK_CODE: // 1/2/3 bytes
93 d = c & BLOCK_ARGS; 93 d = c & BLOCK_ARGS;
94 if (!(c & BLOCK_MODE)) 94 if (!(c & BLOCK_MODE))
95 { 95 {
96 e = src[i++]; 96 e = src[i++];
97 e = (d << 8) + (e + 0x21); 97 e = (d << 8) + (e + 0x21);
98 98
99 d = static_cast<word>(i ^ j); 99 d = static_cast<word>(i ^ j);
100 } 100 }
101 else 101 else
102 { 102 {
103 e = d + 1; 103 e = d + 1;
104 104
105 d = static_cast<word>(i ^ j); 105 d = static_cast<word>(i ^ j);
106 } 106 }
107 if (d & 1) 107 if (d & 1)
108 { 108 {
109 i++; 109 i++;
110 } 110 }
111 111
112 decode_pattern(src, dst, e, i, j, true, 1); 112 decode_pattern(src, dst, e, i, j, true, 1);
113 break; 113 break;
114 114
115 case LONG_RUN_CODE: // 3 bytes 115 case LONG_RUN_CODE: // 3 bytes
116 d = src[i++]; 116 d = src[i++];
117 e = ((c & ARGS_MASK) << 8) + (d + 0x42); 117 e = ((c & ARGS_MASK) << 8) + (d + 0x42);
118 118
119 d = src[i++]; 119 d = src[i++];
120 d = ((d & 7) << 5) | ((d >> 3) & 0x1F); 120 d = ((d & 7) << 5) | ((d >> 3) & 0x1F);
121 121
122 decode_run(dst, e, static_cast<byte>(d), j); 122 decode_run(dst, e, static_cast<byte>(d), j);
123 break; 123 break;
124 124
125 case SHORT_RUN_CODE: // 2 bytes 125 case SHORT_RUN_CODE: // 2 bytes
126 d = src[i++]; 126 d = src[i++];
127 d = ((d & 3) << 6) | ((d >> 2) & 0x3F); 127 d = ((d & 3) << 6) | ((d >> 2) & 0x3F);
128 128
129 e = (c & ARGS_MASK) + 2; 129 e = (c & ARGS_MASK) + 2;
130 130
131 decode_run(dst, e, static_cast<byte>(d), j); 131 decode_run(dst, e, static_cast<byte>(d), j);
132 break; 132 break;
133 }; 133 };
134 } while (i < srclen && j < dstlen); 134 } while (i < srclen && j < dstlen);
135 135
136 return j; 136 return j;
137} 137}
138 138
139namespace { 139namespace {
140int encode_run(byte* dst, int& dstidx, byte val, int len, int dstlen) 140int encode_run(byte* dst, int& dstidx, byte val, int len, int dstlen)
141{ 141{
142 if (len < 2) 142 if (len < 2)
143 throw std::invalid_argument("Length is too small."); 143 throw std::invalid_argument("Length is too small.");
144 144
145 int ret = 0; 145 int ret = 0;
146 if (len <= 0x41) 146 if (len <= 0x41)
147 { 147 {
148 if ((dstidx + 2) > dstlen) 148 if ((dstidx + 2) > dstlen)
149 throw std::runtime_error("Not enough space to store run."); 149 throw std::runtime_error("Not enough space to store run.");
150 150
151 dst[dstidx++] = SHORT_RUN_CODE | (((len - 2) & ARGS_MASK)); 151 dst[dstidx++] = SHORT_RUN_CODE | (((len - 2) & ARGS_MASK));
152 dst[dstidx++] = ((val >> 6) & 3) | ((val & 0x3F) << 2); 152 dst[dstidx++] = ((val >> 6) & 3) | ((val & 0x3F) << 2);
153 153
154 ret = 2; 154 ret = 2;
155 } 155 }
156 else if (len <= 0x4041) 156 else if (len <= 0x4041)
157 { 157 {
158 if ((dstidx + 3) > dstlen) 158 if ((dstidx + 3) > dstlen)
159 throw std::runtime_error("Not enough space to store run."); 159 throw std::runtime_error("Not enough space to store run.");
160 160
161 byte b1 = (len - 0x42) >> 8; 161 byte b1 = (len - 0x42) >> 8;
162 byte b2 = (len - 0x42) & 0xFF; 162 byte b2 = (len - 0x42) & 0xFF;
163 163
164 dst[dstidx++] = LONG_RUN_CODE | ((b1 & ARGS_MASK)); 164 dst[dstidx++] = LONG_RUN_CODE | ((b1 & ARGS_MASK));
165 dst[dstidx++] = b2; 165 dst[dstidx++] = b2;
166 dst[dstidx++] = ((val >> 5) & 7) | ((val & 0x1F) << 3); 166 dst[dstidx++] = ((val >> 5) & 7) | ((val & 0x1F) << 3);
167 167
168 ret = 3; 168 ret = 3;
169 } 169 }
170 else 170 else
171 { 171 {
172 int long_count = len / 0x4041; 172 int long_count = len / 0x4041;
173 int short_len = len % 0x4041; 173 int short_len = len % 0x4041;
174 bool toosmall = short_len == 1; 174 bool toosmall = short_len == 1;
175 175
176 int run_len = 0x4041; 176 int run_len = 0x4041;
177 for (int i = 0; i < long_count; i++) 177 for (int i = 0; i < long_count; i++)
178 { 178 {
179 if (toosmall && (i == (long_count-1))) 179 if (toosmall && (i == (long_count-1)))
180 { 180 {
181 run_len--; 181 run_len--;
182 toosmall = false; 182 toosmall = false;
183 } 183 }
184 int tmp = encode_run(dst, dstidx, val, run_len, dstlen); 184 int tmp = encode_run(dst, dstidx, val, run_len, dstlen);
185 if (!tmp) return 0; 185 if (!tmp) return 0;
186 ret += tmp; 186 ret += tmp;
187 len -= run_len; 187 len -= run_len;
188 } 188 }
189 189
190 if (len) 190 if (len)
191 { 191 {
192 int short_count = len / 0x41; 192 int short_count = len / 0x41;
193 int short_rest = short_count ? (len % 0x41) : 0; 193 int short_rest = short_count ? (len % 0x41) : 0;
194 toosmall = short_rest == 1; 194 toosmall = short_rest == 1;
195 195
196 run_len = 0x41; 196 run_len = 0x41;
197 for (int i = 0; i < short_count; i++) 197 for (int i = 0; i < short_count; i++)
198 { 198 {
199 if (toosmall && (i == (short_count-1))) 199 if (toosmall && (i == (short_count-1)))
200 { 200 {
201 run_len--; 201 run_len--;
202 toosmall = false; 202 toosmall = false;
203 } 203 }
204 int tmp = encode_run(dst, dstidx, val, run_len, dstlen); 204 int tmp = encode_run(dst, dstidx, val, run_len, dstlen);
205 if (!tmp) return 0; 205 if (!tmp) return 0;
206 ret += tmp; 206 ret += tmp;
207 len -= run_len; 207 len -= run_len;
208 } 208 }
209 int tmp = encode_run(dst, dstidx, val, len, dstlen); 209 int tmp = encode_run(dst, dstidx, val, len, dstlen);
210 if (!tmp) return 0; 210 if (!tmp) return 0;
211 ret += tmp; 211 ret += tmp;
212 len -= len; 212 len -= len;
213 } 213 }
214 } 214 }
215 215
216 return ret; 216 return ret;
217} 217}
218 218
219int encode_block(byte* dst, int& dstidx, byte* src, int& srcidx, int len, 219int encode_block(byte* dst, int& dstidx, byte* src, int& srcidx, int len,
220 int dstlen) 220 int dstlen)
221{ 221{
222 if (len < 1) 222 if (len < 1)
223 throw std::invalid_argument("Length is too small."); 223 throw std::invalid_argument("Length is too small.");
224 224
225 int startidx = dstidx; 225 int startidx = dstidx;
226 if (len < 0x21) 226 if (len < 0x21)
227 { 227 {
228 if ((dstidx + 2 + len) > dstlen) 228 if ((dstidx + 2 + len) > dstlen)
229 throw std::runtime_error("Not enough space to store block."); 229 throw std::runtime_error("Not enough space to store block.");
230 230
231 dst[dstidx++] = BLOCK_CODE | BLOCK_MODE | ((len - 1) & BLOCK_ARGS); 231 dst[dstidx++] = BLOCK_CODE | BLOCK_MODE | ((len - 1) & BLOCK_ARGS);
232 if ((dstidx ^ srcidx) & 1) 232 if ((dstidx ^ srcidx) & 1)
233 dst[dstidx++] = 0; 233 dst[dstidx++] = 0;
234 234
235 for (int i = 0; i < len; i++) 235 for (int i = 0; i < len; i++)
236 { 236 {
237 byte c = src[srcidx++]; 237 byte c = src[srcidx++];
238 byte d = (c & 7) << 5; 238 byte d = (c & 7) << 5;
239 c = (c & 0xF8) >> 3; 239 c = (c & 0xF8) >> 3;
240 dst[dstidx++] = c | d; 240 dst[dstidx++] = c | d;
241 } 241 }
242 } 242 }
243 else if (len < 0x2021) 243 else if (len < 0x2021)
244 { 244 {
245 if ((dstidx + 3 + len) > dstlen) 245 if ((dstidx + 3 + len) > dstlen)
246 throw std::runtime_error("Not enough space to store block."); 246 throw std::runtime_error("Not enough space to store block.");
247 247
248 dst[dstidx++] = BLOCK_CODE | (((len - 0x21) >> 8) & BLOCK_ARGS); 248 dst[dstidx++] = BLOCK_CODE | (((len - 0x21) >> 8) & BLOCK_ARGS);
249 dst[dstidx++] = (len - 0x21) & 0xFF; 249 dst[dstidx++] = (len - 0x21) & 0xFF;
250 if ((dstidx ^ srcidx) & 1) 250 if ((dstidx ^ srcidx) & 1)
251 dst[dstidx++] = 0; 251 dst[dstidx++] = 0;
252 252
253 for (int i = 0; i < len; i++) 253 for (int i = 0; i < len; i++)
254 { 254 {
255 byte c = src[srcidx++]; 255 byte c = src[srcidx++];
256 byte d = (c & 7) << 5; 256 byte d = (c & 7) << 5;
257 c = (c & 0xF8) >> 3; 257 c = (c & 0xF8) >> 3;
258 dst[dstidx++] = c | d; 258 dst[dstidx++] = c | d;
259 } 259 }
260 } 260 }
261 else 261 else
262 { 262 {
263 int longblocks = len / 0x2020; 263 int longblocks = len / 0x2020;
264 int rest = len % 0x2020; 264 int rest = len % 0x2020;
265 for (int i = 0; i < longblocks; i++) 265 for (int i = 0; i < longblocks; i++)
266 { 266 {
267 int tmp = encode_block(dst, dstidx, src, srcidx, 0x2020, dstlen); 267 int tmp = encode_block(dst, dstidx, src, srcidx, 0x2020, dstlen);
268 if (!tmp) return 0; 268 if (!tmp) return 0;
269 } 269 }
270 if (rest) 270 if (rest)
271 { 271 {
272 int shortblocks = rest / 0x20; 272 int shortblocks = rest / 0x20;
273 for (int i = 0; i < shortblocks; i++) 273 for (int i = 0; i < shortblocks; i++)
274 { 274 {
275 int tmp = encode_block(dst, dstidx, src, srcidx, 0x20, dstlen); 275 int tmp = encode_block(dst, dstidx, src, srcidx, 0x20, dstlen);
276 if (!tmp) return 0; 276 if (!tmp) return 0;
277 } 277 }
278 rest = rest % 0x20; 278 rest = rest % 0x20;
279 int tmp = encode_block(dst, dstidx, src, srcidx, rest, dstlen); 279 int tmp = encode_block(dst, dstidx, src, srcidx, rest, dstlen);
280 if (!tmp) return 0; 280 if (!tmp) return 0;
281 } 281 }
282 } 282 }
283 283
284 return (dstidx - startidx); 284 return (dstidx - startidx);
285} 285}
286}; //namespace 286}; //namespace
287 287
288int zen::cenc_encode(byte* src, int srclen, byte* dst, int dstlen) 288int zen::cenc_encode(byte* src, int srclen, byte* dst, int dstlen)
289{ 289{
290 if (!src || !srclen || !dst || !dstlen) 290 if (!src || !srclen || !dst || !dstlen)
291 { 291 {
292 throw std::invalid_argument("Invalid argument(s)."); 292 throw std::invalid_argument("Invalid argument(s).");
293 } 293 }
294 294
295 int i = 0, j = 0, k = 0; 295 int i = 0, j = 0, k = 0;
296 word c, d, e; 296 word c, d, e;
297 int runlen = 0; 297 int runlen = 0;
298 while (i < srclen && j < dstlen) 298 while (i < srclen && j < dstlen)
299 { 299 {
300 k = i; 300 k = i;
301 c = src[i++]; 301 c = src[i++];
302 runlen = 1; 302 runlen = 1;
303 while (i < srclen && src[i] == c) 303 while (i < srclen && src[i] == c)
304 { 304 {
305 runlen++; 305 runlen++;
306 i++; 306 i++;
307 } 307 }
308 if (runlen >= 2) 308 if (runlen >= 2)
309 { 309 {
310 if (!encode_run(dst, j, c, runlen, dstlen)) 310 if (!encode_run(dst, j, c, runlen, dstlen))
311 return 0; 311 return 0;
312 } 312 }
313 else 313 else
314 { 314 {
315 runlen = 0; 315 runlen = 0;
316 i = k; 316 i = k;
317 while (i < (srclen - 1) && (src[i] != src[i + 1])) 317 while (i < (srclen - 1) && (src[i] != src[i + 1]))
318 { 318 {
319 runlen++; 319 runlen++;
320 i++; 320 i++;
321 } 321 }
322 if (i == (srclen - 1)) 322 if (i == (srclen - 1))
323 { 323 {
324 runlen++; 324 runlen++;
325 i++; 325 i++;
326 } 326 }
327 if (!encode_block(dst, j, src, k, runlen, dstlen)) 327 if (!encode_block(dst, j, src, k, runlen, dstlen))
328 return 0; 328 return 0;
329 } 329 }
330 } 330 }
331 331
332 return j; 332 return j;
333} 333}
diff --git a/utils/zenutils/source/shared/cenc.h b/utils/zenutils/source/shared/cenc.h
index 12a7c92516..e96794dcc4 100755..100644
--- a/utils/zenutils/source/shared/cenc.h
+++ b/utils/zenutils/source/shared/cenc.h
@@ -1,29 +1,29 @@
1/* zenutils - Utilities for working with creative firmwares. 1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com> 2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 * 3 *
4 * This program is free software; you can redistribute it and/or modify 4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by 5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or 6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. 7 * (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software 15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */ 17 */
18 18
19#ifndef ZEN_CENC_H_INCLUDED 19#ifndef ZEN_CENC_H_INCLUDED
20#define ZEN_CENC_H_INCLUDED 20#define ZEN_CENC_H_INCLUDED
21 21
22#include <utils.h> 22#include <utils.h>
23 23
24namespace zen { 24namespace zen {
25 int cenc_decode(byte* src, int srclen, byte* dst, int dstlen); 25 int cenc_decode(byte* src, int srclen, byte* dst, int dstlen);
26 int cenc_encode(byte* src, int srclen, byte* dst, int dstlen); 26 int cenc_encode(byte* src, int srclen, byte* dst, int dstlen);
27}; //namespace zen 27}; //namespace zen
28 28
29#endif //CENC_H_INCLUDED 29#endif //CENC_H_INCLUDED
diff --git a/utils/zenutils/source/shared/crypt.cpp b/utils/zenutils/source/shared/crypt.cpp
index 9c2d33870c..3f15ac64f1 100755..100644
--- a/utils/zenutils/source/shared/crypt.cpp
+++ b/utils/zenutils/source/shared/crypt.cpp
@@ -1,91 +1,91 @@
1/* zenutils - Utilities for working with creative firmwares. 1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com> 2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 * 3 *
4 * This program is free software; you can redistribute it and/or modify 4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by 5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or 6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. 7 * (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software 15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */ 17 */
18 18
19#include "crypt.h" 19#include "crypt.h"
20#include <stdexcept> 20#include <stdexcept>
21#include <beecrypt/hmacsha1.h> 21#include <beecrypt/hmacsha1.h>
22#include <beecrypt/blockmode.h> 22#include <beecrypt/blockmode.h>
23#include <beecrypt/blowfish.h> 23#include <beecrypt/blowfish.h>
24 24
25 25
26bool zen::hmac_sha1_calc(const byte* key, size_t keylen, const byte* data, 26bool zen::hmac_sha1_calc(const byte* key, size_t keylen, const byte* data,
27 size_t datalen, byte* sig, size_t* siglen) 27 size_t datalen, byte* sig, size_t* siglen)
28{ 28{
29 hmacsha1Param param; 29 hmacsha1Param param;
30 if (hmacsha1Setup(&param, key, keylen * 8)) 30 if (hmacsha1Setup(&param, key, keylen * 8))
31 return false; 31 return false;
32 if (hmacsha1Update(&param, data, datalen)) 32 if (hmacsha1Update(&param, data, datalen))
33 return false; 33 return false;
34 if (hmacsha1Digest(&param, sig)) 34 if (hmacsha1Digest(&param, sig))
35 return false; 35 return false;
36 return true; 36 return true;
37} 37}
38 38
39bool zen::bf_cbc_encrypt(const byte* key, size_t keylen, byte* data, 39bool zen::bf_cbc_encrypt(const byte* key, size_t keylen, byte* data,
40 size_t datalen, const byte* iv) 40 size_t datalen, const byte* iv)
41{ 41{
42 if (datalen % blowfish.blocksize) 42 if (datalen % blowfish.blocksize)
43 throw std::invalid_argument( 43 throw std::invalid_argument(
44 "The length must be aligned on a 8 byte boundary."); 44 "The length must be aligned on a 8 byte boundary.");
45 45
46 blowfishParam param; 46 blowfishParam param;
47 if (blowfishSetup(&param, key, keylen * 8, ENCRYPT)) 47 if (blowfishSetup(&param, key, keylen * 8, ENCRYPT))
48 return false; 48 return false;
49 if (blowfishSetIV(&param, iv)) 49 if (blowfishSetIV(&param, iv))
50 return false; 50 return false;
51 51
52 byte* plain = new byte[datalen]; 52 byte* plain = new byte[datalen];
53 memcpy(plain, data, datalen); 53 memcpy(plain, data, datalen);
54 54
55 unsigned int nblocks = datalen / blowfish.blocksize; 55 unsigned int nblocks = datalen / blowfish.blocksize;
56 if (blockEncryptCBC(&blowfish, &param, (uint32_t*)data, (uint32_t*)plain, 56 if (blockEncryptCBC(&blowfish, &param, (uint32_t*)data, (uint32_t*)plain,
57 nblocks)) 57 nblocks))
58 { 58 {
59 delete [] plain; 59 delete [] plain;
60 return false; 60 return false;
61 } 61 }
62 62
63 return true; 63 return true;
64} 64}
65 65
66bool zen::bf_cbc_decrypt(const byte* key, size_t keylen, byte* data, 66bool zen::bf_cbc_decrypt(const byte* key, size_t keylen, byte* data,
67 size_t datalen, const byte* iv) 67 size_t datalen, const byte* iv)
68{ 68{
69 if (datalen % blowfish.blocksize) 69 if (datalen % blowfish.blocksize)
70 throw std::invalid_argument( 70 throw std::invalid_argument(
71 "The length must be aligned on a 8 byte boundary."); 71 "The length must be aligned on a 8 byte boundary.");
72 72
73 blowfishParam param; 73 blowfishParam param;
74 if (blowfishSetup(&param, key, keylen * 8, ENCRYPT)) 74 if (blowfishSetup(&param, key, keylen * 8, ENCRYPT))
75 return false; 75 return false;
76 if (blowfishSetIV(&param, iv)) 76 if (blowfishSetIV(&param, iv))
77 return false; 77 return false;
78 78
79 byte* cipher = new byte[datalen]; 79 byte* cipher = new byte[datalen];
80 memcpy(cipher, data, datalen); 80 memcpy(cipher, data, datalen);
81 81
82 unsigned int nblocks = datalen / blowfish.blocksize; 82 unsigned int nblocks = datalen / blowfish.blocksize;
83 if (blockDecryptCBC(&blowfish, &param, (uint32_t*)data, (uint32_t*)cipher, 83 if (blockDecryptCBC(&blowfish, &param, (uint32_t*)data, (uint32_t*)cipher,
84 nblocks)) 84 nblocks))
85 { 85 {
86 delete [] cipher; 86 delete [] cipher;
87 return false; 87 return false;
88 } 88 }
89 89
90 return true; 90 return true;
91} 91}
diff --git a/utils/zenutils/source/shared/crypt.h b/utils/zenutils/source/shared/crypt.h
index a057055b70..a357fef042 100755..100644
--- a/utils/zenutils/source/shared/crypt.h
+++ b/utils/zenutils/source/shared/crypt.h
@@ -1,30 +1,30 @@
1/* zenutils - Utilities for working with creative firmwares. 1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com> 2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 * 3 *
4 * This program is free software; you can redistribute it and/or modify 4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by 5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or 6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. 7 * (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software 15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */ 17 */
18 18
19#ifndef ZEN_CRYPT_H_INCLUDED 19#ifndef ZEN_CRYPT_H_INCLUDED
20#define ZEN_CRYPT_H_INCLUDED 20#define ZEN_CRYPT_H_INCLUDED
21 21
22#include <utils.h> 22#include <utils.h>
23 23
24namespace zen { 24namespace zen {
25 bool hmac_sha1_calc(const byte* key, size_t keylen, const byte* data, size_t datalen, byte* sig, size_t* siglen); 25 bool hmac_sha1_calc(const byte* key, size_t keylen, const byte* data, size_t datalen, byte* sig, size_t* siglen);
26 bool bf_cbc_encrypt(const byte* key, size_t keylen, byte* data, size_t datalen, const byte* iv); 26 bool bf_cbc_encrypt(const byte* key, size_t keylen, byte* data, size_t datalen, const byte* iv);
27 bool bf_cbc_decrypt(const byte* key, size_t keylen, byte* data, size_t datalen, const byte* iv); 27 bool bf_cbc_decrypt(const byte* key, size_t keylen, byte* data, size_t datalen, const byte* iv);
28}; //namespace zen 28}; //namespace zen
29 29
30#endif //ZEN_CRYPT_H_INCLUDED 30#endif //ZEN_CRYPT_H_INCLUDED
diff --git a/utils/zenutils/source/shared/file.cpp b/utils/zenutils/source/shared/file.cpp
index 2c31498972..b1b1093170 100755..100644
--- a/utils/zenutils/source/shared/file.cpp
+++ b/utils/zenutils/source/shared/file.cpp
@@ -1,106 +1,106 @@
1/* zenutils - Utilities for working with creative firmwares. 1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com> 2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 * 3 *
4 * This program is free software; you can redistribute it and/or modify 4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by 5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or 6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. 7 * (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software 15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */ 17 */
18 18
19#include "file.h" 19#include "file.h"
20#include <fstream> 20#include <fstream>
21 21
22 22
23bool shared::read_file(const std::string& filename, bytes& buffer, 23bool shared::read_file(const std::string& filename, bytes& buffer,
24 std::streampos offset, std::streamsize count) 24 std::streampos offset, std::streamsize count)
25{ 25{
26 std::ifstream ifs; 26 std::ifstream ifs;
27 ifs.open(filename.c_str(), std::ios::binary); 27 ifs.open(filename.c_str(), std::ios::binary);
28 if (!ifs) 28 if (!ifs)
29 { 29 {
30 return false; 30 return false;
31 } 31 }
32 32
33 std::ifstream::pos_type startpos = offset; 33 std::ifstream::pos_type startpos = offset;
34 ifs.seekg(offset, std::ios::beg); 34 ifs.seekg(offset, std::ios::beg);
35 if (count == -1) 35 if (count == -1)
36 ifs.seekg(0, std::ios::end); 36 ifs.seekg(0, std::ios::end);
37 else 37 else
38 ifs.seekg(count, std::ios::cur); 38 ifs.seekg(count, std::ios::cur);
39 std::ifstream::pos_type endpos = ifs.tellg(); 39 std::ifstream::pos_type endpos = ifs.tellg();
40 40
41 buffer.resize(endpos-startpos); 41 buffer.resize(endpos-startpos);
42 ifs.seekg(offset, std::ios::beg); 42 ifs.seekg(offset, std::ios::beg);
43 43
44 ifs.read((char*)&buffer[0], endpos-startpos); 44 ifs.read((char*)&buffer[0], endpos-startpos);
45 45
46 ifs.close(); 46 ifs.close();
47 return ifs.good(); 47 return ifs.good();
48} 48}
49 49
50 50
51bool shared::write_file(const std::string& filename, bytes& buffer, 51bool shared::write_file(const std::string& filename, bytes& buffer,
52 bool truncate, std::streampos offset, 52 bool truncate, std::streampos offset,
53 std::streamsize count) 53 std::streamsize count)
54{ 54{
55 std::ios::openmode mode = std::ios::in|std::ios::out|std::ios::binary; 55 std::ios::openmode mode = std::ios::in|std::ios::out|std::ios::binary;
56 if (truncate) 56 if (truncate)
57 mode |= std::ios::trunc; 57 mode |= std::ios::trunc;
58 58
59 std::fstream ofs; 59 std::fstream ofs;
60 ofs.open(filename.c_str(), mode); 60 ofs.open(filename.c_str(), mode);
61 if (!ofs) 61 if (!ofs)
62 { 62 {
63 return false; 63 return false;
64 } 64 }
65 65
66 if (count == -1) 66 if (count == -1)
67 count = buffer.size(); 67 count = buffer.size();
68 else if (count > buffer.size()) 68 else if (count > buffer.size())
69 return false; 69 return false;
70 70
71 ofs.seekg(offset, std::ios::beg); 71 ofs.seekg(offset, std::ios::beg);
72 72
73 ofs.write((char*)&buffer[0], count); 73 ofs.write((char*)&buffer[0], count);
74 74
75 ofs.close(); 75 ofs.close();
76 return ofs.good(); 76 return ofs.good();
77} 77}
78 78
79bool shared::file_exists(const std::string& filename) 79bool shared::file_exists(const std::string& filename)
80{ 80{
81 std::ifstream ifs; 81 std::ifstream ifs;
82 ifs.open(filename.c_str(), std::ios::in); 82 ifs.open(filename.c_str(), std::ios::in);
83 if (ifs.is_open()) 83 if (ifs.is_open())
84 { 84 {
85 ifs.close(); 85 ifs.close();
86 return true; 86 return true;
87 } 87 }
88 return false; 88 return false;
89} 89}
90 90
91bool shared::copy_file(const std::string& srcname, const std::string& dstname) 91bool shared::copy_file(const std::string& srcname, const std::string& dstname)
92{ 92{
93 bytes buffer; 93 bytes buffer;
94 if (!read_file(srcname, buffer)) 94 if (!read_file(srcname, buffer))
95 return false; 95 return false;
96 return write_file(dstname, buffer, true); 96 return write_file(dstname, buffer, true);
97} 97}
98 98
99bool shared::backup_file(const std::string& filename, bool force) 99bool shared::backup_file(const std::string& filename, bool force)
100{ 100{
101 std::string backupname = filename + ".bak"; 101 std::string backupname = filename + ".bak";
102 if (!force) 102 if (!force)
103 if (file_exists(backupname)) 103 if (file_exists(backupname))
104 return true; 104 return true;
105 return copy_file(filename, backupname); 105 return copy_file(filename, backupname);
106} 106}
diff --git a/utils/zenutils/source/shared/file.h b/utils/zenutils/source/shared/file.h
index 8fa533c981..770f39a900 100755..100644
--- a/utils/zenutils/source/shared/file.h
+++ b/utils/zenutils/source/shared/file.h
@@ -1,36 +1,36 @@
1/* zenutils - Utilities for working with creative firmwares. 1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com> 2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 * 3 *
4 * This program is free software; you can redistribute it and/or modify 4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by 5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or 6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. 7 * (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software 15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */ 17 */
18 18
19#ifndef SHARED_FILE_H_INCLUDED 19#ifndef SHARED_FILE_H_INCLUDED
20#define SHARED_FILE_H_INCLUDED 20#define SHARED_FILE_H_INCLUDED
21 21
22#include <string> 22#include <string>
23#include <iostream> 23#include <iostream>
24#include "utils.h" 24#include "utils.h"
25 25
26namespace shared { 26namespace shared {
27 bool read_file(const std::string& filename, bytes& buffer, 27 bool read_file(const std::string& filename, bytes& buffer,
28 std::streampos offset = 0, std::streamsize count = -1); 28 std::streampos offset = 0, std::streamsize count = -1);
29 bool write_file(const std::string& filename, bytes& buffer, bool truncate, 29 bool write_file(const std::string& filename, bytes& buffer, bool truncate,
30 std::streampos offset = 0, std::streamsize count = -1); 30 std::streampos offset = 0, std::streamsize count = -1);
31 bool file_exists(const std::string& filename); 31 bool file_exists(const std::string& filename);
32 bool copy_file(const std::string& srcname, const std::string& dstname); 32 bool copy_file(const std::string& srcname, const std::string& dstname);
33 bool backup_file(const std::string& filename, bool force = false); 33 bool backup_file(const std::string& filename, bool force = false);
34}; //namespace shared 34}; //namespace shared
35 35
36#endif //SHARED_FILE_H_INCLUDED 36#endif //SHARED_FILE_H_INCLUDED
diff --git a/utils/zenutils/source/shared/firmware.cpp b/utils/zenutils/source/shared/firmware.cpp
index 7767b55d8f..811b8146b4 100755..100644
--- a/utils/zenutils/source/shared/firmware.cpp
+++ b/utils/zenutils/source/shared/firmware.cpp
@@ -1,387 +1,387 @@
1/* zenutils - Utilities for working with creative firmwares. 1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com> 2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 * 3 *
4 * This program is free software; you can redistribute it and/or modify 4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by 5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or 6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. 7 * (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software 15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */ 17 */
18 18
19#include "firmware.h" 19#include "firmware.h"
20#include <iostream> 20#include <iostream>
21#include <stdexcept> 21#include <stdexcept>
22 22
23 23
24zen::firmware_entry::firmware_entry(bool big_endian) 24zen::firmware_entry::firmware_entry(bool big_endian)
25 : _big_endian(big_endian) 25 : _big_endian(big_endian)
26{ 26{
27} 27}
28 28
29zen::firmware_entry::firmware_entry(const firmware_entry& copy) 29zen::firmware_entry::firmware_entry(const firmware_entry& copy)
30{ 30{
31 assign(copy); 31 assign(copy);
32} 32}
33 33
34zen::firmware_entry& zen::firmware_entry::operator=(const firmware_entry& right) 34zen::firmware_entry& zen::firmware_entry::operator=(const firmware_entry& right)
35{ 35{
36 assign(right); 36 assign(right);
37 return *this; 37 return *this;
38} 38}
39 39
40 40
41bool zen::firmware_entry::read(std::istream& is) 41bool zen::firmware_entry::read(std::istream& is)
42{ 42{
43 // Read the header. 43 // Read the header.
44 is.read((char*)&_header, sizeof(firmware_header_t)); 44 is.read((char*)&_header, sizeof(firmware_header_t));
45 if (!is.good()) 45 if (!is.good())
46 return false; 46 return false;
47 47
48 // If the firmware is big-endian, swap the header values to little-endian. 48 // If the firmware is big-endian, swap the header values to little-endian.
49 if (_big_endian) 49 if (_big_endian)
50 { 50 {
51 _header.tag = shared::swap(_header.tag); 51 _header.tag = shared::swap(_header.tag);
52 if (_header.tag != 'NULL') 52 if (_header.tag != 'NULL')
53 { 53 {
54 _header.size = shared::swap(_header.size); 54 _header.size = shared::swap(_header.size);
55 } 55 }
56 } 56 }
57 57
58 // Resize the bytes buffer to the size specified in the header. 58 // Resize the bytes buffer to the size specified in the header.
59 _bytes.resize(_header.size); 59 _bytes.resize(_header.size);
60 60
61 // Read the entry contents. 61 // Read the entry contents.
62 is.read(reinterpret_cast<char*>(&_bytes[0]), 62 is.read(reinterpret_cast<char*>(&_bytes[0]),
63 _header.size); 63 _header.size);
64 64
65 return is.good(); 65 return is.good();
66} 66}
67 67
68bool zen::firmware_entry::write(std::ostream& os) const 68bool zen::firmware_entry::write(std::ostream& os) const
69{ 69{
70 // Form a header using the current size of the bytes buffer. 70 // Form a header using the current size of the bytes buffer.
71 firmware_header_t header = { 71 firmware_header_t header = {
72 _header.tag, 72 _header.tag,
73 static_cast<dword>(_bytes.size()) 73 static_cast<dword>(_bytes.size())
74 }; 74 };
75 75
76 // If the firmware is big-endian, swap the header values back into big-endian. 76 // If the firmware is big-endian, swap the header values back into big-endian.
77 if (_big_endian) 77 if (_big_endian)
78 { 78 {
79 if (header.tag != 'NULL') 79 if (header.tag != 'NULL')
80 { 80 {
81 header.size = shared::swap(header.size); 81 header.size = shared::swap(header.size);
82 } 82 }
83 header.tag = shared::swap(header.tag); 83 header.tag = shared::swap(header.tag);
84 } 84 }
85 85
86 // Write the header. 86 // Write the header.
87 os.write((const char*)&header, sizeof(firmware_header_t)); 87 os.write((const char*)&header, sizeof(firmware_header_t));
88 if (!os.good()) 88 if (!os.good())
89 return false; 89 return false;
90 90
91 // Write the entry contents. 91 // Write the entry contents.
92 os.write(reinterpret_cast<const char*>(&_bytes[0]), 92 os.write(reinterpret_cast<const char*>(&_bytes[0]),
93 static_cast<std::streamsize>(_bytes.size())); 93 static_cast<std::streamsize>(_bytes.size()));
94 94
95 return os.good(); 95 return os.good();
96} 96}
97 97
98 98
99bool zen::firmware_entry::is_big_endian() const 99bool zen::firmware_entry::is_big_endian() const
100{ 100{
101 return _big_endian; 101 return _big_endian;
102} 102}
103 103
104const zen::firmware_header_t& zen::firmware_entry::get_header() const 104const zen::firmware_header_t& zen::firmware_entry::get_header() const
105{ 105{
106 return _header; 106 return _header;
107} 107}
108zen::firmware_header_t& zen::firmware_entry::get_header() 108zen::firmware_header_t& zen::firmware_entry::get_header()
109{ 109{
110 return _header; 110 return _header;
111} 111}
112 112
113const shared::bytes& zen::firmware_entry::get_bytes() const 113const shared::bytes& zen::firmware_entry::get_bytes() const
114{ 114{
115 return _bytes; 115 return _bytes;
116} 116}
117shared::bytes& zen::firmware_entry::get_bytes() 117shared::bytes& zen::firmware_entry::get_bytes()
118{ 118{
119 return _bytes; 119 return _bytes;
120} 120}
121 121
122 122
123std::string zen::firmware_entry::get_name() const 123std::string zen::firmware_entry::get_name() const
124{ 124{
125 char name[5]; 125 char name[5];
126 *(dword*)name = shared::swap(_header.tag); 126 *(dword*)name = shared::swap(_header.tag);
127 name[4] = '\0'; 127 name[4] = '\0';
128 128
129 // Determine if all characters in the tag are printable. 129 // Determine if all characters in the tag are printable.
130 bool isprintable = true; 130 bool isprintable = true;
131 for (int i = 0; i < 4; i++) 131 for (int i = 0; i < 4; i++)
132 { 132 {
133 if (!isprint((byte)name[i])) 133 if (!isprint((byte)name[i]))
134 { 134 {
135 isprintable = false; 135 isprintable = false;
136 break; 136 break;
137 } 137 }
138 } 138 }
139 139
140 // If they are, simply return the tag as a string. 140 // If they are, simply return the tag as a string.
141 if (isprintable) 141 if (isprintable)
142 { 142 {
143 return std::string(name); 143 return std::string(name);
144 } 144 }
145 145
146 // Otherwise, encode the tag into a hexadecimal string. 146 // Otherwise, encode the tag into a hexadecimal string.
147 char buffer[11]; 147 char buffer[11];
148 sprintf(buffer, "0x%08x", _header.tag); 148 sprintf(buffer, "0x%08x", _header.tag);
149 return std::string(buffer); 149 return std::string(buffer);
150} 150}
151 151
152std::string zen::firmware_entry::get_content_name() const 152std::string zen::firmware_entry::get_content_name() const
153{ 153{
154 std::string name = get_name(); 154 std::string name = get_name();
155 if (name == "DATA") 155 if (name == "DATA")
156 { 156 {
157 name = ""; 157 name = "";
158 int nameoff = is_big_endian() ? 1 : 0; 158 int nameoff = is_big_endian() ? 1 : 0;
159 for (int i = 0; i < 16; i++) 159 for (int i = 0; i < 16; i++)
160 { 160 {
161 char c = get_bytes()[i * 2 + nameoff]; 161 char c = get_bytes()[i * 2 + nameoff];
162 if (!c) 162 if (!c)
163 break; 163 break;
164 name += c; 164 name += c;
165 } 165 }
166 } 166 }
167 else if (name == "EXT0") 167 else if (name == "EXT0")
168 { 168 {
169 name = ""; 169 name = "";
170 int nameoff = is_big_endian() ? 1 : 0; 170 int nameoff = is_big_endian() ? 1 : 0;
171 for (int i = 0; i < 12; i++) 171 for (int i = 0; i < 12; i++)
172 { 172 {
173 char c = get_bytes()[i * 2 + nameoff]; 173 char c = get_bytes()[i * 2 + nameoff];
174 if (!c) 174 if (!c)
175 break; 175 break;
176 name += c; 176 name += c;
177 } 177 }
178 } 178 }
179 return name; 179 return name;
180} 180}
181 181
182size_t zen::firmware_entry::get_content_offset() const 182size_t zen::firmware_entry::get_content_offset() const
183{ 183{
184 std::string name = get_name(); 184 std::string name = get_name();
185 if (name == "DATA") 185 if (name == "DATA")
186 { 186 {
187 return 32; 187 return 32;
188 } 188 }
189 else if (name == "EXT0") 189 else if (name == "EXT0")
190 { 190 {
191 return 24; 191 return 24;
192 } 192 }
193 return 0; 193 return 0;
194} 194}
195 195
196size_t zen::firmware_entry::calc_size() const 196size_t zen::firmware_entry::calc_size() const
197{ 197{
198 return _bytes.size() + sizeof(firmware_header_t); 198 return _bytes.size() + sizeof(firmware_header_t);
199} 199}
200 200
201 201
202void zen::firmware_entry::assign(const firmware_entry& copy) 202void zen::firmware_entry::assign(const firmware_entry& copy)
203{ 203{
204 _big_endian = copy._big_endian; 204 _big_endian = copy._big_endian;
205 _header.tag = copy._header.tag; 205 _header.tag = copy._header.tag;
206 _header.size = copy._header.size; 206 _header.size = copy._header.size;
207 _bytes.assign(copy._bytes.begin(), copy._bytes.end()); 207 _bytes.assign(copy._bytes.begin(), copy._bytes.end());
208} 208}
209 209
210 210
211 211
212zen::firmware_archive::firmware_archive(bool big_endian) 212zen::firmware_archive::firmware_archive(bool big_endian)
213 : _big_endian(big_endian) 213 : _big_endian(big_endian)
214{ 214{
215} 215}
216 216
217zen::firmware_archive::firmware_archive(const firmware_archive& copy) 217zen::firmware_archive::firmware_archive(const firmware_archive& copy)
218{ 218{
219 assign(copy); 219 assign(copy);
220} 220}
221 221
222zen::firmware_archive& zen::firmware_archive::operator=(const firmware_archive& right) 222zen::firmware_archive& zen::firmware_archive::operator=(const firmware_archive& right)
223{ 223{
224 assign(right); 224 assign(right);
225 return *this; 225 return *this;
226} 226}
227 227
228 228
229bool zen::firmware_archive::read(std::istream& is) 229bool zen::firmware_archive::read(std::istream& is)
230{ 230{
231 // Read the root entry's header. 231 // Read the root entry's header.
232 firmware_header_t root; 232 firmware_header_t root;
233 is.read((char*)&root, sizeof(firmware_header_t)); 233 is.read((char*)&root, sizeof(firmware_header_t));
234 if (!is.good()) 234 if (!is.good())
235 return false; 235 return false;
236 236
237 if ((root.tag != 'CIFF') && (root.tag != 'FFIC')) 237 if ((root.tag != 'CIFF') && (root.tag != 'FFIC'))
238 { 238 {
239 throw std::runtime_error("Invalid firmware archive format!"); 239 throw std::runtime_error("Invalid firmware archive format!");
240 } 240 }
241 241
242 _big_endian = root.tag == 'FFIC' ? true : false; 242 _big_endian = root.tag == 'FFIC' ? true : false;
243 if (_big_endian) 243 if (_big_endian)
244 { 244 {
245 root.tag = shared::swap(root.tag); 245 root.tag = shared::swap(root.tag);
246 root.size = shared::swap(root.size); 246 root.size = shared::swap(root.size);
247 } 247 }
248 248
249 // Save the current stream position. 249 // Save the current stream position.
250 std::istream::pos_type endpos = is.tellg(); 250 std::istream::pos_type endpos = is.tellg();
251 std::istream::pos_type curpos = endpos; 251 std::istream::pos_type curpos = endpos;
252 endpos += std::istream::pos_type(root.size); 252 endpos += std::istream::pos_type(root.size);
253 253
254 // Read untill the end of the root entry contents. 254 // Read untill the end of the root entry contents.
255 while (curpos < endpos) 255 while (curpos < endpos)
256 { 256 {
257 firmware_entry entry(_big_endian); 257 firmware_entry entry(_big_endian);
258 if (!entry.read(is)) 258 if (!entry.read(is))
259 return false; 259 return false;
260 260
261 _children.push_back(entry); 261 _children.push_back(entry);
262 curpos = is.tellg(); 262 curpos = is.tellg();
263 } 263 }
264 264
265 curpos = is.tellg(); 265 curpos = is.tellg();
266 is.seekg(0, std::ios::end); 266 is.seekg(0, std::ios::end);
267 endpos = is.tellg(); 267 endpos = is.tellg();
268 is.seekg(curpos); 268 is.seekg(curpos);
269 269
270 // Read untill the end of the file. 270 // Read untill the end of the file.
271 while (((size_t)curpos + sizeof(firmware_header_t)) < endpos) 271 while (((size_t)curpos + sizeof(firmware_header_t)) < endpos)
272 { 272 {
273 firmware_entry entry(_big_endian); 273 firmware_entry entry(_big_endian);
274 if (!entry.read(is)) 274 if (!entry.read(is))
275 return false; 275 return false;
276 276
277 _neighbours.push_back(entry); 277 _neighbours.push_back(entry);
278 curpos = is.tellg(); 278 curpos = is.tellg();
279 } 279 }
280 280
281 return true; 281 return true;
282} 282}
283 283
284bool zen::firmware_archive::write(std::ostream& os) const 284bool zen::firmware_archive::write(std::ostream& os) const
285{ 285{
286 // Read the root entry's header. 286 // Read the root entry's header.
287 firmware_header_t root = {'CIFF', 0}; 287 firmware_header_t root = {'CIFF', 0};
288 288
289 // Calculate the total size of all the children entries. 289 // Calculate the total size of all the children entries.
290 for (firmware_entries::const_iterator i = _children.begin(); 290 for (firmware_entries::const_iterator i = _children.begin();
291 i != _children.end(); ++i) 291 i != _children.end(); ++i)
292 { 292 {
293 root.size += i->calc_size(); 293 root.size += i->calc_size();
294 } 294 }
295 295
296 // If the firmware is big-endian, swap the header values back into big-endian. 296 // If the firmware is big-endian, swap the header values back into big-endian.
297 if (_big_endian) 297 if (_big_endian)
298 { 298 {
299 root.tag = shared::swap(root.tag); 299 root.tag = shared::swap(root.tag);
300 root.size = shared::swap(root.size); 300 root.size = shared::swap(root.size);
301 } 301 }
302 302
303 // Write the header. 303 // Write the header.
304 os.write((const char*)&root, sizeof(firmware_header_t)); 304 os.write((const char*)&root, sizeof(firmware_header_t));
305 if (!os.good()) 305 if (!os.good())
306 return false; 306 return false;
307 307
308 // Write all the child entries. 308 // Write all the child entries.
309 for (firmware_entries::const_iterator i = _children.begin(); 309 for (firmware_entries::const_iterator i = _children.begin();
310 i != _children.end(); ++i) 310 i != _children.end(); ++i)
311 { 311 {
312 if (!i->write(os)) 312 if (!i->write(os))
313 return false; 313 return false;
314 } 314 }
315 315
316 // Write all the neighbour entries. 316 // Write all the neighbour entries.
317 for (firmware_entries::const_iterator i = _neighbours.begin(); 317 for (firmware_entries::const_iterator i = _neighbours.begin();
318 i != _neighbours.end(); ++i) 318 i != _neighbours.end(); ++i)
319 { 319 {
320 if (!i->write(os)) 320 if (!i->write(os))
321 return false; 321 return false;
322 } 322 }
323 323
324 return true; 324 return true;
325} 325}
326 326
327 327
328bool zen::firmware_archive::is_big_endian() const 328bool zen::firmware_archive::is_big_endian() const
329{ 329{
330 return _big_endian; 330 return _big_endian;
331} 331}
332 332
333const zen::firmware_entries& zen::firmware_archive::get_children() const 333const zen::firmware_entries& zen::firmware_archive::get_children() const
334{ 334{
335 return _children; 335 return _children;
336} 336}
337zen::firmware_entries& zen::firmware_archive::get_children() 337zen::firmware_entries& zen::firmware_archive::get_children()
338{ 338{
339 return _children; 339 return _children;
340} 340}
341 341
342const zen::firmware_entries& zen::firmware_archive::get_neighbours() const 342const zen::firmware_entries& zen::firmware_archive::get_neighbours() const
343{ 343{
344 return _neighbours; 344 return _neighbours;
345} 345}
346zen::firmware_entries& zen::firmware_archive::get_neighbours() 346zen::firmware_entries& zen::firmware_archive::get_neighbours()
347{ 347{
348 return _neighbours; 348 return _neighbours;
349} 349}
350 350
351bool zen::firmware_archive::is_signed() const 351bool zen::firmware_archive::is_signed() const
352{ 352{
353 for (firmware_entries::const_iterator i = _neighbours.begin(); 353 for (firmware_entries::const_iterator i = _neighbours.begin();
354 i != _neighbours.end(); i++) 354 i != _neighbours.end(); i++)
355 { 355 {
356 if (i->get_name() == "NULL") 356 if (i->get_name() == "NULL")
357 return true; 357 return true;
358 } 358 }
359 return false; 359 return false;
360} 360}
361 361
362size_t zen::firmware_archive::calc_size() const 362size_t zen::firmware_archive::calc_size() const
363{ 363{
364 size_t size = sizeof(firmware_header_t); 364 size_t size = sizeof(firmware_header_t);
365 365
366 for (firmware_entries::const_iterator i = _children.begin(); 366 for (firmware_entries::const_iterator i = _children.begin();
367 i != _children.end(); i++) 367 i != _children.end(); i++)
368 { 368 {
369 size += i->calc_size(); 369 size += i->calc_size();
370 } 370 }
371 371
372 for (firmware_entries::const_iterator i = _neighbours.begin(); 372 for (firmware_entries::const_iterator i = _neighbours.begin();
373 i != _neighbours.end(); i++) 373 i != _neighbours.end(); i++)
374 { 374 {
375 size += i->calc_size(); 375 size += i->calc_size();
376 } 376 }
377 377
378 return size; 378 return size;
379} 379}
380 380
381 381
382void zen::firmware_archive::assign(const firmware_archive& copy) 382void zen::firmware_archive::assign(const firmware_archive& copy)
383{ 383{
384 _big_endian = copy._big_endian; 384 _big_endian = copy._big_endian;
385 _children.assign(copy._children.begin(), copy._children.end()); 385 _children.assign(copy._children.begin(), copy._children.end());
386 _neighbours.assign(copy._neighbours.begin(), copy._neighbours.end()); 386 _neighbours.assign(copy._neighbours.begin(), copy._neighbours.end());
387} 387}
diff --git a/utils/zenutils/source/shared/firmware.h b/utils/zenutils/source/shared/firmware.h
index 3542186590..3cd233c3b6 100755..100644
--- a/utils/zenutils/source/shared/firmware.h
+++ b/utils/zenutils/source/shared/firmware.h
@@ -1,92 +1,92 @@
1/* zenutils - Utilities for working with creative firmwares. 1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com> 2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 * 3 *
4 * This program is free software; you can redistribute it and/or modify 4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by 5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or 6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. 7 * (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software 15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */ 17 */
18 18
19#ifndef ZEN_FIRMWARE_H_INCLUDED 19#ifndef ZEN_FIRMWARE_H_INCLUDED
20#define ZEN_FIRMWARE_H_INCLUDED 20#define ZEN_FIRMWARE_H_INCLUDED
21 21
22#include <list> 22#include <list>
23#include <utils.h> 23#include <utils.h>
24 24
25namespace zen { 25namespace zen {
26 struct firmware_header_t 26 struct firmware_header_t
27 { 27 {
28 dword tag; 28 dword tag;
29 dword size; 29 dword size;
30 }; //struct firmware_header_t 30 }; //struct firmware_header_t
31 31
32 class firmware_entry 32 class firmware_entry
33 { 33 {
34 public: 34 public:
35 firmware_entry(bool big_endian); 35 firmware_entry(bool big_endian);
36 firmware_entry(const firmware_entry& copy); 36 firmware_entry(const firmware_entry& copy);
37 firmware_entry& operator=(const firmware_entry& right); 37 firmware_entry& operator=(const firmware_entry& right);
38 38
39 bool read(std::istream& is); 39 bool read(std::istream& is);
40 bool write(std::ostream& os) const; 40 bool write(std::ostream& os) const;
41 41
42 bool is_big_endian() const; 42 bool is_big_endian() const;
43 const firmware_header_t& get_header() const; 43 const firmware_header_t& get_header() const;
44 firmware_header_t& get_header(); 44 firmware_header_t& get_header();
45 const shared::bytes& get_bytes() const; 45 const shared::bytes& get_bytes() const;
46 shared::bytes& get_bytes(); 46 shared::bytes& get_bytes();
47 47
48 std::string get_name() const; 48 std::string get_name() const;
49 std::string get_content_name() const; 49 std::string get_content_name() const;
50 size_t get_content_offset() const; 50 size_t get_content_offset() const;
51 size_t calc_size() const; 51 size_t calc_size() const;
52 52
53 protected: 53 protected:
54 void assign(const firmware_entry& copy); 54 void assign(const firmware_entry& copy);
55 55
56 private: 56 private:
57 bool _big_endian; 57 bool _big_endian;
58 firmware_header_t _header; 58 firmware_header_t _header;
59 shared::bytes _bytes; 59 shared::bytes _bytes;
60 }; //class firmware_entry 60 }; //class firmware_entry
61 61
62 typedef std::list<firmware_entry> firmware_entries; 62 typedef std::list<firmware_entry> firmware_entries;
63 63
64 class firmware_archive 64 class firmware_archive
65 { 65 {
66 public: 66 public:
67 firmware_archive(bool big_endian); 67 firmware_archive(bool big_endian);
68 firmware_archive(const firmware_archive& copy); 68 firmware_archive(const firmware_archive& copy);
69 firmware_archive& operator=(const firmware_archive& right); 69 firmware_archive& operator=(const firmware_archive& right);
70 70
71 bool read(std::istream& is); 71 bool read(std::istream& is);
72 bool write(std::ostream& os) const; 72 bool write(std::ostream& os) const;
73 73
74 bool is_big_endian() const; 74 bool is_big_endian() const;
75 const firmware_entries& get_children() const; 75 const firmware_entries& get_children() const;
76 firmware_entries& get_children(); 76 firmware_entries& get_children();
77 const firmware_entries& get_neighbours() const; 77 const firmware_entries& get_neighbours() const;
78 firmware_entries& get_neighbours(); 78 firmware_entries& get_neighbours();
79 bool is_signed() const; 79 bool is_signed() const;
80 size_t calc_size() const; 80 size_t calc_size() const;
81 81
82 protected: 82 protected:
83 void assign(const firmware_archive& copy); 83 void assign(const firmware_archive& copy);
84 84
85 private: 85 private:
86 firmware_entries _children; 86 firmware_entries _children;
87 firmware_entries _neighbours; 87 firmware_entries _neighbours;
88 bool _big_endian; 88 bool _big_endian;
89 }; //class firmware_archive 89 }; //class firmware_archive
90}; //namespace zen 90}; //namespace zen
91 91
92#endif //ZEN_FIRMWARE_ARCHIVE_H_INCLUDED 92#endif //ZEN_FIRMWARE_ARCHIVE_H_INCLUDED
diff --git a/utils/zenutils/source/shared/pe.cpp b/utils/zenutils/source/shared/pe.cpp
index c86ec6c8cc..10070074dd 100755..100644
--- a/utils/zenutils/source/shared/pe.cpp
+++ b/utils/zenutils/source/shared/pe.cpp
@@ -1,128 +1,128 @@
1/* zenutils - Utilities for working with creative firmwares. 1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com> 2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 * 3 *
4 * This program is free software; you can redistribute it and/or modify 4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by 5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or 6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. 7 * (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software 15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */ 17 */
18 18
19#include "pe.h" 19#include "pe.h"
20 20
21 21
22shared::pe_file::pe_file(PeLib::PeFile* pef) : _pef(pef) 22shared::pe_file::pe_file(PeLib::PeFile* pef) : _pef(pef)
23{ 23{
24} 24}
25shared::pe_file::~pe_file() 25shared::pe_file::~pe_file()
26{ 26{
27 if (_pef != NULL) 27 if (_pef != NULL)
28 delete _pef; 28 delete _pef;
29} 29}
30 30
31bool shared::pe_file::is_valid() const 31bool shared::pe_file::is_valid() const
32{ 32{
33 if (_pef->getBits() == 32) 33 if (_pef->getBits() == 32)
34 { 34 {
35 PeLib::PeHeader32& pef32 = static_cast<PeLib::PeFile32*>(_pef)->peHeader(); 35 PeLib::PeHeader32& pef32 = static_cast<PeLib::PeFile32*>(_pef)->peHeader();
36 if (!pef32.isValid()) 36 if (!pef32.isValid())
37 return false; 37 return false;
38 return true; 38 return true;
39 } 39 }
40 else if (_pef->getBits() == 64) 40 else if (_pef->getBits() == 64)
41 { 41 {
42 PeLib::PeHeader64& pef64 = static_cast<PeLib::PeFile64*>(_pef)->peHeader(); 42 PeLib::PeHeader64& pef64 = static_cast<PeLib::PeFile64*>(_pef)->peHeader();
43 if (!pef64.isValid()) 43 if (!pef64.isValid())
44 return false; 44 return false;
45 return true; 45 return true;
46 } 46 }
47 return false; 47 return false;
48} 48}
49 49
50bool shared::pe_file::read(const std::string& filename) 50bool shared::pe_file::read(const std::string& filename)
51{ 51{
52 if (_pef != NULL) 52 if (_pef != NULL)
53 { 53 {
54 delete _pef; 54 delete _pef;
55 _pef = NULL; 55 _pef = NULL;
56 } 56 }
57 57
58 _pef = PeLib::openPeFile(filename); 58 _pef = PeLib::openPeFile(filename);
59 if (!_pef) 59 if (!_pef)
60 { 60 {
61 return false; 61 return false;
62 } 62 }
63 if (_pef->readMzHeader()) 63 if (_pef->readMzHeader())
64 { 64 {
65 delete _pef; 65 delete _pef;
66 return false; 66 return false;
67 } 67 }
68 if (!_pef->mzHeader().isValid()) 68 if (!_pef->mzHeader().isValid())
69 { 69 {
70 delete _pef; 70 delete _pef;
71 return false; 71 return false;
72 } 72 }
73 if (_pef->readPeHeader()) 73 if (_pef->readPeHeader())
74 { 74 {
75 delete _pef; 75 delete _pef;
76 return false; 76 return false;
77 } 77 }
78 if (!is_valid()) 78 if (!is_valid())
79 { 79 {
80 delete _pef; 80 delete _pef;
81 return false; 81 return false;
82 } 82 }
83 return true; 83 return true;
84} 84}
85 85
86bool shared::pe_file::find_section(const std::string& name, section_info& info) const 86bool shared::pe_file::find_section(const std::string& name, section_info& info) const
87{ 87{
88 if (_pef->getBits() == 32) 88 if (_pef->getBits() == 32)
89 return find_section(static_cast<PeLib::PeFile32*>(_pef), 89 return find_section(static_cast<PeLib::PeFile32*>(_pef),
90 name, info); 90 name, info);
91 else if (_pef->getBits() == 64) 91 else if (_pef->getBits() == 64)
92 return find_section(static_cast<PeLib::PeFile64*>(_pef), 92 return find_section(static_cast<PeLib::PeFile64*>(_pef),
93 name, info); 93 name, info);
94 return false; 94 return false;
95} 95}
96 96
97bool shared::pe_file::add_section(const std::string& name, 97bool shared::pe_file::add_section(const std::string& name,
98 const bytes& buffer, section_info& info) 98 const bytes& buffer, section_info& info)
99{ 99{
100 if (_pef->getBits() == 32) 100 if (_pef->getBits() == 32)
101 { 101 {
102 return add_section(static_cast<PeLib::PeFile32*>(_pef), 102 return add_section(static_cast<PeLib::PeFile32*>(_pef),
103 name, buffer, info); 103 name, buffer, info);
104 } 104 }
105 else if (_pef->getBits() == 64) 105 else if (_pef->getBits() == 64)
106 { 106 {
107 return add_section(static_cast<PeLib::PeFile64*>(_pef), 107 return add_section(static_cast<PeLib::PeFile64*>(_pef),
108 name, buffer, info); 108 name, buffer, info);
109 } 109 }
110 return false; 110 return false;
111} 111}
112 112
113dword shared::pe_file::get_image_base() const 113dword shared::pe_file::get_image_base() const
114{ 114{
115 if (_pef->getBits() == 32) 115 if (_pef->getBits() == 32)
116 return static_cast<PeLib::PeFile32*>(_pef)->peHeader().getImageBase(); 116 return static_cast<PeLib::PeFile32*>(_pef)->peHeader().getImageBase();
117 else 117 else
118 return static_cast<PeLib::PeFile64*>(_pef)->peHeader().getImageBase(); 118 return static_cast<PeLib::PeFile64*>(_pef)->peHeader().getImageBase();
119 return 0; 119 return 0;
120} 120}
121dword shared::pe_file::pa_to_va(dword pa) const 121dword shared::pe_file::pa_to_va(dword pa) const
122{ 122{
123 if (_pef->getBits() == 32) 123 if (_pef->getBits() == 32)
124 return static_cast<PeLib::PeFile32*>(_pef)->peHeader().offsetToVa(pa); 124 return static_cast<PeLib::PeFile32*>(_pef)->peHeader().offsetToVa(pa);
125 else 125 else
126 return static_cast<PeLib::PeFile64*>(_pef)->peHeader().offsetToVa(pa); 126 return static_cast<PeLib::PeFile64*>(_pef)->peHeader().offsetToVa(pa);
127 return 0; 127 return 0;
128} 128}
diff --git a/utils/zenutils/source/shared/pe.h b/utils/zenutils/source/shared/pe.h
index 92a272d3c7..f2f3aa48e8 100755..100644
--- a/utils/zenutils/source/shared/pe.h
+++ b/utils/zenutils/source/shared/pe.h
@@ -1,142 +1,142 @@
1/* zenutils - Utilities for working with creative firmwares. 1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com> 2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 * 3 *
4 * This program is free software; you can redistribute it and/or modify 4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by 5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or 6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. 7 * (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software 15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */ 17 */
18 18
19#ifndef SHARED_PE_H_INCLUDED 19#ifndef SHARED_PE_H_INCLUDED
20#define SHARED_PE_H_INCLUDED 20#define SHARED_PE_H_INCLUDED
21 21
22#include <string> 22#include <string>
23#include <pelib/PeLib.h> 23#include <pelib/PeLib.h>
24#include <utils.h> 24#include <utils.h>
25 25
26namespace shared { 26namespace shared {
27 struct section_info 27 struct section_info
28 { 28 {
29 word index; 29 word index;
30 dword virtual_address; 30 dword virtual_address;
31 dword virtual_size; 31 dword virtual_size;
32 dword raw_address; 32 dword raw_address;
33 dword raw_size; 33 dword raw_size;
34 dword characteristics; 34 dword characteristics;
35 }; //struct section_info 35 }; //struct section_info
36 36
37 class pe_file 37 class pe_file
38 { 38 {
39 public: 39 public:
40 pe_file(PeLib::PeFile* pef = NULL); 40 pe_file(PeLib::PeFile* pef = NULL);
41 ~pe_file(); 41 ~pe_file();
42 42
43 bool is_valid() const; 43 bool is_valid() const;
44 bool read(const std::string& filename); 44 bool read(const std::string& filename);
45 bool find_section(const std::string& name, section_info& info) const; 45 bool find_section(const std::string& name, section_info& info) const;
46 bool add_section(const std::string& name, const bytes& buffer, section_info& info); 46 bool add_section(const std::string& name, const bytes& buffer, section_info& info);
47 dword get_image_base() const; 47 dword get_image_base() const;
48 dword pa_to_va(PeLib::dword pa) const; 48 dword pa_to_va(PeLib::dword pa) const;
49 49
50 protected: 50 protected:
51 template <int _Bits> 51 template <int _Bits>
52 static bool find_section(const PeLib::PeFileT<_Bits>* pef, 52 static bool find_section(const PeLib::PeFileT<_Bits>* pef,
53 const std::string& name, section_info& info); 53 const std::string& name, section_info& info);
54 template <int _Bits> 54 template <int _Bits>
55 static bool add_section(PeLib::PeFileT<_Bits>* pef, 55 static bool add_section(PeLib::PeFileT<_Bits>* pef,
56 const std::string& name, const bytes& buffer, 56 const std::string& name, const bytes& buffer,
57 section_info& info); 57 section_info& info);
58 58
59 private: 59 private:
60 PeLib::PeFile* _pef; 60 PeLib::PeFile* _pef;
61 }; //class pe_file 61 }; //class pe_file
62 62
63 63
64 template <int _Bits> 64 template <int _Bits>
65 bool pe_file::find_section(const PeLib::PeFileT<_Bits>* pef, 65 bool pe_file::find_section(const PeLib::PeFileT<_Bits>* pef,
66 const std::string& name, section_info& info) 66 const std::string& name, section_info& info)
67 { 67 {
68 for (PeLib::word i = 0; i < pef->peHeader().getNumberOfSections(); i++) 68 for (PeLib::word i = 0; i < pef->peHeader().getNumberOfSections(); i++)
69 { 69 {
70 if (pef->peHeader().getSectionName(i) == name) 70 if (pef->peHeader().getSectionName(i) == name)
71 { 71 {
72 info.index = i; 72 info.index = i;
73 info.virtual_address = pef->peHeader().getVirtualAddress(i); 73 info.virtual_address = pef->peHeader().getVirtualAddress(i);
74 info.virtual_size = pef->peHeader().getVirtualSize(i); 74 info.virtual_size = pef->peHeader().getVirtualSize(i);
75 info.raw_address = pef->peHeader().getPointerToRawData(i); 75 info.raw_address = pef->peHeader().getPointerToRawData(i);
76 info.raw_size = pef->peHeader().getSizeOfRawData(i); 76 info.raw_size = pef->peHeader().getSizeOfRawData(i);
77 info.characteristics = pef->peHeader().getCharacteristics(i); 77 info.characteristics = pef->peHeader().getCharacteristics(i);
78 return true; 78 return true;
79 } 79 }
80 } 80 }
81 return false; 81 return false;
82 } 82 }
83 83
84 template <int _Bits> 84 template <int _Bits>
85 bool pe_file::add_section(PeLib::PeFileT<_Bits>* pef, 85 bool pe_file::add_section(PeLib::PeFileT<_Bits>* pef,
86 const std::string& name, const bytes& buffer, 86 const std::string& name, const bytes& buffer,
87 section_info& info) 87 section_info& info)
88 { 88 {
89 using namespace PeLib; 89 using namespace PeLib;
90 90
91 // Check if the last section has the same name as the one being added. 91 // Check if the last section has the same name as the one being added.
92 PeLib::word secnum = pef->peHeader().getNumberOfSections(); 92 PeLib::word secnum = pef->peHeader().getNumberOfSections();
93 if (pef->peHeader().getSectionName(secnum-1) == name) 93 if (pef->peHeader().getSectionName(secnum-1) == name)
94 { 94 {
95 // If it is, we change the attributes of the existing section. 95 // If it is, we change the attributes of the existing section.
96 secnum = secnum - 1; 96 secnum = secnum - 1;
97 pef->peHeader().setSizeOfRawData(secnum, 97 pef->peHeader().setSizeOfRawData(secnum,
98 alignOffset(buffer.size(), 98 alignOffset(buffer.size(),
99 pef->peHeader().getFileAlignment())); 99 pef->peHeader().getFileAlignment()));
100 pef->peHeader().setVirtualSize(secnum, 100 pef->peHeader().setVirtualSize(secnum,
101 alignOffset(buffer.size(), 101 alignOffset(buffer.size(),
102 pef->peHeader().getSectionAlignment())); 102 pef->peHeader().getSectionAlignment()));
103 PeLib::dword chars = pef->peHeader().getCharacteristics(secnum-1); 103 PeLib::dword chars = pef->peHeader().getCharacteristics(secnum-1);
104 pef->peHeader().setCharacteristics(secnum, 104 pef->peHeader().setCharacteristics(secnum,
105 chars | PELIB_IMAGE_SCN_MEM_WRITE | PELIB_IMAGE_SCN_MEM_READ); 105 chars | PELIB_IMAGE_SCN_MEM_WRITE | PELIB_IMAGE_SCN_MEM_READ);
106 } 106 }
107 else 107 else
108 { 108 {
109 // Otherwise we add a new section. 109 // Otherwise we add a new section.
110 if (pef->peHeader().addSection(name, buffer.size()) != NO_ERROR) 110 if (pef->peHeader().addSection(name, buffer.size()) != NO_ERROR)
111 { 111 {
112 return false; 112 return false;
113 } 113 }
114 pef->peHeader().makeValid(pef->mzHeader().getAddressOfPeHeader()); 114 pef->peHeader().makeValid(pef->mzHeader().getAddressOfPeHeader());
115 pef->peHeader().write(pef->getFileName(), pef->mzHeader().getAddressOfPeHeader()); 115 pef->peHeader().write(pef->getFileName(), pef->mzHeader().getAddressOfPeHeader());
116 } 116 }
117 117
118 // Save the section headers to the file. 118 // Save the section headers to the file.
119 if (pef->peHeader().writeSections(pef->getFileName()) != NO_ERROR) 119 if (pef->peHeader().writeSections(pef->getFileName()) != NO_ERROR)
120 { 120 {
121 return false; 121 return false;
122 } 122 }
123 123
124 // Save the section data to the file. 124 // Save the section data to the file.
125 if (pef->peHeader().writeSectionData(pef->getFileName(), secnum, buffer) != NO_ERROR) 125 if (pef->peHeader().writeSectionData(pef->getFileName(), secnum, buffer) != NO_ERROR)
126 { 126 {
127 return false; 127 return false;
128 } 128 }
129 129
130 // Fill out the section information. 130 // Fill out the section information.
131 info.index = secnum; 131 info.index = secnum;
132 info.virtual_address = pef->peHeader().getVirtualAddress(secnum); 132 info.virtual_address = pef->peHeader().getVirtualAddress(secnum);
133 info.virtual_size = pef->peHeader().getVirtualSize(secnum); 133 info.virtual_size = pef->peHeader().getVirtualSize(secnum);
134 info.raw_address = pef->peHeader().getPointerToRawData(secnum); 134 info.raw_address = pef->peHeader().getPointerToRawData(secnum);
135 info.raw_size = pef->peHeader().getSizeOfRawData(secnum); 135 info.raw_size = pef->peHeader().getSizeOfRawData(secnum);
136 info.characteristics = pef->peHeader().getCharacteristics(secnum); 136 info.characteristics = pef->peHeader().getCharacteristics(secnum);
137 137
138 return true; 138 return true;
139 } 139 }
140}; //namespace shared 140}; //namespace shared
141 141
142#endif //SHARED_PE_H_INCLUDED 142#endif //SHARED_PE_H_INCLUDED
diff --git a/utils/zenutils/source/shared/shared.cpp b/utils/zenutils/source/shared/shared.cpp
index e69de29bb2..e69de29bb2 100755..100644
--- a/utils/zenutils/source/shared/shared.cpp
+++ b/utils/zenutils/source/shared/shared.cpp
diff --git a/utils/zenutils/source/shared/updater.cpp b/utils/zenutils/source/shared/updater.cpp
index 77d3f2876c..25d8452992 100755..100644
--- a/utils/zenutils/source/shared/updater.cpp
+++ b/utils/zenutils/source/shared/updater.cpp
@@ -1,151 +1,151 @@
1/* zenutils - Utilities for working with creative firmwares. 1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com> 2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 * 3 *
4 * This program is free software; you can redistribute it and/or modify 4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by 5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or 6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. 7 * (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software 15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */ 17 */
18 18
19#include "updater.h" 19#include "updater.h"
20#include <file.h> 20#include <file.h>
21#include <pe.h> 21#include <pe.h>
22#include <utils.h> 22#include <utils.h>
23 23
24 24
25const char* zen::find_firmware_key(const byte* buffer, size_t len) 25const char* zen::find_firmware_key(const byte* buffer, size_t len)
26{ 26{
27 char szkey1[] = "34d1"; 27 char szkey1[] = "34d1";
28 size_t cchkey1 = strlen(szkey1); 28 size_t cchkey1 = strlen(szkey1);
29 char szkey2[] = "TbnCboEbn"; 29 char szkey2[] = "TbnCboEbn";
30 size_t cchkey2 = strlen(szkey2); 30 size_t cchkey2 = strlen(szkey2);
31 for (int i = 0; i < static_cast<int>(len); i++) 31 for (int i = 0; i < static_cast<int>(len); i++)
32 { 32 {
33 if (len >= cchkey1) 33 if (len >= cchkey1)
34 { 34 {
35 if (!strncmp((char*)&buffer[i], szkey1, cchkey1)) 35 if (!strncmp((char*)&buffer[i], szkey1, cchkey1))
36 { 36 {
37 return (const char*)&buffer[i]; 37 return (const char*)&buffer[i];
38 } 38 }
39 } 39 }
40 if (len >= cchkey2) 40 if (len >= cchkey2)
41 { 41 {
42 if (!strncmp((char*)&buffer[i], szkey2, cchkey2)) 42 if (!strncmp((char*)&buffer[i], szkey2, cchkey2))
43 { 43 {
44 return (const char*)&buffer[i]; 44 return (const char*)&buffer[i];
45 } 45 }
46 } 46 }
47 } 47 }
48 return NULL; 48 return NULL;
49} 49}
50 50
51dword zen::find_firmware_offset(byte* buffer, size_t len) 51dword zen::find_firmware_offset(byte* buffer, size_t len)
52{ 52{
53 for (dword i = 0; i < static_cast<dword>(len); i += 0x10) 53 for (dword i = 0; i < static_cast<dword>(len); i += 0x10)
54 { 54 {
55 dword size = *(dword*)&buffer[i]; 55 dword size = *(dword*)&buffer[i];
56 if (size < (i + len) && size > (len >> 1)) 56 if (size < (i + len) && size > (len >> 1))
57 { 57 {
58 if (buffer[i + sizeof(dword)] != 0 58 if (buffer[i + sizeof(dword)] != 0
59 && buffer[i + sizeof(dword) + 1] != 0 59 && buffer[i + sizeof(dword) + 1] != 0
60 && buffer[i + sizeof(dword) + 2] != 0 60 && buffer[i + sizeof(dword) + 2] != 0
61 && buffer[i + sizeof(dword) + 3] != 0) 61 && buffer[i + sizeof(dword) + 3] != 0)
62 { 62 {
63 return i; 63 return i;
64 } 64 }
65 } 65 }
66 } 66 }
67 return 0; 67 return 0;
68} 68}
69 69
70bool zen::find_firmware_archive(const std::string& filename, dword& va, dword& pa) 70bool zen::find_firmware_archive(const std::string& filename, dword& va, dword& pa)
71{ 71{
72 shared::pe_file pef; 72 shared::pe_file pef;
73 if (!pef.read(filename)) 73 if (!pef.read(filename))
74 { 74 {
75 return false; 75 return false;
76 } 76 }
77 shared::section_info data_section; 77 shared::section_info data_section;
78 if (!pef.find_section(".data", data_section)) 78 if (!pef.find_section(".data", data_section))
79 { 79 {
80 return false; 80 return false;
81 } 81 }
82 shared::bytes buffer; 82 shared::bytes buffer;
83 if (!shared::read_file(filename, buffer, data_section.raw_address, 83 if (!shared::read_file(filename, buffer, data_section.raw_address,
84 data_section.raw_size)) 84 data_section.raw_size))
85 { 85 {
86 return false; 86 return false;
87 } 87 }
88 dword offset = find_firmware_offset(&buffer[0], buffer.size()); 88 dword offset = find_firmware_offset(&buffer[0], buffer.size());
89 if (!offset) 89 if (!offset)
90 { 90 {
91 return false; 91 return false;
92 } 92 }
93 va = data_section.virtual_address + offset; 93 va = data_section.virtual_address + offset;
94 pa = data_section.raw_address + offset; 94 pa = data_section.raw_address + offset;
95 95
96 return true; 96 return true;
97} 97}
98 98
99 99
100bool zen::crypt_firmware(const char* key, byte* buffer, size_t len) 100bool zen::crypt_firmware(const char* key, byte* buffer, size_t len)
101{ 101{
102 // Determine if the key length is dword aligned. 102 // Determine if the key length is dword aligned.
103 int keylen = strlen(key); 103 int keylen = strlen(key);
104 int keylen_rem = keylen % sizeof(dword); 104 int keylen_rem = keylen % sizeof(dword);
105 105
106 // Determine how many times the key must be repeated to be dword aligned. 106 // Determine how many times the key must be repeated to be dword aligned.
107 int keycycle = keylen_rem ? (sizeof(dword) / keylen_rem) : 1; 107 int keycycle = keylen_rem ? (sizeof(dword) / keylen_rem) : 1;
108 int keyscount = (keylen * keycycle) / sizeof(dword); 108 int keyscount = (keylen * keycycle) / sizeof(dword);
109 109
110 // Allocate a buffer to hold the key as an array of dwords. 110 // Allocate a buffer to hold the key as an array of dwords.
111 dword* keys = new dword[keyscount]; 111 dword* keys = new dword[keyscount];
112 112
113 // Copy the key into the key array, whilst mutating it. 113 // Copy the key into the key array, whilst mutating it.
114 for (int i = 0; i < keyscount; i++) 114 for (int i = 0; i < keyscount; i++)
115 { 115 {
116 dword val; 116 dword val;
117 int keyoffset = (i * sizeof(dword)) % keylen; 117 int keyoffset = (i * sizeof(dword)) % keylen;
118 if ((keyoffset+sizeof(dword)) < keylen) 118 if ((keyoffset+sizeof(dword)) < keylen)
119 { 119 {
120 val = *(dword*)&key[keyoffset]; 120 val = *(dword*)&key[keyoffset];
121 } 121 }
122 else 122 else
123 { 123 {
124 val = key[keyoffset] 124 val = key[keyoffset]
125 | (key[(keyoffset + 1) % keylen] << 8) 125 | (key[(keyoffset + 1) % keylen] << 8)
126 | (key[(keyoffset + 2) % keylen] << 16) 126 | (key[(keyoffset + 2) % keylen] << 16)
127 | (key[(keyoffset + 3) % keylen] << 24); 127 | (key[(keyoffset + 3) % keylen] << 24);
128 } 128 }
129 keys[i] = (val - 0x01010101) | 0x80808080; 129 keys[i] = (val - 0x01010101) | 0x80808080;
130 } 130 }
131 131
132 // Determine the number of dwords in the buffer. 132 // Determine the number of dwords in the buffer.
133 int len_div = len / sizeof(dword); 133 int len_div = len / sizeof(dword);
134 134
135 // Decrypt all dwords of the buffer. 135 // Decrypt all dwords of the buffer.
136 for (int i = 0; i < len_div; i++) 136 for (int i = 0; i < len_div; i++)
137 { 137 {
138 ((dword*)buffer)[i] ^= keys[i % keyscount]; 138 ((dword*)buffer)[i] ^= keys[i % keyscount];
139 } 139 }
140 140
141 // Determine the remaining number of bytes in the buffer. 141 // Determine the remaining number of bytes in the buffer.
142 int len_rem = len % sizeof(dword); 142 int len_rem = len % sizeof(dword);
143 143
144 // Decrypt the remaining number of bytes in the buffer. 144 // Decrypt the remaining number of bytes in the buffer.
145 for (int i = len_div * sizeof(dword); i < len; i++) 145 for (int i = len_div * sizeof(dword); i < len; i++)
146 { 146 {
147 buffer[i] ^= ((key[i % keylen] - 0x01) | 0x80); 147 buffer[i] ^= ((key[i % keylen] - 0x01) | 0x80);
148 } 148 }
149 149
150 return true; 150 return true;
151} 151}
diff --git a/utils/zenutils/source/shared/updater.h b/utils/zenutils/source/shared/updater.h
index 57f9979c30..884fe9568c 100755..100644
--- a/utils/zenutils/source/shared/updater.h
+++ b/utils/zenutils/source/shared/updater.h
@@ -1,32 +1,32 @@
1/* zenutils - Utilities for working with creative firmwares. 1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com> 2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 * 3 *
4 * This program is free software; you can redistribute it and/or modify 4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by 5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or 6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. 7 * (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software 15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */ 17 */
18 18
19#ifndef ZEN_UPDATER_H_INCLUDED 19#ifndef ZEN_UPDATER_H_INCLUDED
20#define ZEN_UPDATER_H_INCLUDED 20#define ZEN_UPDATER_H_INCLUDED
21 21
22#include <pelib/PeLib.h> 22#include <pelib/PeLib.h>
23#include <utils.h> 23#include <utils.h>
24 24
25namespace zen { 25namespace zen {
26 const char* find_firmware_key(const byte* buffer, size_t len); 26 const char* find_firmware_key(const byte* buffer, size_t len);
27 dword find_firmware_offset(byte* buffer, size_t len); 27 dword find_firmware_offset(byte* buffer, size_t len);
28 bool find_firmware_archive(const std::string& filename, dword& va, dword& pa); 28 bool find_firmware_archive(const std::string& filename, dword& va, dword& pa);
29 bool crypt_firmware(const char* key, byte* buffer, size_t len); 29 bool crypt_firmware(const char* key, byte* buffer, size_t len);
30}; //namespace zen 30}; //namespace zen
31 31
32#endif //ZEN_UPDATER_H_INCLUDED 32#endif //ZEN_UPDATER_H_INCLUDED
diff --git a/utils/zenutils/source/shared/utils.cpp b/utils/zenutils/source/shared/utils.cpp
index 8f45de5d3f..fbb223b42b 100755..100644
--- a/utils/zenutils/source/shared/utils.cpp
+++ b/utils/zenutils/source/shared/utils.cpp
@@ -1,211 +1,211 @@
1/* zenutils - Utilities for working with creative firmwares. 1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com> 2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 * 3 *
4 * This program is free software; you can redistribute it and/or modify 4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by 5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or 6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. 7 * (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software 15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */ 17 */
18 18
19#include "utils.h" 19#include "utils.h"
20#include <fstream> 20#include <fstream>
21#include <zlib/zlib.h> 21#include <zlib/zlib.h>
22 22
23 23
24std::string shared::replace_extension(const std::string& filename, const std::string& extension) 24std::string shared::replace_extension(const std::string& filename, const std::string& extension)
25{ 25{
26 std::string newname; 26 std::string newname;
27 const char* name = filename.c_str(); 27 const char* name = filename.c_str();
28 const char* ext = strrchr(name, '.'); 28 const char* ext = strrchr(name, '.');
29 if (ext) 29 if (ext)
30 { 30 {
31 // If an extension was found, replace it. 31 // If an extension was found, replace it.
32 newname.assign(name, ext-name); 32 newname.assign(name, ext-name);
33 newname += extension; 33 newname += extension;
34 } 34 }
35 else 35 else
36 { 36 {
37 // If an extension was not found, append it. 37 // If an extension was not found, append it.
38 newname = name; 38 newname = name;
39 newname += extension; 39 newname += extension;
40 } 40 }
41 return newname; 41 return newname;
42} 42}
43 43
44std::string shared::remove_extension(const std::string& filename) 44std::string shared::remove_extension(const std::string& filename)
45{ 45{
46 std::string newname; 46 std::string newname;
47 const char* name = filename.c_str(); 47 const char* name = filename.c_str();
48 const char* ext = strrchr(name, '.'); 48 const char* ext = strrchr(name, '.');
49 if (ext) 49 if (ext)
50 { 50 {
51 newname.assign(name, ext-name); 51 newname.assign(name, ext-name);
52 } 52 }
53 else 53 else
54 { 54 {
55 newname = name; 55 newname = name;
56 } 56 }
57 return newname; 57 return newname;
58} 58}
59 59
60std::string shared::double_quote(const std::string& str) 60std::string shared::double_quote(const std::string& str)
61{ 61{
62 std::string out; 62 std::string out;
63 for (int i = 0, j = str.length(); i < j; i++) 63 for (int i = 0, j = str.length(); i < j; i++)
64 { 64 {
65 if (str[i] == '\\') 65 if (str[i] == '\\')
66 out += "\\\\"; 66 out += "\\\\";
67 else 67 else
68 out += str[i]; 68 out += str[i];
69 } 69 }
70 return out; 70 return out;
71} 71}
72 72
73bool shared::inflate_to_file(const bytes& buffer, const char* filename) 73bool shared::inflate_to_file(const bytes& buffer, const char* filename)
74{ 74{
75 // Open output file. 75 // Open output file.
76 std::ofstream ofs; 76 std::ofstream ofs;
77 ofs.open(filename, std::ios::binary); 77 ofs.open(filename, std::ios::binary);
78 if (!ofs) 78 if (!ofs)
79 { 79 {
80 return false; 80 return false;
81 } 81 }
82 82
83 // Initialize zlib. 83 // Initialize zlib.
84 z_stream d_stream; // decompression stream 84 z_stream d_stream; // decompression stream
85 85
86 d_stream.zalloc = Z_NULL; 86 d_stream.zalloc = Z_NULL;
87 d_stream.zfree = Z_NULL; 87 d_stream.zfree = Z_NULL;
88 d_stream.opaque = Z_NULL; 88 d_stream.opaque = Z_NULL;
89 89
90 d_stream.next_in = const_cast<bytes::value_type*>(&buffer[0]); 90 d_stream.next_in = const_cast<bytes::value_type*>(&buffer[0]);
91 d_stream.avail_in = static_cast<uInt>(buffer.size()); 91 d_stream.avail_in = static_cast<uInt>(buffer.size());
92 92
93 int ret = inflateInit(&d_stream); 93 int ret = inflateInit(&d_stream);
94 if (ret != Z_OK) 94 if (ret != Z_OK)
95 return false; 95 return false;
96 96
97 // Allocate buffer to hold the inflated data. 97 // Allocate buffer to hold the inflated data.
98 const size_t BUFSIZE = 1048576; 98 const size_t BUFSIZE = 1048576;
99 Bytef* infbuf = new Bytef[BUFSIZE]; 99 Bytef* infbuf = new Bytef[BUFSIZE];
100 if (!infbuf) 100 if (!infbuf)
101 return false; 101 return false;
102 102
103 // Decompress untill the end of the input buffer. 103 // Decompress untill the end of the input buffer.
104 uLong totalout = 0; 104 uLong totalout = 0;
105 bool bLoop = true; 105 bool bLoop = true;
106 while (bLoop) 106 while (bLoop)
107 { 107 {
108 d_stream.next_out = infbuf; 108 d_stream.next_out = infbuf;
109 d_stream.avail_out = BUFSIZE; 109 d_stream.avail_out = BUFSIZE;
110 110
111 ret = inflate(&d_stream, Z_NO_FLUSH); 111 ret = inflate(&d_stream, Z_NO_FLUSH);
112 if (ret == Z_STREAM_END) 112 if (ret == Z_STREAM_END)
113 { 113 {
114 bLoop = false; 114 bLoop = false;
115 } 115 }
116 else if (ret != Z_OK) 116 else if (ret != Z_OK)
117 { 117 {
118 inflateEnd(&d_stream); 118 inflateEnd(&d_stream);
119 delete [] infbuf; 119 delete [] infbuf;
120 return false; 120 return false;
121 } 121 }
122 122
123 // Write the inflated data to the output file. 123 // Write the inflated data to the output file.
124 if (!ofs.write((const char*)infbuf, d_stream.total_out-totalout)) 124 if (!ofs.write((const char*)infbuf, d_stream.total_out-totalout))
125 { 125 {
126 inflateEnd(&d_stream); 126 inflateEnd(&d_stream);
127 delete [] infbuf; 127 delete [] infbuf;
128 return false; 128 return false;
129 } 129 }
130 totalout = d_stream.total_out; 130 totalout = d_stream.total_out;
131 } 131 }
132 132
133 // Cleanup and return. 133 // Cleanup and return.
134 inflateEnd(&d_stream); 134 inflateEnd(&d_stream);
135 delete [] infbuf; 135 delete [] infbuf;
136 136
137 return true; 137 return true;
138} 138}
139 139
140bool shared::deflate_to_file(const bytes& buffer, const char* filename) 140bool shared::deflate_to_file(const bytes& buffer, const char* filename)
141{ 141{
142 // Open output file. 142 // Open output file.
143 std::ofstream ofs; 143 std::ofstream ofs;
144 ofs.open(filename, std::ios::binary); 144 ofs.open(filename, std::ios::binary);
145 if (!ofs) 145 if (!ofs)
146 { 146 {
147 return false; 147 return false;
148 } 148 }
149 149
150 // Initialize zlib. 150 // Initialize zlib.
151 z_stream c_stream; // compression stream. 151 z_stream c_stream; // compression stream.
152 152
153 c_stream.zalloc = Z_NULL; 153 c_stream.zalloc = Z_NULL;
154 c_stream.zfree = Z_NULL; 154 c_stream.zfree = Z_NULL;
155 c_stream.opaque = Z_NULL; 155 c_stream.opaque = Z_NULL;
156 156
157 int ret = deflateInit(&c_stream, Z_BEST_COMPRESSION); 157 int ret = deflateInit(&c_stream, Z_BEST_COMPRESSION);
158 if (ret != Z_OK) 158 if (ret != Z_OK)
159 return false; 159 return false;
160 160
161 // Allocate buffer to hold the deflated data. 161 // Allocate buffer to hold the deflated data.
162 const size_t BUFSIZE = 1048576; 162 const size_t BUFSIZE = 1048576;
163 Bytef* defbuf = new Bytef[BUFSIZE]; 163 Bytef* defbuf = new Bytef[BUFSIZE];
164 if (!defbuf) 164 if (!defbuf)
165 return false; 165 return false;
166 166
167 c_stream.avail_in = static_cast<uInt>(buffer.size()); 167 c_stream.avail_in = static_cast<uInt>(buffer.size());
168 c_stream.next_in = const_cast<bytes::value_type*>(&buffer[0]); 168 c_stream.next_in = const_cast<bytes::value_type*>(&buffer[0]);
169 169
170 // Compress until end of the buffer. 170 // Compress until end of the buffer.
171 uLong totalout = 0; 171 uLong totalout = 0;
172 bool bLoop = true; 172 bool bLoop = true;
173 while (bLoop) 173 while (bLoop)
174 { 174 {
175 c_stream.avail_out = BUFSIZE; 175 c_stream.avail_out = BUFSIZE;
176 c_stream.next_out = defbuf; 176 c_stream.next_out = defbuf;
177 177
178 ret = deflate(&c_stream, Z_NO_FLUSH); // no bad return value 178 ret = deflate(&c_stream, Z_NO_FLUSH); // no bad return value
179 if (ret == Z_STREAM_END) 179 if (ret == Z_STREAM_END)
180 { 180 {
181 bLoop = false; 181 bLoop = false;
182 } 182 }
183 else if (ret == Z_BUF_ERROR && !c_stream.avail_in) 183 else if (ret == Z_BUF_ERROR && !c_stream.avail_in)
184 { 184 {
185 ret = deflate(&c_stream, Z_FINISH); // no bad return value 185 ret = deflate(&c_stream, Z_FINISH); // no bad return value
186 bLoop = false; 186 bLoop = false;
187 } 187 }
188 else if (ret != Z_OK) 188 else if (ret != Z_OK)
189 { 189 {
190 deflateEnd(&c_stream); 190 deflateEnd(&c_stream);
191 delete [] defbuf; 191 delete [] defbuf;
192 return false; 192 return false;
193 } 193 }
194 194
195 // Write the inflated data to the output file. 195 // Write the inflated data to the output file.
196 if (!ofs.write((const char*)defbuf, c_stream.total_out-totalout)) 196 if (!ofs.write((const char*)defbuf, c_stream.total_out-totalout))
197 { 197 {
198 deflateEnd(&c_stream); 198 deflateEnd(&c_stream);
199 delete [] defbuf; 199 delete [] defbuf;
200 return false; 200 return false;
201 } 201 }
202 202
203 totalout = c_stream.total_out; 203 totalout = c_stream.total_out;
204 } 204 }
205 205
206 // Clean up and return. 206 // Clean up and return.
207 deflateEnd(&c_stream); 207 deflateEnd(&c_stream);
208 delete [] defbuf; 208 delete [] defbuf;
209 209
210 return true; 210 return true;
211} 211}
diff --git a/utils/zenutils/source/shared/utils.h b/utils/zenutils/source/shared/utils.h
index ca9e291514..694cb9c8b1 100755..100644
--- a/utils/zenutils/source/shared/utils.h
+++ b/utils/zenutils/source/shared/utils.h
@@ -1,68 +1,68 @@
1/* zenutils - Utilities for working with creative firmwares. 1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com> 2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 * 3 *
4 * This program is free software; you can redistribute it and/or modify 4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by 5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or 6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. 7 * (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software 15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */ 17 */
18 18
19#ifndef SHARED_UTILS_H_INCLUDED 19#ifndef SHARED_UTILS_H_INCLUDED
20#define SHARED_UTILS_H_INCLUDED 20#define SHARED_UTILS_H_INCLUDED
21 21
22#include <vector> 22#include <vector>
23#include <pelib/PeLib.h> 23#include <pelib/PeLib.h>
24 24
25#ifndef byte 25#ifndef byte
26typedef PeLib::byte byte; 26typedef PeLib::byte byte;
27#endif 27#endif
28#ifndef word 28#ifndef word
29typedef PeLib::word word; 29typedef PeLib::word word;
30#endif 30#endif
31#ifndef dword 31#ifndef dword
32typedef PeLib::dword dword; 32typedef PeLib::dword dword;
33#endif 33#endif
34 34
35namespace shared { 35namespace shared {
36 typedef std::vector<byte> bytes; 36 typedef std::vector<byte> bytes;
37 37
38 inline dword swap(dword val) 38 inline dword swap(dword val)
39 { 39 {
40 return ((val & 0xFF) << 24) 40 return ((val & 0xFF) << 24)
41 | ((val & 0xFF00) << 8) 41 | ((val & 0xFF00) << 8)
42 | ((val & 0xFF0000) >> 8) 42 | ((val & 0xFF0000) >> 8)
43 | ((val & 0xFF000000) >> 24); 43 | ((val & 0xFF000000) >> 24);
44 } 44 }
45 45
46 template <typename _Type> 46 template <typename _Type>
47 inline void reverse(_Type* start, _Type* end) 47 inline void reverse(_Type* start, _Type* end)
48 { 48 {
49 while (start < end) 49 while (start < end)
50 { 50 {
51 *start ^= *end; 51 *start ^= *end;
52 *end ^= *start; 52 *end ^= *start;
53 *start ^= *end; 53 *start ^= *end;
54 start++; 54 start++;
55 end--; 55 end--;
56 } 56 }
57 } 57 }
58 58
59 std::string replace_extension(const std::string& filename, const std::string& extension); 59 std::string replace_extension(const std::string& filename, const std::string& extension);
60 std::string remove_extension(const std::string& filename); 60 std::string remove_extension(const std::string& filename);
61 std::string get_path(const std::string& filename); 61 std::string get_path(const std::string& filename);
62 std::string double_quote(const std::string& str); 62 std::string double_quote(const std::string& str);
63 63
64 bool inflate_to_file(const bytes& buffer, const char* filename); 64 bool inflate_to_file(const bytes& buffer, const char* filename);
65 bool deflate_to_file(const bytes& buffer, const char* filename); 65 bool deflate_to_file(const bytes& buffer, const char* filename);
66}; //namespace shared 66}; //namespace shared
67 67
68#endif //SHARED_UTILS_H_INCLUDED 68#endif //SHARED_UTILS_H_INCLUDED
diff --git a/utils/zenutils/source/update_extract/CMakeLists.txt b/utils/zenutils/source/update_extract/CMakeLists.txt
index 813e389bed..60d298be11 100755..100644
--- a/utils/zenutils/source/update_extract/CMakeLists.txt
+++ b/utils/zenutils/source/update_extract/CMakeLists.txt
@@ -1,3 +1,3 @@
1ADD_EXECUTABLE(update_extract main.cpp) 1ADD_EXECUTABLE(update_extract main.cpp)
2 2
3TARGET_LINK_LIBRARIES (update_extract shared) 3TARGET_LINK_LIBRARIES (update_extract shared)
diff --git a/utils/zenutils/source/update_extract/main.cpp b/utils/zenutils/source/update_extract/main.cpp
index 0fae29e00c..4891329397 100755..100644
--- a/utils/zenutils/source/update_extract/main.cpp
+++ b/utils/zenutils/source/update_extract/main.cpp
@@ -1,279 +1,279 @@
1/* zenutils - Utilities for working with creative firmwares. 1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com> 2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 * 3 *
4 * This program is free software; you can redistribute it and/or modify 4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by 5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or 6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. 7 * (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software 15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */ 17 */
18 18
19#include <iostream> 19#include <iostream>
20#include <iomanip> 20#include <iomanip>
21#include <ctime> 21#include <ctime>
22#include <getpot/getpot.hpp> 22#include <getpot/getpot.hpp>
23#include <file.h> 23#include <file.h>
24#include <updater.h> 24#include <updater.h>
25#include <utils.h> 25#include <utils.h>
26 26
27 27
28static const char VERSION[] = "0.1"; 28static const char VERSION[] = "0.1";
29 29
30void print_version() 30void print_version()
31{ 31{
32 std::cout 32 std::cout
33 << "update_extract - Extracts a Creative firmware from an updater" 33 << "update_extract - Extracts a Creative firmware from an updater"
34 " executable." << std::endl 34 " executable." << std::endl
35 << "Version " << VERSION << std::endl 35 << "Version " << VERSION << std::endl
36 << "Copyright (c) 2007 Rasmus Ry" << std::endl; 36 << "Copyright (c) 2007 Rasmus Ry" << std::endl;
37} 37}
38 38
39void print_help() 39void print_help()
40{ 40{
41 print_version(); 41 print_version();
42 std::cout << std::endl 42 std::cout << std::endl
43 << "Usage: update_extract [command] [options]" << std::endl 43 << "Usage: update_extract [command] [options]" << std::endl
44 << std::endl 44 << std::endl
45 << " Commands:" << std::endl 45 << " Commands:" << std::endl
46 << " -h,--help" << std::endl 46 << " -h,--help" << std::endl
47 << " prints this message." << std::endl 47 << " prints this message." << std::endl
48 << " -u,--updater [file]" << std::endl 48 << " -u,--updater [file]" << std::endl
49 << " specifies the updater executable." << std::endl 49 << " specifies the updater executable." << std::endl
50 << std::endl 50 << std::endl
51 << " Options:" << std::endl 51 << " Options:" << std::endl
52 << " -V,--verbose" << std::endl 52 << " -V,--verbose" << std::endl
53 << " prints verbose messages." << std::endl 53 << " prints verbose messages." << std::endl
54 << " -f,--firmware [file]" << std::endl 54 << " -f,--firmware [file]" << std::endl
55 << " specifies the firmware arhive file name." << std::endl 55 << " specifies the firmware arhive file name." << std::endl
56 << " -k,--key [key]" << std::endl 56 << " -k,--key [key]" << std::endl
57 << " specifies the firmware archive key." << std::endl 57 << " specifies the firmware archive key." << std::endl
58 << " -o,--offset [offset]" << std::endl 58 << " -o,--offset [offset]" << std::endl
59 << " specifies the firmware archive offset in c-style" 59 << " specifies the firmware archive offset in c-style"
60 " hexadecimal." << std::endl 60 " hexadecimal." << std::endl
61 << std::endl 61 << std::endl
62 ; 62 ;
63} 63}
64 64
65std::string options_name(const std::string& name) 65std::string options_name(const std::string& name)
66{ 66{
67 return shared::replace_extension(name, ".opt"); 67 return shared::replace_extension(name, ".opt");
68} 68}
69 69
70std::string default_firmware_name(const std::string& name) 70std::string default_firmware_name(const std::string& name)
71{ 71{
72 return shared::replace_extension(name, "_rk.bin"); 72 return shared::replace_extension(name, "_rk.bin");
73} 73}
74 74
75int process_arguments(int argc, char* argv[]) 75int process_arguments(int argc, char* argv[])
76{ 76{
77 //-------------------------------------------------------------------- 77 //--------------------------------------------------------------------
78 // Parse input variables. 78 // Parse input variables.
79 //-------------------------------------------------------------------- 79 //--------------------------------------------------------------------
80 80
81 GetPot cl(argc, argv); 81 GetPot cl(argc, argv);
82 if (cl.size() == 1 || cl.search(2, "-h", "--help")) 82 if (cl.size() == 1 || cl.search(2, "-h", "--help"))
83 { 83 {
84 print_help(); 84 print_help();
85 return 1; 85 return 1;
86 } 86 }
87 87
88 std::string updatername; 88 std::string updatername;
89 if (cl.search("-u") || cl.search("--updater")) 89 if (cl.search("-u") || cl.search("--updater"))
90 updatername = cl.next(""); 90 updatername = cl.next("");
91 if (updatername.empty()) 91 if (updatername.empty())
92 { 92 {
93 std::cerr << "Updater executable must be specified." << std::endl; 93 std::cerr << "Updater executable must be specified." << std::endl;
94 return 2; 94 return 2;
95 } 95 }
96 96
97 std::string firmarename = default_firmware_name(updatername); 97 std::string firmarename = default_firmware_name(updatername);
98 if (cl.search("-f") || cl.search("--firmware")) 98 if (cl.search("-f") || cl.search("--firmware"))
99 firmarename = cl.next(firmarename.c_str()); 99 firmarename = cl.next(firmarename.c_str());
100 100
101 bool verbose = false; 101 bool verbose = false;
102 if (cl.search("-V") || cl.search("--verbose")) 102 if (cl.search("-V") || cl.search("--verbose"))
103 verbose = true; 103 verbose = true;
104 104
105 // Get or find the firmware archive key. 105 // Get or find the firmware archive key.
106 std::string key; 106 std::string key;
107 if (cl.search("-k") || cl.search("--key")) 107 if (cl.search("-k") || cl.search("--key"))
108 key = cl.next(""); 108 key = cl.next("");
109 109
110 if (key.empty()) 110 if (key.empty())
111 { 111 {
112 if (verbose) 112 if (verbose)
113 std::cout << "[*] Looking for firmware archive key..." 113 std::cout << "[*] Looking for firmware archive key..."
114 << std::endl; 114 << std::endl;
115 shared::bytes buffer; 115 shared::bytes buffer;
116 if (!shared::read_file(updatername, buffer)) 116 if (!shared::read_file(updatername, buffer))
117 { 117 {
118 std::cerr << "Failed to read the firmware updater executable." 118 std::cerr << "Failed to read the firmware updater executable."
119 << std::endl; 119 << std::endl;
120 return 3; 120 return 3;
121 } 121 }
122 key = zen::find_firmware_key(&buffer[0], buffer.size()); 122 key = zen::find_firmware_key(&buffer[0], buffer.size());
123 if (key.empty()) 123 if (key.empty())
124 { 124 {
125 std::cerr << "Failed to find the firmware archive key." 125 std::cerr << "Failed to find the firmware archive key."
126 << std::endl; 126 << std::endl;
127 return 4; 127 return 4;
128 } 128 }
129 } 129 }
130 130
131 // Get or find the firmware archive offset. 131 // Get or find the firmware archive offset.
132 std::string offset; 132 std::string offset;
133 dword offset_pa = 0; 133 dword offset_pa = 0;
134 if (cl.search("-o") || cl.search("--ofset")) 134 if (cl.search("-o") || cl.search("--ofset"))
135 offset = cl.next(""); 135 offset = cl.next("");
136 136
137 if (offset.empty()) 137 if (offset.empty())
138 { 138 {
139 if (verbose) 139 if (verbose)
140 std::cout << "[*] Looking for firmware archive offset..." 140 std::cout << "[*] Looking for firmware archive offset..."
141 << std::endl; 141 << std::endl;
142 142
143 dword offset_va = 0; 143 dword offset_va = 0;
144 if (!zen::find_firmware_archive(updatername, offset_va, offset_pa)) 144 if (!zen::find_firmware_archive(updatername, offset_va, offset_pa))
145 { 145 {
146 std::cerr << "Failed to find the firmware archive offset." 146 std::cerr << "Failed to find the firmware archive offset."
147 << std::endl; 147 << std::endl;
148 return 5; 148 return 5;
149 } 149 }
150 } 150 }
151 else 151 else
152 { 152 {
153 int offset_val; 153 int offset_val;
154 if (!sscanf(offset.c_str(), "0x%x", &offset_val)) 154 if (!sscanf(offset.c_str(), "0x%x", &offset_val))
155 { 155 {
156 if (!sscanf(offset.c_str(), "0x%X", &offset_val)) 156 if (!sscanf(offset.c_str(), "0x%X", &offset_val))
157 { 157 {
158 std::cerr << "\'" << offset 158 std::cerr << "\'" << offset
159 << "\' is not a valid c-style hexadecimal value." 159 << "\' is not a valid c-style hexadecimal value."
160 << std::endl; 160 << std::endl;
161 return 6; 161 return 6;
162 } 162 }
163 } 163 }
164 offset_pa = static_cast<dword>(offset_val); 164 offset_pa = static_cast<dword>(offset_val);
165 } 165 }
166 166
167 // Read firmware archive size. 167 // Read firmware archive size.
168 shared::bytes buffer; 168 shared::bytes buffer;
169 if (!shared::read_file(updatername, buffer, offset_pa, sizeof(dword))) 169 if (!shared::read_file(updatername, buffer, offset_pa, sizeof(dword)))
170 { 170 {
171 std::cerr << "Failed to read the firmware archive size." << std::endl; 171 std::cerr << "Failed to read the firmware archive size." << std::endl;
172 return 7; 172 return 7;
173 } 173 }
174 dword archive_size = *(dword*)&buffer[0]; 174 dword archive_size = *(dword*)&buffer[0];
175 175
176 if (verbose) 176 if (verbose)
177 { 177 {
178 std::cout << "[*] Printing input variables..." << std::endl; 178 std::cout << "[*] Printing input variables..." << std::endl;
179 std::cout << " Updater executable: " << updatername << std::endl; 179 std::cout << " Updater executable: " << updatername << std::endl;
180 std::cout << " Firmware archive: " << firmarename << std::endl; 180 std::cout << " Firmware archive: " << firmarename << std::endl;
181 std::cout << " Key: " << key << std::endl; 181 std::cout << " Key: " << key << std::endl;
182 std::cout << " Offset: " 182 std::cout << " Offset: "
183 << std::hex << std::showbase << std::setw(10) 183 << std::hex << std::showbase << std::setw(10)
184 << std::setfill('0') << std::internal 184 << std::setfill('0') << std::internal
185 << offset_pa << std::endl; 185 << offset_pa << std::endl;
186 std::cout << " Size: " 186 std::cout << " Size: "
187 << std::hex << std::showbase << std::setw(10) 187 << std::hex << std::showbase << std::setw(10)
188 << std::setfill('0') << std::internal 188 << std::setfill('0') << std::internal
189 << archive_size << std::endl; 189 << archive_size << std::endl;
190 } 190 }
191 191
192 192
193 //-------------------------------------------------------------------- 193 //--------------------------------------------------------------------
194 // Extract the firmware archive from the updater. 194 // Extract the firmware archive from the updater.
195 //-------------------------------------------------------------------- 195 //--------------------------------------------------------------------
196 196
197 if (verbose) 197 if (verbose)
198 std::cout << "[*] Reading firmware archive..." << std::endl; 198 std::cout << "[*] Reading firmware archive..." << std::endl;
199 199
200 // Read the firmware archive. 200 // Read the firmware archive.
201 offset_pa += sizeof(dword); 201 offset_pa += sizeof(dword);
202 if (!shared::read_file(updatername, buffer, offset_pa, archive_size)) 202 if (!shared::read_file(updatername, buffer, offset_pa, archive_size))
203 { 203 {
204 std::cerr << "Failed to read the firmware archive." << std::endl; 204 std::cerr << "Failed to read the firmware archive." << std::endl;
205 return 8; 205 return 8;
206 } 206 }
207 207
208 if (verbose) 208 if (verbose)
209 std::cout << "[*] Decrypting firmware archive..." << std::endl; 209 std::cout << "[*] Decrypting firmware archive..." << std::endl;
210 210
211 // Decrypt the firmware archive. 211 // Decrypt the firmware archive.
212 if (!zen::crypt_firmware(key.c_str(), &buffer[0], buffer.size())) 212 if (!zen::crypt_firmware(key.c_str(), &buffer[0], buffer.size()))
213 { 213 {
214 std::cerr << "Failed to decrypt the firmware archive." << std::endl; 214 std::cerr << "Failed to decrypt the firmware archive." << std::endl;
215 return 9; 215 return 9;
216 } 216 }
217 217
218 if (verbose) 218 if (verbose)
219 std::cout << "[*] Decompressing firmware archive..." << std::endl; 219 std::cout << "[*] Decompressing firmware archive..." << std::endl;
220 220
221 // Inflate the firmware archive to the output file. 221 // Inflate the firmware archive to the output file.
222 if (!shared::inflate_to_file(buffer, firmarename.c_str())) 222 if (!shared::inflate_to_file(buffer, firmarename.c_str()))
223 { 223 {
224 std::cerr << "Failed to decompress the firmware archive." << std::endl; 224 std::cerr << "Failed to decompress the firmware archive." << std::endl;
225 return 10; 225 return 10;
226 } 226 }
227 227
228 228
229 //-------------------------------------------------------------------- 229 //--------------------------------------------------------------------
230 // Generate an options file for the extracted firmware archive. 230 // Generate an options file for the extracted firmware archive.
231 //-------------------------------------------------------------------- 231 //--------------------------------------------------------------------
232 232
233 // Get options filename for the given input file. 233 // Get options filename for the given input file.
234 std::string optionsname = options_name(updatername); 234 std::string optionsname = options_name(updatername);
235 235
236 if (verbose) 236 if (verbose)
237 std::cout << "[*] Producing options file..." << std::endl; 237 std::cout << "[*] Producing options file..." << std::endl;
238 238
239 // Produce options file for the given input file. 239 // Produce options file for the given input file.
240 std::ofstream ofs; 240 std::ofstream ofs;
241 ofs.open(optionsname.c_str(), std::ios::binary); 241 ofs.open(optionsname.c_str(), std::ios::binary);
242 if (!ofs) 242 if (!ofs)
243 { 243 {
244 std::cerr << "Failed to create firmware archive options file." 244 std::cerr << "Failed to create firmware archive options file."
245 << std::endl; 245 << std::endl;
246 return 11; 246 return 11;
247 } 247 }
248 248
249 time_t timeval = time(NULL); 249 time_t timeval = time(NULL);
250 ofs << "# Options file generated at: " << ctime(&timeval) 250 ofs << "# Options file generated at: " << ctime(&timeval)
251 << "updater = \'" << shared::double_quote(updatername) << "\'" 251 << "updater = \'" << shared::double_quote(updatername) << "\'"
252 << std::endl 252 << std::endl
253 << "firmware = \'" << shared::double_quote(firmarename) << "\'" 253 << "firmware = \'" << shared::double_quote(firmarename) << "\'"
254 << std::endl 254 << std::endl
255 << "offset = " << (offset_pa - sizeof(dword)) << std::endl 255 << "offset = " << (offset_pa - sizeof(dword)) << std::endl
256 << "size = " << archive_size << std::endl 256 << "size = " << archive_size << std::endl
257 << "key = \'" << key << "\'" << std::endl; 257 << "key = \'" << key << "\'" << std::endl;
258 258
259 return 0; 259 return 0;
260} 260}
261 261
262int main(int argc, char* argv[]) 262int main(int argc, char* argv[])
263{ 263{
264 try 264 try
265 { 265 {
266 return process_arguments(argc, argv); 266 return process_arguments(argc, argv);
267 } 267 }
268 catch (const std::exception& xcpt) 268 catch (const std::exception& xcpt)
269 { 269 {
270 std::cerr << "Exception caught: " << xcpt.what() << std::endl; 270 std::cerr << "Exception caught: " << xcpt.what() << std::endl;
271 return -1; 271 return -1;
272 } 272 }
273 catch (...) 273 catch (...)
274 { 274 {
275 std::cerr << "Unknown exception caught." << std::endl; 275 std::cerr << "Unknown exception caught." << std::endl;
276 return -2; 276 return -2;
277 } 277 }
278 return -3; 278 return -3;
279} 279}
diff --git a/utils/zenutils/source/update_patch/CMakeLists.txt b/utils/zenutils/source/update_patch/CMakeLists.txt
index 11474b7ff8..7b509dc40d 100755..100644
--- a/utils/zenutils/source/update_patch/CMakeLists.txt
+++ b/utils/zenutils/source/update_patch/CMakeLists.txt
@@ -1,3 +1,3 @@
1ADD_EXECUTABLE(update_patch main.cpp) 1ADD_EXECUTABLE(update_patch main.cpp)
2 2
3TARGET_LINK_LIBRARIES (update_patch shared) 3TARGET_LINK_LIBRARIES (update_patch shared)
diff --git a/utils/zenutils/source/update_patch/main.cpp b/utils/zenutils/source/update_patch/main.cpp
index d48797b46d..5467694728 100755..100644
--- a/utils/zenutils/source/update_patch/main.cpp
+++ b/utils/zenutils/source/update_patch/main.cpp
@@ -1,409 +1,409 @@
1/* zenutils - Utilities for working with creative firmwares. 1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com> 2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 * 3 *
4 * This program is free software; you can redistribute it and/or modify 4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by 5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or 6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. 7 * (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software 15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */ 17 */
18 18
19#include <iostream> 19#include <iostream>
20#include <iomanip> 20#include <iomanip>
21#include <cstdio> 21#include <cstdio>
22#include <getpot/getpot.hpp> 22#include <getpot/getpot.hpp>
23#include <file.h> 23#include <file.h>
24#include <updater.h> 24#include <updater.h>
25#include <utils.h> 25#include <utils.h>
26#include <pe.h> 26#include <pe.h>
27 27
28 28
29static const char VERSION[] = "0.1"; 29static const char VERSION[] = "0.1";
30 30
31void print_version() 31void print_version()
32{ 32{
33 std::cout 33 std::cout
34 << "update_patch - Patches a Creative firmware into an updater" 34 << "update_patch - Patches a Creative firmware into an updater"
35 " executable." << std::endl 35 " executable." << std::endl
36 << "Version " << VERSION << std::endl 36 << "Version " << VERSION << std::endl
37 << "Copyright (c) 2007 Rasmus Ry" << std::endl; 37 << "Copyright (c) 2007 Rasmus Ry" << std::endl;
38} 38}
39 39
40void print_help() 40void print_help()
41{ 41{
42 print_version(); 42 print_version();
43 std::cout << std::endl 43 std::cout << std::endl
44 << "Usage: update_patch [command] [options]" << std::endl 44 << "Usage: update_patch [command] [options]" << std::endl
45 << std::endl 45 << std::endl
46 << " Commands:" << std::endl 46 << " Commands:" << std::endl
47 << " -h,--help" << std::endl 47 << " -h,--help" << std::endl
48 << " prints this message." << std::endl 48 << " prints this message." << std::endl
49 << " -u,--updater [file]" << std::endl 49 << " -u,--updater [file]" << std::endl
50 << " specifies the updater executable." << std::endl 50 << " specifies the updater executable." << std::endl
51 << std::endl 51 << std::endl
52 << " Options:" << std::endl 52 << " Options:" << std::endl
53 << " -V,--verbose" << std::endl 53 << " -V,--verbose" << std::endl
54 << " prints verbose messages." << std::endl 54 << " prints verbose messages." << std::endl
55 << " -f,--firmware [file]" << std::endl 55 << " -f,--firmware [file]" << std::endl
56 << " specifies the firmware arhive file name." << std::endl 56 << " specifies the firmware arhive file name." << std::endl
57 << " -k,--key [key]" << std::endl 57 << " -k,--key [key]" << std::endl
58 << " specifies the firmware archive key." << std::endl 58 << " specifies the firmware archive key." << std::endl
59 << " -o,--offset [offset]" << std::endl 59 << " -o,--offset [offset]" << std::endl
60 << " specifies the firmware archive offset in c-style" 60 << " specifies the firmware archive offset in c-style"
61 " hexadecimal." << std::endl 61 " hexadecimal." << std::endl
62 << std::endl 62 << std::endl
63 ; 63 ;
64} 64}
65 65
66std::string options_name(const std::string& name) 66std::string options_name(const std::string& name)
67{ 67{
68 return shared::replace_extension(name, ".opt"); 68 return shared::replace_extension(name, ".opt");
69} 69}
70 70
71std::string default_firmware_name(const std::string& name) 71std::string default_firmware_name(const std::string& name)
72{ 72{
73 return shared::replace_extension(name, "_rk.bin"); 73 return shared::replace_extension(name, "_rk.bin");
74} 74}
75 75
76int process_arguments(int argc, char* argv[]) 76int process_arguments(int argc, char* argv[])
77{ 77{
78 //-------------------------------------------------------------------- 78 //--------------------------------------------------------------------
79 // Parse input variables. 79 // Parse input variables.
80 //-------------------------------------------------------------------- 80 //--------------------------------------------------------------------
81 81
82 GetPot cl(argc, argv); 82 GetPot cl(argc, argv);
83 if (cl.size() == 1 || cl.search(2, "-h", "--help")) 83 if (cl.size() == 1 || cl.search(2, "-h", "--help"))
84 { 84 {
85 print_help(); 85 print_help();
86 return 1; 86 return 1;
87 } 87 }
88 88
89 std::string updatername; 89 std::string updatername;
90 if (cl.search("-u") || cl.search("--updater")) 90 if (cl.search("-u") || cl.search("--updater"))
91 updatername = cl.next(""); 91 updatername = cl.next("");
92 if (updatername.empty()) 92 if (updatername.empty())
93 { 93 {
94 std::cerr << "Updater executable must be specified." << std::endl; 94 std::cerr << "Updater executable must be specified." << std::endl;
95 return 2; 95 return 2;
96 } 96 }
97 97
98 bool verbose = false; 98 bool verbose = false;
99 if (cl.search("-V") || cl.search("--verbose")) 99 if (cl.search("-V") || cl.search("--verbose"))
100 verbose = true; 100 verbose = true;
101 101
102 if (verbose) 102 if (verbose)
103 std::cout << "[*] Parsing options file..." << std::endl; 103 std::cout << "[*] Parsing options file..." << std::endl;
104 104
105 GetPot optfile(options_name(updatername.c_str()).c_str()); 105 GetPot optfile(options_name(updatername.c_str()).c_str());
106 if (verbose) 106 if (verbose)
107 optfile.print(); 107 optfile.print();
108 108
109 std::string firmwarename = optfile("firmware", 109 std::string firmwarename = optfile("firmware",
110 default_firmware_name(updatername).c_str()); 110 default_firmware_name(updatername).c_str());
111 dword offset_pa = optfile("offset", 0); 111 dword offset_pa = optfile("offset", 0);
112 dword size = optfile("size", 0); 112 dword size = optfile("size", 0);
113 std::string key = optfile("key", ""); 113 std::string key = optfile("key", "");
114 114
115 if (cl.search("-f") || cl.search("--firmware")) 115 if (cl.search("-f") || cl.search("--firmware"))
116 firmwarename = cl.next(firmwarename.c_str()); 116 firmwarename = cl.next(firmwarename.c_str());
117 117
118 std::string offset; 118 std::string offset;
119 if (cl.search("-o") || cl.search("--offset")) 119 if (cl.search("-o") || cl.search("--offset"))
120 offset = cl.next(""); 120 offset = cl.next("");
121 121
122 if (offset.empty() && !offset_pa) 122 if (offset.empty() && !offset_pa)
123 { 123 {
124 if (verbose) 124 if (verbose)
125 std::cout << "[*] Looking for firmware archive offset..." 125 std::cout << "[*] Looking for firmware archive offset..."
126 << std::endl; 126 << std::endl;
127 127
128 dword offset_va = 0; 128 dword offset_va = 0;
129 if (!zen::find_firmware_archive(updatername, offset_va, offset_pa)) 129 if (!zen::find_firmware_archive(updatername, offset_va, offset_pa))
130 { 130 {
131 std::cerr << "Failed to find the firmware archive offset." 131 std::cerr << "Failed to find the firmware archive offset."
132 << std::endl; 132 << std::endl;
133 return 3; 133 return 3;
134 } 134 }
135 } 135 }
136 else if (!offset_pa) 136 else if (!offset_pa)
137 { 137 {
138 int offset_val; 138 int offset_val;
139 if (!sscanf(offset.c_str(), "0x%x", &offset_val)) 139 if (!sscanf(offset.c_str(), "0x%x", &offset_val))
140 { 140 {
141 if (!sscanf(offset.c_str(), "0x%X", &offset_val)) 141 if (!sscanf(offset.c_str(), "0x%X", &offset_val))
142 { 142 {
143 std::cerr << "\'" << offset 143 std::cerr << "\'" << offset
144 << "\' is not a valid c-style hexadecimal value." 144 << "\' is not a valid c-style hexadecimal value."
145 << std::endl; 145 << std::endl;
146 return 4; 146 return 4;
147 } 147 }
148 } 148 }
149 offset_pa = static_cast<dword>(offset_val); 149 offset_pa = static_cast<dword>(offset_val);
150 } 150 }
151 151
152 if (key.empty()) 152 if (key.empty())
153 { 153 {
154 if (verbose) 154 if (verbose)
155 std::cout << "[*] Looking for firmware archive key..." 155 std::cout << "[*] Looking for firmware archive key..."
156 << std::endl; 156 << std::endl;
157 shared::bytes buffer; 157 shared::bytes buffer;
158 if (!shared::read_file(updatername, buffer)) 158 if (!shared::read_file(updatername, buffer))
159 { 159 {
160 std::cerr << "Failed to read the firmware updater executable." 160 std::cerr << "Failed to read the firmware updater executable."
161 << std::endl; 161 << std::endl;
162 return 5; 162 return 5;
163 } 163 }
164 key = zen::find_firmware_key(&buffer[0], buffer.size()); 164 key = zen::find_firmware_key(&buffer[0], buffer.size());
165 if (key.empty()) 165 if (key.empty())
166 { 166 {
167 std::cerr << "Failed to find the firmware archive key." 167 std::cerr << "Failed to find the firmware archive key."
168 << std::endl; 168 << std::endl;
169 return 6; 169 return 6;
170 } 170 }
171 } 171 }
172 172
173 if (verbose) 173 if (verbose)
174 { 174 {
175 std::cout << "[*] Printing input variables..." << std::endl; 175 std::cout << "[*] Printing input variables..." << std::endl;
176 std::cout << " Updater executable: " << updatername << std::endl; 176 std::cout << " Updater executable: " << updatername << std::endl;
177 std::cout << " Firmware archive: " << firmwarename << std::endl; 177 std::cout << " Firmware archive: " << firmwarename << std::endl;
178 std::cout << " Key: " << key << std::endl; 178 std::cout << " Key: " << key << std::endl;
179 std::cout << " Offset: " 179 std::cout << " Offset: "
180 << std::hex << std::showbase << std::setw(10) 180 << std::hex << std::showbase << std::setw(10)
181 << std::setfill('0') << std::internal 181 << std::setfill('0') << std::internal
182 << offset_pa << std::endl; 182 << offset_pa << std::endl;
183 std::cout << " Size: " 183 std::cout << " Size: "
184 << std::hex << std::showbase << std::setw(10) 184 << std::hex << std::showbase << std::setw(10)
185 << std::setfill('0') << std::internal 185 << std::setfill('0') << std::internal
186 << size << std::endl; 186 << size << std::endl;
187 } 187 }
188 188
189 189
190 //-------------------------------------------------------------------- 190 //--------------------------------------------------------------------
191 // Prepare the firmware archive for being patched into the updater. 191 // Prepare the firmware archive for being patched into the updater.
192 //-------------------------------------------------------------------- 192 //--------------------------------------------------------------------
193 193
194 if (verbose) 194 if (verbose)
195 std::cout << "[*] Reading firmware archive..." << std::endl; 195 std::cout << "[*] Reading firmware archive..." << std::endl;
196 196
197 shared::bytes buffer; 197 shared::bytes buffer;
198 if (!shared::read_file(firmwarename, buffer)) 198 if (!shared::read_file(firmwarename, buffer))
199 { 199 {
200 std::cerr << "Failed to read the firmware archive." << std::endl; 200 std::cerr << "Failed to read the firmware archive." << std::endl;
201 return 7; 201 return 7;
202 } 202 }
203 203
204 if (verbose) 204 if (verbose)
205 std::cout << " Bytes read: " 205 std::cout << " Bytes read: "
206 << std::hex << std::showbase << std::setw(10) 206 << std::hex << std::showbase << std::setw(10)
207 << std::setfill('0') << std::internal 207 << std::setfill('0') << std::internal
208 << buffer.size() << std::endl; 208 << buffer.size() << std::endl;
209 209
210 if (verbose) 210 if (verbose)
211 std::cout << "[*] Compressing firmware archive..." << std::endl; 211 std::cout << "[*] Compressing firmware archive..." << std::endl;
212 212
213 std::string compfirmware = shared::replace_extension(firmwarename, ".def"); 213 std::string compfirmware = shared::replace_extension(firmwarename, ".def");
214 if (!shared::deflate_to_file(buffer, compfirmware.c_str())) 214 if (!shared::deflate_to_file(buffer, compfirmware.c_str()))
215 { 215 {
216 std::cerr << "Failed to compress the firmware archive." << std::endl; 216 std::cerr << "Failed to compress the firmware archive." << std::endl;
217 return 8; 217 return 8;
218 } 218 }
219 219
220 if (verbose) 220 if (verbose)
221 std::cout << "[*] Reading compressed firmware archive..." << std::endl; 221 std::cout << "[*] Reading compressed firmware archive..." << std::endl;
222 222
223 if (!shared::read_file(compfirmware, buffer)) 223 if (!shared::read_file(compfirmware, buffer))
224 { 224 {
225 std::cerr << "Failed to read the compressed firmware archive." 225 std::cerr << "Failed to read the compressed firmware archive."
226 << std::endl; 226 << std::endl;
227 return 9; 227 return 9;
228 } 228 }
229 229
230 if (verbose) 230 if (verbose)
231 std::cout << " Bytes read: " 231 std::cout << " Bytes read: "
232 << std::hex << std::showbase << std::setw(10) 232 << std::hex << std::showbase << std::setw(10)
233 << std::setfill('0') << std::internal 233 << std::setfill('0') << std::internal
234 << buffer.size() << std::endl; 234 << buffer.size() << std::endl;
235 235
236 // Delete the temporary firmware file. 236 // Delete the temporary firmware file.
237 std::remove(compfirmware.c_str()); 237 std::remove(compfirmware.c_str());
238 238
239 if (verbose) 239 if (verbose)
240 std::cout << "[*] Encrypting compressed firmware archive..." 240 std::cout << "[*] Encrypting compressed firmware archive..."
241 << std::endl; 241 << std::endl;
242 242
243 if (!zen::crypt_firmware(key.c_str(), &buffer[0], buffer.size())) 243 if (!zen::crypt_firmware(key.c_str(), &buffer[0], buffer.size()))
244 { 244 {
245 std::cerr << "Failed to encrypt the compressed firmware archive." 245 std::cerr << "Failed to encrypt the compressed firmware archive."
246 << std::endl; 246 << std::endl;
247 return 10; 247 return 10;
248 } 248 }
249 249
250 250
251 //-------------------------------------------------------------------- 251 //--------------------------------------------------------------------
252 // Backup the updater and patch the firmware archive into it. 252 // Backup the updater and patch the firmware archive into it.
253 //-------------------------------------------------------------------- 253 //--------------------------------------------------------------------
254 254
255 if (verbose) 255 if (verbose)
256 std::cout << "[*] Backing up the updater executable..." << std::endl; 256 std::cout << "[*] Backing up the updater executable..." << std::endl;
257 257
258 if (!shared::backup_file(updatername)) 258 if (!shared::backup_file(updatername))
259 { 259 {
260 std::cerr << "Failed to backup the updater executable." << std::endl; 260 std::cerr << "Failed to backup the updater executable." << std::endl;
261 return 11; 261 return 11;
262 } 262 }
263 263
264 // Is there enough space within the existing firmware archive 264 // Is there enough space within the existing firmware archive
265 // to hold the new one? 265 // to hold the new one?
266 if (size < buffer.size()) 266 if (size < buffer.size())
267 { 267 {
268 // No, we need to add a new section to hold the new firmware archive. 268 // No, we need to add a new section to hold the new firmware archive.
269 if (verbose) 269 if (verbose)
270 std::cout << "[*] Adding new section to the updater executable..." 270 std::cout << "[*] Adding new section to the updater executable..."
271 << std::endl; 271 << std::endl;
272 272
273 // Construct a new buffer with the archive size prepended. 273 // Construct a new buffer with the archive size prepended.
274 shared::bytes newbuffer(buffer.size() + sizeof(dword)); 274 shared::bytes newbuffer(buffer.size() + sizeof(dword));
275 *(dword*)&newbuffer[0] = static_cast<dword>(buffer.size()); 275 *(dword*)&newbuffer[0] = static_cast<dword>(buffer.size());
276 std::copy(buffer.begin(), buffer.end(), &newbuffer[4]); 276 std::copy(buffer.begin(), buffer.end(), &newbuffer[4]);
277 277
278 // Read the updater portable executable. 278 // Read the updater portable executable.
279 shared::pe_file pef; 279 shared::pe_file pef;
280 if (!pef.read(updatername)) 280 if (!pef.read(updatername))
281 { 281 {
282 std::cerr << "Failed to read the updater portable executable" 282 std::cerr << "Failed to read the updater portable executable"
283 " structure." << std::endl; 283 " structure." << std::endl;
284 return 12; 284 return 12;
285 } 285 }
286 286
287 // Add a new section to the updater, containing the encrypted 287 // Add a new section to the updater, containing the encrypted
288 // firmware archive. 288 // firmware archive.
289 shared::section_info newsection; 289 shared::section_info newsection;
290 if (!pef.add_section(".firm", newbuffer, newsection)) 290 if (!pef.add_section(".firm", newbuffer, newsection))
291 { 291 {
292 std::cerr << "Failed to add an extra section to the updater" 292 std::cerr << "Failed to add an extra section to the updater"
293 " executable." << std::endl; 293 " executable." << std::endl;
294 return 13; 294 return 13;
295 } 295 }
296 296
297 if (verbose) 297 if (verbose)
298 std::cout << "[*] Relocating code references to the firmware" 298 std::cout << "[*] Relocating code references to the firmware"
299 " archive..." << std::endl; 299 " archive..." << std::endl;
300 300
301 // Locate the code section. 301 // Locate the code section.
302 shared::section_info textsection; 302 shared::section_info textsection;
303 if (!pef.find_section(".text", textsection)) 303 if (!pef.find_section(".text", textsection))
304 { 304 {
305 std::cerr << "Failed to find the code section in the updater" 305 std::cerr << "Failed to find the code section in the updater"
306 " executable." << std::endl; 306 " executable." << std::endl;
307 return 14; 307 return 14;
308 } 308 }
309 309
310 // Read the code section data. 310 // Read the code section data.
311 if (!shared::read_file(updatername, buffer, textsection.raw_address, 311 if (!shared::read_file(updatername, buffer, textsection.raw_address,
312 textsection.raw_size)) 312 textsection.raw_size))
313 { 313 {
314 std::cerr << "Failed to read the code section from the updater" 314 std::cerr << "Failed to read the code section from the updater"
315 " executable." << std::endl; 315 " executable." << std::endl;
316 return 15; 316 return 15;
317 } 317 }
318 318
319 // Determine the addresses of the new and old firmware archives. 319 // Determine the addresses of the new and old firmware archives.
320 dword oldva = pef.pa_to_va(offset_pa); 320 dword oldva = pef.pa_to_va(offset_pa);
321 dword newva = pef.pa_to_va(newsection.raw_address); 321 dword newva = pef.pa_to_va(newsection.raw_address);
322 if (!oldva || !newva) 322 if (!oldva || !newva)
323 { 323 {
324 std::cerr << "Failed to compute address of the new or old" 324 std::cerr << "Failed to compute address of the new or old"
325 " archive." << std::endl; 325 " archive." << std::endl;
326 return 16; 326 return 16;
327 } 327 }
328 328
329 // Relocate references to the old firmware archive. 329 // Relocate references to the old firmware archive.
330 dword imgbase = pef.get_image_base(); 330 dword imgbase = pef.get_image_base();
331 for (int i = 0, j = buffer.size() - sizeof(dword) + 1; i < j; i++) 331 for (int i = 0, j = buffer.size() - sizeof(dword) + 1; i < j; i++)
332 { 332 {
333 dword val = *(dword*)&buffer[i]; 333 dword val = *(dword*)&buffer[i];
334 if (val >= oldva && val <= (oldva + 3)) 334 if (val >= oldva && val <= (oldva + 3))
335 { 335 {
336 *(dword*)&buffer[i] = newva + (val - oldva); 336 *(dword*)&buffer[i] = newva + (val - oldva);
337 if (verbose) 337 if (verbose)
338 std::cout << " " 338 std::cout << " "
339 << std::hex << std::showbase << std::setw(10) 339 << std::hex << std::showbase << std::setw(10)
340 << std::setfill('0') << std::internal 340 << std::setfill('0') << std::internal
341 << (imgbase + textsection.virtual_address + i) 341 << (imgbase + textsection.virtual_address + i)
342 << ": " 342 << ": "
343 << std::hex << std::showbase << std::setw(10) 343 << std::hex << std::showbase << std::setw(10)
344 << std::setfill('0') << std::internal 344 << std::setfill('0') << std::internal
345 << val 345 << val
346 << " -> " 346 << " -> "
347 << std::hex << std::showbase << std::setw(10) 347 << std::hex << std::showbase << std::setw(10)
348 << std::setfill('0') << std::internal 348 << std::setfill('0') << std::internal
349 << (newva + (val - oldva)) << std::endl; 349 << (newva + (val - oldva)) << std::endl;
350 } 350 }
351 } 351 }
352 352
353 // Write the relocated code section data. 353 // Write the relocated code section data.
354 if (!shared::write_file(updatername, buffer, false, textsection.raw_address, 354 if (!shared::write_file(updatername, buffer, false, textsection.raw_address,
355 buffer.size())) 355 buffer.size()))
356 { 356 {
357 std::cerr << "Failed to write the relocated code section to the" 357 std::cerr << "Failed to write the relocated code section to the"
358 " updater executable." << std::endl; 358 " updater executable." << std::endl;
359 return 17; 359 return 17;
360 } 360 }
361 } //if (size < buffer.size()) 361 } //if (size < buffer.size())
362 else 362 else
363 { 363 {
364 // Yes, overwrite the existing firmware archive. 364 // Yes, overwrite the existing firmware archive.
365 if (verbose) 365 if (verbose)
366 std::cout << "[*] Overwriting existing firmware archive..." 366 std::cout << "[*] Overwriting existing firmware archive..."
367 << std::endl; 367 << std::endl;
368 368
369 shared::bytes archive_size(sizeof(dword)); 369 shared::bytes archive_size(sizeof(dword));
370 *(dword*)&archive_size[0] = buffer.size(); 370 *(dword*)&archive_size[0] = buffer.size();
371 371
372 if (!shared::write_file(updatername, archive_size, false, offset_pa, 372 if (!shared::write_file(updatername, archive_size, false, offset_pa,
373 archive_size.size())) 373 archive_size.size()))
374 { 374 {
375 std::cerr << "Failed to write archive size to the updater" 375 std::cerr << "Failed to write archive size to the updater"
376 " executable." << std::endl; 376 " executable." << std::endl;
377 return 18; 377 return 18;
378 } 378 }
379 379
380 if (!shared::write_file(updatername, buffer, false, 380 if (!shared::write_file(updatername, buffer, false,
381 offset_pa+archive_size.size(), buffer.size())) 381 offset_pa+archive_size.size(), buffer.size()))
382 { 382 {
383 std::cerr << "Failed to write the new archive to the updater" 383 std::cerr << "Failed to write the new archive to the updater"
384 " exectuable." << std::endl; 384 " exectuable." << std::endl;
385 return 19; 385 return 19;
386 } 386 }
387 } 387 }
388 388
389 return 0; 389 return 0;
390} 390}
391 391
392int main(int argc, char* argv[]) 392int main(int argc, char* argv[])
393{ 393{
394 try 394 try
395 { 395 {
396 return process_arguments(argc, argv); 396 return process_arguments(argc, argv);
397 } 397 }
398 catch (const std::exception& xcpt) 398 catch (const std::exception& xcpt)
399 { 399 {
400 std::cerr << "Exception caught: " << xcpt.what() << std::endl; 400 std::cerr << "Exception caught: " << xcpt.what() << std::endl;
401 return -1; 401 return -1;
402 } 402 }
403 catch (...) 403 catch (...)
404 { 404 {
405 std::cerr << "Unknown exception caught." << std::endl; 405 std::cerr << "Unknown exception caught." << std::endl;
406 return -2; 406 return -2;
407 } 407 }
408 return -3; 408 return -3;
409} 409}
diff --git a/utils/zenutils/source/zen_crypt/CMakeLists.txt b/utils/zenutils/source/zen_crypt/CMakeLists.txt
index e88e8951a5..5721bbfa06 100755..100644
--- a/utils/zenutils/source/zen_crypt/CMakeLists.txt
+++ b/utils/zenutils/source/zen_crypt/CMakeLists.txt
@@ -1,4 +1,4 @@
1ADD_EXECUTABLE(zen_crypt main.cpp) 1ADD_EXECUTABLE(zen_crypt main.cpp)
2 2
3TARGET_LINK_LIBRARIES(zen_crypt shared) 3TARGET_LINK_LIBRARIES(zen_crypt shared)
4TARGET_LINK_LIBRARIES(zen_crypt beecrypt) 4TARGET_LINK_LIBRARIES(zen_crypt beecrypt)
diff --git a/utils/zenutils/source/zen_crypt/main.cpp b/utils/zenutils/source/zen_crypt/main.cpp
index 8301cbbea5..9944ba97f8 100755..100644
--- a/utils/zenutils/source/zen_crypt/main.cpp
+++ b/utils/zenutils/source/zen_crypt/main.cpp
@@ -1,687 +1,687 @@
1/* zenutils - Utilities for working with creative firmwares. 1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com> 2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 * 3 *
4 * This program is free software; you can redistribute it and/or modify 4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by 5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or 6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. 7 * (at your option) any later version.
8 * 8 *
9 * This program is distributed in the hope that it will be useful, 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software 15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */ 17 */
18 18
19#include <iostream> 19#include <iostream>
20#include <getpot/getpot.hpp> 20#include <getpot/getpot.hpp>
21#include <cenc.h> 21#include <cenc.h>
22#include <crypt.h> 22#include <crypt.h>
23#include <file.h> 23#include <file.h>
24#include <firmware.h> 24#include <firmware.h>
25#include <utils.h> 25#include <utils.h>
26 26
27 27
28namespace { 28namespace {
29enum command_t 29enum command_t
30{ 30{
31 cmd_none = 0, 31 cmd_none = 0,
32 cmd_sign, 32 cmd_sign,
33 cmd_verify, 33 cmd_verify,
34 cmd_encrypt, 34 cmd_encrypt,
35 cmd_decrypt 35 cmd_decrypt
36}; 36};
37 37
38enum mode_t 38enum mode_t
39{ 39{
40 mode_none = 0, 40 mode_none = 0,
41 mode_cenc, 41 mode_cenc,
42 mode_fresc, 42 mode_fresc,
43 mode_tl 43 mode_tl
44}; 44};
45 45
46struct player_info_t 46struct player_info_t
47{ 47{
48 const char* name; 48 const char* name;
49 const char* null_key; // HMAC-SHA1 key 49 const char* null_key; // HMAC-SHA1 key
50 const char* fresc_key; // BlowFish key 50 const char* fresc_key; // BlowFish key
51 const char* tl_key; // BlowFish key 51 const char* tl_key; // BlowFish key
52 bool big_endian; 52 bool big_endian;
53}; 53};
54}; //namespace 54}; //namespace
55 55
56 56
57static const char VERSION[] = "0.1"; 57static const char VERSION[] = "0.1";
58 58
59static const char null_key_v1[] = "CTL:N0MAD|PDE0.SIGN."; 59static const char null_key_v1[] = "CTL:N0MAD|PDE0.SIGN.";
60static const char null_key_v2[] = "CTL:N0MAD|PDE0.DPMP."; 60static const char null_key_v2[] = "CTL:N0MAD|PDE0.DPMP.";
61 61
62static const char fresc_key[] = "Copyright (C) CTL. -" 62static const char fresc_key[] = "Copyright (C) CTL. -"
63 " zN0MAD iz v~p0wderful!"; 63 " zN0MAD iz v~p0wderful!";
64 64
65static const char tl_zvm_key[] = "1sN0TM3D az u~may th1nk*" 65static const char tl_zvm_key[] = "1sN0TM3D az u~may th1nk*"
66 "Creative Zen Vision:M"; 66 "Creative Zen Vision:M";
67static const char tl_zvw_key[] = "1sN0TM3D az u~may th1nk*" 67static const char tl_zvw_key[] = "1sN0TM3D az u~may th1nk*"
68 "Creative ZEN Vision W"; 68 "Creative ZEN Vision W";
69static const char tl_zm_key[] = "1sN0TM3D az u~may th1nk*" 69static const char tl_zm_key[] = "1sN0TM3D az u~may th1nk*"
70 "Creative Zen Micro"; 70 "Creative Zen Micro";
71static const char tl_zmp_key[] = "1sN0TM3D az u~may th1nk*" 71static const char tl_zmp_key[] = "1sN0TM3D az u~may th1nk*"
72 "Creative Zen MicroPhoto"; 72 "Creative Zen MicroPhoto";
73static const char tl_zs_key[] = "1sN0TM3D az u~may th1nk*" 73static const char tl_zs_key[] = "1sN0TM3D az u~may th1nk*"
74 "Creative Zen Sleek"; 74 "Creative Zen Sleek";
75static const char tl_zsp_key[] = "1sN0TM3D az u~may th1nk*" 75static const char tl_zsp_key[] = "1sN0TM3D az u~may th1nk*"
76 "Creative Zen Sleek Photo"; 76 "Creative Zen Sleek Photo";
77static const char tl_zt_key[] = "1sN0TM3D az u~may th1nk*" 77static const char tl_zt_key[] = "1sN0TM3D az u~may th1nk*"
78 "Creative Zen Touch"; 78 "Creative Zen Touch";
79static const char tl_zx_key[] = "1sN0TM3D az u~may th1nk*" 79static const char tl_zx_key[] = "1sN0TM3D az u~may th1nk*"
80 "NOMAD Jukebox Zen Xtra"; 80 "NOMAD Jukebox Zen Xtra";
81 81
82player_info_t players[] = { 82player_info_t players[] = {
83 {"Vision:M", null_key_v2, fresc_key, tl_zvm_key, false}, 83 {"Vision:M", null_key_v2, fresc_key, tl_zvm_key, false},
84 {"Vision W", null_key_v2, fresc_key, tl_zvw_key, false}, 84 {"Vision W", null_key_v2, fresc_key, tl_zvw_key, false},
85 {"Micro", null_key_v1, fresc_key, tl_zm_key, true}, 85 {"Micro", null_key_v1, fresc_key, tl_zm_key, true},
86 {"MicroPhoto", null_key_v1, fresc_key, tl_zmp_key, true}, 86 {"MicroPhoto", null_key_v1, fresc_key, tl_zmp_key, true},
87 {"Sleek", null_key_v1, fresc_key, tl_zs_key, true}, 87 {"Sleek", null_key_v1, fresc_key, tl_zs_key, true},
88 {"SleekPhoto", null_key_v1, fresc_key, tl_zsp_key, true}, 88 {"SleekPhoto", null_key_v1, fresc_key, tl_zsp_key, true},
89 {"Touch", null_key_v1, fresc_key, tl_zt_key, true}, 89 {"Touch", null_key_v1, fresc_key, tl_zt_key, true},
90 {"Xtra", null_key_v1, fresc_key, tl_zx_key, true}, 90 {"Xtra", null_key_v1, fresc_key, tl_zx_key, true},
91 {NULL, NULL, NULL, NULL, false} 91 {NULL, NULL, NULL, NULL, false}
92}; 92};
93 93
94 94
95player_info_t* find_player_info(std::string player) 95player_info_t* find_player_info(std::string player)
96{ 96{
97 for (int i = 0; players[i].name != NULL; i++) 97 for (int i = 0; players[i].name != NULL; i++)
98 { 98 {
99 if (!stricmp(players[i].name, player.c_str())) 99 if (!stricmp(players[i].name, player.c_str()))
100 { 100 {
101 return &players[i]; 101 return &players[i];
102 } 102 }
103 } 103 }
104 return NULL; 104 return NULL;
105} 105}
106 106
107void print_version() 107void print_version()
108{ 108{
109 std::cout 109 std::cout
110 << "zen_crypt - A utility for encrypting, decrypting or signing" 110 << "zen_crypt - A utility for encrypting, decrypting or signing"
111 " Creative firmwares." << std::endl 111 " Creative firmwares." << std::endl
112 << "Version " << VERSION << std::endl 112 << "Version " << VERSION << std::endl
113 << "Copyright (c) 2007 Rasmus Ry" << std::endl; 113 << "Copyright (c) 2007 Rasmus Ry" << std::endl;
114} 114}
115 115
116void print_help() 116void print_help()
117{ 117{
118 print_version(); 118 print_version();
119 std::cout << std::endl 119 std::cout << std::endl
120 << "Usage: zen_crypt [command] [options]" << std::endl 120 << "Usage: zen_crypt [command] [options]" << std::endl
121 << std::endl 121 << std::endl
122 << " Commands:" << std::endl 122 << " Commands:" << std::endl
123 << " -h,--help" << std::endl 123 << " -h,--help" << std::endl
124 << " prints this message." << std::endl 124 << " prints this message." << std::endl
125 << " -s,--sign" << std::endl 125 << " -s,--sign" << std::endl
126 << " signs a given input file." << std::endl 126 << " signs a given input file." << std::endl
127 << " -v,--verify" << std::endl 127 << " -v,--verify" << std::endl
128 << " verifies a signed input file." << std::endl 128 << " verifies a signed input file." << std::endl
129 << " -e,--encrypt" << std::endl 129 << " -e,--encrypt" << std::endl
130 << " encrypts a given input file." << std::endl 130 << " encrypts a given input file." << std::endl
131 << " -d,--decrypt" << std::endl 131 << " -d,--decrypt" << std::endl
132 << " decrypts a given input file." << std::endl 132 << " decrypts a given input file." << std::endl
133 << std::endl 133 << std::endl
134 << " Options:" << std::endl 134 << " Options:" << std::endl
135 << " -V,--verbose" << std::endl 135 << " -V,--verbose" << std::endl
136 << " prints verbose messages." << std::endl 136 << " prints verbose messages." << std::endl
137 << " -b,--big-endian" << std::endl 137 << " -b,--big-endian" << std::endl
138 << " specifies that the input is big-endian, default is" 138 << " specifies that the input is big-endian, default is"
139 " little-endian." << std::endl 139 " little-endian." << std::endl
140 << " -i,--input [file]" << std::endl 140 << " -i,--input [file]" << std::endl
141 << " specifies the input file." << std::endl 141 << " specifies the input file." << std::endl
142 << " -o,--output [file]" << std::endl 142 << " -o,--output [file]" << std::endl
143 << " specifies the output file." << std::endl 143 << " specifies the output file." << std::endl
144 << " -m,--mode [CENC|FRESC|TL]" << std::endl 144 << " -m,--mode [CENC|FRESC|TL]" << std::endl
145 << " specifies which algorithm to use." << std::endl 145 << " specifies which algorithm to use." << std::endl
146 << " -k,--key [player|key]" << std::endl 146 << " -k,--key [player|key]" << std::endl
147 << " specifies which key to use." << std::endl 147 << " specifies which key to use." << std::endl
148 << std::endl 148 << std::endl
149 ; 149 ;
150 std::cout << " Players:" << std::endl; 150 std::cout << " Players:" << std::endl;
151 for (int i = 0; players[i].name != NULL; i++) 151 for (int i = 0; players[i].name != NULL; i++)
152 { 152 {
153 std::cout << " " << players[i].name; 153 std::cout << " " << players[i].name;
154 if (!i) 154 if (!i)
155 std::cout << " (default)"; 155 std::cout << " (default)";
156 std::cout << std::endl; 156 std::cout << std::endl;
157 } 157 }
158} 158}
159 159
160size_t find_null_signature(shared::bytes& data) 160size_t find_null_signature(shared::bytes& data)
161{ 161{
162 size_t index = data.size(); 162 size_t index = data.size();
163 if (index < (20 + 8 + 7)) 163 if (index < (20 + 8 + 7))
164 return 0; 164 return 0;
165 index -= 20 + 8; 165 index -= 20 + 8;
166 for (int i = 0; i < 7; i++) 166 for (int i = 0; i < 7; i++)
167 { 167 {
168 if (*(dword*)&data[index-i] == 'NULL' || 168 if (*(dword*)&data[index-i] == 'NULL' ||
169 *(dword*)&data[index-i] == 'LLUN') 169 *(dword*)&data[index-i] == 'LLUN')
170 { 170 {
171 return index-i; 171 return index-i;
172 } 172 }
173 } 173 }
174 return 0; 174 return 0;
175} 175}
176 176
177 177
178bool sign(shared::bytes& data, player_info_t* pi, const std::string& file, 178bool sign(shared::bytes& data, player_info_t* pi, const std::string& file,
179 bool verbose) 179 bool verbose)
180{ 180{
181 if (verbose) 181 if (verbose)
182 std::cout << "[*] Checking for the presence of an existing" 182 std::cout << "[*] Checking for the presence of an existing"
183 " NULL signature..." << std::endl; 183 " NULL signature..." << std::endl;
184 size_t index = find_null_signature(data); 184 size_t index = find_null_signature(data);
185 if (index) 185 if (index)
186 { 186 {
187 if (verbose) 187 if (verbose)
188 std::cout << "[*] Found NULL signature at: " 188 std::cout << "[*] Found NULL signature at: "
189 << std::hex << index << std::endl; 189 << std::hex << index << std::endl;
190 190
191 if (verbose) 191 if (verbose)
192 std::cout << "[*] Computing digest..." << std::endl; 192 std::cout << "[*] Computing digest..." << std::endl;
193 193
194 shared::bytes digest(20); 194 shared::bytes digest(20);
195 if (!zen::hmac_sha1_calc((const byte*)pi->null_key, 195 if (!zen::hmac_sha1_calc((const byte*)pi->null_key,
196 strlen(pi->null_key)+1, &data[0], index, 196 strlen(pi->null_key)+1, &data[0], index,
197 &digest[0], NULL)) 197 &digest[0], NULL))
198 { 198 {
199 std::cerr << "Failed to compute digest." << std::endl; 199 std::cerr << "Failed to compute digest." << std::endl;
200 return false; 200 return false;
201 } 201 }
202 202
203 if (verbose) 203 if (verbose)
204 std::cout << "[*] Writing file data..." << std::endl; 204 std::cout << "[*] Writing file data..." << std::endl;
205 205
206 if (!shared::write_file(file, data, true)) 206 if (!shared::write_file(file, data, true))
207 { 207 {
208 std::cerr << "Failed to write file data." << std::endl; 208 std::cerr << "Failed to write file data." << std::endl;
209 return false; 209 return false;
210 } 210 }
211 211
212 if (verbose) 212 if (verbose)
213 std::cout << "[*] Writing digest data..." << std::endl; 213 std::cout << "[*] Writing digest data..." << std::endl;
214 214
215 if (!shared::write_file(file, digest, false, index+8)) 215 if (!shared::write_file(file, digest, false, index+8))
216 { 216 {
217 std::cerr << "Failed to write digest data." << std::endl; 217 std::cerr << "Failed to write digest data." << std::endl;
218 return false; 218 return false;
219 } 219 }
220 } 220 }
221 else 221 else
222 { 222 {
223 if (verbose) 223 if (verbose)
224 std::cout << "[*] Computing digest..." << std::endl; 224 std::cout << "[*] Computing digest..." << std::endl;
225 225
226 shared::bytes signature(20+8); 226 shared::bytes signature(20+8);
227 if (!zen::hmac_sha1_calc((const byte*)pi->null_key, 227 if (!zen::hmac_sha1_calc((const byte*)pi->null_key,
228 strlen(pi->null_key)+1, &data[0], data.size(), 228 strlen(pi->null_key)+1, &data[0], data.size(),
229 &signature[8], NULL)) 229 &signature[8], NULL))
230 { 230 {
231 std::cerr << "Failed to compute digest." << std::endl; 231 std::cerr << "Failed to compute digest." << std::endl;
232 return false; 232 return false;
233 } 233 }
234 234
235 235
236 zen::firmware_header_t header = {'NULL', 20}; 236 zen::firmware_header_t header = {'NULL', 20};
237 if (pi->big_endian) 237 if (pi->big_endian)
238 { 238 {
239 header.tag = shared::swap(header.tag); 239 header.tag = shared::swap(header.tag);
240 header.size = shared::swap(header.size); 240 header.size = shared::swap(header.size);
241 } 241 }
242 memcpy(&signature[0], &header, sizeof(zen::firmware_header_t)); 242 memcpy(&signature[0], &header, sizeof(zen::firmware_header_t));
243 243
244 if (verbose) 244 if (verbose)
245 std::cout << "[*] Writing file data..." << std::endl; 245 std::cout << "[*] Writing file data..." << std::endl;
246 246
247 if (!shared::write_file(file, data, true)) 247 if (!shared::write_file(file, data, true))
248 { 248 {
249 std::cerr << "Failed to write file data." << std::endl; 249 std::cerr << "Failed to write file data." << std::endl;
250 return false; 250 return false;
251 } 251 }
252 252
253 if (verbose) 253 if (verbose)
254 std::cout << "[*] Writing signature data..." << std::endl; 254 std::cout << "[*] Writing signature data..." << std::endl;
255 255
256 if (!shared::write_file(file, signature, false, data.size())) 256 if (!shared::write_file(file, signature, false, data.size()))
257 { 257 {
258 std::cerr << "Failed to write signature data." << std::endl; 258 std::cerr << "Failed to write signature data." << std::endl;
259 return false; 259 return false;
260 } 260 }
261 261
262 if (verbose) 262 if (verbose)
263 std::cout << "[*] Ensuring that the file length is" 263 std::cout << "[*] Ensuring that the file length is"
264 " 32-bit aligned..." << std::endl; 264 " 32-bit aligned..." << std::endl;
265 265
266 int length = data.size() + signature.size(); 266 int length = data.size() + signature.size();
267 int align = length % 4; 267 int align = length % 4;
268 if (align) 268 if (align)
269 { 269 {
270 shared::bytes padding(4 - align, 0); 270 shared::bytes padding(4 - align, 0);
271 if (!shared::write_file(file, padding, false, length)) 271 if (!shared::write_file(file, padding, false, length))
272 { 272 {
273 std::cerr << "Failed to write padding data." << std::endl; 273 std::cerr << "Failed to write padding data." << std::endl;
274 return false; 274 return false;
275 } 275 }
276 } 276 }
277 } 277 }
278 278
279 return true; 279 return true;
280} 280}
281 281
282bool verify(shared::bytes& data, player_info_t* pi, bool verbose) 282bool verify(shared::bytes& data, player_info_t* pi, bool verbose)
283{ 283{
284 if (verbose) 284 if (verbose)
285 std::cout << "[*] Checking for the presence of an existing" 285 std::cout << "[*] Checking for the presence of an existing"
286 " NULL signature..." << std::endl; 286 " NULL signature..." << std::endl;
287 size_t index = find_null_signature(data); 287 size_t index = find_null_signature(data);
288 if (!index) 288 if (!index)
289 { 289 {
290 std::cerr << "No NULL signature present in the input file." 290 std::cerr << "No NULL signature present in the input file."
291 << std::endl; 291 << std::endl;
292 return false; 292 return false;
293 } 293 }
294 if (verbose) 294 if (verbose)
295 std::cout << "[*] Found NULL signature at: " 295 std::cout << "[*] Found NULL signature at: "
296 << std::hex << index << std::endl; 296 << std::hex << index << std::endl;
297 297
298 if (verbose) 298 if (verbose)
299 std::cout << "[*] Computing digest..." << std::endl; 299 std::cout << "[*] Computing digest..." << std::endl;
300 300
301 byte digest[20]; 301 byte digest[20];
302 if (!zen::hmac_sha1_calc((const byte*)pi->null_key, strlen(pi->null_key)+1, 302 if (!zen::hmac_sha1_calc((const byte*)pi->null_key, strlen(pi->null_key)+1,
303 &data[0], index, digest, NULL)) 303 &data[0], index, digest, NULL))
304 { 304 {
305 std::cerr << "Failed to compute digest." << std::endl; 305 std::cerr << "Failed to compute digest." << std::endl;
306 return false; 306 return false;
307 } 307 }
308 308
309 if (verbose) 309 if (verbose)
310 std::cout << "[*] Verifying NULL signature digest..." << std::endl; 310 std::cout << "[*] Verifying NULL signature digest..." << std::endl;
311 311
312 if (memcmp(&digest[0], &data[index+8], 20)) 312 if (memcmp(&digest[0], &data[index+8], 20))
313 { 313 {
314 std::cerr << "The NULL signature contains an incorrect digest." 314 std::cerr << "The NULL signature contains an incorrect digest."
315 << std::endl; 315 << std::endl;
316 return false; 316 return false;
317 } 317 }
318 318
319 return true; 319 return true;
320} 320}
321 321
322bool encrypt(shared::bytes& data, int mode, player_info_t* pi, 322bool encrypt(shared::bytes& data, int mode, player_info_t* pi,
323 const std::string& file, bool verbose) 323 const std::string& file, bool verbose)
324{ 324{
325 if (mode == mode_cenc) 325 if (mode == mode_cenc)
326 { 326 {
327 if (verbose) 327 if (verbose)
328 std::cout << "[*] Encoding input file..." << std::endl; 328 std::cout << "[*] Encoding input file..." << std::endl;
329 329
330 shared::bytes outbuf(data.size() * 2); 330 shared::bytes outbuf(data.size() * 2);
331 int len = zen::cenc_encode(&data[0], data.size(), &outbuf[0], outbuf.size()); 331 int len = zen::cenc_encode(&data[0], data.size(), &outbuf[0], outbuf.size());
332 if (!len) 332 if (!len)
333 { 333 {
334 std::cerr << "Failed to encode the input file." << std::endl; 334 std::cerr << "Failed to encode the input file." << std::endl;
335 return false; 335 return false;
336 } 336 }
337 337
338 if (verbose) 338 if (verbose)
339 std::cout << "[*] Writing decoded length to file..." << std::endl; 339 std::cout << "[*] Writing decoded length to file..." << std::endl;
340 340
341 shared::bytes length(sizeof(dword)); 341 shared::bytes length(sizeof(dword));
342 *(dword*)&length[0] = pi->big_endian ? shared::swap(data.size()) : data.size(); 342 *(dword*)&length[0] = pi->big_endian ? shared::swap(data.size()) : data.size();
343 if (!shared::write_file(file, length, true)) 343 if (!shared::write_file(file, length, true))
344 { 344 {
345 std::cerr << "Failed to write the file data." << std::endl; 345 std::cerr << "Failed to write the file data." << std::endl;
346 return false; 346 return false;
347 } 347 }
348 348
349 if (verbose) 349 if (verbose)
350 std::cout << "[*] Writing file data..." << std::endl; 350 std::cout << "[*] Writing file data..." << std::endl;
351 351
352 if (!shared::write_file(file, outbuf, sizeof(dword), len)) 352 if (!shared::write_file(file, outbuf, sizeof(dword), len))
353 { 353 {
354 std::cerr << "Failed to write the file data." << std::endl; 354 std::cerr << "Failed to write the file data." << std::endl;
355 return false; 355 return false;
356 } 356 }
357 } 357 }
358 else if (mode == mode_fresc) 358 else if (mode == mode_fresc)
359 { 359 {
360 std::cerr << "FRESC mode is not supported." << std::endl; 360 std::cerr << "FRESC mode is not supported." << std::endl;
361 return false; 361 return false;
362 } 362 }
363 else if (mode == mode_tl) 363 else if (mode == mode_tl)
364 { 364 {
365 if (verbose) 365 if (verbose)
366 std::cout << "[*] Encoding input file..." << std::endl; 366 std::cout << "[*] Encoding input file..." << std::endl;
367 367
368 shared::bytes outbuf(data.size() * 2); 368 shared::bytes outbuf(data.size() * 2);
369 *(dword*)&outbuf[0] = pi->big_endian ? shared::swap(data.size()) : data.size(); 369 *(dword*)&outbuf[0] = pi->big_endian ? shared::swap(data.size()) : data.size();
370 int len = zen::cenc_encode(&data[0], data.size(), 370 int len = zen::cenc_encode(&data[0], data.size(),
371 &outbuf[sizeof(dword)], 371 &outbuf[sizeof(dword)],
372 outbuf.size()-sizeof(dword)); 372 outbuf.size()-sizeof(dword));
373 if (!len) 373 if (!len)
374 { 374 {
375 std::cerr << "Failed to encode the input file." << std::endl; 375 std::cerr << "Failed to encode the input file." << std::endl;
376 return false; 376 return false;
377 } 377 }
378 len += sizeof(dword); 378 len += sizeof(dword);
379 379
380 int align = len % 8; 380 int align = len % 8;
381 align = align ? (8 - align) : 0; 381 align = align ? (8 - align) : 0;
382 len += align; 382 len += align;
383 383
384 if (verbose) 384 if (verbose)
385 std::cout << "[*] Encrypting encoded data..." << std::endl; 385 std::cout << "[*] Encrypting encoded data..." << std::endl;
386 386
387 dword iv[2] = {0, shared::swap(len)}; 387 dword iv[2] = {0, shared::swap(len)};
388 if (!zen::bf_cbc_encrypt((const byte*)pi->tl_key, strlen(pi->tl_key)+1, 388 if (!zen::bf_cbc_encrypt((const byte*)pi->tl_key, strlen(pi->tl_key)+1,
389 &outbuf[0], len, (const byte*)iv)) 389 &outbuf[0], len, (const byte*)iv))
390 { 390 {
391 std::cerr << "Failed to decrypt the input file." << std::endl; 391 std::cerr << "Failed to decrypt the input file." << std::endl;
392 return false; 392 return false;
393 } 393 }
394 394
395 if (verbose) 395 if (verbose)
396 std::cout << "[*] Writing file data..." << std::endl; 396 std::cout << "[*] Writing file data..." << std::endl;
397 397
398 if (!shared::write_file(file, outbuf, true, 0, len)) 398 if (!shared::write_file(file, outbuf, true, 0, len))
399 { 399 {
400 std::cerr << "Failed to save the output file." << std::endl; 400 std::cerr << "Failed to save the output file." << std::endl;
401 return false; 401 return false;
402 } 402 }
403 } 403 }
404 else 404 else
405 { 405 {
406 std::cerr << "Invalid mode specified." << std::endl; 406 std::cerr << "Invalid mode specified." << std::endl;
407 return false; 407 return false;
408 } 408 }
409 409
410 return true; 410 return true;
411} 411}
412 412
413bool decrypt(shared::bytes& data, int mode, player_info_t* pi, 413bool decrypt(shared::bytes& data, int mode, player_info_t* pi,
414 const std::string& file, bool verbose) 414 const std::string& file, bool verbose)
415{ 415{
416 if (mode == mode_cenc) 416 if (mode == mode_cenc)
417 { 417 {
418 dword length = *(dword*)&data[0]; 418 dword length = *(dword*)&data[0];
419 length = pi->big_endian ? shared::swap(length) : length; 419 length = pi->big_endian ? shared::swap(length) : length;
420 420
421 if (verbose) 421 if (verbose)
422 std::cout << "[*] Decoding input file..." << std::endl; 422 std::cout << "[*] Decoding input file..." << std::endl;
423 423
424 shared::bytes outbuf(length); 424 shared::bytes outbuf(length);
425 if (!zen::cenc_decode(&data[sizeof(dword)], data.size()-sizeof(dword), 425 if (!zen::cenc_decode(&data[sizeof(dword)], data.size()-sizeof(dword),
426 &outbuf[0], length)) 426 &outbuf[0], length))
427 { 427 {
428 std::cerr << "Failed to decode the input file." << std::endl; 428 std::cerr << "Failed to decode the input file." << std::endl;
429 return false; 429 return false;
430 } 430 }
431 431
432 if (verbose) 432 if (verbose)
433 std::cout << "[*] Writing file data..." << std::endl; 433 std::cout << "[*] Writing file data..." << std::endl;
434 434
435 if (!shared::write_file(file, outbuf, true)) 435 if (!shared::write_file(file, outbuf, true))
436 { 436 {
437 std::cerr << "Failed to write the file data." << std::endl; 437 std::cerr << "Failed to write the file data." << std::endl;
438 return false; 438 return false;
439 } 439 }
440 } 440 }
441 else if (mode == mode_fresc) 441 else if (mode == mode_fresc)
442 { 442 {
443 if (verbose) 443 if (verbose)
444 std::cout << "[*] Decrypting input file..." << std::endl; 444 std::cout << "[*] Decrypting input file..." << std::endl;
445 445
446 dword iv[2] = {shared::swap(data.size()), 0}; 446 dword iv[2] = {shared::swap(data.size()), 0};
447 if (!zen::bf_cbc_decrypt((const byte*)pi->fresc_key, 447 if (!zen::bf_cbc_decrypt((const byte*)pi->fresc_key,
448 strlen(pi->fresc_key)+1, &data[0], 448 strlen(pi->fresc_key)+1, &data[0],
449 data.size(), (const byte*)iv)) 449 data.size(), (const byte*)iv))
450 { 450 {
451 std::cerr << "Failed to decrypt the input file." << std::endl; 451 std::cerr << "Failed to decrypt the input file." << std::endl;
452 return false; 452 return false;
453 } 453 }
454 454
455 if (verbose) 455 if (verbose)
456 std::cout << "[*] Writing file data..." << std::endl; 456 std::cout << "[*] Writing file data..." << std::endl;
457 457
458 if (!shared::write_file(file, data, true)) 458 if (!shared::write_file(file, data, true))
459 { 459 {
460 std::cerr << "Failed to save the output file." << std::endl; 460 std::cerr << "Failed to save the output file." << std::endl;
461 return false; 461 return false;
462 } 462 }
463 } 463 }
464 else if (mode == mode_tl) 464 else if (mode == mode_tl)
465 { 465 {
466 if (verbose) 466 if (verbose)
467 std::cout << "[*] Decrypting input file..." << std::endl; 467 std::cout << "[*] Decrypting input file..." << std::endl;
468 468
469 dword iv[2] = {0, shared::swap(data.size())}; 469 dword iv[2] = {0, shared::swap(data.size())};
470 if (!zen::bf_cbc_decrypt((const byte*)pi->tl_key, strlen(pi->tl_key)+1, 470 if (!zen::bf_cbc_decrypt((const byte*)pi->tl_key, strlen(pi->tl_key)+1,
471 &data[0], data.size(), (const byte*)iv)) 471 &data[0], data.size(), (const byte*)iv))
472 { 472 {
473 std::cerr << "Failed to decrypt the input file." << std::endl; 473 std::cerr << "Failed to decrypt the input file." << std::endl;
474 return false; 474 return false;
475 } 475 }
476 476
477 dword length = *(dword*)&data[0]; 477 dword length = *(dword*)&data[0];
478 length = pi->big_endian ? shared::swap(length) : length; 478 length = pi->big_endian ? shared::swap(length) : length;
479 if (length > (data.size() * 3)) 479 if (length > (data.size() * 3))
480 { 480 {
481 std::cerr << "Decrypted length is unexpectedly large: " 481 std::cerr << "Decrypted length is unexpectedly large: "
482 << std::hex << length 482 << std::hex << length
483 << " Check the endian and key settings." << std::endl; 483 << " Check the endian and key settings." << std::endl;
484 return false; 484 return false;
485 } 485 }
486 486
487 if (verbose) 487 if (verbose)
488 std::cout << "[*] Decoding decrypted data..." << std::endl; 488 std::cout << "[*] Decoding decrypted data..." << std::endl;
489 489
490 shared::bytes outbuf(length); 490 shared::bytes outbuf(length);
491 if (!zen::cenc_decode(&data[sizeof(dword)], data.size()-sizeof(dword), 491 if (!zen::cenc_decode(&data[sizeof(dword)], data.size()-sizeof(dword),
492 &outbuf[0], length)) 492 &outbuf[0], length))
493 { 493 {
494 std::cerr << "Failed to decode the input file." << std::endl; 494 std::cerr << "Failed to decode the input file." << std::endl;
495 return false; 495 return false;
496 } 496 }
497 497
498 if (verbose) 498 if (verbose)
499 std::cout << "[*] Writing file data..." << std::endl; 499 std::cout << "[*] Writing file data..." << std::endl;
500 500
501 if (!shared::write_file(file, outbuf, true)) 501 if (!shared::write_file(file, outbuf, true))
502 { 502 {
503 std::cerr << "Failed to save the output file." << std::endl; 503 std::cerr << "Failed to save the output file." << std::endl;
504 return false; 504 return false;
505 } 505 }
506 } 506 }
507 else 507 else
508 { 508 {
509 std::cerr << "Invalid mode specified." << std::endl; 509 std::cerr << "Invalid mode specified." << std::endl;
510 return false; 510 return false;
511 } 511 }
512 512
513 return true; 513 return true;
514} 514}
515 515
516int process_arguments(int argc, char*argv[]) 516int process_arguments(int argc, char*argv[])
517{ 517{
518 //-------------------------------------------------------------------- 518 //--------------------------------------------------------------------
519 // Parse input variables. 519 // Parse input variables.
520 //-------------------------------------------------------------------- 520 //--------------------------------------------------------------------
521 521
522 GetPot cl(argc, argv); 522 GetPot cl(argc, argv);
523 if (cl.size() == 1 || cl.search(2, "-h", "--help")) 523 if (cl.size() == 1 || cl.search(2, "-h", "--help"))
524 { 524 {
525 print_help(); 525 print_help();
526 return 1; 526 return 1;
527 } 527 }
528 528
529 int command = cmd_none; 529 int command = cmd_none;
530 if (cl.search(2, "-s", "--sign")) 530 if (cl.search(2, "-s", "--sign"))
531 command = cmd_sign; 531 command = cmd_sign;
532 else if (cl.search(2, "-v", "--verify")) 532 else if (cl.search(2, "-v", "--verify"))
533 command = cmd_verify; 533 command = cmd_verify;
534 else if (cl.search(2, "-e", "--encrypt")) 534 else if (cl.search(2, "-e", "--encrypt"))
535 command = cmd_encrypt; 535 command = cmd_encrypt;
536 else if (cl.search(2, "-d", "--decrypt")) 536 else if (cl.search(2, "-d", "--decrypt"))
537 command = cmd_decrypt; 537 command = cmd_decrypt;
538 538
539 if (command == cmd_none) 539 if (command == cmd_none)
540 { 540 {
541 std::cerr << "No command specified." << std::endl; 541 std::cerr << "No command specified." << std::endl;
542 return 2; 542 return 2;
543 } 543 }
544 544
545 int mode = mode_none; 545 int mode = mode_none;
546 if (command == cmd_encrypt || command == cmd_decrypt) 546 if (command == cmd_encrypt || command == cmd_decrypt)
547 { 547 {
548 if (!cl.search(2, "-m", "--mode")) 548 if (!cl.search(2, "-m", "--mode"))
549 { 549 {
550 std::cerr << "The specified command requires that" 550 std::cerr << "The specified command requires that"
551 " a mode is specified." 551 " a mode is specified."
552 << std::endl; 552 << std::endl;
553 return 3; 553 return 3;
554 } 554 }
555 std::string name = cl.next(""); 555 std::string name = cl.next("");
556 if (!name.empty()) 556 if (!name.empty())
557 { 557 {
558 if (!stricmp(name.c_str(), "CENC")) 558 if (!stricmp(name.c_str(), "CENC"))
559 mode = mode_cenc; 559 mode = mode_cenc;
560 else if (!stricmp(name.c_str(), "FRESC")) 560 else if (!stricmp(name.c_str(), "FRESC"))
561 mode = mode_fresc; 561 mode = mode_fresc;
562 else if (!stricmp(name.c_str(), "TL")) 562 else if (!stricmp(name.c_str(), "TL"))
563 mode = mode_tl; 563 mode = mode_tl;
564 } 564 }
565 if (mode == mode_none) 565 if (mode == mode_none)
566 { 566 {
567 std::cerr << "Invalid mode specified." << std::endl; 567 std::cerr << "Invalid mode specified." << std::endl;
568 return 4; 568 return 4;
569 } 569 }
570 } 570 }
571 571
572 bool verbose = false; 572 bool verbose = false;
573 if (cl.search(2, "-V", "--verbose")) 573 if (cl.search(2, "-V", "--verbose"))
574 verbose = true; 574 verbose = true;
575 575
576 bool big_endian = false; 576 bool big_endian = false;
577 if (cl.search(2, "-b", "--big-endian")) 577 if (cl.search(2, "-b", "--big-endian"))
578 big_endian = true; 578 big_endian = true;
579 579
580 std::string infile; 580 std::string infile;
581 if (cl.search(2, "-i", "--input")) 581 if (cl.search(2, "-i", "--input"))
582 infile = cl.next(""); 582 infile = cl.next("");
583 if (infile.empty()) 583 if (infile.empty())
584 { 584 {
585 std::cerr << "An input file must be specified." << std::endl; 585 std::cerr << "An input file must be specified." << std::endl;
586 return 5; 586 return 5;
587 } 587 }
588 588
589 std::string outfile = infile; 589 std::string outfile = infile;
590 if (cl.search(2, "-o", "--output")) 590 if (cl.search(2, "-o", "--output"))
591 outfile = cl.next(outfile.c_str()); 591 outfile = cl.next(outfile.c_str());
592 592
593 player_info_t* pi = &players[0]; 593 player_info_t* pi = &players[0];
594 std::string key; 594 std::string key;
595 if (cl.search(2, "-k", "--key")) 595 if (cl.search(2, "-k", "--key"))
596 key = cl.next(""); 596 key = cl.next("");
597 if (!key.empty()) 597 if (!key.empty())
598 { 598 {
599 player_info_t* pitmp = find_player_info(key); 599 player_info_t* pitmp = find_player_info(key);
600 if (pitmp != NULL) 600 if (pitmp != NULL)
601 pi = pitmp; 601 pi = pitmp;
602 else 602 else
603 { 603 {
604 static player_info_t player = { 604 static player_info_t player = {
605 NULL, key.c_str(), key.c_str(), key.c_str(), false 605 NULL, key.c_str(), key.c_str(), key.c_str(), false
606 }; 606 };
607 pi = &player; 607 pi = &player;
608 } 608 }
609 } 609 }
610 if (big_endian) 610 if (big_endian)
611 pi->big_endian = big_endian; 611 pi->big_endian = big_endian;
612 612
613 613
614 //-------------------------------------------------------------------- 614 //--------------------------------------------------------------------
615 // Read the input file. 615 // Read the input file.
616 //-------------------------------------------------------------------- 616 //--------------------------------------------------------------------
617 617
618 if (verbose) 618 if (verbose)
619 std::cout << "[*] Reading input file..." << std::endl; 619 std::cout << "[*] Reading input file..." << std::endl;
620 620
621 shared::bytes buffer; 621 shared::bytes buffer;
622 if (!shared::read_file(infile, buffer)) 622 if (!shared::read_file(infile, buffer))
623 { 623 {
624 std::cerr << "Failed to read the input file." << std::endl; 624 std::cerr << "Failed to read the input file." << std::endl;
625 return 6; 625 return 6;
626 } 626 }
627 627
628 628
629 //-------------------------------------------------------------------- 629 //--------------------------------------------------------------------
630 // Process the input file. 630 // Process the input file.
631 //-------------------------------------------------------------------- 631 //--------------------------------------------------------------------
632 632
633 switch (command) 633 switch (command)
634 { 634 {
635 case cmd_sign: 635 case cmd_sign:
636 if (verbose) 636 if (verbose)
637 std::cout << "[*] Signing input file..." << std::endl; 637 std::cout << "[*] Signing input file..." << std::endl;
638 if (!sign(buffer, pi, outfile, verbose)) 638 if (!sign(buffer, pi, outfile, verbose))
639 return 7; 639 return 7;
640 std::cout << "Successfully signed the input file." << std::endl; 640 std::cout << "Successfully signed the input file." << std::endl;
641 break; 641 break;
642 case cmd_verify: 642 case cmd_verify:
643 if (verbose) 643 if (verbose)
644 std::cout << "[*] Verifying signature on input file..." 644 std::cout << "[*] Verifying signature on input file..."
645 << std::endl; 645 << std::endl;
646 if (!verify(buffer, pi, verbose)) 646 if (!verify(buffer, pi, verbose))
647 return 8; 647 return 8;
648 std::cout << "Successfully verified the input file signature." 648 std::cout << "Successfully verified the input file signature."
649 << std::endl; 649 << std::endl;
650 break; 650 break;
651 case cmd_encrypt: 651 case cmd_encrypt:
652 if (verbose) 652 if (verbose)
653 std::cout << "[*] Encrypting input file..." << std::endl; 653 std::cout << "[*] Encrypting input file..." << std::endl;
654 if (!encrypt(buffer, mode, pi, outfile, verbose)) 654 if (!encrypt(buffer, mode, pi, outfile, verbose))
655 return 9; 655 return 9;
656 std::cout << "Successfully encrypted the input file." << std::endl; 656 std::cout << "Successfully encrypted the input file." << std::endl;
657 break; 657 break;
658 case cmd_decrypt: 658 case cmd_decrypt:
659 if (verbose) 659 if (verbose)
660 std::cout << "[*] Decrypting input file..." << std::endl; 660 std::cout << "[*] Decrypting input file..." << std::endl;
661 if (!decrypt(buffer, mode, pi, outfile, verbose)) 661 if (!decrypt(buffer, mode, pi, outfile, verbose))
662 return 10; 662 return 10;
663 std::cout << "Successfully decrypted the input file." << std::endl; 663 std::cout << "Successfully decrypted the input file." << std::endl;
664 break; 664 break;
665 }; 665 };
666 666
667 return 0; 667 return 0;
668} 668}
669 669
670int main(int argc, char* argv[]) 670int main(int argc, char* argv[])
671{ 671{
672 try 672 try
673 { 673 {
674 return process_arguments(argc, argv); 674 return process_arguments(argc, argv);
675 } 675 }
676 catch (const std::exception& xcpt) 676 catch (const std::exception& xcpt)
677 { 677 {
678 std::cerr << "Exception caught: " << xcpt.what() << std::endl; 678 std::cerr << "Exception caught: " << xcpt.what() << std::endl;
679 return -1; 679 return -1;
680 } 680 }
681 catch (...) 681 catch (...)
682 { 682 {
683 std::cerr << "Unknown exception caught." << std::endl; 683 std::cerr << "Unknown exception caught." << std::endl;
684 return -2; 684 return -2;
685 } 685 }
686 return -3; 686 return -3;
687} 687}