1
0
Fork 0
forked from len0rd/rockbox

Add zook's ZenUtils to SVN

git-svn-id: svn://svn.rockbox.org/rockbox/trunk@18010 a1c6a512-1295-4272-9138-f99709370657
This commit is contained in:
Maurus Cuelenaere 2008-07-11 15:50:46 +00:00
parent 7c84ede378
commit 14c7f45cda
147 changed files with 44667 additions and 0 deletions

13
utils/zenutils/CMakeLists.txt Executable file
View file

@ -0,0 +1,13 @@
PROJECT(zenutils)
SET(EXECUTABLE_OUTPUT_PATH ${zenutils_SOURCE_DIR}/bin/${CMAKE_SYSTEM_NAME})
SUBDIRS(source libraries)
INCLUDE_DIRECTORIES(
${zenutils_SOURCE_DIR}/libraries/beecrypt-4.1.2
${zenutils_SOURCE_DIR}/libraries/getpot-c++-1.1.17
${zenutils_SOURCE_DIR}/libraries/pelib-0.9
${zenutils_SOURCE_DIR}/libraries/zlib123
${zenutils_SOURCE_DIR}/source/shared
)

339
utils/zenutils/COPYING Executable file
View file

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
utils/zenutils/bin/zen_crypt.exe Executable file

Binary file not shown.

View file

@ -0,0 +1,3 @@
ADD_SUBDIRECTORY(beecrypt-4.1.2)
ADD_SUBDIRECTORY(pelib-0.9)
ADD_SUBDIRECTORY(zlib123)

View file

@ -0,0 +1,14 @@
PROJECT(beecrypt)
# source files for beecrypt
SET(beecrypt_srcs
beecrypt/blockmode.c
beecrypt/blowfish.c
beecrypt/endianness.c
beecrypt/hmac.c
beecrypt/hmacsha1.c
beecrypt/mp.c
beecrypt/sha1.c
)
ADD_LIBRARY(beecrypt ${beecrypt_srcs})

View file

@ -0,0 +1,11 @@
BeeCrypt Cryptograpy Library:
Bob Deblier <bob.deblier@pandora.be>
C++ Interface:
Bob Deblier <bob.deblier@pandora.be>
Python Interface:
Jeff Johson <jbj@redhat.com>

View file

@ -0,0 +1,73 @@
Note: timings are average values and may vary under different conditions,
i.e. the amount of free memory, swapped memory, amount of cpu cache, etc.
I've tried to make them as accurate as possible, within limits.
Note: many of the testing systems were provided by HP's testdrive program;
many thanks to them for giving me access to their systems. Also thanks to
SourceForge for their compile farm!
Note: to avoid religious wars, in the table below read GNU/Linux for
Linux - I'm just a little cramped for space...
BENCHmark Modular Exponentation (more is better):
BeeCrypt 4.0.0 | gcc-3.3.3 | Fedora Core 2 | Athlon 64 3000+| 1 GB: 24870
BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 24566
BeeCrypt 4.0.0 | gcc-3.2.2 | SuSE 8 EL | Opteron 1600 | 1 GB: 19460
BeeCrypt 3.0.0 | gcc-3.x | RedHat Linux | Opteron MP 1600 | : 17230
BeeCrypt 3.1.0 | gcc-2.96 | RedHat AS 2.1 | Itanium 2 1400 | 1 GB: 11453
BeeCrypt 3.0.0 | gcc-3.2.2 | Debian Linux 3.0 | Itanium 2 900 | 12 GB: 7317
BeeCrypt 3.0.0 | gcc-3.3 | RedHat AS 2.1 | P4 Xeon 2400 | 4 GB: 6920 [--with-arch=pentium4]
BeeCrypt 4.1.0 | gcc-3.3.3 | Fedora Core 2 | P4 Xeon 2400 | 1 GB: 6811 [--with-arch=pentium4]
BeeCrypt 4.1.0 | gcc-3.3.3 | SuSE Enterprise 9 | POWER4 1000 | 16 GB: 5858
BeeCrypt 3.0.0 | gcc-2.95.4 | Debian Linux 3.0 | Alpha EV6.7 666 | 2 GB: 5742
BeeCrypt 3.0.0 | gcc-2.96 | RedHat AS 2.1 | P4 Xeon 2400 | 4 GB: 3280 [--with-arch=pentiumpro]
BeeCrypt 3.0.0 | gcc-3.x | RedHat Linux | POWER4+ 1200 | : 2592
BeeCrypt 3.0.0 | gcc-3.x | RedHat Linux | P3 Xeon 900 | : 2169
BeeCrypt 3.0.0 | gcc-3.2.2 | AIX 5.1 | POWER3-II 333 | 512 MB: 1782 [--with-arch=powerpc64]
BeeCrypt 3.0.0 | gcc-3.x | RedHat Linux | zSeries 900 | : 1687 (s390x)
BeeCrypt 3.0.0 | gcc-3.3 | SuSE Linux 8.2 | Pentium 3 600 | 512 MB: 1447 [--with-arch=pentium3]
BeeCrypt 3.0.0 | gcc-3.2.2 | AIX 5.1 | POWER3-II 333 | 512 MB: 756
BeeCrypt 3.0.0 | Forte C 5.1 | Solaris 8 | UltraSparc II 400 | 4 GB: 425 [--with-arch=sparcv8plus]
BeeCrypt 3.0.0 | | Debian Linux 3.0 | StrongARM 1110 128 | 32 MB: 341
BeeCrypt 3.0.0 | gcc-2.95.4 | Debian Linux 3.0r1 | M68040 33 | 52 MB: 24
BeeCrypt 3.0.0 | gcc-2.95.4 | Debian Linux 3.0r1 | M68030 25 | 36 MB: 8
BENCHmark Hash Function (more is better):
MD5
BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 190.5 MB/s
BeeCrypt 3.0.0 | gcc-2.96 | RedHat AS 2.1 | P4 Xeon 2400 | 4 GB: 137.0 MB/s [--with-arch=pentiumpro]
BeeCrypt 4.1.0 | gcc-3.3.3 | Fedora Core 2 | P4 Xeon 2400 | 1 GB: 97.2 MB/s [--with-arch=pentium4]
BeeCrypt 4.1.0 | gcc-3.3.3 | SuSE Enterprise 9 | POWER4 1000 | 16 GB: 38.8 MB/s
SHA-1
BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 117.4 MB/s
BeeCrypt 4.1.0 | gcc-3.3.3 | Fedora Core 2 | P4 Xeon 2400 | 1 GB: 81.9 MB/s [--with-arch=pentium4]
BeeCrypt 3.0.0 | gcc-2.96 | RedHat AS 2.1 | P4 Xeon 2400 | 4 GB: 77.0 MB/s [--with-arch=pentiumpro]
BeeCrypt 4.1.0 | gcc-3.3.3 | SuSE Enterprise 9 | POWER4 1000 | 16 GB: 51.2 MB/s
SHA-256
BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 85.1 MB/s
BeeCrypt 4.1.0 | gcc-3.3.3 | Fedora Core 2 | P4 Xeon 2400 | 1 GB: 42.4 MB/s [--with-arch=pentium4]
BeeCrypt 3.0.0 | gcc-2.96 | RedHat AS 2.1 | P4 Xeon 2400 | 4 GB: 37.8 MB/s [--with-arch=pentiumpro]
BeeCrypt 4.1.0 | gcc-3.3.3 | SuSE Enterprise 9 | POWER4 1000 | 16 GB: 33.0 MB/s
SHA-512
BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 129.6 MB/s
BeeCrypt 4.1.0 | gcc-3.3.3 | SuSE Enterprise 9 | POWER4 1000 | 16 GB: 57.6 MB/s
BeeCrypt 4.1.0 | gcc-3.3.3 | Fedora Core 2 | P4 Xeon 2400 | 1 GB: 46.3 MB/s [--with-arch=pentium4]
BENCHmark Block Cipher (more is better):
AES, 128 bits
BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 97.0 MB/s [ECB encrypt]
BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 93.5 MB/s [CBC encrypt]
BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 104.6 MB/s [ECB decrypt]
BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 99.2 MB/s [CBC decrypt]
Blowfish, 128 bits
BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 59.4 MB/s [ECB encrypt]
BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 57.7 MB/s [CBC encrypt]
BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 61.4 MB/s [ECB decrypt]
BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 59.3 MB/s [CBC decrypt]

View file

@ -0,0 +1,69 @@
Legend:
- = open bug
* = fixed bug
4.1.0:
- SuSE 9.2 (x86) compiler is buggy: the MMX-optimized version fails all
test vectors. Since all other Linux distro's handle this perfectly it's
up to them to fix this bug.
3.1.0:
* Error in final result computation of mpextgcd_w in certain circumstances.
* PowerPC 64-bit assembler symbols aren't defined according to LSB 1.3.
3.0.0:
- Can't seem to generate 64-bit shared libraries on AIX; use
--disable-shared on this platform for now.
- Intel icc can't cope with gcj headers. There's also a problem in
combination with aio.h; solution should be to not test gcj when using
this compiler. As a workaround, you can specify --without-javaglue.
- GCC 3.3 produces faster output for Blowfish on Pentium 4 than the
included assembler source; try coding two Blowfish rounds (without swap)
in C and compile to assembler to see how GCC accomplishes this.
2.3.0pre:
* bug in certain instances of computing modular inverse.
* incorrectly translated intel-style assembler version of x86 mp32odd
and mp32even routines into gnu assembler format.
* base64 decoding of '+' and '/' characters is wrong.
* incorrect testing of the result of the gcd operation in mp32prndconone.
* Chinese Remainer Theorem for RSA private key operation doesn't work
* incorrect header file inclusion when --disable-threads is selected or
when no multithreading is available.
2.2.0:
[ Released by Jeff Johnson of RedHat, Inc.; lint & doxygen enhanced version
of 2.1.0. ]
2.1.0:
* Entropy gathering from /dev/dsp contained error; size in words of entropy
data to gather was overwritten with audio sample size - which resulted in
much less entropy.
2.0.0:
- Chinese Remainder Theorem for RSA private key operation doesn't work; it
needs fixing.
1.1.2:
* SHA-1 i586 assembler code uses local variables below the current stack
frame.
1.1.1:
* discrete logarithm domain parameter generator calculations contains bugs
- was detected in this release but present since the first release.
1.1.0:
* The javaglue produces a NullPointerException when initializing with a
null IV; this should be treated correctly, i.e. as an all zero IV.
1.0.2:
1.0.1:
* The Windows 2000 bug is still around
1.0.0:
* On Windows 2000, the entropy system gets error WAVERR_BADFORMAT in
waveInOpen; So far I've been unable to determine why the system does this
for format WAVE_FORMAT_PCM. Suggestions to fix this problem are more than
welcome.
* The assembler code for SHA-1 in gnu/fips180opt.gas.i586.s contains bugs.

View file

@ -0,0 +1,19 @@
I would like to thank the following people (in alphabetical order):
- Seth Arnold, for contributing to the documentation.
- Jan-Rudolph Bührmann, for helping me get started on the 64-bit multi-
precision integer library.
- Luca Filipozzi, maintainer/packager of BeeCrypt for Debian GNU/Linux.
- Jeff Johnson, the guy behind RedHat's Package Manager, who has inspired
and contributed to many of the changes for version 3.0.0; 73 de Bob.
- Jon Sturgeon, bug hunter extraordinaire.
Further thanks go to:
- AMD, for donating a copy of "AMD x86-64 Architecture Programmer's Manual".
- ARM Ltd, for donating a copy of "ARM Architecture Reference Manual".
- HP/Compaq, for their testdrive program, which gave me the opportunity to
test and BeeCrypt on many new platforms.
- SourceForge, for their excellent open source development platform!
Last but not least: thanks to everyone who provided bits of information,
reported bugs and provided feedback.

View file

@ -0,0 +1,336 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Hereny it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Section

View file

@ -0,0 +1,504 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View file

@ -0,0 +1,187 @@
Basic Installation
==================
The `configure' shell script attempts to guess correct values for
various system-dependent variables used during compilation. It uses
those values to create a `Makefile' in each directory of the package.
It may also create one or more `.h' files containing system-dependent
definitions. Finally, it creates a shell script `config.status' that
you can run in the future to recreate the current configuration, a file
`config.cache' that saves the results of its tests to speed up
reconfiguring, and a file `config.log' containing compiler output
(useful mainly for debugging `configure').
If you need to do unusual things to compile the package, please try
to figure out how `configure' could check whether to do them, and mail
diffs or instructions to the address given in the `README' so they can
be considered for the next release. If at some point `config.cache'
contains results you don't want to keep, you may remove or edit it.
The file `configure.in' is used to create `configure' by a program
called `autoconf'. You only need `configure.in' if you want to change
it or regenerate `configure' using a newer version of `autoconf'.
The simplest way to compile this package is:
1. `cd' to the directory containing the package's source code and type
`./configure' to configure the package for your system. If you're
using `csh' on an old version of System V, you might need to type
`sh ./configure' instead to prevent `csh' from trying to execute
`configure' itself.
Running `configure' takes awhile. While running, it prints some
messages telling which features it is checking for.
2. Type `make' to compile the package.
If you're building GNU make on a system which does not already have
a `make', you can use the build.sh shell script to compile. Run
`sh ./build.sh'. This should compile the program in the current
directory. Then you will have a Make program that you can use for
`make install', or whatever else.
3. Optionally, type `./make check' to run any self-tests that come with
the package.
4. Type `make install' to install the programs and any data files and
documentation.
5. You can remove the program binaries and object files from the
source code directory by typing `make clean'. To also remove the
files that `configure' created (so you can compile the package for
a different kind of computer), type `make distclean'. There is
also a `make maintainer-clean' target, but that is intended mainly
for the package's developers. If you use it, you may have to get
all sorts of other programs in order to regenerate files that came
with the distribution.
Compilers and Options
=====================
Some systems require unusual options for compilation or linking that
the `configure' script does not know about. You can give `configure'
initial values for variables by setting them in the environment. Using
a Bourne-compatible shell, you can do that on the command line like
this:
CC=c89 CFLAGS=-O2 LIBS=-lposix ./configure
Or on systems that have the `env' program, you can do it like this:
env CPPFLAGS=-I/usr/local/include LDFLAGS=-s ./configure
Compiling For Multiple Architectures
====================================
You can compile the package for more than one kind of computer at the
same time, by placing the object files for each architecture in their
own directory. To do this, you must use a version of `make' that
supports the `VPATH' variable, such as GNU `make'. `cd' to the
directory where you want the object files and executables to go and run
the `configure' script. `configure' automatically checks for the
source code in the directory that `configure' is in and in `..'.
If you have to use a `make' that does not supports the `VPATH'
variable, you have to compile the package for one architecture at a time
in the source code directory. After you have installed the package for
one architecture, use `make distclean' before reconfiguring for another
architecture.
Installation Names
==================
By default, `make install' will install the package's files in
`/usr/local/bin', `/usr/local/man', etc. You can specify an
installation prefix other than `/usr/local' by giving `configure' the
option `--prefix=PATH'.
You can specify separate installation prefixes for
architecture-specific files and architecture-independent files. If you
give `configure' the option `--exec-prefix=PATH', the package will use
PATH as the prefix for installing programs and libraries.
Documentation and other data files will still use the regular prefix.
In addition, if you use an unusual directory layout you can give
options like `--bindir=PATH' to specify different values for particular
kinds of files. Run `configure --help' for a list of the directories
you can set and what kinds of files go in them.
If the package supports it, you can cause programs to be installed
with an extra prefix or suffix on their names by giving `configure' the
option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'.
Optional Features
=================
Some packages pay attention to `--enable-FEATURE' options to
`configure', where FEATURE indicates an optional part of the package.
They may also pay attention to `--with-PACKAGE' options, where PACKAGE
is something like `gnu-as' or `x' (for the X Window System). The
`README' should mention any `--enable-' and `--with-' options that the
package recognizes.
For packages that use the X Window System, `configure' can usually
find the X include and library files automatically, but if it doesn't,
you can use the `configure' options `--x-includes=DIR' and
`--x-libraries=DIR' to specify their locations.
Specifying the System Type
==========================
There may be some features `configure' can not figure out
automatically, but needs to determine by the type of host the package
will run on. Usually `configure' can figure that out, but if it prints
a message saying it can not guess the host type, give it the
`--host=TYPE' option. TYPE can either be a short name for the system
type, such as `sun4', or a canonical name with three fields:
CPU-COMPANY-SYSTEM
See the file `config.sub' for the possible values of each field. If
`config.sub' isn't included in this package, then this package doesn't
need to know the host type.
If you are building compiler tools for cross-compiling, you can also
use the `--target=TYPE' option to select the type of system they will
produce code for and the `--build=TYPE' option to select the type of
system on which you are compiling the package.
Sharing Defaults
================
If you want to set default values for `configure' scripts to share,
you can create a site shell script called `config.site' that gives
default values for variables like `CC', `cache_file', and `prefix'.
`configure' looks for `PREFIX/share/config.site' if it exists, then
`PREFIX/etc/config.site' if it exists. Or, you can set the
`CONFIG_SITE' environment variable to the location of the site script.
A warning: not all `configure' scripts look for a site script.
Operation Controls
==================
`configure' recognizes the following options to control how it
operates.
`--cache-file=FILE'
Use and save the results of the tests in FILE instead of
`./config.cache'. Set FILE to `/dev/null' to disable caching, for
debugging `configure'.
`--help'
Print a summary of the options to `configure', and exit.
`--quiet'
`--silent'
`-q'
Do not print messages saying which checks are being made. To
suppress all normal output, redirect it to `/dev/null' (any error
messages will still be shown).
`--srcdir=DIR'
Look for the package's source code in directory DIR. Usually
`configure' can determine that directory automatically.
`--version'
Print the version of Autoconf used to generate the `configure'
script, and exit.
`configure' also accepts some other, not widely useful, options.

View file

@ -0,0 +1,184 @@
4.1.2:
- Fixed Cygwin DLL missing symbols problem.
- Fixed GNU-stack assembler section on some platforms (Debian-ARM).
- Fixed problem cause by include of <asm/byteorder.h>.
- Fixed SHA-384 and SHA-512 code Visual C++ compatibility.
- Improved detection of IBM ICU library version; has to be >= 2.8.
4.1.1:
- Fixed shared library version info.
4.1.0:
- Added SHA-384 and SHA-512 algorithms.
- Added HMAC-SHA-384 and HMAC-SHA-512 algorithms.
- Added generic SSE2 optimization for the above algorithms.
- Added more digest algorithms for PKCS#1 EMSA.
- Optimized swap32 and swap64 routines on Linux.
- Fixed missing definition in mpopt.h for s390x.
- Fixed nostackexec configuration bug.
- Fixed problem in Date::toString.
- Fixed deadlock problem which occured in certain cases where security
or crypto SPI constructor called getInstance for another security or
crypto SPI.
- Fixed a bug in the generic CBC encryption code; when called with
nblocks == 1, the feedback was set incorrectly.
- Fixed a bug in mpbsubmod; sometimes it takes multiple additions of
the modulus to get a positive number.
- Fixed PowerPC 64-bit configuration problem on Linux.
4.0.0:
- Added a C++ API interface, modeled after Java's security & crypto API.
- Added the new GNU noexecstack feature.
- Added more x86_64 and s390x assembler routines.
- Modified i2osp, so that it only requires as many octets as there are
significant bytes in the multi-precision integers.
- Fixed a bug in the creation of rsa keypairs; code was not correctly
migrated to new calling sequence. The code now implements the method
described in IEEE P.1363.
- Fixed another bug in mpextgcd_w which sometimes returned incorrect
results.
- Fixed a bug in mprshiftlsz, which didn't work correctly when size = 1.
- Fixed a configuration problem on Tru64 Unix.
3.1.0:
- Added wiping of private key components of keypairs before freeing.
- Fixed bug in mpextgcd_w which sometimes returned incorrect result.
- Fixed error in PowerPC 64-bit assembler symbol definitions.
3.0.0:
- Cleaned up installed header files.
- Modified the API so that all keys can be passed as arrays of bytes.
- Modified the API so that all key sizes are given in bits.
- Modified the multi-precision integer library to work better on 64-bit
machines.
- Modified the assembly source generation mechanism, employing the m4
macro processor.
- Added multi-precision integer vectorized assembler routines for
Itanium.
- Added multi-precision integer assembler routines for PowerPC 64-bit.
- Added multi-precision integer assembler routines for Alpha.
- Added multi-precision integer assembler routines for Opteron.
- Added multi-precision integer assembler routines for IBM zSeries 64-bit.
- Added multi-precision integer assembler routines for M68K.
- Added Jeff Johnson's python bindings.
- Added new unit tests.
- Added new benchmarking programs.
2.3.0pre:
- Modified the header files so that the library now uses self-contained autoconf-generated configuration files; a program employing BeeCrypt can now use the symbols already tested and defined instead of having to regenerate them (thus also eliminating the risk of inconsistencies).
- Added the AES algorithm, with assembler routines for i586 and powerpc.
- Added the DSA signature algorithm.
- Added PowerPC assembler routines for blowfish.
- Added Pentium4 SSE2 assembler multiplication routines.
- Fixed the RSA CRT algorithm.
- Fixed the gas/i386 mp32even and mp32odd routines.
- Fixed a bug in modular inverse computation; thanks to Jeff Johnson of RedHat for pointing this out.
- Fixed a bug in testing the result of a gcd operation in the mp32prndconone routine.
- Fixed an ugly bug in base64 decoding.
- Fixed compatibility with the latest automake & autoconf versions.
- Replaces CPU optimization mechanism in configure script.
2.1.0:
- Added support for automake, autoheader and libtool, which should make compiling the library even easier.
- Changed DHAES API to conform to IEEE P.1363 submission and to allow for uneven key splitting.
- Improved PKCS#5 padding routines.
- Added a hash reset to the hashFunctionContextInit function. This was pointed out by Marko Kreen.
- Fixed problem with configuring on i486-pc-linux-gnu. This was pointed out Steve O'Neill.
- Fixed problem in the C version of mp32sub where carry would sometimes be missed. This was pointed out by Jon Sturgeon.
- Revised entropy gathering system to do timeouts & asynchronous I/O where possible, to avoid hangs in case there's no noise on the audio device (i.e. digital silence), or when no data is available on devices such as /dev/random.
- Changed mp32opt i386 assembler routines for slight performance improvement.
- Changed mp32opt powerpc assembler routines for slight performance improvement.
- Changed mp32opt sparcv9 assembler routines for slight performance improvement.
- Added sparcv8 assembler routines for multi-precision integer multiplication.
- Added arm assembler routines for multi-precision integer multiplication.
- Added prototype 64-bit ia64 assembler routines for multi-precision integer operations.
- Started writing the long-awaited documentation.
2.0.0:
- Changed mp32barrett struct and operations to be multithread-safe; this required a change in API.
- Changed hashFunction struct to incorporate internal block size parameter.
- Changed HMAC algorithm and file names to match names in RFC 2104.
- Changed SHA-1 C code for slightly faster results.
- Changed detection of entropy devices.
- Changed most void-returning functions to return int for error conditions.
- Changed beecrypt-java class names in javaglue.
- Added RSA keypair generation.
- Added RSA private & public key operations.
- Added SHA-256 hash function.
- Added HMAC-MD5 and HMAC-SHA-256 keyed hash functions.
- Added PKCS#5 padding.
- Added DHAES encryption scheme.
- Added Microsoft Visual C support, added Makefile.mak for this purpose.
- Added Solaris/Sparc Forte C 64 bit support.
- Added configure --disable-optimized option (disables assembler & processor-specific optimizations).
- Fixed bug in SHA-1 assembler code for Pentium, where local variables were used below the current stack pointer; this could cause a problem if the routine was interrupted. This was pointed out by Richard Clayton.
- Fixed bug in (certain cases of) modular inverse computation.
- Fixed buffer overrun in base64 encoding. This was pointed out by Jon Sturgeon.
- Fixed various minor bugs.
- Renamed text files to match automake conventions.
1.1.2:
- Fixed bugs in discrete logarithm domain parameter generator. The code to make a generator of order q and (p-1) was wrong. This was pointed out by Susumu Yamamoto.
- Added MD5 hash function.
1.1.1:
- Changed autoconfig script for easier porting.
- Changed sources for easier compilation on Microsoft Visual C++; no assembler-optimization on this platform yet.
- Fixed bug in javaglue when passing null IV to blockcipher.
- Shared library is now linked dynamically, with shared object name and version.
- Tested on Alpha Linux.
- Tested on Alpha FreeBSD.
- Added support for Compaq Alpha Tru64 Unix.
- Added initial support for QNX.
1.1.0:
- Added glue for interfacing from BeeCrypt Java Cryptography Provider.
- Changed blockcipher struct to support interfacing with Java.
- Added better blockcipher IV handling.
- Multi-pass block processing is now possible with blockEncrypt/blockDecrypt.
- Updated config.sub and config.guess to latest version from sources.redhat.com
- Changed opening of entropy devices to blocking read-only mode instead of non-blocking read-write.
- Added win32 'wincrypt' entropy source.
- Added win32 'console' entropy source.
- Added FreeBSD support.
- Added PowerPC assembler optimized multiprecision subtraction routines.
- Added initial ia64 support.
- Added initial Darwin support (everything compiles, but the shared library doesn't build yet).
1.0.2:
- Fixed Windows 2000 entropy bug; instead of using the first waveIn device, entropy now uses WAVE_MAPPER.
- Added sparcv9 mp32addsqrtrc GNU assembler routine.
- Added more hashFunctionContext and keyedHashFunctionContext functions.
1.0.1:
- Added a sliding window modular exponentiation, about 30% faster than left-to-right exponentiation.
- Fixed bugs in fips180opt.gas.i586.s (Linux SHA-1 assembler code for Pentium/Pentium Pro) - the Windows/Metrowerks version was okay.
1.0.0:
- Added Win32 support; compiled as DLL with MetroWerks CodeWarrior Pro 5, it runs fine on Windows 95, 98, NT 4.0 (if you have a soundcard with a microphone port). Note that there is a know issue on Windows 2000, see BUGS.
- Global code overhaul to support Win32
- Added more assembler routines, including SHA-1 for Pentium Pro (60% faster)
- Added cleanup function to randomGenerator
- Added missing functions in endianness.c
- Fixed bug in entropy.c where devices might stay open
- Eliminated mutex.h include file; it was more clear to do everything conditionally than to expand the macros in this file to encompass the Win32 API calls.
0.9.5:
- Added PowerPC assembler optimization for multiprecision integers, 80% faster on our PowerMac 7200/90
- Fixed /dev/random entropy provider
- Changed name SHA1 to SHA-1 in fips180 for consistency
0.9.4a:
- Added missing file 'blowfishopt.o'
0.9.4:
- Changes to configure script, to distinguish between different processors of the x86 family
- Changes to blowfish code, 586/686 assembler optimization added, 30% faster on Pentium/PentiumPro
- Changes to blowfish code, eliminated static blowfishSetupEncrypt; incorporated into regular encrypt
- Changes to Makefile to selectively use blowfish assember code, depending on cpu type
- Added missing routines 'mp32bzero' and 'mp32bnpowmod' to mp32barrett.c
- Fixed 'const register' to 'register const' in mp32.c
- Minor fixes in included header files
0.9.3:
- Initial public release

View file

@ -0,0 +1,143 @@
Welcome to the BeeCrypt crypto library!
Copyright (c) 1997, 1998, 1999, 2000, 2001 Virtual Unlimited B.V.
Copyright (c) 2002, 2003, Bob Deblier (for certain parts)
Author: Bob Deblier <bob.deblier@pandora.be>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
For the specifics of this license, see file 'COPYING.LIB', included in
this distribution.
Welcome to version 3.0.0 of BeeCrypt:
AES support has been added, and the library has been thoroughly debugged,
with the addition of unit tests. Once you've built the library, you can
verify the correct functioning with 'make check'.
Multi-precision integer routines should now perform dramatically better
an 64-bit processors, especially Alpha and Itanium.
Benchmarks can be obtained with 'make bench'.
As usual, your comments are welcome.
About BeeCrypt:
This library is an ongoing project of Virtual Unlimited B.V. Its goal is
to provide strong and fast cryptography for use by our products, but
we're not limiting the use to that. We're releasing it under the LGPL
license, because we feel that cryptography should be open to inspection
by everybody, and available for use by everybody to safeguard privacy.
Note that depending on where you are, the use of cryptography may be
limited or forbidden by law. Before using this library, make sure you
are legally entitled to do so.
For more on Virtual Unlimited B.V. and our products please consult our
website: http://www.virtualunlimited.com/
<plug>
Most of the algorithms are implemented from reliable sources such as:
"Handbook of Applied Cryptography"
Alfred J. Menezes, Paul C. van Oorschot, Scott A. Vanstone
CRC Press
"Applied Cryptography", second edition
Bruce Schneier
Wiley
For crypto enthusiasts these books are invaluable background material.
IEEE P1363 "Standard Specifications for Public Key Cryptography" is a
very interesting draft standard, which we will try to comply with.
</plug>
The structures in the library are geared towards exchange with Java
and its security and cryptography classes. This library can also be
accessed from Java by installing BeeCrypt for Java, a JCE 1.2 crypto
provider and the counterpart of this library.
Included in the library are:
- entropy sources for initializing pseudo-random generators
- pseudo-random generators: FIPS-186, Mersenne Twister
- block ciphers: AES, Blowfish
- hash functions: MD5, SHA-1, SHA-256
- keyed hash functions: HMAC-MD5, HMAC-SHA-1, HMAC-SHA-256
- multi-precision integer library, with assembler-optimized routines
for several processors
- probabilistic primality testing, with optimized small prime trial
division
- discrete logarithm parameter generation over a prime field
- Diffie-Hellman key agreement
- DSA signature scheme
- ElGamal signature scheme (two variants)
- RSA keypair generation with chinese remainder theorem variables
- RSA public & private key operations
- DHAES encryption scheme
Planned for the near future are:
- compliance with and compliance statements for IEEE P1363
- more blockciphers (Twofish, ... )
- more hash functions (RIPEMD-160, SHA-384, SHA-512, HAVAL, Tiger)
- RSA signatures as specified by RFC-2440.
- Elliptic Curves (ECDSA, ... )
- more blockcipher modes (OFB, ... )
The library has been tested on the following platforms:
- AIX 5.1 ppc
- AIX 5.1 ppc64
- Darwin 6.5 (a.k.a. MacOS X 10.2)
- FreeBSD 4.0 alpha
- FreeBSD 4.0, 4.2 x86
- Linux glibc 2.x alpha
- Linux glibc 2.x arm
- Linux glibc 2.x ia64
- Linux glibc 2.x ppc
- Linux glibc 2.x sparc
- Linux glibc 2.x x86
- Solaris 2.6/2.7/2.8/2.9 sparc (with Forte or gnu compilers)
- Solaris 2.7/2.8 x86 (with Forte or GNU compilers)
- Tru64 Unix alpha
- Win32 (Windows 95, 98, NT 4.0, 2000, XP)
The library is currently in the process of being ported to:
- Cygwin (Can't seem to get the DLL to build properly with the current
version of the autotools)
- HP/UX is a pain in the backside; I'll try getting it working, but the
configure script doesn't seem capable of properly detecting gettimeofday.
For more information, refer to the HTML documentation in the docs directory.
If you want to report bugs, make suggestions, contribute fixes or
enhancements, please see the beecrypt-specific website:
http://sourceforge.net/projects/beecrypt
or contact me at mailto:bob.deblier@pandora.be
Sincerely,
Bob Deblier

View file

@ -0,0 +1,37 @@
File beetest.exe is a compiled version of the test program included in
the source distribution, which you can find on our website:
http://beecrypt.virtualunlimited.com/
To run, it needs file beecrypt.dll present in the same directory.
For Developers:
Files beecrypt.dll and beecrypt.lib are a pre-compiled version of the
BeeCrypt library for Pentium Pro processors.
If you want to develop applications with this library, you'll also need
the header files, included in the source distribution (see higher).
Please make sure you respect the term of the license under which the
BeeCrypt library is released:
Copyright (c) 1997, 1998, 1999, 2000, 2001 Virtual Unlimited B.V.
Author: Bob Deblier <bob@virtualunlimited.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
For the specifics of this license, see file 'COPYING', included in this
distribution.

View file

@ -0,0 +1,43 @@
This file contains information on how to build and use the BeeCrypt DLL on
Win32 platforms.
The platform of preference is currently MicroSoft Visual C++ 6.0, but
Metrowerks CodeWarrior is also still supported.
To be able to use the assembler files with Visual C++, you need to have the
Visual C++ 6.0 Processor Pack installed. It can be found at:
http://msdn.microsoft.com/vstudio/downloads/ppack/default.asp
To be able to use the assembler files with Metrowerks CodeWarrior, you will
need to install an unsupported (but working for the included files) assembler
plug-in, which can be found on the CodeWarrior download page.
To build the java glue into the DLL, you should also have Sun's JDK 1.3,
including the JNI headers, installed.
Make sure all Visual C++ tools can be found on the path, i.e.:
cl.exe (the compiler)
ml.exe (the assembler)
link.exe (the linker)
nmake.exe (the make utility)
For convenience, copy file 'Makefile.mak' to 'Makefile' and adjust paths as
required. The Makefile assumes you will be building in support for java.
If this is not the case, you will have to adjust the Makefile, which shouldn't
be too difficult.
Next, run 'nmake' and the library and the test program will be built.
Once running, you can use any of three entropy source available on this
platform, in order of preference:
wavein (uses noise on the soundcard microphone port)
console (uses keyboard clicks with a high resolution timer)
wincrypt (uses random data generated by the Windows CryptAPI)
To enable a specific entropy device, set variable BEECRYPT_ENTROPY to any of
these three values; if not specified, the library will use 'wavein' as default.
In the future, additional sources of entropy on this platform will be made available.

View file

@ -0,0 +1,89 @@
/*
* Copyright (c) 2001, 2002, 2004 Beeyond Software Holding BV
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*!\file api.h
* \brief BeeCrypt API, portability headers.
* \author Bob Deblier <bob.deblier@pandora.be>
*/
#ifndef _BEECRYPT_API_H
#define _BEECRYPT_API_H
#if defined(_WIN32) && !defined(WIN32)
# define WIN32 1
#endif
#if WIN32
# if !__CYGWIN32__
# include "beecrypt/win.h"
# else
# include "beecrypt/gnu.h"
# endif
# ifdef BEECRYPT_DLL_EXPORT
# define BEECRYPTAPI //__declspec(dllexport)
# else
# define BEECRYPTAPI //__declspec(dllimport)
# endif
# ifdef BEECRYPT_CXX_DLL_EXPORT
# define BEECRYPTCXXAPI //__declspec(dllexport)
# define BEECRYPTCXXTEMPLATE
# else
# define BEECRYPTCXXAPI //__declspec(dllimport)
# define BEECRYPTCXXTEMPLATE extern
# endif
#else
# include "beecrypt/gnu.h"
# define BEECRYPTAPI
# define BEECRYPTCXXAPI
#endif
#ifndef ROTL32
# define ROTL32(x, s) (((x) << (s)) | ((x) >> (32 - (s))))
#endif
#ifndef ROTR32
# define ROTR32(x, s) (((x) >> (s)) | ((x) << (32 - (s))))
#endif
#ifndef ROTR64
# define ROTR64(x, s) (((x) >> (s)) | ((x) << (64 - (s))))
#endif
typedef uint8_t byte;
typedef int8_t javabyte;
typedef int16_t javashort;
typedef int32_t javaint;
typedef int64_t javalong;
typedef uint16_t javachar;
#if (MP_WBITS == 64)
typedef uint64_t mpw;
typedef uint32_t mphw;
#elif (MP_WBITS == 32)
# if HAVE_UINT64_T
# define HAVE_MPDW 1
typedef uint64_t mpdw;
# endif
typedef uint32_t mpw;
typedef uint16_t mphw;
#else
# error
#endif
#endif

View file

@ -0,0 +1,799 @@
/*
* Copyright (c) 1999, 2000, 2001, 2002 Virtual Unlimited B.V.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*!\file beecrypt.h
* \brief BeeCrypt API, headers.
*
* These API functions provide an abstract way for using most of
* the various algorithms implemented by the library.
*
* \author Bob Deblier <bob.deblier@pandora.be>
* \ingroup ES_m PRNG_m HASH_m HMAC_m BC_m
*/
#ifndef _BEECRYPT_H
#define _BEECRYPT_H
#include "beecrypt/api.h"
#include "beecrypt/memchunk.h"
#include "beecrypt/mpnumber.h"
/*
* Entropy Sources
*/
/*!\typedef entropyNext
* \brief Prototype definition for an entropy-generating function.
* \ingroup ES_m
*/
typedef int (*entropyNext)(byte*, size_t);
/*!\brief This struct holds information and pointers to code specific to each
* source of entropy.
* \ingroup ES_m
*/
#ifdef __cplusplus
struct BEECRYPTAPI entropySource
#else
struct _entropySource
#endif
{
/*!\var name
* \brief The entropy source's name.
*/
const char* name;
/*!\var next
* \brief Points to the function which produces the entropy.
*/
const entropyNext next;
};
#ifndef __cplusplus
typedef struct _entropySource entropySource;
#endif
#ifdef __cplusplus
extern "C" {
#endif
/*!\fn int entropySourceCount()
* \brief This function returns the number of entropy sources implemented by
* the library.
* \return The number of implemented entropy sources.
*/
BEECRYPTAPI
int entropySourceCount(void);
/*!\fn const entropySource* entropySourceGet(int n)
* \brief This function returns the \a n -th entropy source implemented by
* the library.
* \param n Index of the requested entropy source; legal values are 0
* through entropySourceCount() - 1.
* \return A pointer to an entropy source or null, if the index was out of
* range.
*/
BEECRYPTAPI
const entropySource* entropySourceGet(int n);
/*!\fn const entropySource* entropySourceFind(const char* name)
* \brief This function returns the entropy source specified by the given name.
* \param name Name of the requested entropy source.
* \return A pointer to an entropy source or null, if the name wasn't found.
*/
BEECRYPTAPI
const entropySource* entropySourceFind(const char* name);
/*!\fn const entropySource* entropySourceDefault()
* \brief This functions returns the default entropy source; the default value
* can be specified by setting environment variable BEECRYPT_ENTROPY.
* \return A pointer to an entropy source or null, in case an error occured.
*/
BEECRYPTAPI
const entropySource* entropySourceDefault(void);
/*!\fn int entropyGatherNext(byte* data, size_t size)
* \brief This function gathers \a size bytes of entropy into \a data.
*
* Unless environment variable BEECRYPT_ENTROPY is set, this function will
* try each successive entropy source to gather up the requested amount.
*
* \param data Points to where the entropy should be stored.
* \param size Indicates how many bytes of entropy should be gathered.
* \retval 0 On success.
* \retval -1 On failure.
*/
BEECRYPTAPI
int entropyGatherNext(byte*, size_t);
#ifdef __cplusplus
}
#endif
/*
* Pseudo-random Number Generators
*/
typedef void randomGeneratorParam;
typedef int (*randomGeneratorSetup )(randomGeneratorParam*);
typedef int (*randomGeneratorSeed )(randomGeneratorParam*, const byte*, size_t);
typedef int (*randomGeneratorNext )(randomGeneratorParam*, byte*, size_t);
typedef int (*randomGeneratorCleanup)(randomGeneratorParam*);
/*
* The struct 'randomGenerator' holds information and pointers to code specific
* to each random generator. Each specific random generator MUST be written to
* be multithread safe.
*
* WARNING: each randomGenerator, when used in cryptographic applications, MUST
* be guaranteed to be of suitable quality and strength (i.e. don't use the
* random() function found in most UN*X-es).
*
* Multiple instances of each randomGenerator can be used (even concurrently),
* provided they each use their own randomGeneratorParam parameters, a chunk
* of memory which must be at least as large as indicated by the paramsize
* field.
*
*/
/*!\brief This struct holds information and pointers to code specific to each
* pseudo-random number generator.
* \ingroup PRNG_m
*/
#ifdef __cplusplus
struct BEECRYPTAPI randomGenerator
#else
struct _randomGenerator
#endif
{
/*!\var name
* \brief The random generator's name.
*/
const char* name;
/*!\var paramsize
* \brief The size of the random generator's parameters.
* \note The implementor should set this by using sizeof(<struct holding
* random generator's parameters>).
*/
const size_t paramsize;
/*!\var setup
* \brief Points to the setup function.
*/
const randomGeneratorSetup setup;
/*!\var seed
* \brief Points to the seeding function.
*/
const randomGeneratorSeed seed;
/*!\var seed
* \brief Points to the function which generates the random data.
*/
const randomGeneratorNext next;
/*!\var seed
* \brief Points to the cleanup function.
*/
const randomGeneratorCleanup cleanup;
};
#ifndef __cplusplus
typedef struct _randomGenerator randomGenerator;
#endif
/*
* You can use the following functions to find random generators implemented by
* the library:
*
* randomGeneratorCount returns the number of generators available.
*
* randomGeneratorGet returns the random generator with a given index (starting
* at zero, up to randomGeneratorCount() - 1), or NULL if the index was out of
* bounds.
*
* randomGeneratorFind returns the random generator with the given name, or
* NULL if no random generator exists with that name.
*/
#ifdef __cplusplus
extern "C" {
#endif
BEECRYPTAPI
int randomGeneratorCount(void);
BEECRYPTAPI
const randomGenerator* randomGeneratorGet(int);
BEECRYPTAPI
const randomGenerator* randomGeneratorFind(const char*);
BEECRYPTAPI
const randomGenerator* randomGeneratorDefault(void);
#ifdef __cplusplus
}
#endif
/*
* The struct 'randomGeneratorContext' is used to contain both the functional
* part (the randomGenerator), and its parameters.
*/
#ifdef __cplusplus
struct BEECRYPTAPI randomGeneratorContext
#else
struct _randomGeneratorContext
#endif
{
const randomGenerator* rng;
randomGeneratorParam* param;
#ifdef __cplusplus
randomGeneratorContext();
randomGeneratorContext(const randomGenerator*);
~randomGeneratorContext();
#endif
};
#ifndef __cplusplus
typedef struct _randomGeneratorContext randomGeneratorContext;
#endif
/*
* The following functions can be used to initialize and free a
* randomGeneratorContext. Initializing will allocate a buffer of the size
* required by the randomGenerator, freeing will deallocate that buffer.
*/
#ifdef __cplusplus
extern "C" {
#endif
BEECRYPTAPI
int randomGeneratorContextInit(randomGeneratorContext*, const randomGenerator*);
BEECRYPTAPI
int randomGeneratorContextFree(randomGeneratorContext*);
BEECRYPTAPI
int randomGeneratorContextNext(randomGeneratorContext*, byte*, size_t);
BEECRYPTAPI
int randomGeneratorContextSeed(randomGeneratorContext*, const byte*, size_t);
#ifdef __cplusplus
}
#endif
/*
* Hash Functions
*/
/*!typedef void hashFunctionParam
* \ingroup HASH_m
*/
typedef void hashFunctionParam;
typedef int (*hashFunctionReset )(hashFunctionParam*);
typedef int (*hashFunctionUpdate)(hashFunctionParam*, const byte*, size_t);
typedef int (*hashFunctionDigest)(hashFunctionParam*, byte*);
/*
* The struct 'hashFunction' holds information and pointers to code specific
* to each hash function. Specific hash functions MAY be written to be
* multithread-safe.
*
* NOTE: data MUST have a size (in bytes) of at least 'digestsize' as described
* in the hashFunction struct.
* NOTE: for safety reasons, after calling digest, each specific implementation
* MUST reset itself so that previous values in the parameters are erased.
*/
#ifdef __cplusplus
struct BEECRYPTAPI hashFunction
#else
struct _hashFunction
#endif
{
const char* name;
const size_t paramsize; /* in bytes */
const size_t blocksize; /* in bytes */
const size_t digestsize; /* in bytes */
const hashFunctionReset reset;
const hashFunctionUpdate update;
const hashFunctionDigest digest;
};
#ifndef __cplusplus
typedef struct _hashFunction hashFunction;
#endif
/*
* You can use the following functions to find hash functions implemented by
* the library:
*
* hashFunctionCount returns the number of hash functions available.
*
* hashFunctionGet returns the hash function with a given index (starting
* at zero, up to hashFunctionCount() - 1), or NULL if the index was out of
* bounds.
*
* hashFunctionFind returns the hash function with the given name, or
* NULL if no hash function exists with that name.
*/
#ifdef __cplusplus
extern "C" {
#endif
BEECRYPTAPI
int hashFunctionCount(void);
BEECRYPTAPI
const hashFunction* hashFunctionGet(int);
BEECRYPTAPI
const hashFunction* hashFunctionFind(const char*);
BEECRYPTAPI
const hashFunction* hashFunctionDefault(void);
#ifdef __cplusplus
}
#endif
/*
* The struct 'hashFunctionContext' is used to contain both the functional
* part (the hashFunction), and its parameters.
*/
#ifdef __cplusplus
struct BEECRYPTAPI hashFunctionContext
#else
struct _hashFunctionContext
#endif
{
const hashFunction* algo;
hashFunctionParam* param;
#ifdef __cplusplus
hashFunctionContext();
hashFunctionContext(const hashFunction*);
~hashFunctionContext();
#endif
};
#ifndef __cplusplus
typedef struct _hashFunctionContext hashFunctionContext;
#endif
/*
* The following functions can be used to initialize and free a
* hashFunctionContext. Initializing will allocate a buffer of the size
* required by the hashFunction, freeing will deallocate that buffer.
*/
#ifdef __cplusplus
extern "C" {
#endif
BEECRYPTAPI
int hashFunctionContextInit(hashFunctionContext*, const hashFunction*);
BEECRYPTAPI
int hashFunctionContextFree(hashFunctionContext*);
BEECRYPTAPI
int hashFunctionContextReset(hashFunctionContext*);
BEECRYPTAPI
int hashFunctionContextUpdate(hashFunctionContext*, const byte*, size_t);
BEECRYPTAPI
int hashFunctionContextUpdateMC(hashFunctionContext*, const memchunk*);
BEECRYPTAPI
int hashFunctionContextUpdateMP(hashFunctionContext*, const mpnumber*);
BEECRYPTAPI
int hashFunctionContextDigest(hashFunctionContext*, byte*);
BEECRYPTAPI
int hashFunctionContextDigestMP(hashFunctionContext*, mpnumber*);
BEECRYPTAPI
int hashFunctionContextDigestMatch(hashFunctionContext*, const mpnumber*);
#ifdef __cplusplus
}
#endif
/*
* Keyed Hash Functions, a.k.a. Message Authentication Codes
*/
/*!\typedef void keyedHashFunctionParam
* \ingroup HMAC_m
*/
typedef void keyedHashFunctionParam;
typedef int (*keyedHashFunctionSetup )(keyedHashFunctionParam*, const byte*, size_t);
typedef int (*keyedHashFunctionReset )(keyedHashFunctionParam*);
typedef int (*keyedHashFunctionUpdate )(keyedHashFunctionParam*, const byte*, size_t);
typedef int (*keyedHashFunctionDigest )(keyedHashFunctionParam*, byte*);
/*
* The struct 'keyedHashFunction' holds information and pointers to code
* specific to each keyed hash function. Specific keyed hash functions MAY be
* written to be multithread-safe.
*
* The struct field 'keybitsmin' contains the minimum number of bits a key
* must contains, 'keybitsmax' the maximum number of bits a key may contain,
* 'keybitsinc', the increment in bits that may be used between min and max.
*
* NOTE: data must be at least have a bytesize of 'digestsize' as described
* in the keyedHashFunction struct.
* NOTE: for safety reasons, after calling digest, each specific implementation
* MUST reset itself so that previous values in the parameters are erased.
*/
#ifdef __cplusplus
struct BEECRYPTAPI keyedHashFunction
#else
struct _keyedHashFunction
#endif
{
const char* name;
const size_t paramsize; /* in bytes */
const size_t blocksize; /* in bytes */
const size_t digestsize; /* in bytes */
const size_t keybitsmin; /* in bits */
const size_t keybitsmax; /* in bits */
const size_t keybitsinc; /* in bits */
const keyedHashFunctionSetup setup;
const keyedHashFunctionReset reset;
const keyedHashFunctionUpdate update;
const keyedHashFunctionDigest digest;
};
#ifndef __cplusplus
typedef struct _keyedHashFunction keyedHashFunction;
#endif
/*
* You can use the following functions to find keyed hash functions implemented
* by the library:
*
* keyedHashFunctionCount returns the number of keyed hash functions available.
*
* keyedHashFunctionGet returns the keyed hash function with a given index
* (starting at zero, up to keyedHashFunctionCount() - 1), or NULL if the index
* was out of bounds.
*
* keyedHashFunctionFind returns the keyed hash function with the given name,
* or NULL if no keyed hash function exists with that name.
*/
#ifdef __cplusplus
extern "C" {
#endif
BEECRYPTAPI
int keyedHashFunctionCount(void);
BEECRYPTAPI
const keyedHashFunction* keyedHashFunctionGet(int);
BEECRYPTAPI
const keyedHashFunction* keyedHashFunctionFind(const char*);
BEECRYPTAPI
const keyedHashFunction* keyedHashFunctionDefault(void);
#ifdef __cplusplus
}
#endif
/*
* The struct 'keyedHashFunctionContext' is used to contain both the functional
* part (the keyedHashFunction), and its parameters.
*/
#ifdef __cplusplus
struct BEECRYPTAPI keyedHashFunctionContext
#else
struct _keyedHashFunctionContext
#endif
{
const keyedHashFunction* algo;
keyedHashFunctionParam* param;
#ifdef __cplusplus
keyedHashFunctionContext();
keyedHashFunctionContext(const keyedHashFunction*);
~keyedHashFunctionContext();
#endif
};
#ifndef __cplusplus
typedef struct _keyedHashFunctionContext keyedHashFunctionContext;
#endif
/*
* The following functions can be used to initialize and free a
* keyedHashFunctionContext. Initializing will allocate a buffer of the size
* required by the keyedHashFunction, freeing will deallocate that buffer.
*/
#ifdef __cplusplus
extern "C" {
#endif
BEECRYPTAPI
int keyedHashFunctionContextInit(keyedHashFunctionContext*, const keyedHashFunction*);
BEECRYPTAPI
int keyedHashFunctionContextFree(keyedHashFunctionContext*);
BEECRYPTAPI
int keyedHashFunctionContextSetup(keyedHashFunctionContext*, const byte*, size_t);
BEECRYPTAPI
int keyedHashFunctionContextReset(keyedHashFunctionContext*);
BEECRYPTAPI
int keyedHashFunctionContextUpdate(keyedHashFunctionContext*, const byte*, size_t);
BEECRYPTAPI
int keyedHashFunctionContextUpdateMC(keyedHashFunctionContext*, const memchunk*);
BEECRYPTAPI
int keyedHashFunctionContextUpdateMP(keyedHashFunctionContext*, const mpnumber*);
BEECRYPTAPI
int keyedHashFunctionContextDigest(keyedHashFunctionContext*, byte*);
BEECRYPTAPI
int keyedHashFunctionContextDigestMP(keyedHashFunctionContext*, mpnumber*);
BEECRYPTAPI
int keyedHashFunctionContextDigestMatch(keyedHashFunctionContext*, const mpnumber*);
#ifdef __cplusplus
}
#endif
/*
* Block ciphers
*/
/*!\enum cipherOperation
* \brief Specifies whether to perform encryption or decryption.
* \ingroup BC_m
*/
typedef enum
{
NOCRYPT,
ENCRYPT,
DECRYPT
} cipherOperation;
/*!\typedef void blockCipherParam
* \brief Placeholder type definition for blockcipher parameters.
* \sa aesParam, blowfishParam.
* \ingroup BC_m
*/
typedef void blockCipherParam;
/*!\brief Prototype definition for a setup function.
* \ingroup BC_m
*/
typedef int (*blockCipherSetup )(blockCipherParam*, const byte*, size_t, cipherOperation);
/*!\typedef int (*blockCipherSetIV)(blockCipherParam* bp, const byte* iv)
* \brief Prototype definition for an initialization vector setup function.
* \param bp The blockcipher's parameters.
* \param iv The blockciphers' IV value.
* \note iv length must be equal to the cipher's block size.
* \retval 0 on success.
* \retval -1 on failure.
* \ingroup BC_m
*/
typedef int (*blockCipherSetIV )(blockCipherParam*, const byte*);
/*!\typedef int (*blockCipherRawcrypt)(blockCipherParam* bp, uint32_t* dst, const uint32_t* src)
* \brief Prototype for a \e raw encryption or decryption function.
* \param bp The blockcipher's parameters.
* \param dst The ciphertext address; must be aligned on 32-bit boundary.
* \param src The cleartext address; must be aligned on 32-bit boundary.
* \retval 0 on success.
* \retval -1 on failure.
* \ingroup BC_m
*/
typedef int (*blockCipherRawcrypt)(blockCipherParam*, uint32_t*, const uint32_t*);
/*!\typedef int (*blockCipherModcrypt)(blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks)
* \brief Prototype for a \e encryption or decryption function which operates
* on multiple blocks in a certain mode.
* \param bp The blockcipher's parameters.
* \param dst The ciphertext address; must be aligned on 32-bit boundary.
* \param src The cleartext address; must be aligned on 32-bit boundary.
* \param nblocks The number of blocks to process.
* \retval 0 on success.
* \retval -1 on failure.
* \ingroup BC_m
*/
typedef int (*blockCipherModcrypt)(blockCipherParam*, uint32_t*, const uint32_t*, unsigned int);
typedef uint32_t* (*blockCipherFeedback)(blockCipherParam*);
typedef struct
{
const blockCipherRawcrypt encrypt;
const blockCipherRawcrypt decrypt;
} blockCipherRaw;
typedef struct
{
const blockCipherModcrypt encrypt;
const blockCipherModcrypt decrypt;
} blockCipherMode;
/*!\brief Holds information and pointers to code specific to each cipher.
*
* Specific block ciphers \e may be written to be multithread-safe.
*
* \ingroup BC_m
*/
#ifdef __cplusplus
struct BEECRYPTAPI blockCipher
#else
struct _blockCipher
#endif
{
/*!\var name
* \brief The blockcipher's name.
*/
const char* name;
/*!\var paramsize
* \brief The size of the parameters required by this cipher, in bytes.
*/
const size_t paramsize;
/*!\var blocksize
* \brief The size of one block of data, in bytes.
*/
const size_t blocksize;
/*!\var keybitsmin
* \brief The minimum number of key bits.
*/
const size_t keybitsmin;
/*!\var keybitsmax
* \brief The maximum number of key bits.
*/
const size_t keybitsmax;
/*!\var keybitsinc
* \brief The allowed increment in key bits between min and max.
* \see keybitsmin and keybitsmax.
*/
const size_t keybitsinc;
/*!\var setup
* \brief Pointer to the cipher's setup function.
*/
const blockCipherSetup setup;
/*!\var setiv
* \brief Pointer to the cipher's initialization vector setup function.
*/
const blockCipherSetIV setiv;
/*!\var raw
* \brief The cipher's raw functions.
*/
const blockCipherRaw raw;
/*!\var ecb
* \brief The cipher's ECB functions.
*/
const blockCipherMode ecb;
const blockCipherMode cbc;
/*!\var getfb
* \brief Pointer to the cipher's feedback-returning function.
*/
const blockCipherFeedback getfb;
};
#ifndef __cplusplus
typedef struct _blockCipher blockCipher;
#endif
#ifdef __cplusplus
extern "C" {
#endif
/*!\fn int blockCipherCount()
* \brief This function returns the number of blockciphers implemented
* by the library.
* \return The number of implemented blockciphers.
*/
BEECRYPTAPI
int blockCipherCount(void);
/*!\fn const blockCipher* blockCipherGet(int n)
* \brief This function returns the \a n -th blockcipher implemented by
* the library.
* \param n Index of the requested blockcipher; legal values are 0
* through blockCipherCount() - 1.
* \return A pointer to a blockcipher or null, if the index was out of
* range.
*/
BEECRYPTAPI
const blockCipher* blockCipherGet(int);
/*!\fn const blockCipher* blockCipherFind(const char* name)
* \brief This function returns the blockcipher specified by the given name.
* \param name Name of the requested blockcipher.
* \return A pointer to a blockcipher or null, if the name wasn't found.
*/
BEECRYPTAPI
const blockCipher* blockCipherFind(const char*);
/*!\fn const blockCipher* blockCipherDefault()
* \brief This functions returns the default blockcipher; the default value
* can be specified by setting environment variable BEECRYPT_CIPHER.
* \return A pointer to a blockcipher or null, in case an error occured.
*/
BEECRYPTAPI
const blockCipher* blockCipherDefault(void);
#ifdef __cplusplus
}
#endif
/*!\brief Holds a pointer to a blockcipher as well as its parameters.
* \warning A context can be used by only one thread at the same time.
* \ingroup BC_m
*/
#ifdef __cplusplus
struct BEECRYPTAPI blockCipherContext
#else
struct _blockCipherContext
#endif
{
/*!\var algo
* \brief Pointer to a blockCipher.
*/
const blockCipher* algo;
/*!\var param
* \brief Pointer to the parameters used by algo.
*/
blockCipherParam* param;
/*!\var op
*/
cipherOperation op;
#ifdef __cplusplus
blockCipherContext();
blockCipherContext(const blockCipher*);
~blockCipherContext();
#endif
};
#ifndef __cplusplus
typedef struct _blockCipherContext blockCipherContext;
#endif
/*
* The following functions can be used to initialize and free a
* blockCipherContext. Initializing will allocate a buffer of the size
* required by the blockCipher, freeing will deallocate that buffer.
*/
#ifdef __cplusplus
extern "C" {
#endif
BEECRYPTAPI
int blockCipherContextInit(blockCipherContext*, const blockCipher*);
BEECRYPTAPI
int blockCipherContextSetup(blockCipherContext*, const byte*, size_t, cipherOperation);
BEECRYPTAPI
int blockCipherContextSetIV(blockCipherContext*, const byte*);
BEECRYPTAPI
int blockCipherContextFree(blockCipherContext*);
BEECRYPTAPI
int blockCipherContextECB(blockCipherContext*, uint32_t*, const uint32_t*, int);
BEECRYPTAPI
int blockCipherContextCBC(blockCipherContext*, uint32_t*, const uint32_t*, int);
BEECRYPTAPI
int blockCipherContextValidKeylen(blockCipherContext*, size_t);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,137 @@
/*
* Copyright (c) 2000, 2002 Virtual Unlimited B.V.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*!\file blockmode.c
* \brief Blockcipher operation modes.
* \author Bob Deblier <bob.deblier@pandora.be>
* \ingroup BC_m
*/
#define BEECRYPT_DLL_EXPORT
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "beecrypt/blockmode.h"
int blockEncryptECB(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks)
{
register const unsigned int blockwords = bc->blocksize >> 2;
while (nblocks > 0)
{
bc->raw.encrypt(bp, dst, src);
dst += blockwords;
src += blockwords;
nblocks--;
}
return 0;
}
int blockDecryptECB(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks)
{
register const unsigned int blockwords = bc->blocksize >> 2;
while (nblocks > 0)
{
bc->raw.decrypt(bp, dst, src);
dst += blockwords;
src += blockwords;
nblocks--;
}
return 0;
}
int blockEncryptCBC(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks)
{
register const unsigned int blockwords = bc->blocksize >> 2;
register uint32_t* fdback = bc->getfb(bp);
if (nblocks > 0)
{
register unsigned int i;
for (i = 0; i < blockwords; i++)
dst[i] = src[i] ^ fdback[i];
bc->raw.encrypt(bp, dst, dst);
nblocks--;
while (nblocks > 0)
{
for (i = 0; i < blockwords; i++)
dst[i+blockwords] = src[i+blockwords] ^ dst[i];
dst += blockwords;
bc->raw.encrypt(bp, dst, dst);
src += blockwords;
nblocks--;
}
for (i = 0; i < blockwords; i++)
fdback[i] = dst[i];
}
return 0;
}
int blockDecryptCBC(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks)
{
register const unsigned int blockwords = bc->blocksize >> 2;
register uint32_t* fdback = bc->getfb(bp);
register uint32_t* buf = (uint32_t*) malloc(blockwords * sizeof(uint32_t));
if (buf)
{
while (nblocks > 0)
{
register uint32_t tmp;
register unsigned int i;
bc->raw.decrypt(bp, buf, src);
for (i = 0; i < blockwords; i++)
{
tmp = src[i];
dst[i] = buf[i] ^ fdback[i];
fdback[i] = tmp;
}
dst += blockwords;
src += blockwords;
nblocks--;
}
free(buf);
return 0;
}
return -1;
}

View file

@ -0,0 +1,92 @@
/*
* Copyright (c) 2000, 2002 Virtual Unlimited B.V.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*!\file blockmode.h
* \brief Blockcipher operation modes.
* \todo Additional modes, such as CFB and OFB.
* \author Bob Deblier <bob.deblier@pandora.be>
* \ingroup BC_m
*/
#ifndef _BLOCKMODE_H
#define _BLOCKMODE_H
#include "beecrypt/beecrypt.h"
#ifdef __cplusplus
extern "C" {
#endif
/*!\fn int blockEncryptECB(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks)
* \brief This function encrypts a number of data blocks in Electronic Code
* Book mode.
* \param bc The blockcipher.
* \param bp The cipher's parameter block.
* \param dst The ciphertext data; should be aligned on a 32-bit boundary.
* \param src The cleartext data; should be aligned on a 32-bit boundary.
* \param nblocks The number of blocks to be encrypted.
* \retval 0 on success.
*/
BEECRYPTAPI
int blockEncryptECB(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks);
/*!\fn int blockDecryptECB(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks)
* \brief This function decrypts a number of data blocks in Electronic Code
* Book mode.
* \param bc The blockcipher.
* \param bp The cipher's parameter block.
* \param dst The cleartext data; should be aligned on a 32-bit boundary.
* \param src The ciphertext data; should be aligned on a 32-bit boundary.
* \param nblocks The number of blocks to be decrypted.
* \retval 0 on success.
*/
BEECRYPTAPI
int blockDecryptECB(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks);
/*!\fn int blockEncryptCBC(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks)
* \brief This function encrypts a number of data blocks in Cipher Block
* Chaining mode.
* \param bc The blockcipher.
* \param bp The cipher's parameter block.
* \param dst The ciphertext data; should be aligned on a 32-bit boundary.
* \param src The cleartext data; should be aligned on a 32-bit boundary.
* \param nblocks The number of blocks to be encrypted.
* \retval 0 on success.
*/
BEECRYPTAPI
int blockEncryptCBC(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks);
/*!\fn int blockDecryptCBC(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks)
* \brief This function decrypts a number of data blocks in Cipher Block
* Chaining mode.
* \param bc The blockcipher.
* \param bp The cipher's parameter block.
* \param dst The cleartext data; should be aligned on a 32-bit boundary.
* \param src The ciphertext data; should be aligned on a 32-bit boundary.
* \param nblocks The number of blocks to be decrypted.
* \retval 0 on success.
*/
BEECRYPTAPI
int blockDecryptCBC(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,509 @@
/*
* Copyright (c) 1999, 2000, 2002 Virtual Unlimited B.V.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*!\file blowfish.c
* \brief Blowfish block cipher.
* \author Bob Deblier <bob.deblier@pandora.be>
* \ingroup BC_m BC_blowfish_m
*/
#define BEECRYPT_DLL_EXPORT
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "beecrypt/blowfish.h"
#if HAVE_ENDIAN_H && HAVE_ASM_BYTEORDER_H
# include <endian.h>
#endif
#include "beecrypt/endianness.h"
#ifdef ASM_BLOWFISHENCRYPTECB
extern int blowfishEncryptECB(blowfishparam*, uint32_t*, const uint32_t*, unsigned int);
#endif
#ifdef ASM_BLOWFISHDECRYPTECB
extern int blowfishDecryptECB(blowfishparam*, uint32_t*, const uint32_t*, unsigned int);
#endif
static uint32_t _bf_p[BLOWFISHPSIZE] = {
0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
0x9216d5d9, 0x8979fb1b
};
static uint32_t _bf_s[1024] = {
0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
};
#define EROUND(l,r) l ^= *(p++); r ^= ((s[((l>>24)&0xff)+0x000]+s[((l>>16)&0xff)+0x100])^s[((l>>8)&0xff)+0x200])+s[((l>>0)&0xff)+0x300]
#define DROUND(l,r) l ^= *(p--); r ^= ((s[((l>>24)&0xff)+0x000]+s[((l>>16)&0xff)+0x100])^s[((l>>8)&0xff)+0x200])+s[((l>>0)&0xff)+0x300]
const blockCipher blowfish = {
"Blowfish",
sizeof(blowfishParam),
8,
64,
448,
32,
(blockCipherSetup) blowfishSetup,
(blockCipherSetIV) blowfishSetIV,
/* raw */
{
(blockCipherRawcrypt) blowfishEncrypt,
(blockCipherRawcrypt) blowfishDecrypt
},
/* ecb */
{
#ifdef AES_BLOWFISHENCRYPTECB
(blockCipherModcrypt) blowfishEncryptECB,
#else
(blockCipherModcrypt) 0,
#endif
#ifdef AES_BLOWFISHENCRYPTECB
(blockCipherModcrypt) blowfishDecryptECB,
#else
(blockCipherModcrypt) 0
#endif
},
/* cbc */
{
(blockCipherModcrypt) 0,
(blockCipherModcrypt) 0
},
(blockCipherFeedback) blowfishFeedback
};
int blowfishSetup(blowfishParam* bp, const byte* key, size_t keybits, cipherOperation op)
{
if ((op != ENCRYPT) && (op != DECRYPT))
return -1;
if (((keybits & 7) == 0) && (keybits >= 32) && (keybits <= 448))
{
register uint32_t* p = bp->p;
register uint32_t* s = bp->s;
register unsigned int i, j, k;
uint32_t tmp, work[2];
memcpy(s, _bf_s, 1024 * sizeof(uint32_t));
for (i = 0, k = 0; i < BLOWFISHPSIZE; i++)
{
tmp = 0;
for (j = 0; j < 4; j++)
{
tmp <<= 8;
tmp |= key[k++];
if (k >= (keybits >> 3))
k = 0;
}
p[i] = _bf_p[i] ^ tmp;
}
work[0] = work[1] = 0;
for (i = 0; i < BLOWFISHPSIZE; i += 2, p += 2)
{
blowfishEncrypt(bp, work, work);
#if WORDS_BIGENDIAN
p[0] = work[0];
p[1] = work[1];
#else
p[0] = swapu32(work[0]);
p[1] = swapu32(work[1]);
#endif
}
for (i = 0; i < 1024; i += 2, s += 2)
{
blowfishEncrypt(bp, work, work);
#if WORDS_BIGENDIAN
s[0] = work[0];
s[1] = work[1];
#else
s[0] = swapu32(work[0]);
s[1] = swapu32(work[1]);
#endif
}
/* clear fdback/iv */
bp->fdback[0] = 0;
bp->fdback[1] = 0;
return 0;
}
return -1;
}
#ifndef ASM_BLOWFISHSETIV
int blowfishSetIV(blowfishParam* bp, const byte* iv)
{
if (iv)
memcpy(bp->fdback, iv, 8);
else
memset(bp->fdback, 0, 8);
return 0;
}
#endif
int blowfishBlowit(blowfishParam* bp, uint32_t* dst, const uint32_t* src)
{
register uint32_t xl = src[0], xr = src[1];
register uint32_t* p = bp->p;
register uint32_t* s = bp->s;
EROUND(xl, xr); EROUND(xr, xl);
dst[1] = xr;
dst[0] = xl;
return 0;
}
#ifndef ASM_BLOWFISHENCRYPT
int blowfishEncrypt(blowfishParam* bp, uint32_t* dst, const uint32_t* src)
{
#if WORDS_BIGENDIAN
register uint32_t xl = src[0], xr = src[1];
#else
register uint32_t xl = swapu32(src[0]), xr = swapu32(src[1]);
#endif
register uint32_t* p = bp->p;
register uint32_t* s = bp->s;
EROUND(xl, xr); EROUND(xr, xl);
EROUND(xl, xr); EROUND(xr, xl);
EROUND(xl, xr); EROUND(xr, xl);
EROUND(xl, xr); EROUND(xr, xl);
EROUND(xl, xr); EROUND(xr, xl);
EROUND(xl, xr); EROUND(xr, xl);
EROUND(xl, xr); EROUND(xr, xl);
EROUND(xl, xr); EROUND(xr, xl);
#if WORDS_BIGENDIAN
dst[1] = xl ^ *(p++);
dst[0] = xr ^ *(p++);
#else
dst[1] = swapu32(xl ^ *(p++));
dst[0] = swapu32(xr ^ *(p++));
#endif
return 0;
}
#endif
#ifndef ASM_BLOWFISHDECRYPT
int blowfishDecrypt(blowfishParam* bp, uint32_t* dst, const uint32_t* src)
{
#if WORDS_BIGENDIAN
register uint32_t xl = src[0], xr = src[1];
#else
register uint32_t xl = swapu32(src[0]), xr = swapu32(src[1]);
#endif
register uint32_t* p = bp->p+BLOWFISHPSIZE-1;
register uint32_t* s = bp->s;
DROUND(xl, xr); DROUND(xr, xl);
DROUND(xl, xr); DROUND(xr, xl);
DROUND(xl, xr); DROUND(xr, xl);
DROUND(xl, xr); DROUND(xr, xl);
DROUND(xl, xr); DROUND(xr, xl);
DROUND(xl, xr); DROUND(xr, xl);
DROUND(xl, xr); DROUND(xr, xl);
DROUND(xl, xr); DROUND(xr, xl);
#if WORDS_BIGENDIAN
dst[1] = xl ^ *(p--);
dst[0] = xr ^ *(p--);
#else
dst[1] = swapu32(xl ^ *(p--));
dst[0] = swapu32(xr ^ *(p--));
#endif
return 0;
}
#endif
uint32_t* blowfishFeedback(blowfishParam* bp)
{
return bp->fdback;
}

View file

@ -0,0 +1,132 @@
/*
* Copyright (c) 1999, 2000, 2002 Virtual Unlimited B.V.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*!\file blowfish.h
* \brief Blowfish block cipher.
*
* For more information on this blockcipher, see:
* "Applied Cryptography", second edition
* Bruce Schneier
* Wiley & Sons
*
* Also see http://www.counterpane.com/blowfish.html
*
* \author Bob Deblier <bob.deblier@pandora.be>
* \ingroup BC_m BC_blowfish_m
*/
#ifndef _BLOWFISH_H
#define _BLOWFISH_H
#include "beecrypt/beecrypt.h"
#include "beecrypt/blowfishopt.h"
#define BLOWFISHROUNDS 16
#define BLOWFISHPSIZE (BLOWFISHROUNDS+2)
/*!\brief Holds all the parameters necessary for the Blowfish cipher.
* \ingroup BC_blowfish_m
*/
#ifdef __cplusplus
struct BEECRYPTAPI blowfishParam
#else
struct _blowfishParam
#endif
{
/*!\var p
* \brief Holds the key expansion.
*/
uint32_t p[BLOWFISHPSIZE];
/*!\var s
* \brief Holds the s-boxes.
*/
uint32_t s[1024];
/*!\var fdback
* \brief Buffer to be used by block chaining or feedback modes.
*/
uint32_t fdback[2];
};
#ifndef __cplusplus
typedef struct _blowfishParam blowfishParam;
#endif
#ifdef __cplusplus
extern "C" {
#endif
/*!\var blowfish
* \brief Holds the full API description of the Blowfish algorithm.
*/
extern const BEECRYPTAPI blockCipher blowfish;
/*!\fn int blowfishSetup(blowfishParam* bp, const byte* key, size_t keybits, cipherOperation
op)
* \brief The function performs the cipher's key expansion.
* \param bp The cipher's parameter block.
* \param key The key value.
* \param keybits The number of bits in the key; legal values are: 32 to 448,
* in multiples of 8.
* \param op ENCRYPT or DECRYPT.
* \retval 0 on success.
* \retval -1 on failure.
*/
BEECRYPTAPI
int blowfishSetup (blowfishParam*, const byte*, size_t, cipherOperation);
/*!\fn int blowfishSetIV(blowfishParam* bp, const byte* iv)
* \brief This function sets the Initialization Vector.
* \note This function is only useful in block chaining or feedback modes.
* \param bp The cipher's parameter block.
* \param iv The initialization vector; may be null.
* \retval 0 on success.
*/
BEECRYPTAPI
int blowfishSetIV (blowfishParam*, const byte*);
/*!\fn blowfishEncrypt(blowfishParam* bp, uint32_t* dst, const uint32_t* src)
* \brief This function performs the Blowfish encryption; it encrypts one block
* of 64 bits.
* \param bp The cipher's parameter block.
* \param dst The ciphertext; should be aligned on 32-bit boundary.
* \param src The cleartext; should be aligned on 32-bit boundary.
* \retval 0 on success.
*/
BEECRYPTAPI
int blowfishEncrypt (blowfishParam*, uint32_t*, const uint32_t*);
/*!\fn blowfishDecrypt(blowfishParam* bp, uint32_t* dst, const uint32_t* src)
* \brief This function performs the Blowfish decryption; it Rderypts one block
* of 64 bits.
* \param bp The cipher's parameter block.
* \param dst The cleartext; should be aligned on 32-bit boundary.
* \param src The ciphertext; should be aligned on 32-bit boundary.
* \retval 0 on success.
*/
BEECRYPTAPI
int blowfishDecrypt (blowfishParam*, uint32_t*, const uint32_t*);
BEECRYPTAPI
uint32_t* blowfishFeedback(blowfishParam*);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,82 @@
/*
* Copyright (c) 2000, 2002, 2003 Virtual Unlimited B.V.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*!\file blowfishopt.h
* \brief Blowfish block cipher, assembler-optimized routines, headers.
* \author Bob Deblier <bob.deblier@pandora.be>
* \ingroup BC_blowfish_m
*/
#ifndef _BLOWFISHOPT_H
#define _BLOWFISHOPT_H
#include "beecrypt/beecrypt.h"
#include "beecrypt/blowfish.h"
#ifdef __cplusplus
extern "C" {
#endif
#if WIN32
# if defined(_MSC_VER) && defined(_M_IX86)
# define ASM_BLOWFISHENCRYPT
# define ASM_BLOWFISHDECRYPT
# elif __INTEL__ && __MWERKS__
# define ASM_BLOWFISHENCRYPT
# define ASM_BLOWFISHDECRYPT
# endif
#endif
#if defined(__GNUC__)
# if defined(OPTIMIZE_I586) || defined(OPTIMIZE_I686)
# define ASM_BLOWFISHENCRYPT
# define ASM_BLOWFISHDECRYPT
# endif
# if defined(OPTIMIZE_POWERPC)
# define ASM_BLOWFISHENCRYPT
# define ASM_BLOWFISHDECRYPT
# endif
#endif
#if defined(__IBMC__)
# if defined(OPTIMIZE_POWERPC)
# define ASM_BLOWFISHENCRYPT
# define ASM_BLOWFISHDECRYPT
# endif
#endif
#if defined(__INTEL_COMPILER)
# if defined(OPTIMIZE_I586) || defined(OPTIMIZE_I686)
# define ASM_BLOWFISHENCRYPT
# define ASM_BLOWFISHDECRYPT
# endif
#endif
#if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
/* nothing here yet */
#endif
#undef ASM_BLOWFISHENCRYPT
#undef ASM_BLOWFISHDECRYPT
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,94 @@
/*
* Copyright (c) 1998, 1999, 2000, 2001 Virtual Unlimited B.V.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*!\file endianness.c
* \brief Endian-dependant encoding/decoding.
* \author Bob Deblier <bob.deblier@pandora.be>
*/
#define BEECRYPT_DLL_EXPORT
#if HAVE_CONFIG_H
# include "config.h"
#endif
#if HAVE_ENDIAN_H && HAVE_ASM_BYTEORDER_H
# include <endian.h>
#endif
#include "beecrypt/endianness.h"
#undef swap16
#undef swapu16
#undef swap32
#undef swapu32
#undef swap64
#undef swapu64
int16_t swap16(int16_t n)
{
return ( ((n & 0xff) << 8) |
((n & 0xff00) >> 8) );
}
uint16_t swapu16(uint16_t n)
{
return ( ((n & 0xffU) << 8) |
((n & 0xff00U) >> 8) );
}
int32_t swap32(int32_t n)
{
return ( ((n & 0xff) << 24) |
((n & 0xff00) << 8) |
((n & 0xff0000) >> 8) |
((n & 0xff000000) >> 24) );
}
uint32_t swapu32(uint32_t n)
{
return ( ((n & 0xffU) << 24) |
((n & 0xff00U) << 8) |
((n & 0xff0000U) >> 8) |
((n & 0xff000000U) >> 24) );
}
int64_t swap64(int64_t n)
{
return ( ((n & (((int64_t) 0xff) )) << 56) |
((n & (((int64_t) 0xff) << 8)) << 40) |
((n & (((int64_t) 0xff) << 16)) << 24) |
((n & (((int64_t) 0xff) << 24)) << 8) |
((n & (((int64_t) 0xff) << 32)) >> 8) |
((n & (((int64_t) 0xff) << 40)) >> 24) |
((n & (((int64_t) 0xff) << 48)) >> 40) |
((n & (((int64_t) 0xff) << 56)) >> 56) );
}
uint64_t swapu64(uint64_t n)
{
return ( ((n & (((uint64_t) 0xff) )) << 56) |
((n & (((uint64_t) 0xff) << 8)) << 40) |
((n & (((uint64_t) 0xff) << 16)) << 24) |
((n & (((uint64_t) 0xff) << 24)) << 8) |
((n & (((uint64_t) 0xff) << 32)) >> 8) |
((n & (((uint64_t) 0xff) << 40)) >> 24) |
((n & (((uint64_t) 0xff) << 48)) >> 40) |
((n & (((uint64_t) 0xff) << 56)) >> 56) );
}

View file

@ -0,0 +1,128 @@
/*
* endianness.h
*
* Endian-dependant encoding/decoding, header
*
* Copyright (c) 1998, 1999, 2000, 2001, 2004 Beeyond Software Holding
*
* Author: Bob Deblier <bob.deblier@telenet.be>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifndef _ENDIANNESS_H
#define _ENDIANNESS_H
#include "beecrypt/beecrypt.h"
#if defined(__cplusplus) || HAVE_INLINE
static inline int16_t _swap16(int16_t n)
{
return ( ((n & 0xff) << 8) |
((n & 0xff00) >> 8) );
}
# define swap16(n) _swap16(n)
static inline uint16_t _swapu16(uint16_t n)
{
return ( ((n & 0xffU) << 8) |
((n & 0xff00U) >> 8) );
}
# define swapu16(n) _swap16(n)
# ifdef __arch__swab32
# define swap32(n) __arch__swab32(n)
# define swapu32(n) __arch__swab32(n)
# else
static inline int32_t _swap32(int32_t n)
{
return ( ((n & 0xff) << 24) |
((n & 0xff00) << 8) |
((n & 0xff0000) >> 8) |
((n & 0xff000000) >> 24) );
}
# define swap32(n) _swap32(n)
static inline uint32_t _swapu32(uint32_t n)
{
return ( ((n & 0xffU) << 24) |
((n & 0xff00U) << 8) |
((n & 0xff0000U) >> 8) |
((n & 0xff000000U) >> 24) );
}
# define swapu32(n) _swapu32(n)
# endif
# ifdef __arch__swab64
# define swap64(n) __arch__swab64(n)
# define swapu64(n) __arch__swab64(n)
# else
static inline int64_t _swap64(int64_t n)
{
return ( ((n & ((int64_t) 0xff) ) << 56) |
((n & ((int64_t) 0xff) << 8) << 40) |
((n & ((int64_t) 0xff) << 16) << 24) |
((n & ((int64_t) 0xff) << 24) << 8) |
((n & ((int64_t) 0xff) << 32) >> 8) |
((n & ((int64_t) 0xff) << 40) >> 24) |
((n & ((int64_t) 0xff) << 48) >> 40) |
((n & ((int64_t) 0xff) << 56) >> 56) );
}
# define swap64(n) _swap64(n)
static inline uint64_t _swapu64(uint64_t n)
{
return ( ((n & ((uint64_t) 0xff) ) << 56) |
((n & ((uint64_t) 0xff) << 8) << 40) |
((n & ((uint64_t) 0xff) << 16) << 24) |
((n & ((uint64_t) 0xff) << 24) << 8) |
((n & ((uint64_t) 0xff) << 32) >> 8) |
((n & ((uint64_t) 0xff) << 40) >> 24) |
((n & ((uint64_t) 0xff) << 48) >> 40) |
((n & ((uint64_t) 0xff) << 56) >> 56) );
}
# define swapu64(n) _swapu64(n)
# endif
#else
BEECRYPTAPI
int16_t swap16 (int16_t);
BEECRYPTAPI
uint16_t swapu16(uint16_t);
BEECRYPTAPI
int32_t swap32 (int32_t);
BEECRYPTAPI
uint32_t swapu32(uint32_t);
BEECRYPTAPI
int64_t swap64 (int64_t);
BEECRYPTAPI
uint64_t swapu64(uint64_t);
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,67 @@
/*
* Copyright (c) 2003 Bob Deblier
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifndef _BEECRYPT_GNU_H
#define _BEECRYPT_GNU_H
#include <inttypes.h>
#include <stdint.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dlfcn.h>
typedef pthread_cond_t bc_cond_t;
typedef pthread_mutex_t bc_mutex_t;
typedef pthread_t bc_thread_t;
#if defined(__GNUC__)
# if !defined(__GNUC_PREREQ__)
# define __GNUC_PREREQ__(maj, min) (__GNUC__ > (maj) || __GNUC__ == (maj) && __GNUC_MINOR__ >= (min))
# endif
#else
# define __GNUC__ 0
# define __GNUC_PREREQ__(maj, min) 0
#endif
/* WARNING: overriding this value is dangerous; some assembler routines
* make assumptions about the size set by the configure script
*/
#if !defined(MP_WBITS)
# define MP_WBITS 64U
#endif
#endif

View file

@ -0,0 +1,123 @@
/*
* Copyright (c) 1999, 2000, 2002 Virtual Unlimited B.V.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*!\file hmac.c
* \brief HMAC algorithm.
*
* \see RFC2104 HMAC: Keyed-Hashing for Message Authentication.
* H. Krawczyk, M. Bellare, R. Canetti.
*
* \author Bob Deblier <bob.deblier@pandore.be>
* \ingroup HMAC_m
*/
#define BEECRYPT_DLL_EXPORT
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "beecrypt/hmac.h"
#include "beecrypt/endianness.h"
/*!\addtogroup HMAC_m
* \{
*/
#define HMAC_IPAD 0x36
#define HMAC_OPAD 0x5c
int hmacSetup(byte* kxi, byte* kxo, const hashFunction* hash, hashFunctionParam* param, const byte* key, size_t keybits)
{
register unsigned int i;
size_t keybytes = keybits >> 3;
/* if the key is too large, hash it first */
if (keybytes > hash->blocksize)
{
/* if the hash digest is too large, this doesn't help; this is really a sanity check */
if (hash->digestsize > hash->blocksize)
return -1;
if (hash->reset(param))
return -1;
if (hash->update(param, key, keybytes))
return -1;
if (hash->digest(param, kxi))
return -1;
memcpy(kxo, kxi, keybytes = hash->digestsize);
}
else if (keybytes > 0)
{
memcpy(kxi, key, keybytes);
memcpy(kxo, key, keybytes);
}
else
return -1;
for (i = 0; i < keybytes; i++)
{
kxi[i] ^= HMAC_IPAD;
kxo[i] ^= HMAC_OPAD;
}
for (i = keybytes; i < hash->blocksize; i++)
{
kxi[i] = HMAC_IPAD;
kxo[i] = HMAC_OPAD;
}
return hmacReset(kxi, hash, param);
}
int hmacReset(const byte* kxi, const hashFunction* hash, hashFunctionParam* param)
{
if (hash->reset(param))
return -1;
if (hash->update(param, kxi, hash->blocksize))
return -1;
return 0;
}
int hmacUpdate(const hashFunction* hash, hashFunctionParam* param, const byte* data, size_t size)
{
return hash->update(param, data, size);
}
int hmacDigest(const byte* kxo, const hashFunction* hash, hashFunctionParam* param, byte* data)
{
if (hash->digest(param, data))
return -1;
if (hash->update(param, kxo, hash->blocksize))
return -1;
if (hash->update(param, data, hash->digestsize))
return -1;
if (hash->digest(param, data))
return -1;
return 0;
}
/*!\}
*/

View file

@ -0,0 +1,53 @@
/*
* Copyright (c) 1999, 2000, 2002 Virtual Unlimited B.V.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*!\file hmac.h
* \brief HMAC algorithm, headers.
* \author Bob Deblier <bob.deblier@pandora.be>
* \ingroup HMAC_m
*/
#ifndef _HMAC_H
#define _HMAC_H
#include "beecrypt/beecrypt.h"
/*!\ingroup HMAC_m
*/
#ifdef __cplusplus
extern "C" {
#endif
/* not used directly as keyed hash function, but instead used as generic methods */
BEECRYPTAPI
int hmacSetup ( byte*, byte*, const hashFunction*, hashFunctionParam*, const byte*, size_t);
BEECRYPTAPI
int hmacReset (const byte*, const hashFunction*, hashFunctionParam*);
BEECRYPTAPI
int hmacUpdate( const hashFunction*, hashFunctionParam*, const byte*, size_t);
BEECRYPTAPI
int hmacDigest( const byte*, const hashFunction*, hashFunctionParam*, byte*);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,77 @@
/*
* Copyright (c) 1999, 2000, 2001, 2002 Virtual Unlimited B.V.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*!\file hmacsha1.c
* \brief HMAC-SHA-1 message authentication code.
*
* \see RFC2202 - Test Cases for HMAC-MD5 and HMAC-SHA-1.
* P. Cheng, R. Glenn.
*
* \author Bob Deblier <bob.deblier@pandora.be>
* \ingroup HMAC_m HMAC_sha1_m
*/
#define BEECRYPT_DLL_EXPORT
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "beecrypt/hmacsha1.h"
/*!\addtogroup HMAC_sha1_m
* \{
*/
const keyedHashFunction hmacsha1 = {
"HMAC-SHA-1",
sizeof(hmacsha1Param),
64,
20,
64,
512,
32,
(keyedHashFunctionSetup) hmacsha1Setup,
(keyedHashFunctionReset) hmacsha1Reset,
(keyedHashFunctionUpdate) hmacsha1Update,
(keyedHashFunctionDigest) hmacsha1Digest
};
int hmacsha1Setup (hmacsha1Param* sp, const byte* key, size_t keybits)
{
return hmacSetup(sp->kxi, sp->kxo, &sha1, &sp->sparam, key, keybits);
}
int hmacsha1Reset (hmacsha1Param* sp)
{
return hmacReset(sp->kxi, &sha1, &sp->sparam);
}
int hmacsha1Update(hmacsha1Param* sp, const byte* data, size_t size)
{
return hmacUpdate(&sha1, &sp->sparam, data, size);
}
int hmacsha1Digest(hmacsha1Param* sp, byte* data)
{
return hmacDigest(sp->kxo, &sha1, &sp->sparam, data);
}
/*!\}
*/

View file

@ -0,0 +1,60 @@
/*
* Copyright (c) 1999, 2000, 2001, 2002 Virtual Unlimited B.V.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*!\file hmacsha1.h
* \brief HMAC-SHA-1 message authentication code, headers.
* \author Bob Deblier <bob.deblier@pandora.be>
* \ingroup HMAC_m HMAC_sha1_m
*/
#ifndef _HMACSHA1_H
#define _HMACSHA1_H
#include "beecrypt/hmac.h"
#include "beecrypt/sha1.h"
/*!\ingroup HMAC_sha1_m
*/
typedef struct
{
sha1Param sparam;
byte kxi[64];
byte kxo[64];
} hmacsha1Param;
#ifdef __cplusplus
extern "C" {
#endif
extern BEECRYPTAPI const keyedHashFunction hmacsha1;
BEECRYPTAPI
int hmacsha1Setup (hmacsha1Param*, const byte*, size_t);
BEECRYPTAPI
int hmacsha1Reset (hmacsha1Param*);
BEECRYPTAPI
int hmacsha1Update(hmacsha1Param*, const byte*, size_t);
BEECRYPTAPI
int hmacsha1Digest(hmacsha1Param*, byte*);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,53 @@
/*
* Copyright (c) 2001 Virtual Unlimited B.V.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*!\file memchunk.h
* \author Bob Deblier <bob.deblier@pandora.be>
*/
#ifndef _MEMCHUNK_H
#define _MEMCHUNK_H
#include "beecrypt/api.h"
typedef struct
{
size_t size;
byte* data;
} memchunk;
#ifdef __cplusplus
extern "C" {
#endif
BEECRYPTAPI
memchunk* memchunkAlloc(size_t);
BEECRYPTAPI
void memchunkWipe(memchunk*);
BEECRYPTAPI
void memchunkFree(memchunk*);
BEECRYPTAPI
memchunk* memchunkResize(memchunk*, size_t);
BEECRYPTAPI
memchunk* memchunkClone(const memchunk*);
#ifdef __cplusplus
}
#endif
#endif

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,691 @@
/*
* Copyright (c) 2002, 2003 Bob Deblier
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*!\file mp.h
* \brief Multi-precision integer routines.
*
* The routines declared here are all low-level operations, most of them
* suitable to be implemented in assembler. Prime candidates are in order
* of importance (according to gprof):
* <ul>
* <li>mpaddmul
* <li>mpsetmul
* <li>mpaddsqrtrc
* <li>mpsub
* <li>mpadd
* </ul>
*
* With some smart use of available assembler instructions, it's possible
* to speed these routines up by a factor of 2 to 4.
*
* \author Bob Deblier <bob.deblier@pandora.be>
* \ingroup MP_m
*/
#ifndef _MP_H
#define _MP_H
#include "beecrypt/api.h"
#include "beecrypt/mpopt.h"
#define MP_HWBITS (MP_WBITS >> 1)
#define MP_WBYTES (MP_WBITS >> 3)
#define MP_WNIBBLES (MP_WBITS >> 2)
#if (MP_WBITS == 64)
# define MP_WORDS_TO_BITS(x) ((x) << 6)
# define MP_WORDS_TO_NIBBLES(x) ((x) << 4)
# define MP_WORDS_TO_BYTES(x) ((x) << 3)
# define MP_BITS_TO_WORDS(x) ((x) >> 6)
# define MP_NIBBLES_TO_WORDS(x) ((x) >> 4)
# define MP_BYTES_TO_WORDS(x) ((x) >> 3)
#elif (MP_WBITS == 32)
# define MP_WORDS_TO_BITS(x) ((x) << 5)
# define MP_WORDS_TO_NIBBLES(x) ((x) << 3)
# define MP_WORDS_TO_BYTES(x) ((x) << 2)
# define MP_BITS_TO_WORDS(x) ((x) >> 5)
# define MP_NIBBLES_TO_WORDS(x) ((x) >> 3)
# define MP_BYTES_TO_WORDS(x) ((x) >> 2)
#else
# error
#endif
#define MP_MSBMASK (((mpw) 0x1) << (MP_WBITS-1))
#define MP_LSBMASK ((mpw) 0x1)
#define MP_ALLMASK ~((mpw) 0x0)
#ifdef __cplusplus
extern "C" {
#endif
#ifndef ASM_MPCOPY
# define mpcopy(size, dst, src) memcpy(dst, src, MP_WORDS_TO_BYTES(size))
#else
BEECRYPTAPI
void mpcopy(size_t size, mpw* dest, const mpw* src);
#endif
#ifndef ASM_MPMOVE
# define mpmove(size, dst, src) memmove(dst, src, MP_WORDS_TO_BYTES(size))
#else
BEECRYPTAPI
void mpmove(size_t size, mpw* dest, const mpw* src);
#endif
/*!\fn void mpzero(size_t size, mpw* data)
* \brief This function zeroes a multi-precision integer of a given size.
* \param size The size of the multi-precision integer.
* \param data The multi-precision integer data.
*/
BEECRYPTAPI
void mpzero(size_t size, mpw* data);
/*!\fn void mpfill(size_t size, mpw* data, mpw fill)
* \brief This function fills each word of a multi-precision integer with a
* given value.
* \param size The size of the multi-precision integer.
* \param data The multi-precision integer data.
* \param fill The value fill the data with.
*/
BEECRYPTAPI
void mpfill(size_t size, mpw* data, mpw fill);
/*!\fn int mpodd(size_t size, const mpw* data)
* \brief This functions tests if a multi-precision integer is odd.
* \param size The size of the multi-precision integer.
* \param data The multi-precision integer data.
* \retval 1 if odd
* \retval 0 if even
*/
BEECRYPTAPI
int mpodd (size_t size, const mpw* data);
/*!\fn int mpeven(size_t size, const mpw* data)
* \brief This function tests if a multi-precision integer is even.
* \param size The size of the multi-precision integer.
* \param data The multi-precision integer data.
* \retval 1 if even
* \retval 0 if odd
*/
BEECRYPTAPI
int mpeven(size_t size, const mpw* data);
/*!\fn int mpz(size_t size, const mpw* data)
* \brief This function tests if a multi-precision integer is zero.
* \param size The size of the multi-precision integer.
* \param data The multi-precision integer data.
* \retval 1 if zero
* \retval 0 if not zero
*/
BEECRYPTAPI
int mpz (size_t size, const mpw* data);
/*!\fn int mpnz(size_t size, const mpw* data)
* \brief This function tests if a multi-precision integer is not zero.
* \param size The size of the multi-precision integer.
* \param data The multi-precision integer data.
* \retval 1 if not zero
* \retval 0 if zero
*/
BEECRYPTAPI
int mpnz (size_t size, const mpw* data);
/*!\fn int mpeq(size_t size, const mpw* xdata, const mpw* ydata)
* \brief This function tests if two multi-precision integers of the same size
* are equal.
* \param size The size of the multi-precision integers.
* \param xdata The first multi-precision integer.
* \param ydata The second multi-precision integer.
* \retval 1 if equal
* \retval 0 if not equal
*/
BEECRYPTAPI
int mpeq (size_t size, const mpw* xdata, const mpw* ydata);
/*!\fn int mpne(size_t size, const mpw* xdata, const mpw* ydata)
* \brief This function tests if two multi-precision integers of the same size
* differ.
* \param size The size of the multi-precision integers.
* \param xdata The first multi-precision integer.
* \param ydata The second multi-precision integer.
* \retval 1 if not equal
* \retval 0 if equal
*/
BEECRYPTAPI
int mpne (size_t size, const mpw* xdata, const mpw* ydata);
/*!\fn int mpgt(size_t size, const mpw* xdata, const mpw* ydata)
* \brief This function tests if the first of two multi-precision integers
* of the same size is greater than the second.
* \note The comparison treats the arguments as unsigned.
* \param size The size of the multi-precision integers.
* \param xdata The first multi-precision integer.
* \param ydata The second multi-precision integer.
* \retval 1 if greater
* \retval 0 if less or equal
*/
BEECRYPTAPI
int mpgt (size_t size, const mpw* xdata, const mpw* ydata);
/*!\fn int mplt(size_t size, const mpw* xdata, const mpw* ydata)
* \brief This function tests if the first of two multi-precision integers
* of the same size is less than the second.
* \note The comparison treats the arguments as unsigned.
* \param size The size of the multi-precision integers.
* \param xdata The first multi-precision integer.
* \param ydata The second multi-precision integer.
* \retval 1 if less
* \retval 0 if greater or equal
*/
BEECRYPTAPI
int mplt (size_t size, const mpw* xdata, const mpw* ydata);
/*!\fn int mpge(size_t size, const mpw* xdata, const mpw* ydata)
* \brief This function tests if the first of two multi-precision integers
* of the same size is greater than or equal to the second.
* \note The comparison treats the arguments as unsigned.
* \param size The size of the multi-precision integers.
* \param xdata The first multi-precision integer.
* \param ydata The second multi-precision integer.
* \retval 1 if greater or equal
* \retval 0 if less
*/
BEECRYPTAPI
int mpge (size_t size, const mpw* xdata, const mpw* ydata);
/*!\fn int mple(size_t size, const mpw* xdata, const mpw* ydata)
* \brief This function tests if the first of two multi-precision integers
* of the same size is less than or equal to the second.
* \note The comparison treats the arguments as unsigned.
* \param size The size of the multi-precision integers.
* \param xdata The first multi-precision integer.
* \param ydata The second multi-precision integer.
* \retval 1 if less or equal
* \retval 0 if greater
*/
BEECRYPTAPI
int mple (size_t size, const mpw* xdata, const mpw* ydata);
/*!\fn int mpeqx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
* \brief This function tests if two multi-precision integers of different
* size are equal.
* \param xsize The size of the first multi-precision integer.
* \param xdata The first multi-precision integer.
* \param ysize The size of the first multi-precision integer.
* \param ydata The second multi-precision integer.
* \retval 1 if equal
* \retval 0 if not equal
*/
BEECRYPTAPI
int mpeqx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata);
/*!\fn int mpnex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
* \brief This function tests if two multi-precision integers of different
* size are equal.
* \param xsize The size of the first multi-precision integer.
* \param xdata The first multi-precision integer.
* \param ysize The size of the first multi-precision integer.
* \param ydata The second multi-precision integer.
* \retval 1 if equal
* \retval 0 if not equal
*/
BEECRYPTAPI
int mpnex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata);
/*!\fn int mpgtx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
* \brief This function tests if the first of two multi-precision integers
* of different size is greater than the second.
* \note The comparison treats the arguments as unsigned.
* \param xsize The size of the first multi-precision integer.
* \param xdata The first multi-precision integer.
* \param ysize The size of the second multi-precision integer.
* \param ydata The second multi-precision integer.
* \retval 1 if greater
* \retval 0 if less or equal
*/
BEECRYPTAPI
int mpgtx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata);
/*!\fn int mpltx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
* \brief This function tests if the first of two multi-precision integers
* of different size is less than the second.
* \note The comparison treats the arguments as unsigned.
* \param xsize The size of the first multi-precision integer.
* \param xdata The first multi-precision integer.
* \param ysize The size of the second multi-precision integer.
* \param ydata The second multi-precision integer.
* \retval 1 if less
* \retval 0 if greater or equal
*/
BEECRYPTAPI
int mpltx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata);
/*!\fn int mpgex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
* \brief This function tests if the first of two multi-precision integers
* of different size is greater than or equal to the second.
* \note The comparison treats the arguments as unsigned.
* \param xsize The size of the first multi-precision integer.
* \param xdata The first multi-precision integer.
* \param ysize The size of the second multi-precision integer.
* \param ydata The second multi-precision integer.
* \retval 1 if greater or equal
* \retval 0 if less
*/
BEECRYPTAPI
int mpgex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata);
/*!\fn int mplex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
* \brief This function tests if the first of two multi-precision integers
* of different size is less than or equal to the second.
* \note The comparison treats the arguments as unsigned.
* \param xsize The size of the first multi-precision integer.
* \param xdata The first multi-precision integer.
* \param ysize The size of the second multi-precision integer.
* \param ydata The second multi-precision integer.
* \retval 1 if less or equal
* \retval 0 if greater
*/
BEECRYPTAPI
int mplex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata);
/*!\fn int mpisone(size_t size, const mpw* data)
* \brief This functions tests if the value of a multi-precision integer is
* equal to one.
* \param size The size of the multi-precision integer.
* \param data The multi-precision integer data.
* \retval 1 if one
* \retval 0 if not one
*/
BEECRYPTAPI
int mpisone(size_t size, const mpw* data);
/*!\fn int mpistwo(size_t size, const mpw* data)
* \brief This function tests if the value of a multi-precision integer is
* equal to two.
* \param size The size of the multi-precision integer.
* \param data The multi-precision integer data.
* \retval 1 if two
* \retval 0 if not two
*/
BEECRYPTAPI
int mpistwo(size_t size, const mpw* data);
/*!\fn int mpleone(size_t size, const mpw* data);
* \brief This function tests if the value of a multi-precision integer is
* less than or equal to one.
* \param size The size of the multi-precision integer.
* \param data The multi-precision integer data.
* \retval 1 if less than or equal to one.
* \retval 0 if greater than one.
*/
BEECRYPTAPI
int mpleone(size_t size, const mpw* data);
/*!\fn int mpeqmone(size_t size, const mpw* xdata, const mpw* ydata);
* \brief This function tests if multi-precision integer x is equal to y
* minus one.
* \param size The size of the multi-precision integers.
* \param xdata The first multi-precision integer.
* \param ydata The second multi-precision integer.
* \retval 1 if less than or equal to one.
* \retval 0 if greater than one.
*/
BEECRYPTAPI
int mpeqmone(size_t size, const mpw* xdata, const mpw* ydata);
/*!\fn int mpmsbset(size_t size, const mpw* data)
* \brief This function tests if the most significant bit of a multi-precision
* integer is set.
* \param size The size of the multi-precision integer.
* \param data The multi-precision integer data.
* \retval 1 if set
* \retval 0 if not set
*/
BEECRYPTAPI
int mpmsbset(size_t size, const mpw* data);
/*!\fn int mplsbset(size_t size, const mpw* data)
* \brief This function tests if the leiast significant bit of a multi-precision
* integer is set.
* \param size The size of the multi-precision integer.
* \param data The multi-precision integer data.
* \retval 1 if set
* \retval 0 if not set
*/
BEECRYPTAPI
int mplsbset(size_t size, const mpw* data);
/*!\fn void mpsetmsb(size_t size, mpw* data)
* \brief This function sets the most significant bit of a multi-precision
* integer.
* \param size The size of the multi-precision integer.
* \param data The multi-precision integer data.
*/
BEECRYPTAPI
void mpsetmsb(size_t size, mpw* data);
/*!\fn void mpsetlsb(size_t size, mpw* data)
* \brief This function sets the least significant bit of a multi-precision
* integer.
* \param size The size of the multi-precision integer.
* \param data The multi-precision integer data.
*/
BEECRYPTAPI
void mpsetlsb(size_t size, mpw* data);
/*!\fn void mpclrmsb(size_t size, mpw* data)
* \brief This function clears the most significant bit of a multi-precision
* integer.
* \param size The size of the multi-precision integer.
* \param data The multi-precision integer data.
*/
BEECRYPTAPI
void mpclrmsb(size_t size, mpw* data);
/*!\fn void mpclrlsb(size_t size, mpw* data)
* \brief This function clears the least significant bit of a multi-precision
* integer.
* \param size The size of the multi-precision integer.
* \param data The multi-precision integer data.
*/
BEECRYPTAPI
void mpclrlsb(size_t size, mpw* data);
/*!\fn mpand(size_t size, mpw* xdata, const mpw* ydata)
* \brief This function computes the bit-wise AND of two multi-precision
* integers. Modifies xdata.
* \param size The size of the multi-precision integers.
* \param xdata The multi-precision integer data.
* \param ydata The multi-precision integer data.
*/
BEECRYPTAPI
void mpand(size_t size, mpw* xdata, const mpw* ydata);
/*!\fn void mpor(size_t size, mpw* xdata, const mpw* ydata)
* \brief This function computes the bit-wise OR of two multi-precision
* integers. Modifies xdata.
* \param size The size of the multi-precision integer.
* \param xdata The multi-precision integer data.
* \param ydata The multi-precision integer data.
*/
BEECRYPTAPI
void mpor(size_t size, mpw* xdata, const mpw* ydata);
/*!\fn void mpxor(size_t size, mpw* xdata, const mpw* ydata)
* \brief This function computes the bit-wise XOR of two multi-precision
* integers. Modifies xdata.
* \param size The size of the multi-precision integer.
* \param xdata The multi-precision integer data.
* \param ydata The multi-precision integer data.
*/
BEECRYPTAPI
void mpxor(size_t size, mpw* xdata, const mpw* ydata);
/*!\fn mpnot(size_t size, mpw* data)
* \brief This function flips all bits of a multi-precision integer.
* \param size The size of the multi-precision integer.
* \param data The multi-precision integer data.
*/
BEECRYPTAPI
void mpnot(size_t size, mpw* data);
/*!\fn void mpsetw(size_t size, mpw* xdata, mpw y)
* \brief This function sets the value of a multi-precision integer to the
* given word. The given value is copied into the least significant word,
* while the most significant words are zeroed.
* \param size The size of the multi-precision integer.
* \param xdata The first multi-precision integer.
* \param y The multi-precision word.
*/
BEECRYPTAPI
void mpsetw(size_t size, mpw* xdata, mpw y);
/*!\fn void mpsetx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata)
* \brief This function set the value of the first multi-precision integer
* to the second, truncating the most significant words if ysize > xsize, or
* zeroing the most significant words if ysize < xsize.
* \param xsize The size of the first multi-precision integer.
* \param xdata The first multi-precision integer.
* \param ysize The size of the second multi-precision integer.
* \param ydata The second multi-precision integer.
*/
void mpsetx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata);
/*!\fn int mpaddw(size_t size, mpw* xdata, mpw y)
* \brief This function adds one word to a multi-precision integer.
* The performed operation is in pseudocode: x += y.
* \param size The size of the multi-precision integer.
* \param xdata The first multi-precision integer.
* \param y The multi-precision word.
* \return The carry-over value of the operation; this value is either 0 or 1.
*/
BEECRYPTAPI
int mpaddw(size_t size, mpw* xdata, mpw y);
/*!\fn int mpadd(size_t size, mpw* xdata, const mpw* ydata)
* \brief This function adds two multi-precision integers of equal size.
* The performed operation is in pseudocode: x += y.
* \param size The size of the multi-precision integers.
* \param xdata The first multi-precision integer.
* \param ydata The second multi-precision integer.
* \return The carry-over value of the operation; this value is either 0 or 1.
*/
BEECRYPTAPI
int mpadd (size_t size, mpw* xdata, const mpw* ydata);
/*!\fn int mpaddx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata)
* \brief This function adds two multi-precision integers of different size.
* The performed operation in pseudocode: x += y.
* \param xsize The size of the first multi-precision integer.
* \param xdata The first multi-precision integer.
* \param ysize The size of the second multi-precision integer.
* \param ydata The second multi-precision integer.
* \return The carry-over value of the operation; this value is either 0 or 1.
*/
BEECRYPTAPI
int mpaddx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata);
/*!\fn int mpsubw(size_t size, mpw* xdata, mpw y)
* \brief This function subtracts one word to a multi-precision integer.
* The performed operation in pseudocode: x -= y
* \param size The size of the multi-precision integers.
* \param xdata The first multi-precision integer.
* \param y The multi-precision word.
* \return The carry-over value of the operation; this value is either 0 or 1.
*/
BEECRYPTAPI
int mpsubw(size_t size, mpw* xdata, mpw y);
/*!\fn int mpsub(size_t size, mpw* xdata, const mpw* ydata)
* \brief This function subtracts two multi-precision integers of equal size.
* The performed operation in pseudocode: x -= y
* \param size The size of the multi-precision integers.
* \param xdata The first multi-precision integer.
* \param ydata The second multi-precision integer.
* \return The carry-over value of the operation; this value is either 0 or 1.
*/
BEECRYPTAPI
int mpsub (size_t size, mpw* xdata, const mpw* ydata);
/*!\fn int mpsubx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata)
* \brief This function subtracts two multi-precision integers of different
* size. The performed operation in pseudocode: x -= y.
* \param xsize The size of the first multi-precision integer.
* \param xdata The first multi-precision integer.
* \param ysize The size of the second multi-precision integer.
* \param ydata The second multi-precision integer.
* \return The carry-over value of the operation; this value is either 0 or 1.
*/
BEECRYPTAPI
int mpsubx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata);
BEECRYPTAPI
int mpmultwo(size_t size, mpw* data);
/*!\fn void mpneg(size_t size, mpw* data)
* \brief This function negates a multi-precision integer.
* \param size The size of the multi-precision integer.
* \param data The multi-precision integer data.
*/
BEECRYPTAPI
void mpneg(size_t size, mpw* data);
/*!\fn size_t mpsize(size_t size, const mpw* data)
* \brief This function returns the true size of a multi-precision
* integer, after stripping leading zero words.
* \param size The size of the multi-precision integer.
* \param data The multi-precision integer data.
*/
BEECRYPTAPI
size_t mpsize(size_t size, const mpw* data);
/*!\fn size_t mpbits(size_t size, const mpw* data)
* \brief This function returns the number of significant bits
* in a multi-precision integer.
* \param size The size of the multi-precision integer.
* \param data The multi-precision integer data.
*/
BEECRYPTAPI
size_t mpbits(size_t size, const mpw* data);
BEECRYPTAPI
size_t mpmszcnt(size_t size, const mpw* data);
BEECRYPTAPI
size_t mplszcnt(size_t size, const mpw* data);
BEECRYPTAPI
void mplshift(size_t size, mpw* data, size_t count);
BEECRYPTAPI
void mprshift(size_t size, mpw* data, size_t count);
BEECRYPTAPI
size_t mprshiftlsz(size_t size, mpw* data);
BEECRYPTAPI
size_t mpnorm(size_t size, mpw* data);
BEECRYPTAPI
void mpdivtwo (size_t size, mpw* data);
BEECRYPTAPI
void mpsdivtwo(size_t size, mpw* data);
/*!\fn mpw mpsetmul(size_t size, mpw* result, const mpw* data, mpw y)
* \brief This function performs a multi-precision multiply-setup.
*
* This function is used in the computation of a full multi-precision
* multiplication. By using it we can shave off a few cycles; otherwise we'd
* have to zero the least significant half of the result first and use
* another call to the slightly slower mpaddmul function.
*
* \param size The size of multi-precision integer multiplier.
* \param result The place where result will be accumulated.
* \param data The multi-precision integer multiplier.
* \param y The multiplicand.
* \return The carry-over multi-precision word.
*/
BEECRYPTAPI
mpw mpsetmul (size_t size, mpw* result, const mpw* data, mpw y);
/*!\fn mpw mpaddmul(size_t size, mpw* result, const mpw* data, mpw y)
* \brief This function performs a mult-precision multiply-accumulate.
*
* This function is used in the computation of a full multi-precision
* multiplication. It computes the product-by-one-word and accumulates it with
* the previous result.
*
* \param size The size of multi-precision integer multiplier.
* \param result The place where result will be accumulated.
* \param data The multi-precision integer multiplier.
* \param y The multiplicand.
* \retval The carry-over multi-precision word.
*/
BEECRYPTAPI
mpw mpaddmul (size_t size, mpw* result, const mpw* data, mpw y);
/*!\fn void mpaddsqrtrc(size_t size, mpw* result, const mpw* data)
* \brief This function is used in the calculation of a multi-precision
* squaring.
*/
BEECRYPTAPI
void mpaddsqrtrc(size_t size, mpw* result, const mpw* data);
/*!\fn void mpmul(mpw* result, size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
* \brief This function computes a full multi-precision product.
*/
BEECRYPTAPI
void mpmul(mpw* result, size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata);
/*!\fn void mpsqr(mpw* result, size_t size, const mpw* data)
* \brief This function computes a full multi-precision square.
*/
BEECRYPTAPI
void mpsqr(mpw* result, size_t size, const mpw* data);
BEECRYPTAPI
void mpgcd_w(size_t size, const mpw* xdata, const mpw* ydata, mpw* result, mpw* wksp);
BEECRYPTAPI
int mpextgcd_w(size_t size, const mpw* xdata, const mpw* ydata, mpw* result, mpw* wksp);
BEECRYPTAPI
mpw mppndiv(mpw xhi, mpw xlo, mpw y);
BEECRYPTAPI
void mpmod (mpw* result, size_t xsize, const mpw* xdata, size_t ysize, const mpw*ydata, mpw* wksp);
BEECRYPTAPI
void mpndivmod(mpw* result, size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata, mpw* wksp);
/*
* Output Routines
*/
BEECRYPTAPI
void mpprint(size_t size, const mpw* data);
BEECRYPTAPI
void mpprintln(size_t size, const mpw* data);
BEECRYPTAPI
void mpfprint(FILE* f, size_t size, const mpw* data);
BEECRYPTAPI
void mpfprintln(FILE* f, size_t size, const mpw* data);
/*
* Conversion Routines
*/
BEECRYPTAPI
int os2ip(mpw* idata, size_t isize, const byte* osdata, size_t ossize);
BEECRYPTAPI
int i2osp(byte* osdata, size_t ossize, const mpw* idata, size_t isize);
BEECRYPTAPI
int hs2ip(mpw* idata, size_t isize, const char* hsdata, size_t hssize);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,115 @@
/*
* Copyright (c) 2003 Bob Deblier
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*!\file mpnumber.h
* \brief Multi-precision numbers, headers.
* \author Bob Deblier <bob.deblier@pandora.be>
* \ingroup MP_m
*/
#ifndef _MPNUMBER_H
#define _MPNUMBER_H
#include "beecrypt/mp.h"
#ifdef __cplusplus
# include <iostream>
#endif
#ifdef __cplusplus
struct BEECRYPTAPI mpnumber
#else
struct _mpnumber
#endif
{
size_t size;
mpw* data;
#ifdef __cplusplus
static const mpnumber ZERO;
static const mpnumber ONE;
mpnumber();
mpnumber(unsigned int);
mpnumber(const mpnumber&);
~mpnumber();
const mpnumber& operator=(const mpnumber&);
bool operator==(const mpnumber&) const throw ();
bool operator!=(const mpnumber&) const throw ();
void wipe();
size_t bitlength() const throw ();
#endif
};
#ifndef __cplusplus
typedef struct _mpnumber mpnumber;
#else
BEECRYPTAPI
std::ostream& operator<<(std::ostream&, const mpnumber&);
/*
BEECRYPTAPI
std::istream& operator>>(std::istream&, mpnumber&);
*/
#endif
#ifdef __cplusplus
extern "C" {
#endif
BEECRYPTAPI
void mpnzero(mpnumber*);
BEECRYPTAPI
void mpnsize(mpnumber*, size_t);
BEECRYPTAPI
void mpninit(mpnumber*, size_t, const mpw*);
BEECRYPTAPI
void mpnfree(mpnumber*);
BEECRYPTAPI
void mpncopy(mpnumber*, const mpnumber*);
BEECRYPTAPI
void mpnwipe(mpnumber*);
BEECRYPTAPI
void mpnset (mpnumber*, size_t, const mpw*);
BEECRYPTAPI
void mpnsetw (mpnumber*, mpw);
BEECRYPTAPI
int mpnsetbin(mpnumber*, const byte*, size_t);
BEECRYPTAPI
int mpnsethex(mpnumber*, const char*);
BEECRYPTAPI
int mpninv(mpnumber*, const mpnumber*, const mpnumber*);
/*!\brief Truncate the mpnumber to the specified number of (least significant) bits.
*/
BEECRYPTAPI
size_t mpntrbits(mpnumber*, size_t);
BEECRYPTAPI
size_t mpnbits(const mpnumber*);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,205 @@
/*
* Copyright (c) 2003 Bob Deblier
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*!\file mpopt.h
* \brief Multi-precision integer optimization definitions.
* \author Bob Deblier <bob.deblier@pandora.be>
* \ingroup MP_m
*/
#ifndef _MPOPT_H
#define _MPOPT_H
#if WIN32
# if __MWERKS__ && __INTEL__
# elif defined(_MSC_VER) && defined(_M_IX86)
# define ASM_MPZERO
# define ASM_MPFILL
# define ASM_MPEVEN
# define ASM_MPODD
# define ASM_MPADDW
# define ASM_MPSUBW
# define ASM_MPADD
# define ASM_MPSUB
# define ASM_MPMULTWO
# define ASM_MPDIVTWO
# define ASM_MPSETMUL
# define ASM_MPADDMUL
# define ASM_MPADDSQRTRC
# endif
#endif
#if defined(__DECC)
# if defined(OPTIMIZE_ALPHA)
# define ASM_MPADD
# define ASM_MPSUB
# define ASM_MPSETMUL
# define ASM_MPADDMUL
# define ASM_MPADDSQRTRC
# endif
#endif
#if defined(__GNUC__)
# if defined(OPTIMIZE_ALPHA)
# define ASM_MPADD
# define ASM_MPSUB
# define ASM_MPSETMUL
# define ASM_MPADDMUL
# define ASM_MPADDSQRTRC
# elif defined(OPTIMIZE_ARM)
# define ASM_MPSETMUL
# define ASM_MPADDMUL
# define ASM_MPADDSQRTRC
# elif defined(OPTIMIZE_I386) || defined(OPTIMIZE_I486) || defined(OPTIMIZE_I586) || defined(OPTIMIZE_I686)
# define ASM_MPZERO
# define ASM_MPFILL
# define ASM_MPEVEN
# define ASM_MPODD
# define ASM_MPADD
# define ASM_MPADDW
# define ASM_MPSUB
# define ASM_MPSUBW
# define ASM_MPMULTWO
# define ASM_MPDIVTWO
# define ASM_MPSETMUL
# define ASM_MPADDMUL
# define ASM_MPADDSQRTRC
# define ASM_MPPNDIV
# elif defined(OPTIMIZE_IA64)
# define ASM_MPZERO
# define ASM_MPCOPY
# define ASM_MPADD
# define ASM_MPSUB
# define ASM_MPMULTWO
# define ASM_MPSETMUL
# define ASM_MPADDMUL
# elif defined(OPTIMIZE_M68K)
# define ASM_MPADD
# define ASM_MPSUB
# define ASM_MPSETMUL
# define ASM_MPADDMUL
# define ASM_MPADDSQRTRC
# elif defined(OPTIMIZE_POWERPC) || defined(OPTIMIZE_POWERPC64)
# define ASM_MPSETMUL
# define ASM_MPADD
# define ASM_MPADDW
# define ASM_MPSUB
# define ASM_MPSUBW
# define ASM_MPMULTWO
# define ASM_MPADDMUL
# define ASM_MPADDSQRTRC
# elif defined(OPTIMIZE_S390X)
# define ASM_MPSETMUL
# define ASM_MPADDMUL
# define ASM_MPADDSQRTRC
# elif defined(OPTIMIZE_SPARCV8)
# define ASM_MPSETMUL
# define ASM_MPADDMUL
# define ASM_MPADDSQRTRC
# elif defined(OPTIMIZE_SPARCV8PLUS)
# define ASM_MPADDW
# define ASM_MPSUBW
# define ASM_MPADD
# define ASM_MPSUB
# define ASM_MPMULTWO
# define ASM_MPSETMUL
# define ASM_MPADDMUL
# define ASM_MPADDSQRTRC
# elif defined(OPTIMIZE_X86_64)
# define ASM_MPZERO
# define ASM_MPFILL
# define ASM_MPEVEN
# define ASM_MPODD
# define ASM_MPADD
# define ASM_MPADDW
# define ASM_MPSUB
# define ASM_MPSUBW
# define ASM_MPDIVTWO
# define ASM_MPMULTWO
# define ASM_MPSETMUL
# define ASM_MPADDMUL
# define ASM_MPADDSQRTRC
# endif
#endif
#if defined(__IBMC__)
# if defined(OPTIMIZE_POWERPC) || defined(OPTIMIZE_POWERPC64)
# define ASM_MPSETMUL
# define ASM_MPADDW
# define ASM_MPSUBW
# define ASM_MPADD
# define ASM_MPSUB
# define ASM_MPMULTWO
# define ASM_MPADDMUL
# define ASM_MPADDSQRTRC
# endif
#endif
#if defined(__INTEL_COMPILER)
# if defined(OPTIMIZE_I386) || defined(OPTIMIZE_I486) || defined(OPTIMIZE_I586) || defined(OPTIMIZE_I686)
# define ASM_MPZERO
# define ASM_MPFILL
# define ASM_MPEVEN
# define ASM_MPODD
# define ASM_MPADDW
# define ASM_MPSUBW
# define ASM_MPADD
# define ASM_MPSUB
# define ASM_MPMULTWO
# define ASM_MPDIVTWO
# define ASM_MPSETMUL
# define ASM_MPADDMUL
# define ASM_MPADDSQRTRC
# define ASM_MPPNDIV
# endif
#endif
#if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
# if defined(OPTIMIZE_SPARCV8)
# define ASM_MPSETMUL
# define ASM_MPADDMUL
# define ASM_MPADDSQRTRC
# elif defined(OPTIMIZE_SPARCV8PLUS)
# define ASM_MPADDW
# define ASM_MPSUBW
# define ASM_MPADD
# define ASM_MPSUB
# define ASM_MPMULTWO
# define ASM_MPSETMUL
# define ASM_MPADDMUL
# define ASM_MPADDSQRTRC
# endif
#endif
#undef ASM_MPZERO
#undef ASM_MPFILL
#undef ASM_MPEVEN
#undef ASM_MPODD
#undef ASM_MPADD
#undef ASM_MPADDW
#undef ASM_MPSUB
#undef ASM_MPSUBW
#undef ASM_MPMULTWO
#undef ASM_MPDIVTWO
#undef ASM_MPSETMUL
#undef ASM_MPADDMUL
#undef ASM_MPADDSQRTRC
#undef ASM_MPPNDIV
#endif

View file

@ -0,0 +1,121 @@
/*
* Copyright (c) 2000, 2002 Virtual Unlimited B.V.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*!\file rsa.h
* \brief RSA algorithm.
* \author Bob Deblier <bob.deblier@pandora.be>
* \ingroup IF_m IF_rsa_m
*/
#ifndef _RSA_H
#define _RSA_H
#include "beecrypt/rsakp.h"
#ifdef __cplusplus
extern "C" {
#endif
/*!\fn int rsapub(const mpbarrett* n, const mpnumber* e, const mpnumber* m, mpnumber* c)
* \brief This function performs a raw RSA public key operation.
*
* This function can be used for encryption and verifying.
*
* It performs the following operation:
* \li \f$c=m^{e}\ \textrm{mod}\ n\f$
*
* \param n The RSA modulus.
* \param e The RSA public exponent.
* \param m The message.
* \param c The ciphertext.
* \retval 0 on success.
* \retval -1 on failure.
*/
BEECRYPTAPI
int rsapub(const mpbarrett* n, const mpnumber* e,
const mpnumber* m, mpnumber* c);
/*!\fn int rsapri(const mpbarrett* n, const mpnumber* d, const mpnumber* c, mpnumber* m)
* \brief This function performs a raw RSA private key operation.
*
* This function can be used for decryption and signing.
*
* It performs the operation:
* \li \f$m=c^{d}\ \textrm{mod}\ n\f$
*
* \param n The RSA modulus.
* \param d The RSA private exponent.
* \param c The ciphertext.
* \param m The message.
* \retval 0 on success.
* \retval -1 on failure.
*/
BEECRYPTAPI
int rsapri(const mpbarrett* n, const mpnumber* d,
const mpnumber* c, mpnumber* m);
/*!\fn int rsapricrt(const mpbarrett* n, const mpbarrett* p, const mpbarrett* q, const mpnumber* dp, const mpnumber* dq, const mpnumber* qi, const mpnumber* c, mpnumber* m)
*
* \brief This function performs a raw RSA private key operation, with
* application of the Chinese Remainder Theorem.
*
* It performs the operation:
* \li \f$j_1=c^{dp}\ \textrm{mod}\ p\f$
* \li \f$j_2=c^{dq}\ \textrm{mod}\ q\f$
* \li \f$h=qi \cdot (j_1-j_2)\ \textrm{mod}\ p\f$
* \li \f$m=j_2+hq\f$
*
* \param n The RSA modulus.
* \param p The first RSA prime factor.
* \param q The second RSA prime factor.
* \param dp
* \param dq
* \param qi
* \param c The ciphertext.
* \param m The message.
* \retval 0 on success.
* \retval -1 on failure.
*/
BEECRYPTAPI
int rsapricrt(const mpbarrett* n, const mpbarrett* p, const mpbarrett* q,
const mpnumber* dp, const mpnumber* dq, const mpnumber* qi,
const mpnumber* c, mpnumber* m);
/*!\fn int rsavrfy(const mpbarrett* n, const mpnumber* e, const mpnumber* m, const mpnumber* c)
* \brief This function performs a raw RSA verification.
*
* It verifies if ciphertext \a c was encrypted from cleartext \a m
* with the private key matching the given public key \a (n, e).
*
* \param n The RSA modulus.
* \param e The RSA public exponent.
* \param m The cleartext message.
* \param c The ciphertext message.
* \retval 1 on success.
* \retval 0 on failure.
*/
BEECRYPTAPI
int rsavrfy(const mpbarrett* n, const mpnumber* e,
const mpnumber* m, const mpnumber* c);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,329 @@
/*
* Copyright (c) 1997, 1998, 1999, 2000, 2001 Virtual Unlimited B.V.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*!\file sha1.c
* \brief SHA-1 hash function, as specified by NIST FIPS 180-1.
* \author Bob Deblier <bob.deblier@pandora.be>
* \ingroup HASH_m HASH_sha1_m
*/
#define BEECRYPT_DLL_EXPORT
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "beecrypt/sha1.h"
#if HAVE_ENDIAN_H && HAVE_ASM_BYTEORDER_H
# include <endian.h>
#endif
#include "beecrypt/endianness.h"
/*!\addtogroup HASH_sha1_m
* \{
*/
static const uint32_t k[4] = { 0x5a827999U, 0x6ed9eba1U, 0x8f1bbcdcU, 0xca62c1d6U };
static const uint32_t hinit[5] = { 0x67452301U, 0xefcdab89U, 0x98badcfeU, 0x10325476U, 0xc3d2e1f0U };
const hashFunction sha1 = {
"SHA-1",
sizeof(sha1Param),
64,
20,
(hashFunctionReset) sha1Reset,
(hashFunctionUpdate) sha1Update,
(hashFunctionDigest) sha1Digest
};
int sha1Reset(register sha1Param* p)
{
memcpy(p->h, hinit, 5 * sizeof(uint32_t));
memset(p->data, 0, 80 * sizeof(uint32_t));
#if (MP_WBITS == 64)
mpzero(1, p->length);
#elif (MP_WBITS == 32)
mpzero(2, p->length);
#else
# error
#endif
p->offset = 0;
return 0;
}
#define SUBROUND1(a, b, c, d, e, w, k) \
e = ROTL32(a, 5) + ((b&(c^d))^d) + e + w + k; \
b = ROTR32(b, 2)
#define SUBROUND2(a, b, c, d, e, w, k) \
e = ROTL32(a, 5) + (b^c^d) + e + w + k; \
b = ROTR32(b, 2)
#define SUBROUND3(a, b, c, d, e, w, k) \
e = ROTL32(a, 5) + (((b|c)&d)|(b&c)) + e + w + k; \
b = ROTR32(b, 2)
#define SUBROUND4(a, b, c, d, e, w, k) \
e = ROTL32(a, 5) + (b^c^d) + e + w + k; \
b = ROTR32(b, 2)
#ifndef ASM_SHA1PROCESS
void sha1Process(sha1Param* sp)
{
register uint32_t a, b, c, d, e;
register uint32_t *w;
register byte t;
#if WORDS_BIGENDIAN
w = sp->data + 16;
#else
w = sp->data;
t = 16;
while (t--)
{
register uint32_t temp = swapu32(*w);
*(w++) = temp;
}
#endif
t = 64;
while (t--)
{
register uint32_t temp = w[-3] ^ w[-8] ^ w[-14] ^ w[-16];
*(w++) = ROTL32(temp, 1);
}
w = sp->data;
a = sp->h[0]; b = sp->h[1]; c = sp->h[2]; d = sp->h[3]; e = sp->h[4];
SUBROUND1(a,b,c,d,e,w[ 0],k[0]);
SUBROUND1(e,a,b,c,d,w[ 1],k[0]);
SUBROUND1(d,e,a,b,c,w[ 2],k[0]);
SUBROUND1(c,d,e,a,b,w[ 3],k[0]);
SUBROUND1(b,c,d,e,a,w[ 4],k[0]);
SUBROUND1(a,b,c,d,e,w[ 5],k[0]);
SUBROUND1(e,a,b,c,d,w[ 6],k[0]);
SUBROUND1(d,e,a,b,c,w[ 7],k[0]);
SUBROUND1(c,d,e,a,b,w[ 8],k[0]);
SUBROUND1(b,c,d,e,a,w[ 9],k[0]);
SUBROUND1(a,b,c,d,e,w[10],k[0]);
SUBROUND1(e,a,b,c,d,w[11],k[0]);
SUBROUND1(d,e,a,b,c,w[12],k[0]);
SUBROUND1(c,d,e,a,b,w[13],k[0]);
SUBROUND1(b,c,d,e,a,w[14],k[0]);
SUBROUND1(a,b,c,d,e,w[15],k[0]);
SUBROUND1(e,a,b,c,d,w[16],k[0]);
SUBROUND1(d,e,a,b,c,w[17],k[0]);
SUBROUND1(c,d,e,a,b,w[18],k[0]);
SUBROUND1(b,c,d,e,a,w[19],k[0]);
SUBROUND2(a,b,c,d,e,w[20],k[1]);
SUBROUND2(e,a,b,c,d,w[21],k[1]);
SUBROUND2(d,e,a,b,c,w[22],k[1]);
SUBROUND2(c,d,e,a,b,w[23],k[1]);
SUBROUND2(b,c,d,e,a,w[24],k[1]);
SUBROUND2(a,b,c,d,e,w[25],k[1]);
SUBROUND2(e,a,b,c,d,w[26],k[1]);
SUBROUND2(d,e,a,b,c,w[27],k[1]);
SUBROUND2(c,d,e,a,b,w[28],k[1]);
SUBROUND2(b,c,d,e,a,w[29],k[1]);
SUBROUND2(a,b,c,d,e,w[30],k[1]);
SUBROUND2(e,a,b,c,d,w[31],k[1]);
SUBROUND2(d,e,a,b,c,w[32],k[1]);
SUBROUND2(c,d,e,a,b,w[33],k[1]);
SUBROUND2(b,c,d,e,a,w[34],k[1]);
SUBROUND2(a,b,c,d,e,w[35],k[1]);
SUBROUND2(e,a,b,c,d,w[36],k[1]);
SUBROUND2(d,e,a,b,c,w[37],k[1]);
SUBROUND2(c,d,e,a,b,w[38],k[1]);
SUBROUND2(b,c,d,e,a,w[39],k[1]);
SUBROUND3(a,b,c,d,e,w[40],k[2]);
SUBROUND3(e,a,b,c,d,w[41],k[2]);
SUBROUND3(d,e,a,b,c,w[42],k[2]);
SUBROUND3(c,d,e,a,b,w[43],k[2]);
SUBROUND3(b,c,d,e,a,w[44],k[2]);
SUBROUND3(a,b,c,d,e,w[45],k[2]);
SUBROUND3(e,a,b,c,d,w[46],k[2]);
SUBROUND3(d,e,a,b,c,w[47],k[2]);
SUBROUND3(c,d,e,a,b,w[48],k[2]);
SUBROUND3(b,c,d,e,a,w[49],k[2]);
SUBROUND3(a,b,c,d,e,w[50],k[2]);
SUBROUND3(e,a,b,c,d,w[51],k[2]);
SUBROUND3(d,e,a,b,c,w[52],k[2]);
SUBROUND3(c,d,e,a,b,w[53],k[2]);
SUBROUND3(b,c,d,e,a,w[54],k[2]);
SUBROUND3(a,b,c,d,e,w[55],k[2]);
SUBROUND3(e,a,b,c,d,w[56],k[2]);
SUBROUND3(d,e,a,b,c,w[57],k[2]);
SUBROUND3(c,d,e,a,b,w[58],k[2]);
SUBROUND3(b,c,d,e,a,w[59],k[2]);
SUBROUND4(a,b,c,d,e,w[60],k[3]);
SUBROUND4(e,a,b,c,d,w[61],k[3]);
SUBROUND4(d,e,a,b,c,w[62],k[3]);
SUBROUND4(c,d,e,a,b,w[63],k[3]);
SUBROUND4(b,c,d,e,a,w[64],k[3]);
SUBROUND4(a,b,c,d,e,w[65],k[3]);
SUBROUND4(e,a,b,c,d,w[66],k[3]);
SUBROUND4(d,e,a,b,c,w[67],k[3]);
SUBROUND4(c,d,e,a,b,w[68],k[3]);
SUBROUND4(b,c,d,e,a,w[69],k[3]);
SUBROUND4(a,b,c,d,e,w[70],k[3]);
SUBROUND4(e,a,b,c,d,w[71],k[3]);
SUBROUND4(d,e,a,b,c,w[72],k[3]);
SUBROUND4(c,d,e,a,b,w[73],k[3]);
SUBROUND4(b,c,d,e,a,w[74],k[3]);
SUBROUND4(a,b,c,d,e,w[75],k[3]);
SUBROUND4(e,a,b,c,d,w[76],k[3]);
SUBROUND4(d,e,a,b,c,w[77],k[3]);
SUBROUND4(c,d,e,a,b,w[78],k[3]);
SUBROUND4(b,c,d,e,a,w[79],k[3]);
sp->h[0] += a;
sp->h[1] += b;
sp->h[2] += c;
sp->h[3] += d;
sp->h[4] += e;
}
#endif
int sha1Update(sha1Param* sp, const byte* data, size_t size)
{
register uint32_t proclength;
#if (MP_WBITS == 64)
mpw add[1];
mpsetw(1, add, size);
mplshift(1, add, 3);
mpadd(1, sp->length, add);
#elif (MP_WBITS == 32)
mpw add[2];
mpsetw(2, add, size);
mplshift(2, add, 3);
mpadd(2, sp->length, add);
#else
# error
#endif
while (size > 0)
{
proclength = ((sp->offset + size) > 64U) ? (64U - sp->offset) : size;
memcpy(((byte *) sp->data) + sp->offset, data, proclength);
size -= proclength;
data += proclength;
sp->offset += proclength;
if (sp->offset == 64)
{
sha1Process(sp);
sp->offset = 0;
}
}
return 0;
}
static void sha1Finish(sha1Param* sp)
{
register byte *ptr = ((byte *) sp->data) + sp->offset++;
*(ptr++) = 0x80;
if (sp->offset > 56)
{
while (sp->offset++ < 64)
*(ptr++) = 0;
sha1Process(sp);
sp->offset = 0;
}
ptr = ((byte*) sp->data) + sp->offset;
while (sp->offset++ < 56)
*(ptr++) = 0;
#if WORDS_BIGENDIAN
memcpy(ptr, sp->length, 8);
#else
# if (MP_WBITS == 64)
ptr[0] = (byte)(sp->length[0] >> 56);
ptr[1] = (byte)(sp->length[0] >> 48);
ptr[2] = (byte)(sp->length[0] >> 40);
ptr[3] = (byte)(sp->length[0] >> 32);
ptr[4] = (byte)(sp->length[0] >> 24);
ptr[5] = (byte)(sp->length[0] >> 16);
ptr[6] = (byte)(sp->length[0] >> 8);
ptr[7] = (byte)(sp->length[0] );
#elif (MP_WBITS == 32)
ptr[0] = (byte)(sp->length[0] >> 24);
ptr[1] = (byte)(sp->length[0] >> 16);
ptr[2] = (byte)(sp->length[0] >> 8);
ptr[3] = (byte)(sp->length[0] );
ptr[4] = (byte)(sp->length[1] >> 24);
ptr[5] = (byte)(sp->length[1] >> 16);
ptr[6] = (byte)(sp->length[1] >> 8);
ptr[7] = (byte)(sp->length[1] );
# else
# error
# endif
#endif
sha1Process(sp);
sp->offset = 0;
}
int sha1Digest(sha1Param* sp, byte* data)
{
sha1Finish(sp);
#if WORDS_BIGENDIAN
memcpy(data, sp->h, 20);
#else
/* encode 5 integers big-endian style */
data[ 0] = (byte)(sp->h[0] >> 24);
data[ 1] = (byte)(sp->h[0] >> 16);
data[ 2] = (byte)(sp->h[0] >> 8);
data[ 3] = (byte)(sp->h[0] >> 0);
data[ 4] = (byte)(sp->h[1] >> 24);
data[ 5] = (byte)(sp->h[1] >> 16);
data[ 6] = (byte)(sp->h[1] >> 8);
data[ 7] = (byte)(sp->h[1] >> 0);
data[ 8] = (byte)(sp->h[2] >> 24);
data[ 9] = (byte)(sp->h[2] >> 16);
data[10] = (byte)(sp->h[2] >> 8);
data[11] = (byte)(sp->h[2] >> 0);
data[12] = (byte)(sp->h[3] >> 24);
data[13] = (byte)(sp->h[3] >> 16);
data[14] = (byte)(sp->h[3] >> 8);
data[15] = (byte)(sp->h[3] >> 0);
data[16] = (byte)(sp->h[4] >> 24);
data[17] = (byte)(sp->h[4] >> 16);
data[18] = (byte)(sp->h[4] >> 8);
data[19] = (byte)(sp->h[4] >> 0);
#endif
sha1Reset(sp);
return 0;
}
/*!\}
*/

View file

@ -0,0 +1,120 @@
/*
* Copyright (c) 1997, 1998, 1999, 2000, 2002 Virtual Unlimited B.V.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*!\file sha1.h
* \brief SHA-1 hash function, headers.
* \author Bob Deblier <bob.deblier@pandora.be>
* \ingroup HASH_m HASH_sha1_m
*/
#ifndef _SHA1_H
#define _SHA1_H
#include "beecrypt/beecrypt.h"
#include "beecrypt/sha1opt.h"
/*!\brief Holds all the parameters necessary for the SHA-1 algorithm.
* \ingroup HASH_sha1_m
*/
#ifdef __cplusplus
struct BEECRYPTAPI sha1Param
#else
struct _sha1Param
#endif
{
/*!\var h
*/
uint32_t h[5];
/*!\var data
*/
uint32_t data[80];
/*!\var length
* \brief Multi-precision integer counter for the bits that have been
* processed so far.
*/
#if (MP_WBITS == 64)
mpw length[1];
#elif (MP_WBITS == 32)
mpw length[2];
#else
# error
#endif
/*!\var offset
* \brief Offset into \a data; points to the place where new data will be
* copied before it is processed.
*/
uint32_t offset;
};
#ifndef __cplusplus
typedef struct _sha1Param sha1Param;
#endif
#ifdef __cplusplus
extern "C" {
#endif
/*!\var sha1
* \brief Holds the full API description of the SHA-1 algorithm.
*/
extern BEECRYPTAPI const hashFunction sha1;
/*!\fn void sha1Process(sha1Param* sp)
* \brief This function performs the core of the SHA-1 hash algorithm; it
* processes a block of 64 bytes.
* \param sp The hash function's parameter block.
*/
BEECRYPTAPI
void sha1Process(sha1Param* sp);
/*!\fn int sha1Reset(sha1Param* sp)
* \brief This function resets the parameter block so that it's ready for a
* new hash.
* \param sp The hash function's parameter block.
* \retval 0 on success.
*/
BEECRYPTAPI
int sha1Reset (sha1Param* sp);
/*!\fn int sha1Update(sha1Param* sp, const byte* data, size_t size)
* \brief This function should be used to pass successive blocks of data
* to be hashed.
* \param sp The hash function's parameter block.
* \param data
* \param size
* \retval 0 on success.
*/
BEECRYPTAPI
int sha1Update (sha1Param* sp, const byte* data, size_t size);
/*!\fn int sha1Digest(sha1Param* sp, byte* digest)
* \brief This function finishes the current hash computation and copies
* the digest value into \a digest.
* \param sp The hash function's parameter block.
* \param digest The place to store the 20-byte digest.
* \retval 0 on success.
*/
BEECRYPTAPI
int sha1Digest (sha1Param* sp, byte* digest);
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,65 @@
/*
* sha1opt.h
*
* SHA-1 assembler-optimized routines, header
*
* Copyright (c) 2000, 2003 Virtual Unlimited B.V.
*
* Author: Bob Deblier <bob.deblier@pandora.be>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifndef _SHA1OPT_H
#define _SHA1OPT_H
#include "beecrypt/beecrypt.h"
#include "beecrypt/sha1.h"
#ifdef __cplusplus
extern "C" {
#endif
#if WIN32
# if defined(_MSC_VER) && defined(_M_IX86)
# define ASM_SHA1PROCESS
# elif __INTEL__ && __MWERKS__
# define ASM_SHA1PROCESS
# endif
#endif
#if defined(__GNUC__)
# if defined(OPTIMIZE_I386) || defined(OPTIMIZE_I486) || defined(OPTIMIZE_I586) || defined(OPTIMIZE_I686)
# define ASM_SHA1PROCESS
# endif
#endif
#if defined(__INTEL_COMPILER)
# if defined(OPTIMIZE_I386) || defined(OPTIMIZE_I486) || defined(OPTIMIZE_I586) || defined(OPTIMIZE_I686)
# define ASM_SHA1PROCESS
# endif
#endif
#if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
#endif
#undef ASM_SHA1PROCESS
#ifdef __cplusplus
}
#endif
#endif

View file

@ -0,0 +1,139 @@
/*
* Copyright (c) 2000, 2001, 2002 Virtual Unlimited B.V.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*!\file win.h
* \brief BeeCrypt API, windows headers.
* \author Bob Deblier <bob.deblier@pandora.be>
*/
#ifndef _BEECRYPT_WIN_H
#define _BEECRYPT_WIN_H
#define _REENTRANT
#if !defined(_WIN32_WINNT)
#define _WIN32_WINNT 0x0400
#endif
#include <windows.h>
#if __MWERKS__
# if __INTEL__
# define WORDS_BIGENDIAN 0
# else
# error Unknown CPU type in MetroWerks CodeWarrior
# endif
#elif defined(_MSC_VER)
# if defined(_M_IX86)
# define WORDS_BIGENDIAN 0
# define ROTL32(x, s) _rotl(x, s)
# define ROTR32(x, s) _rotr(x, s)
# else
# error Unknown CPU type in Microsoft Visual C
# endif
#else
# error Unknown compiler for WIN32
#endif
#if defined(_MSC_VER) || __MWERKS__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HAVE_ERRNO_H 1
#define HAVE_CTYPE_H 1
#define HAVE_FCNTL_H 1
#define HAVE_TIME_H 1
#define HAVE_SYS_TYPES_H 0
#define HAVE_SYS_TIME_H 0
#define HAVE_THREAD_H 0
#define HAVE_SYNCH_H 0
#define HAVE_PTHREAD_H 0
#define HAVE_SEMAPHORE_H 0
#define HAVE_TERMIO_H 0
#define HAVE_SYS_AUDIOIO_H 0
#define HAVE_SYS_IOCTL_H 0
#define HAVE_SYS_SOUNDCARD_H 0
#define HAVE_GETTIMEOFDAY 0
#define HAVE_GETHRTIME 0
#define HAVE_DEV_TTY 0
#define HAVE_DEV_AUDIO 0
#define HAVE_DEV_DSP 0
#define HAVE_DEV_RANDOM 0
#define HAVE_DEV_URANDOM 0
#define HAVE_DEV_TTY 0
#else
#error Not set up for this compiler
#endif
#if __MWERKS__
#define HAVE_SYS_STAT_H 0
#define HAVE_LONG_LONG 1
#define HAVE_UNSIGNED_LONG_LONG 1
#define HAVE_64_BIT_INT 1
#define HAVE_64_BIT_UINT 1
typedef char int8_t;
typedef short int16_t;
typedef long int32_t;
typedef long long int64_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned long uint32_t;
typedef unsigned long long uint64_t;
#elif defined(_MSC_VER)
#define HAVE_SYS_STAT_H 1
#define HAVE_LONG_LONG 0
#define HAVE_UNSIGNED_LONG_LONG 0
#define HAVE_64_BIT_INT 1
#define HAVE_64_BIT_UINT 1
typedef signed char int8_t;
typedef signed short int16_t;
typedef signed int int32_t;
typedef signed __int64 int64_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned __int64 uint64_t;
typedef long off_t;
#endif
#define MP_WBITS 32U
typedef HANDLE bc_cond_t;
typedef HANDLE bc_mutex_t;
typedef HANDLE bc_thread_t;
#endif

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,504 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View file

@ -0,0 +1,50 @@
GetPot - C++:
--------------
Attention: This version contains a couple of beautiful
---------- new features, that are not documented yet.
E.g.: -- automated ufo detection
-- arbitrary comment delimiters
-- arbitrary vector field separators
-- tails, i.e. easy access to all tails
of options such as '-L' or '-I'.
Please, refere to the example/ directory
for usage descriptions.
This is the C++ version of the popular GetPot library for
command line and input file parsing. The documentation
can be downloaded at:
http://getpot.sourceforge.net
The files in the 'examples' directory should be enough, though, to be
able to use this library. It is fairly easy to use.
Installation:
-------------
In order to install GetPot, simply copy the file 'GetPot'
somewhere where your c++ compiler can find it.
The 'file emacs-getpot-mode.el' contains some lines of
emacs-lisp code. If you append these lines to your .emacs
file, it will highlight your 'getpot' - input files.
Bug reports, Feature requests:
------------------------------
Please, notify me in case there are any bugs or you think
that there should be more features in the library.
My email address is:
fschaef@users.sourceforge.net
Thanks for using this software.
Enjoy !
Juli 2005,
Frank R. Schaefer

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,20 @@
PROJECT(pelib)
# source files for pelib
SET(pelib_srcs
pelib/BoundImportDirectory.cpp
pelib/ComHeaderDirectory.cpp
pelib/DebugDirectory.cpp
pelib/ExportDirectory.cpp
pelib/IatDirectory.cpp
pelib/MzHeader.cpp
pelib/PeFile.cpp
pelib/PeHeader.cpp
pelib/PeLibAux.cpp
pelib/RelocationsDirectory.cpp
pelib/ResourceDirectory.cpp
pelib/buffer/InputBuffer.cpp
pelib/buffer/OutputBuffer.cpp
)
ADD_LIBRARY(pelib ${pelib_srcs})

View file

@ -0,0 +1,511 @@
/*
* BoundImportDirectory.cpp - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#include "PeLibInc.h"
#include "BoundImportDirectory.h"
#include <numeric>
#include <set>
#include <map>
namespace PeLib
{
/**
* Adds another bound import to the BoundImport directory.
* @param strModuleName Name of the PE file which will be imported.
* @param dwTds Value of the TimeDateStamp of the bound import field.
* @param wOmn Value of the OffsetModuleName of the bound import field.
* @param wWfr Value of the NumberOfModuleForwarderRefs of the bound import field.
**/
int BoundImportDirectory::addBoundImport(const std::string& strModuleName, dword dwTds, word wOmn, word wWfr)
{
for (unsigned int i=0;i<m_vIbd.size();i++)
{
if (isEqualNc(strModuleName, m_vIbd[i].strModuleName))
{
return ERROR_DUPLICATE_ENTRY;
}
}
PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR ibidCurrent;
ibidCurrent.TimeDateStamp = dwTds;
ibidCurrent.OffsetModuleName = wOmn;
ibidCurrent.NumberOfModuleForwarderRefs = wWfr;
PELIB_IMAGE_BOUND_DIRECTORY ibdCurrent;
ibdCurrent.ibdDescriptor = ibidCurrent;
ibdCurrent.strModuleName = strModuleName;
m_vIbd.push_back(ibdCurrent);
return NO_ERROR;
}
/**
* Searches for the first instance of a module with the given modulename.
* @param strModuleName The name of a module.
* @return The id of the module.
**/
int BoundImportDirectory::getModuleIndex(const std::string& strModuleName) const
{
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));
if (Iter == m_vIbd.end())
{
return ERROR_ENTRY_NOT_FOUND;
}
return static_cast<int>(std::distance(m_vIbd.begin(), Iter));
}
/**
* @return Number of files in the current BoundImport directory.
**/
unsigned int BoundImportDirectory::calcNumberOfModules() const
{
return static_cast<unsigned int>(m_vIbd.size());
}
int BoundImportDirectory::read(InputBuffer& inpBuffer, unsigned char* data, unsigned int dwSize)
{
std::vector<PELIB_IMAGE_BOUND_DIRECTORY> currentDirectory;
do
{
PELIB_IMAGE_BOUND_DIRECTORY ibdCurrent;
inpBuffer >> ibdCurrent.ibdDescriptor.TimeDateStamp;
inpBuffer >> ibdCurrent.ibdDescriptor.OffsetModuleName;
inpBuffer >> ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs;
if (ibdCurrent.ibdDescriptor.TimeDateStamp == 0 && ibdCurrent.ibdDescriptor.OffsetModuleName == 0 && ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs == 0) break;
for (int i=0;i<ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs;i++)
{
PELIB_IMAGE_BOUND_DIRECTORY currentForwarder;
inpBuffer >> currentForwarder.ibdDescriptor.TimeDateStamp;
inpBuffer >> currentForwarder.ibdDescriptor.OffsetModuleName;
inpBuffer >> currentForwarder.ibdDescriptor.NumberOfModuleForwarderRefs;
ibdCurrent.moduleForwarders.push_back(currentForwarder);
}
currentDirectory.push_back(ibdCurrent);
ibdCurrent.moduleForwarders.clear();
} while (true);
for (unsigned int i=0;i<currentDirectory.size();i++)
{
dword wOmn = currentDirectory[i].ibdDescriptor.OffsetModuleName;
if (wOmn > dwSize)
{
return ERROR_INVALID_FILE;
}
currentDirectory[i].strModuleName = "";
for (int k=0;data[wOmn + k] != 0 && k + wOmn < dwSize;k++)
{
currentDirectory[i].strModuleName += data[wOmn + k];
}
for (unsigned int j=0;j<currentDirectory[i].moduleForwarders.size();j++)
{
dword wOmn = currentDirectory[i].moduleForwarders[j].ibdDescriptor.OffsetModuleName;
if (wOmn > dwSize)
{
return ERROR_INVALID_FILE;
}
// m_vIbd[i].moduleForwarders[j].strModuleName.assign((char*)(&vBimpDir[wOmn]));
currentDirectory[i].moduleForwarders[j].strModuleName = "";
for (int k=0;data[wOmn + k] != 0 && k + wOmn < dwSize;k++)
{
currentDirectory[i].moduleForwarders[j].strModuleName += data[wOmn + k];
}
}
}
std::swap(m_vIbd, currentDirectory);
return NO_ERROR;
}
/**
* Reads the BoundImport directory from a PE file.
* @param strModuleName The name of the PE file from which the BoundImport directory is read.
* @param dwOffset The file offset where the BoundImport directory can be found (see #PeFile::PeHeader::getIDBoundImportRVA).
* @param dwSize The size of the BoundImport directory (see #PeFile::PeHeader::getIDBoundImportSize).
**/
int BoundImportDirectory::read(const std::string& strModuleName, dword dwOffset, unsigned int uiSize)
{
std::ifstream ifFile(strModuleName.c_str(), std::ios::binary);
if (!ifFile)
{
return ERROR_OPENING_FILE;
}
if (fileSize(ifFile) < dwOffset + uiSize)
{
return ERROR_INVALID_FILE;
}
ifFile.seekg(dwOffset, std::ios::beg);
std::vector<unsigned char> vBimpDir(uiSize);
ifFile.read(reinterpret_cast<char*>(&vBimpDir[0]), uiSize);
InputBuffer inpBuffer(vBimpDir);
return read(inpBuffer, &vBimpDir[0], uiSize);
}
int BoundImportDirectory::read(unsigned char* pcBuffer, unsigned int uiSize)
{
std::vector<unsigned char> vBimpDir(pcBuffer, pcBuffer + uiSize);
InputBuffer inpBuffer(vBimpDir);
return read(inpBuffer, &vBimpDir[0], uiSize);
}
unsigned int BoundImportDirectory::totalModules() const
{
unsigned int modules = static_cast<unsigned int>(m_vIbd.size());
for (unsigned int i=0;i<m_vIbd.size();i++)
{
modules += static_cast<unsigned int>(m_vIbd[i].moduleForwarders.size());
}
return modules;
}
/**
* Rebuilds the BoundImport directory. The rebuilded BoundImport directory can then be
* written back to a PE file.
* @param vBuffer Buffer where the rebuilt BoundImport directory will be stored.
* @param fMakeValid If this flag is true a valid directory will be produced.
**/
void BoundImportDirectory::rebuild(std::vector<byte>& vBuffer, bool fMakeValid) const
{
std::map<std::string, word> filename_offsets;
OutputBuffer obBuffer(vBuffer);
word ulNameOffset = static_cast<word>((totalModules() + 1) * PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size());
for (unsigned int i=0;i<m_vIbd.size();i++)
{
obBuffer << m_vIbd[i].ibdDescriptor.TimeDateStamp;
// Recalculate the offsets if a valid directory is wanted.
if (fMakeValid)
{
if (filename_offsets.find(m_vIbd[i].strModuleName) == filename_offsets.end())
{
filename_offsets[m_vIbd[i].strModuleName] = ulNameOffset;
obBuffer << ulNameOffset;
ulNameOffset += static_cast<word>(m_vIbd[i].strModuleName.size() + 1);
}
else
{
obBuffer << filename_offsets[m_vIbd[i].strModuleName];
}
}
else // Otherwise just copy the old values into the buffer.
{
obBuffer << m_vIbd[i].ibdDescriptor.OffsetModuleName;
}
obBuffer << m_vIbd[i].ibdDescriptor.NumberOfModuleForwarderRefs;
for (int j=0;j<calcNumberOfModuleForwarderRefs(i);j++)
{
obBuffer << m_vIbd[i].moduleForwarders[j].ibdDescriptor.TimeDateStamp;
if (fMakeValid)
{
if (filename_offsets.find(m_vIbd[i].strModuleName) == filename_offsets.end())
{
filename_offsets[m_vIbd[i].moduleForwarders[j].strModuleName] = ulNameOffset;
obBuffer << ulNameOffset;
ulNameOffset += static_cast<word>(m_vIbd[i].moduleForwarders[j].strModuleName.size() + 1);
}
else
{
obBuffer << filename_offsets[m_vIbd[i].moduleForwarders[j].strModuleName];
}
}
else // Otherwise just copy the old values into the buffer.
{
obBuffer << m_vIbd[i].moduleForwarders[j].ibdDescriptor.OffsetModuleName;
}
obBuffer << m_vIbd[i].moduleForwarders[j].ibdDescriptor.NumberOfModuleForwarderRefs;
}
}
obBuffer << static_cast<dword>(0);
obBuffer << static_cast<word>(0);
obBuffer << static_cast<word>(0);
for (unsigned int i=0;i<m_vIbd.size();i++)
{
if (filename_offsets.find(m_vIbd[i].strModuleName) != filename_offsets.end())
{
obBuffer.add(getModuleName(i).c_str(), static_cast<unsigned long>(getModuleName(i).size() + 1));
filename_offsets.erase(m_vIbd[i].strModuleName);
}
for (int j=0;j<calcNumberOfModuleForwarderRefs(i);j++)
{
if (filename_offsets.find(getModuleName(i, j)) != filename_offsets.end())
{
obBuffer.add(getModuleName(i, j).c_str(), static_cast<unsigned long>(getModuleName(i, j).size() + 1));
filename_offsets.erase(getModuleName(i, j));
}
}
}
}
/**
* Removes all bound import files.
**/
void BoundImportDirectory::clear()
{
m_vIbd.clear();
}
/**
* Removes a field specified by the parameter filename from the BoundImport directory.
* @param strModuleName Name of the file whose field will be removed from the BoundImport directory.
**/
void BoundImportDirectory::removeBoundImport(const std::string& strModuleName)
{
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());
}
/**
* Returns the size of the rebuilt BoundImportDirectory.
* @return Size of the rebuilt BoundImportDirectory.
**/
unsigned int BoundImportDirectory::size() const
{
unsigned int size = PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size();
std::set<std::string> filenames;
for (unsigned int i = 0; i < m_vIbd.size(); i++)
{
filenames.insert(m_vIbd[i].strModuleName);
size += PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size();
for (unsigned int j = 0; j < m_vIbd[i].moduleForwarders.size(); j++)
{
filenames.insert(m_vIbd[i].moduleForwarders[j].strModuleName);
size += PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size();
}
}
for (std::set<std::string>::iterator iter = filenames.begin(); iter != filenames.end(); ++iter)
{
size += static_cast<unsigned int>(iter->size()) + 1;
}
return size;
}
/**
* @param strFilename Name of the file.
* @param dwOffset File offset the bound importdirectory will be written to.
* @param fMakeValid If this flag is true a valid directory will be produced.
**/
int BoundImportDirectory::write(const std::string& strFilename, dword dwOffset, bool fMakeValid) const
{
std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
if (!ofFile)
{
ofFile.clear();
ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
}
else
{
ofFile.close();
ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
}
if (!ofFile)
{
return ERROR_OPENING_FILE;
}
ofFile.seekp(dwOffset, std::ios::beg);
std::vector<unsigned char> vBuffer;
rebuild(vBuffer, fMakeValid);
ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<std::streamsize>(vBuffer.size()));
ofFile.close();
return NO_ERROR;
}
/**
* Retrieves the value of the TimeDateStamp value of a bound import field.
* @param dwBidnr Number of the bound import field.
* @return Value of the TimeDateStamp of the bound import field.
**/
dword BoundImportDirectory::getTimeDateStamp(dword dwBidnr) const
{
return m_vIbd[dwBidnr].ibdDescriptor.TimeDateStamp;
}
/**
* Retrieves the value of the OffsetModuleName value of a bound import field.
* @param dwBidnr Number of the bound import field.
* @return Value of the OffsetModuleName of the bound import field.
**/
word BoundImportDirectory::getOffsetModuleName(dword dwBidnr) const
{
return m_vIbd[dwBidnr].ibdDescriptor.OffsetModuleName;
}
/**
* Retrieves the value of the NumberOfModuleForwarderRefs value of a bound import field.
* @param dwBidnr Number of the bound import field.
* @return Value of the NumberOfModuleForwarderRefs of the bound import field.
**/
word BoundImportDirectory::getNumberOfModuleForwarderRefs(dword dwBidnr) const
{
return m_vIbd[dwBidnr].ibdDescriptor.NumberOfModuleForwarderRefs;
}
/**
* Retrieves the value of the ModuleName value of a bound import field.
* @param dwBidnr Number of the bound import field.
* @return Value of the ModuleName of the bound import field.
**/
std::string BoundImportDirectory::getModuleName(dword dwBidnr) const
{
return m_vIbd[dwBidnr].strModuleName;
}
/**
* Changes the TimeDateStamp value of an existing bound import field.
* @param dwBidnr Number of the bound import field which will be changed.
* @param dwTds New value of the TimeDateStamp of the bound import field.
**/
void BoundImportDirectory::setTimeDateStamp(dword dwBidnr, dword dwTds)
{
m_vIbd[dwBidnr].ibdDescriptor.TimeDateStamp = dwTds;
}
/**
* Changes the OffsetModuleName value of an existing bound import field.
* @param dwBidnr Number of the bound import field which will be changed.
* @param wOmn New value of the OffsetModuleName of the bound import field.
**/
void BoundImportDirectory::setOffsetModuleName(dword dwBidnr, word wOmn)
{
m_vIbd[dwBidnr].ibdDescriptor.OffsetModuleName = wOmn;
}
/**
* Changes the NumberOfModuleForwarderRefs value of an existing bound import field.
* @param dwBidnr Number of the bound import field which will be changed.
* @param wMfr New value of the NumberOfModuleForwarderRefs of the bound import field.
**/
void BoundImportDirectory::setNumberOfModuleForwarderRefs(dword dwBidnr, word wMfr)
{
m_vIbd[dwBidnr].ibdDescriptor.NumberOfModuleForwarderRefs = wMfr;
}
/**
* Changes the ModuleName value of an existing bound import field.
* @param dwBidnr Number of the bound import field which will be changed.
* @param strModuleName New value of the ModuleName of the bound import field.
**/
void BoundImportDirectory::setModuleName(dword dwBidnr, const std::string& strModuleName)
{
m_vIbd[dwBidnr].strModuleName = strModuleName;
}
dword BoundImportDirectory::getTimeDateStamp(dword dwBidnr, dword forwardedModule) const
{
return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.TimeDateStamp;
}
word BoundImportDirectory::getOffsetModuleName(dword dwBidnr, dword forwardedModule) const
{
return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.OffsetModuleName;
}
word BoundImportDirectory::getNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule) const
{
return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.NumberOfModuleForwarderRefs;
}
std::string BoundImportDirectory::getModuleName(dword dwBidnr, dword forwardedModule) const
{
return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].strModuleName;
}
void BoundImportDirectory::setTimeDateStamp(dword dwBidnr, dword forwardedModule, dword dwTds)
{
m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.TimeDateStamp = dwTds;
}
void BoundImportDirectory::setOffsetModuleName(dword dwBidnr, dword forwardedModule, word wOmn)
{
m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.OffsetModuleName = wOmn;
}
void BoundImportDirectory::setNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule, word wMfr)
{
m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.NumberOfModuleForwarderRefs = wMfr;
}
void BoundImportDirectory::setModuleName(dword dwBidnr, dword forwardedModule, const std::string& strModuleName)
{
m_vIbd[dwBidnr].moduleForwarders[forwardedModule].strModuleName = strModuleName;
}
word BoundImportDirectory::calcNumberOfModuleForwarderRefs(dword dwBidnr) const
{
return static_cast<word>(m_vIbd[dwBidnr].moduleForwarders.size());
}
void BoundImportDirectory::addForwardedModule(dword dwBidnr, const std::string& name, dword timeStamp, word offsetModuleName, word forwardedModules)
{
// XXX: Maybe test if there are already 0xFFFF forwarded modules.
// XXX: Check for duplicate entries. Is it also necessary to check
// non-forwarded entries and forwarded entries in other non-forwarded
// entries?
// XXX: Can forwarders forward recursively?
PELIB_IMAGE_BOUND_DIRECTORY ibdCurrent;
ibdCurrent.strModuleName = name;
ibdCurrent.ibdDescriptor.TimeDateStamp = timeStamp;
ibdCurrent.ibdDescriptor.OffsetModuleName = offsetModuleName;
ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs = forwardedModules;
m_vIbd[dwBidnr].moduleForwarders.push_back(ibdCurrent);
}
void BoundImportDirectory::removeForwardedModule(dword dwBidnr, word forwardedModule)
{
m_vIbd[dwBidnr].moduleForwarders.erase(m_vIbd[dwBidnr].moduleForwarders.begin() + forwardedModule);
}
}

View file

@ -0,0 +1,87 @@
/*
* BoundImportDirectory.h - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#ifndef BOUNDIMPORTDIRECTORY_H
#define BOUNDIMPORTDIRECTORY_H
#include "PeLibAux.h"
namespace PeLib
{
/// Class that handles the BoundImport directory.
/**
* This class can read and modify the BoundImport directory table of a PE file.
**/
class BoundImportDirectory
{
private:
std::vector<PELIB_IMAGE_BOUND_DIRECTORY> m_vIbd; ///< Stores the individual BoundImport fields.
int read(InputBuffer& inpBuffer, unsigned char* data, unsigned int dwSize);
unsigned int totalModules() const;
public:
/// Adds another bound import.
int addBoundImport(const std::string& strModuleName, dword dwTds, word dwOmn, word wWfr); // EXPORT
/// Identifies a module through it's name.
int getModuleIndex(const std::string& strModuleName) const; // EXPORT
/// Returns the number of files in the BoundImport directory.
unsigned int calcNumberOfModules() const; // EXPORT
/// Reads the BoundImport directory table from a PE file.
int read(const std::string& strFileName, dword dwOffset, unsigned int uiSize); // EXPORT
int read(unsigned char* pcBuffer, unsigned int uiSize); // EXPORT
/// Rebuilds the BoundImport directory.
void rebuild(std::vector<byte>& vBuffer, bool fMakeValid = true) const; // EXPORT
/// Empties the BoundImport directory.
void clear(); // EXPORT
/// Removes a bound import.
void removeBoundImport(const std::string& strModuleName); // EXPORT
/// Returns the size of the BoundImport directory.
unsigned int size() const; // EXPORT
/// Writes the current bound import directory to a file.
int write(const std::string& strFilename, dword dwOffset, bool fMakeValid = true) const; // EXPORT
/// Retrieves the TimeDateStamp value of a bound import.
dword getTimeDateStamp(dword dwBidnr) const; // EXPORT
/// Retrieves the OffsetModuleName value of a bound import.
word getOffsetModuleName(dword dwBidnr) const; // EXPORT
/// Retrieves the NumberOfModuleForwarderRefs value of a bound import.
word getNumberOfModuleForwarderRefs(dword dwBidnr) const; // EXPORT
/// Retrieves the ModuleName value of a bound import.
std::string getModuleName(dword dwBidnr) const; // EXPORT
/// Updates the TimeDateStamp value of a bound import.
void setTimeDateStamp(dword dwBidnr, dword dwTds); // EXPORT
/// Updates the OffsetModuleName value of a bound import.
void setOffsetModuleName(dword dwBidnr, word wOmn); // EXPORT
/// Updates the NumberOfModuleForwarderRefs value of a bound import.
void setNumberOfModuleForwarderRefs(dword dwBidnr, word wMfr); // EXPORT
/// Updates the ModuleName value of a bound import.
void setModuleName(dword dwBidnr, const std::string& strModuleName); // EXPORT
dword getTimeDateStamp(dword dwBidnr, dword forwardedModule) const; // EXPORT _module
word getOffsetModuleName(dword dwBidnr, dword forwardedModule) const; // EXPORT _module
word getNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule) const; // EXPORT _module
std::string getModuleName(dword dwBidnr, dword forwardedModule) const; // EXPORT _module
void setTimeDateStamp(dword dwBidnr, dword forwardedModule, dword dwTds); // EXPORT _module
void setOffsetModuleName(dword dwBidnr, dword forwardedModule, word wOmn); // EXPORT _module
void setNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule, word wMfr); // EXPORT _module
void setModuleName(dword dwBidnr, dword forwardedModule, const std::string& strModuleName); // EXPORT _module
word calcNumberOfModuleForwarderRefs(dword dwBidnr) const; // EXPORT
void addForwardedModule(dword dwBidnr, const std::string& name, dword timeStamp = 0, word offsetModuleName = 0, word forwardedModules = 0); // EXPORT
void removeForwardedModule(dword dwBidnr, word forwardedModule); // EXPORT
};
}
#endif

View file

@ -0,0 +1,467 @@
/*
* ComHeaderDirectory.cpp - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#include "PeLibInc.h"
#include "ComHeaderDirectory.h"
namespace PeLib
{
void ComHeaderDirectory::read(InputBuffer& inputbuffer)
{
PELIB_IMAGE_COR20_HEADER ichCurr;
inputbuffer >> ichCurr.cb;
inputbuffer >> ichCurr.MajorRuntimeVersion;
inputbuffer >> ichCurr.MinorRuntimeVersion;
inputbuffer >> ichCurr.MetaData.VirtualAddress;
inputbuffer >> ichCurr.MetaData.Size;
inputbuffer >> ichCurr.Flags;
inputbuffer >> ichCurr.EntryPointToken;
inputbuffer >> ichCurr.Resources.VirtualAddress;
inputbuffer >> ichCurr.Resources.Size;
inputbuffer >> ichCurr.StrongNameSignature.VirtualAddress;
inputbuffer >> ichCurr.StrongNameSignature.Size;
inputbuffer >> ichCurr.CodeManagerTable.VirtualAddress;
inputbuffer >> ichCurr.CodeManagerTable.Size;
inputbuffer >> ichCurr.VTableFixups.VirtualAddress;
inputbuffer >> ichCurr.VTableFixups.Size;
inputbuffer >> ichCurr.ExportAddressTableJumps.VirtualAddress;
inputbuffer >> ichCurr.ExportAddressTableJumps.Size;
inputbuffer >> ichCurr.ManagedNativeHeader.VirtualAddress;
inputbuffer >> ichCurr.ManagedNativeHeader.Size;
std::swap(ichCurr, m_ichComHeader);
}
int ComHeaderDirectory::read(unsigned char* buffer, unsigned int buffersize)
{
if (buffersize < PELIB_IMAGE_COR20_HEADER::size())
{
return ERROR_INVALID_FILE;
}
std::vector<byte> vComDescDirectory(buffer, buffer + buffersize);
InputBuffer ibBuffer(vComDescDirectory);
read(ibBuffer);
return NO_ERROR;
}
/**
* Reads a file's COM+ descriptor.
* @param strFilename Name of the file.
* @param uiOffset File offset of the COM+ descriptor.
* @param uiSize Size of the COM+ descriptor.
**/
int ComHeaderDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize)
{
std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
unsigned int ulFileSize = fileSize(ifFile);
if (!ifFile)
{
return ERROR_OPENING_FILE;
}
if (ulFileSize < uiOffset + uiSize)
{
return ERROR_INVALID_FILE;
}
ifFile.seekg(uiOffset, std::ios::beg);
std::vector<byte> vComDescDirectory(uiSize);
ifFile.read(reinterpret_cast<char*>(&vComDescDirectory[0]), uiSize);
InputBuffer ibBuffer(vComDescDirectory);
read(ibBuffer);
return NO_ERROR;
}
/**
* Rebuilds the current COM+ descriptor.
* @param vBuffer Buffer where the COM+ descriptor will be written to.
**/
void ComHeaderDirectory::rebuild(std::vector<byte>& vBuffer) const
{
OutputBuffer obBuffer(vBuffer);
obBuffer << m_ichComHeader.cb;
obBuffer << m_ichComHeader.MajorRuntimeVersion;
obBuffer << m_ichComHeader.MinorRuntimeVersion;
obBuffer << m_ichComHeader.MetaData.VirtualAddress;
obBuffer << m_ichComHeader.MetaData.Size;
obBuffer << m_ichComHeader.Flags;
obBuffer << m_ichComHeader.EntryPointToken;
obBuffer << m_ichComHeader.Resources.VirtualAddress;
obBuffer << m_ichComHeader.Resources.Size;
obBuffer << m_ichComHeader.StrongNameSignature.VirtualAddress;
obBuffer << m_ichComHeader.StrongNameSignature.Size;
obBuffer << m_ichComHeader.CodeManagerTable.VirtualAddress;
obBuffer << m_ichComHeader.CodeManagerTable.Size;
obBuffer << m_ichComHeader.VTableFixups.VirtualAddress;
obBuffer << m_ichComHeader.VTableFixups.Size;
obBuffer << m_ichComHeader.ExportAddressTableJumps.VirtualAddress;
obBuffer << m_ichComHeader.ExportAddressTableJumps.Size;
obBuffer << m_ichComHeader.ManagedNativeHeader.VirtualAddress;
obBuffer << m_ichComHeader.ManagedNativeHeader.Size;
}
/**
* @return Size in bytes.
**/
unsigned int ComHeaderDirectory::size() const
{
return PELIB_IMAGE_COR20_HEADER::size();
}
/**
* @param strFilename Name of the file.
* @param dwOffset File offset the COM+ descriptor will be written to.
**/
int ComHeaderDirectory::write(const std::string& strFilename, unsigned int dwOffset) const
{
std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
if (!ofFile)
{
ofFile.clear();
ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
}
else
{
ofFile.close();
ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
}
if (!ofFile)
{
return ERROR_OPENING_FILE;
}
ofFile.seekp(dwOffset, std::ios::beg);
std::vector<unsigned char> vBuffer;
rebuild(vBuffer);
ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
ofFile.close();
return NO_ERROR;
}
/**
* @return SizeOfHeader value of the current COM+ descriptor.
**/
dword ComHeaderDirectory::getSizeOfHeader() const
{
return m_ichComHeader.cb;
}
/**
* @return MajorRuntimeVersion value of the current COM+ descriptor.
**/
word ComHeaderDirectory::getMajorRuntimeVersion() const
{
return m_ichComHeader.MajorRuntimeVersion;
}
/**
* @return MinorRuntimeVersion value of the current COM+ descriptor.
**/
word ComHeaderDirectory::getMinorRuntimeVersion() const
{
return m_ichComHeader.MinorRuntimeVersion;
}
/**
* @return MetaData (Virtual Address) value of the current COM+ descriptor.
**/
dword ComHeaderDirectory::getMetaDataVa() const
{
return m_ichComHeader.MetaData.VirtualAddress;
}
/**
* @return MetaData (Size) value of the current COM+ descriptor.
**/
dword ComHeaderDirectory::getMetaDataSize() const
{
return m_ichComHeader.MetaData.Size;
}
/**
* @return Flags value of the current COM+ descriptor.
**/
dword ComHeaderDirectory::getFlags() const
{
return m_ichComHeader.Flags;
}
/**
* @return EntryPointToken value of the current COM+ descriptor.
**/
dword ComHeaderDirectory::getEntryPointToken() const
{
return m_ichComHeader.EntryPointToken;
}
/**
* @return Resources (Virtual Address) value of the current COM+ descriptor.
**/
dword ComHeaderDirectory::getResourcesVa() const
{
return m_ichComHeader.Resources.VirtualAddress;
}
/**
* @return Resources (Size) value of the current COM+ descriptor.
**/
dword ComHeaderDirectory::getResourcesSize()
{
return m_ichComHeader.Resources.Size;
}
/**
* @return StrongNameSignature (Virtual Address) value of the current COM+ descriptor.
**/
dword ComHeaderDirectory::getStrongNameSignatureVa() const
{
return m_ichComHeader.StrongNameSignature.VirtualAddress;
}
/**
* @return StrongNameSignature (Size) value of the current COM+ descriptor.
**/
dword ComHeaderDirectory::getStrongNameSignagureSize() const
{
return m_ichComHeader.StrongNameSignature.Size;
}
/**
* @return CodeManagerTable (Virtual Address) value of the current COM+ descriptor.
**/
dword ComHeaderDirectory::getCodeManagerTableVa() const
{
return m_ichComHeader.CodeManagerTable.VirtualAddress;
}
/**
* @return CodeManagerTable (Size) value of the current COM+ descriptor.
**/
dword ComHeaderDirectory::getCodeManagerTableSize() const
{
return m_ichComHeader.CodeManagerTable.Size;
}
/**
* @return VTableFixups (Virtual Address) value of the current COM+ descriptor.
**/
dword ComHeaderDirectory::getVTableFixupsVa() const
{
return m_ichComHeader.VTableFixups.VirtualAddress;
}
/**
* @return VTableFixups (Size) value of the current COM+ descriptor.
**/
dword ComHeaderDirectory::getVTableFixupsSize() const
{
return m_ichComHeader.VTableFixups.Size;
}
/**
* @return ExportAddressTableJumps (Virtual Address) value of the current COM+ descriptor.
**/
dword ComHeaderDirectory::getExportAddressTableJumpsVa() const
{
return m_ichComHeader.ExportAddressTableJumps.VirtualAddress;
}
/**
* @return ExportAddressTableJumps (Size) value of the current COM+ descriptor.
**/
dword ComHeaderDirectory::getExportAddressTableJumpsSize() const
{
return m_ichComHeader.ExportAddressTableJumps.Size;
}
/**
* @return ManagedNativeHeader (Virtual Address) value of the current COM+ descriptor.
**/
dword ComHeaderDirectory::getManagedNativeHeaderVa() const
{
return m_ichComHeader.ManagedNativeHeader.VirtualAddress;
}
/**
* @return ManagedNativeHeader (Size) value of the current COM+ descriptor.
**/
dword ComHeaderDirectory::getManagedNativeHeaderSize() const
{
return m_ichComHeader.ManagedNativeHeader.Size;
}
/**
* @param dwValue New value for the current SizeOfHeader (cb) value.
**/
void ComHeaderDirectory::setSizeOfHeader(dword dwValue)
{
m_ichComHeader.cb = dwValue;
}
/**
* @param wValue New value for the current MajorRuntimeVersion value.
**/
void ComHeaderDirectory::setMajorRuntimeVersion(word wValue)
{
m_ichComHeader.MajorRuntimeVersion = wValue;
}
/**
* @param wValue New value for the current MinorRuntimeVersion value.
**/
void ComHeaderDirectory::setMinorRuntimeVersion(word wValue)
{
m_ichComHeader.MinorRuntimeVersion = wValue;
}
/**
* @param dwValue New value for the current MetaData (VirtualAddress) value.
**/
void ComHeaderDirectory::setMetaDataVa(dword dwValue)
{
m_ichComHeader.MetaData.VirtualAddress = dwValue;
}
/**
* @param dwValue New value for the current MetaData (Size) value.
**/
void ComHeaderDirectory::setMetaDataSize(dword dwValue)
{
m_ichComHeader.MetaData.Size = dwValue;
}
/**
* @param dwValue New value for the current Flags value.
**/
void ComHeaderDirectory::setFlags(dword dwValue)
{
m_ichComHeader.Flags = dwValue;
}
/**
* @param dwValue New value for the current EntryPointToken value.
**/
void ComHeaderDirectory::setEntryPointToken(dword dwValue)
{
m_ichComHeader.EntryPointToken = dwValue;
}
/**
* @param dwValue New value for the current Resources (VirtualAddress) value.
**/
void ComHeaderDirectory::setResourcesVa(dword dwValue)
{
m_ichComHeader.Resources.VirtualAddress = dwValue;
}
/**
* @param dwValue New value for the current Resources (Size) value.
**/
void ComHeaderDirectory::setResourcesSize(dword dwValue)
{
m_ichComHeader.Resources.Size = dwValue;
}
/**
* @param dwValue New value for the current StrongNameSignature (VirtualAddress) value.
**/
void ComHeaderDirectory::setStrongNameSignatureVa(dword dwValue)
{
m_ichComHeader.StrongNameSignature.VirtualAddress = dwValue;
}
/**
* @param dwValue New value for the current StrongNameSignature (Size) value.
**/
void ComHeaderDirectory::setStrongNameSignagureSize(dword dwValue)
{
m_ichComHeader.StrongNameSignature.Size = dwValue;
}
/**
* @param dwValue New value for the current CodeManagerTable (VirtualAddress) value.
**/
void ComHeaderDirectory::setCodeManagerTableVa(dword dwValue)
{
m_ichComHeader.CodeManagerTable.VirtualAddress = dwValue;
}
/**
* @param dwValue New value for the current CodeManagerTable (Size) value.
**/
void ComHeaderDirectory::setCodeManagerTableSize(dword dwValue)
{
m_ichComHeader.CodeManagerTable.Size = dwValue;
}
/**
* @param dwValue New value for the current VTableFixups (VirtualAddress) value.
**/
void ComHeaderDirectory::setVTableFixupsVa(dword dwValue)
{
m_ichComHeader.VTableFixups.VirtualAddress = dwValue;
}
/**
* @param dwValue New value for the current VTableFixups (Size) value.
**/
void ComHeaderDirectory::setVTableFixupsSize(dword dwValue)
{
m_ichComHeader.VTableFixups.Size = dwValue;
}
/**
* @param dwValue New value for the current ExportAddressTableJumps (VirtualAddress) value.
**/
void ComHeaderDirectory::setExportAddressTableJumpsVa(dword dwValue)
{
m_ichComHeader.ExportAddressTableJumps.VirtualAddress = dwValue;
}
/**
* @param dwValue New value for the current ExportAddressTableJumps (Size) value.
**/
void ComHeaderDirectory::setExportAddressTableJumpsSize(dword dwValue)
{
m_ichComHeader.ExportAddressTableJumps.Size = dwValue;
}
/**
* @param dwValue New value for the current ManagedNativeHeader (VirtualAddress) value.
**/
void ComHeaderDirectory::setManagedNativeHeaderVa(dword dwValue)
{
m_ichComHeader.ManagedNativeHeader.VirtualAddress = dwValue;
}
/**
* @param dwValue New value for the current ManagedNativeHeader (Size) value.
**/
void ComHeaderDirectory::setManagedNativeHeaderSize(dword dwValue)
{
m_ichComHeader.ManagedNativeHeader.Size = dwValue;
}
}

View file

@ -0,0 +1,120 @@
/*
* ComHeaderDirectory.h - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#ifndef COMHEADERDIRECTORY_H
#define COMHEADERDIRECTORY_H
namespace PeLib
{
/// Class that handles the COM+ descriptor directory.
/**
* This class handles the COM+ Descriptor directory which was added to PE files
* which work with the .NET runtime modules.
**/
class ComHeaderDirectory
{
private:
PELIB_IMAGE_COR20_HEADER m_ichComHeader; ///< The COM+ descriptor.
void read(InputBuffer& inputbuffer);
public:
/// Read a file's COM+ runtime descriptor directory.
int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize); // EXPORT
int read(unsigned char* buffer, unsigned int buffersize); // EXPORT
/// Rebuild the COM+ descriptor.
void rebuild(std::vector<byte>& vBuffer) const; // EXPORT
/// Returns the size of the current COM+ descriptor.
unsigned int size() const; // EXPORT
/// Writes the current COM+ descriptor directory to a file.
int write(const std::string& strFilename, unsigned int dwOffset) const; // EXPORT
/// Get the COM+ descriptor's SizeOfHeader (cb) value.
dword getSizeOfHeader() const; // EXPORT
/// Get the COM+ descriptor's MajorRuntimeVersion value.
word getMajorRuntimeVersion() const; // EXPORT
/// Get the COM+ descriptor's MinorRuntimeVersion value.
word getMinorRuntimeVersion() const; // EXPORT
/// Get the COM+ descriptor's MetaData (Virtual Address) value.
dword getMetaDataVa() const; // EXPORT
/// Get the COM+ descriptor's MetaData (Size) value.
dword getMetaDataSize() const; // EXPORT
/// Get the COM+ descriptor's Flags value.
dword getFlags() const; // EXPORT
/// Get the COM+ descriptor's EntryPointToken value.
dword getEntryPointToken() const; // EXPORT
/// Get the COM+ descriptor's Resources (Virtual Address) value.
dword getResourcesVa() const; // EXPORT
/// Get the COM+ descriptor's Resources (Size) value.
dword getResourcesSize(); // EXPORT
/// Get the COM+ descriptor's StrongNameSignature (Virtual Address) value.
dword getStrongNameSignatureVa() const; // EXPORT
/// Get the COM+ descriptor's StrongNameSignature (Size) value.
dword getStrongNameSignagureSize() const; // EXPORT
/// Get the COM+ descriptor's CodeManagerTable (Virtual Address) value.
dword getCodeManagerTableVa() const; // EXPORT
/// Get the COM+ descriptor's CodeManagerTable (Size) value.
dword getCodeManagerTableSize() const; // EXPORT
/// Get the COM+ descriptor's VTableFixup (Virtual Address) value.
dword getVTableFixupsVa() const; // EXPORT
/// Get the COM+ descriptor's VTableFixup (Size) value.
dword getVTableFixupsSize() const; // EXPORT
/// Get the COM+ descriptor's ExportAddressTable (Virtual Address) value.
dword getExportAddressTableJumpsVa() const; // EXPORT
/// Get the COM+ descriptor's ExportAddressTable (Size) value.
dword getExportAddressTableJumpsSize() const; // EXPORT
/// Get the COM+ descriptor's ManagedNativeHeader (Virtual Address) value.
dword getManagedNativeHeaderVa() const; // EXPORT
/// Get the COM+ descriptor's ManagedNativeHeader (Size) value.
dword getManagedNativeHeaderSize() const; // EXPORT
/// Change the COM+ descriptor's SizeOfHeader (cb) value.
void setSizeOfHeader(dword dwValue); // EXPORT
/// Change the COM+ descriptor's MajorRuntimeVersion value.
void setMajorRuntimeVersion(word wValue); // EXPORT
/// Change the COM+ descriptor's MinorRuntimeVersion value.
void setMinorRuntimeVersion(word wValue); // EXPORT
/// Change the COM+ descriptor's MetaData (VirtualAddress) value.
void setMetaDataVa(dword dwValue); // EXPORT
/// Change the COM+ descriptor's MetaData (Size) value.
void setMetaDataSize(dword dwValue); // EXPORT
/// Change the COM+ descriptor's Flags value.
void setFlags(dword dwValue); // EXPORT
/// Change the COM+ descriptor's EntryPointToken value.
void setEntryPointToken(dword dwValue); // EXPORT
/// Change the COM+ descriptor's Resources (VirtualAddress) value.
void setResourcesVa(dword dwValue); // EXPORT
/// Change the COM+ descriptor's Resources (Size) value.
void setResourcesSize(dword dwValue); // EXPORT
/// Change the COM+ descriptor's StrongNameSignatureVa (VirtualAddress) value.
void setStrongNameSignatureVa(dword dwValue); // EXPORT
/// Change the COM+ descriptor's StrongNameSignatureVa (Size) value.
void setStrongNameSignagureSize(dword dwValue); // EXPORT
/// Change the COM+ descriptor's CodeManagerTable (VirtualAddress) value.
void setCodeManagerTableVa(dword dwValue); // EXPORT
/// Change the COM+ descriptor's CodeManagerTable (Size) value.
void setCodeManagerTableSize(dword dwValue); // EXPORT
/// Change the COM+ descriptor's VTableFixups (VirtualAddress) value.
void setVTableFixupsVa(dword dwValue); // EXPORT
/// Change the COM+ descriptor's VTableFixups (Size) value.
void setVTableFixupsSize(dword dwValue); // EXPORT
/// Change the COM+ descriptor's ExportAddressTableJumps (VirtualAddress) value.
void setExportAddressTableJumpsVa(dword dwValue); // EXPORT
/// Change the COM+ descriptor's ExportAddressTableJumps (Size) value.
void setExportAddressTableJumpsSize(dword dwValue); // EXPORT
/// Change the COM+ descriptor's ManagedNativeHeader (VirtualAddress) value.
void setManagedNativeHeaderVa(dword dwValue); // EXPORT
/// Change the COM+ descriptor's ManagedNativeHeader (Size) value.
void setManagedNativeHeaderSize(dword dwValue); // EXPORT
};
}
#endif

View file

@ -0,0 +1,383 @@
/*
* DebugDirectory.cpp - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#include "PeLibInc.h"
#include "DebugDirectory.h"
namespace PeLib
{
void DebugDirectory::clear()
{
m_vDebugInfo.clear();
}
std::vector<PELIB_IMG_DEBUG_DIRECTORY> DebugDirectory::read(InputBuffer& ibBuffer, unsigned int uiSize)
{
std::vector<PELIB_IMG_DEBUG_DIRECTORY> currDebugInfo;
PELIB_IMG_DEBUG_DIRECTORY iddCurr;
for (unsigned int i=0;i<uiSize/PELIB_IMAGE_DEBUG_DIRECTORY::size();i++)
{
ibBuffer >> iddCurr.idd.Characteristics;
ibBuffer >> iddCurr.idd.TimeDateStamp;
ibBuffer >> iddCurr.idd.MajorVersion;
ibBuffer >> iddCurr.idd.MinorVersion;
ibBuffer >> iddCurr.idd.Type;
ibBuffer >> iddCurr.idd.SizeOfData;
ibBuffer >> iddCurr.idd.AddressOfRawData;
ibBuffer >> iddCurr.idd.PointerToRawData;
currDebugInfo.push_back(iddCurr);
}
return currDebugInfo;
}
int DebugDirectory::read(unsigned char* buffer, unsigned int buffersize)
{
// XXX: Note, debug data is not read at all. This might or might not change
// in the future.
std::vector<byte> vDebugDirectory(buffer, buffer + buffersize);
InputBuffer ibBuffer(vDebugDirectory);
std::vector<PELIB_IMG_DEBUG_DIRECTORY> currDebugInfo = read(ibBuffer, buffersize);
std::swap(currDebugInfo, m_vDebugInfo);
return NO_ERROR;
}
/**
* @param strFilename Name of the file which will be read.
* @param uiOffset File offset of the Debug directory.
* @param uiSize Size of the Debug directory.
**/
int DebugDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize)
{
std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
unsigned int ulFileSize = fileSize(ifFile);
if (!ifFile)
{
return ERROR_OPENING_FILE;
}
if (ulFileSize < uiOffset + uiSize)
{
return ERROR_INVALID_FILE;
}
ifFile.seekg(uiOffset, std::ios::beg);
std::vector<byte> vDebugDirectory(uiSize);
ifFile.read(reinterpret_cast<char*>(&vDebugDirectory[0]), uiSize);
InputBuffer ibBuffer(vDebugDirectory);
std::vector<PELIB_IMG_DEBUG_DIRECTORY> currDebugInfo = read(ibBuffer, uiSize);
for (unsigned int i=0;i<currDebugInfo.size();i++)
{
ifFile.seekg(currDebugInfo[i].idd.PointerToRawData, std::ios::beg);
currDebugInfo[i].data.resize(currDebugInfo[i].idd.SizeOfData);
ifFile.read(reinterpret_cast<char*>(&currDebugInfo[i].data[0]), currDebugInfo[i].idd.SizeOfData);
if (!ifFile) return ERROR_INVALID_FILE;
}
std::swap(currDebugInfo, m_vDebugInfo);
return NO_ERROR;
}
/**
* Rebuilds the current debug directory.
* @param vBuffer Buffer where the rebuilt directory is stored.
**/
void DebugDirectory::rebuild(std::vector<byte>& vBuffer) const
{
OutputBuffer obBuffer(vBuffer);
for (unsigned int i=0;i<m_vDebugInfo.size();i++)
{
obBuffer << m_vDebugInfo[i].idd.Characteristics;
obBuffer << m_vDebugInfo[i].idd.TimeDateStamp;
obBuffer << m_vDebugInfo[i].idd.MajorVersion;
obBuffer << m_vDebugInfo[i].idd.MinorVersion;
obBuffer << m_vDebugInfo[i].idd.Type;
obBuffer << m_vDebugInfo[i].idd.SizeOfData;
obBuffer << m_vDebugInfo[i].idd.AddressOfRawData;
obBuffer << m_vDebugInfo[i].idd.PointerToRawData;
}
}
/**
* @return Size of the debug directory.
**/
unsigned int DebugDirectory::size() const
{
return static_cast<unsigned int>(m_vDebugInfo.size()) * PELIB_IMAGE_DEBUG_DIRECTORY::size();
}
/**
* @param strFilename Name of the file which will be written.
* @param uiOffset File offset where the debug directory will be stored.
**/
int DebugDirectory::write(const std::string& strFilename, unsigned int uiOffset) const
{
std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
if (!ofFile)
{
ofFile.clear();
ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
}
else
{
ofFile.close();
ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
}
if (!ofFile)
{
return ERROR_OPENING_FILE;
}
ofFile.seekp(uiOffset, std::ios::beg);
std::vector<unsigned char> vBuffer;
rebuild(vBuffer);
ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
ofFile.close();
return NO_ERROR;
}
/**
* @return Number of debug structures in the current Debug directory.
**/
unsigned int DebugDirectory::calcNumberOfEntries() const
{
return static_cast<unsigned int>(m_vDebugInfo.size());
}
/**
* Adds a new debug structure to the debug directory. The initial values of all members of the structure
* are undefined.
**/
void DebugDirectory::addEntry()
{
PELIB_IMG_DEBUG_DIRECTORY p;
m_vDebugInfo.push_back(p);
}
/**
* Removes a debug structure from the current debug directory. If an invalid structure is specified
* by the parameter uiIndex the result will be undefined behaviour.
* @param uiIndex Identifies the debug structure.
**/
void DebugDirectory::removeEntry(unsigned int uiIndex)
{
m_vDebugInfo.erase(m_vDebugInfo.begin() + uiIndex);
}
/**
* Returns the Characteristics value of a debug structure. If an invalid structure is specified
* by the parameter uiIndex the result will be undefined behaviour.
* @param uiIndex Identifies the debug structure.
* @return Characteristics value of the debug structure.
**/
dword DebugDirectory::getCharacteristics(unsigned int uiIndex) const
{
return m_vDebugInfo[uiIndex].idd.Characteristics;
}
/**
* Returns the TimeDateStamp value of a debug structure. If an invalid structure is specified
* by the parameter uiIndex the result will be undefined behaviour.
* @param uiIndex Identifies the debug structure.
* @return TimeDateStamp value of the debug structure.
**/
dword DebugDirectory::getTimeDateStamp(unsigned int uiIndex) const
{
return m_vDebugInfo[uiIndex].idd.TimeDateStamp;
}
/**
* Returns the MajorVersion value of a debug structure. If an invalid structure is specified
* by the parameter uiIndex the result will be undefined behaviour.
* @param uiIndex Identifies the debug structure.
* @return MajorVersion value of the debug structure.
**/
word DebugDirectory::getMajorVersion(unsigned int uiIndex) const
{
return m_vDebugInfo[uiIndex].idd.MajorVersion;
}
/**
* Returns the MinorVersion value of a debug structure. If an invalid structure is specified
* by the parameter uiIndex the result will be undefined behaviour.
* @param uiIndex Identifies the debug structure.
* @return MinorVersion value of the debug structure.
**/
word DebugDirectory::getMinorVersion(unsigned int uiIndex) const
{
return m_vDebugInfo[uiIndex].idd.MinorVersion;
}
/**
* Returns the Type value of a debug structure. If an invalid structure is specified
* by the parameter uiIndex the result will be undefined behaviour.
* @param uiIndex Identifies the debug structure.
* @return Type value of the debug structure.
**/
dword DebugDirectory::getType(unsigned int uiIndex) const
{
return m_vDebugInfo[uiIndex].idd.Type;
}
/**
* Returns the SizeOfData value of a debug structure. If an invalid structure is specified
* by the parameter uiIndex the result will be undefined behaviour.
* @param uiIndex Identifies the debug structure.
* @return SizeOfData value of the debug structure.
**/
dword DebugDirectory::getSizeOfData(unsigned int uiIndex) const
{
return m_vDebugInfo[uiIndex].idd.SizeOfData;
}
/**
* Returns the AddressOfRawData value of a debug structure. If an invalid structure is specified
* by the parameter uiIndex the result will be undefined behaviour.
* @param uiIndex Identifies the debug structure.
* @return AddressOfRawData value of the debug structure.
**/
dword DebugDirectory::getAddressOfRawData(unsigned int uiIndex) const
{
return m_vDebugInfo[uiIndex].idd.AddressOfRawData;
}
/**
* Returns the PointerToRawData value of a debug structure. If an invalid structure is specified
* by the parameter uiIndex the result will be undefined behaviour.
* @param uiIndex Identifies the debug structure.
* @return PointerToRawData value of the debug structure.
**/
dword DebugDirectory::getPointerToRawData(unsigned int uiIndex) const
{
return m_vDebugInfo[uiIndex].idd.PointerToRawData;
}
std::vector<byte> DebugDirectory::getData(unsigned int index) const
{
return m_vDebugInfo[index].data;
}
/**
* Changes the Characteristics value of a debug structure. If an invalid structure is specified
* by the parameter uiIndex the result will be undefined behaviour.
* @param uiIndex Identifies the debug structure.
* @param dwValue New value of the Characteristics value of the debug structure.
**/
void DebugDirectory::setCharacteristics(unsigned int uiIndex, dword dwValue)
{
m_vDebugInfo[uiIndex].idd.Characteristics = dwValue;
}
/**
* Changes the TimeDateStamp value of a debug structure. If an invalid structure is specified
* by the parameter uiIndex the result will be undefined behaviour.
* @param uiIndex Identifies the debug structure.
* @param dwValue New value of the TimeDateStamp value of the debug structure.
**/
void DebugDirectory::setTimeDateStamp(unsigned int uiIndex, dword dwValue)
{
m_vDebugInfo[uiIndex].idd.TimeDateStamp = dwValue;
}
/**
* Changes the MajorVersion value of a debug structure. If an invalid structure is specified
* by the parameter uiIndex the result will be undefined behaviour.
* @param uiIndex Identifies the debug structure.
* @param wValue New value of the MajorVersion value of the debug structure.
**/
void DebugDirectory::setMajorVersion(unsigned int uiIndex, word wValue)
{
m_vDebugInfo[uiIndex].idd.MajorVersion = wValue;
}
/**
* Changes the MinorVersion value of a debug structure. If an invalid structure is specified
* by the parameter uiIndex the result will be undefined behaviour.
* @param uiIndex Identifies the debug structure.
* @param wValue New value of the MinorVersion value of the debug structure.
**/
void DebugDirectory::setMinorVersion(unsigned int uiIndex, word wValue)
{
m_vDebugInfo[uiIndex].idd.MinorVersion = wValue;
}
/**
* Changes the Type value of a debug structure. If an invalid structure is specified
* by the parameter uiIndex the result will be undefined behaviour.
* @param uiIndex Identifies the debug structure.
* @param dwValue New value of the Type value of the debug structure.
**/
void DebugDirectory::setType(unsigned int uiIndex, dword dwValue)
{
m_vDebugInfo[uiIndex].idd.Type = dwValue;
}
/**
* Changes the SizeOfData value of a debug structure. If an invalid structure is specified
* by the parameter uiIndex the result will be undefined behaviour.
* @param uiIndex Identifies the debug structure.
* @param dwValue New value of the SizeOfData value of the debug structure.
**/
void DebugDirectory::setSizeOfData(unsigned int uiIndex, dword dwValue)
{
m_vDebugInfo[uiIndex].idd.SizeOfData = dwValue;
}
/**
* Changes the AddressOfRawData value of a debug structure. If an invalid structure is specified
* by the parameter uiIndex the result will be undefined behaviour.
* @param uiIndex Identifies the debug structure.
* @param dwValue New value of the AddressOfRawData value of the debug structure.
**/
void DebugDirectory::setAddressOfRawData(unsigned int uiIndex, dword dwValue)
{
m_vDebugInfo[uiIndex].idd.AddressOfRawData = dwValue;
}
/**
* Changes the PointerToRawData value of a debug structure. If an invalid structure is specified
* by the parameter uiIndex the result will be undefined behaviour.
* @param uiIndex Identifies the debug structure.
* @param dwValue New value of the PointerToRawData value of the debug structure.
**/
void DebugDirectory::setPointerToRawData(unsigned int uiIndex, dword dwValue)
{
m_vDebugInfo[uiIndex].idd.PointerToRawData = dwValue;
}
void DebugDirectory::setData(unsigned int index, const std::vector<byte>& data)
{
m_vDebugInfo[index].data = data;
}
}

View file

@ -0,0 +1,84 @@
/*
* DebugDirectory.h - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#ifndef DEBUGDIRECTORY_H
#define DEBUGDIRECTORY_H
namespace PeLib
{
/// Class that handles the Debug directory.
class DebugDirectory
{
private:
/// Stores the various DebugDirectory structures.
std::vector<PELIB_IMG_DEBUG_DIRECTORY> m_vDebugInfo;
std::vector<PELIB_IMG_DEBUG_DIRECTORY> read(InputBuffer& ibBuffer, unsigned int uiSize);
public:
void clear(); // EXPORT
/// Reads the Debug directory from a file.
int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize); // EXPORT
int read(unsigned char* buffer, unsigned int buffersize);
/// Rebuilds the current Debug directory.
void rebuild(std::vector<byte>& obBuffer) const; // EXPORT
/// Returns the size the current Debug directory needs after rebuilding.
unsigned int size() const;
/// Writes the current Debug directory back to a file.
int write(const std::string& strFilename, unsigned int uiOffset) const; // EXPORT
/// Returns the number of DebugDirectory image structures in the current DebugDirectory.
unsigned int calcNumberOfEntries() const; // EXPORT
/// Adds a new debug structure.
void addEntry(); // EXPORT
/// Removes a debug structure.
void removeEntry(unsigned int uiIndex); // EXPORT
/// Returns the Characteristics value of a debug structure.
dword getCharacteristics(unsigned int uiIndex) const; // EXPORT
/// Returns the TimeDateStamp value of a debug structure.
dword getTimeDateStamp(unsigned int uiIndex) const; // EXPORT
/// Returns the MajorVersion value of a debug structure.
word getMajorVersion(unsigned int uiIndex) const; // EXPORT
/// Returns the MinorVersion value of a debug structure.
word getMinorVersion(unsigned int uiIndex) const; // EXPORT
/// Returns the Type value of a debug structure.
dword getType(unsigned int uiIndex) const; // EXPORT
/// Returns the SizeOfData value of a debug structure.
dword getSizeOfData(unsigned int uiIndex) const; // EXPORT
/// Returns the AddressOfRawData value of a debug structure.
dword getAddressOfRawData(unsigned int uiIndex) const; // EXPORT
/// Returns the PointerToRawData value of a debug structure.
dword getPointerToRawData(unsigned int uiIndex) const; // EXPORT
std::vector<byte> getData(unsigned int index) const; // EXPORT
/// Sets the Characteristics value of a debug structure.
void setCharacteristics(unsigned int uiIndex, dword dwValue); // EXPORT
/// Sets the TimeDateStamp value of a debug structure.
void setTimeDateStamp(unsigned int uiIndex, dword dwValue); // EXPORT
/// Sets the MajorVersion value of a debug structure.
void setMajorVersion(unsigned int uiIndex, word wValue); // EXPORT
/// Sets the MinorVersion value of a debug structure.
void setMinorVersion(unsigned int uiIndex, word wValue); // EXPORT
/// Sets the Type value of a debug structure.
void setType(unsigned int uiIndex, dword dwValue); // EXPORT
/// Sets the SizeOfData value of a debug structure.
void setSizeOfData(unsigned int uiIndex, dword dwValue); // EXPORT
/// Sets the AddressOfRawData value of a debug structure.
void setAddressOfRawData(unsigned int uiIndex, dword dwValue); // EXPORT
/// Sets the PointerToRawData value of a debug structure.
void setPointerToRawData(unsigned int uiIndex, dword dwValue); // EXPORT
void setData(unsigned int index, const std::vector<byte>& data); // EXPORT
};
}
#endif

View file

@ -0,0 +1,692 @@
/*
* ExportDirectory.cpp - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
//#ifdef false
#include "PeLibInc.h"
#include "ExportDirectory.h"
namespace PeLib
{
/**
* @param strFuncname Name of the function.
* @param dwFuncAddr RVA of the function.
**/
void ExportDirectory::addFunction(const std::string& strFuncname, dword dwFuncAddr)
{
PELIB_EXP_FUNC_INFORMATION efiCurr;
efiCurr.funcname = strFuncname;
efiCurr.addroffunc = dwFuncAddr;
m_ied.functions.push_back(efiCurr);
}
void ExportDirectory::removeFunction(unsigned int index)
{
m_ied.functions.erase(m_ied.functions.begin() + index);
}
void ExportDirectory::clear()
{
m_ied.functions.clear();
}
unsigned int ExportDirectory::calcNumberOfFunctions() const
{
return static_cast<unsigned int>(m_ied.functions.size());
}
/**
* Identifies an exported function through it's name.
* @param strFunctionName Name of the function
* @return Number which identifies the functions.
**/
int ExportDirectory::getFunctionIndex(const std::string& strFunctionName) const
{
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));
if (Iter == m_ied.functions.end())
{
// throw Exceptions::InvalidName(ExportDirectoryId, __LINE__);
return -1;
}
return static_cast<int>(std::distance(m_ied.functions.begin(), Iter));
}
/**
* @param strFilename Name of the file.
* @param uiOffset File offset of the export directory.
* @param uiSize Size of the export directory.
* @param pehHeader A valid PE header which is necessary because some RVA calculations need to be done.
* \todo: Proper use of InputBuffer
**/
int ExportDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, const PeHeader& pehHeader)
{
std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
if (!ifFile)
{
return ERROR_OPENING_FILE;
}
unsigned int filesize = fileSize(ifFile);
if (filesize < uiOffset + uiSize)
{
return ERROR_INVALID_FILE;
}
ifFile.seekg(uiOffset, std::ios::beg);
PELIB_IMAGE_EXP_DIRECTORY iedCurr;
std::vector<unsigned char> vExportdirectory(uiSize);
ifFile.read(reinterpret_cast<char*>(&vExportdirectory[0]), uiSize);
InputBuffer inpBuffer(vExportdirectory);
inpBuffer >> iedCurr.ied.Characteristics;
inpBuffer >> iedCurr.ied.TimeDateStamp;
inpBuffer >> iedCurr.ied.MajorVersion;
inpBuffer >> iedCurr.ied.MinorVersion;
inpBuffer >> iedCurr.ied.Name;
inpBuffer >> iedCurr.ied.Base;
inpBuffer >> iedCurr.ied.NumberOfFunctions;
inpBuffer >> iedCurr.ied.NumberOfNames;
inpBuffer >> iedCurr.ied.AddressOfFunctions;
inpBuffer >> iedCurr.ied.AddressOfNames;
inpBuffer >> iedCurr.ied.AddressOfNameOrdinals;
if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
{
unsigned int offset = p32->rvaToOffset(iedCurr.ied.Name);
if (offset >= filesize)
return ERROR_INVALID_FILE;
ifFile.seekg(offset, std::ios::beg);
}
else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
{
// XXX: Files might be > 4 GB
unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.Name));
if (offset >= filesize)
return ERROR_INVALID_FILE;
ifFile.seekg(offset, std::ios::beg);
}
char c = 0;
std::string strFname = "";
do
{
ifFile.read(reinterpret_cast<char*>(&c), sizeof(c));
if (!ifFile) return ERROR_INVALID_FILE;
if (c) strFname += c;
}
while (c != 0);
iedCurr.name = strFname;
if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
{
unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfFunctions);
if (offset >= filesize)
return ERROR_INVALID_FILE;
ifFile.seekg(offset, std::ios::beg);
}
else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
{
// XXX: File might be > 4 GB
unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfFunctions));
if (offset >= filesize)
return ERROR_INVALID_FILE;
ifFile.seekg(offset, std::ios::beg);
}
PELIB_EXP_FUNC_INFORMATION efiCurr;
efiCurr.ordinal = 0; efiCurr.addroffunc = 0; efiCurr.addrofname = 0;
for (unsigned int i=0;i<iedCurr.ied.NumberOfFunctions;i++)
{
if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
{
unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfFunctions) + i*sizeof(efiCurr.addroffunc);
if (offset >= filesize)
return ERROR_INVALID_FILE;
ifFile.seekg(offset, std::ios::beg);
}
else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
{
// XXX: File might be > 4GB
unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfFunctions)) + i*sizeof(efiCurr.addroffunc);
if (offset >= filesize)
return ERROR_INVALID_FILE;
ifFile.seekg(offset, std::ios::beg);
}
ifFile.read(reinterpret_cast<char*>(&efiCurr.addroffunc), sizeof(efiCurr.addroffunc));
if (!ifFile)
return ERROR_INVALID_FILE;
efiCurr.ordinal = i;
iedCurr.functions.push_back(efiCurr);
}
for (unsigned int i=0;i<iedCurr.ied.NumberOfNames;i++)
{
if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
{
unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfNameOrdinals) + i*sizeof(efiCurr.ordinal);
if (offset >= filesize)
return ERROR_INVALID_FILE;
ifFile.seekg(offset, std::ios::beg);
}
else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
{
// XXX: File might be > 4 GB
unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfNameOrdinals)) + i*sizeof(efiCurr.ordinal);
if (offset >= filesize)
return ERROR_INVALID_FILE;
ifFile.seekg(offset, std::ios::beg);
}
word ordinal;
ifFile.read(reinterpret_cast<char*>(&ordinal), sizeof(ordinal));
if (!ifFile)
return ERROR_INVALID_FILE;
iedCurr.functions[ordinal].ordinal = ordinal;
if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
{
unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfNames) + i*sizeof(efiCurr.addrofname);
if (offset >= filesize)
return ERROR_INVALID_FILE;
ifFile.seekg(offset, std::ios::beg);
}
else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
{
// XXX: File might be > 4 GB.
unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfNames)) + i*sizeof(efiCurr.addrofname);
if (offset >= filesize)
return ERROR_INVALID_FILE;
ifFile.seekg(offset, std::ios::beg);
}
ifFile.read(reinterpret_cast<char*>(&iedCurr.functions[ordinal].addrofname), sizeof(iedCurr.functions[ordinal].addrofname));
if (!ifFile)
return ERROR_INVALID_FILE;
if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
{
unsigned int offset = p32->rvaToOffset(iedCurr.functions[ordinal].addrofname);
if (offset >= filesize)
return ERROR_INVALID_FILE;
ifFile.seekg(offset, std::ios::beg);
}
else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
{
// XXX: File might be > 4 GB.
unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.functions[ordinal].addrofname));
if (offset >= filesize)
return ERROR_INVALID_FILE;
ifFile.seekg(static_cast<unsigned int>(p64->rvaToOffset(iedCurr.functions[ordinal].addrofname)), std::ios::beg);
}
char c = 0;
std::string strFname = "";
do
{
ifFile.read(reinterpret_cast<char*>(&c), sizeof(c));
if (!ifFile)
return ERROR_INVALID_FILE;
if (c) strFname += c;
}
while (c != 0);
iedCurr.functions[ordinal].funcname = strFname;
}
std::swap(m_ied, iedCurr);
return NO_ERROR;
}
/**
* @param vBuffer Buffer where the rebuilt export directory is written to.
* @param dwRva RVA of the export directory.
* \todo fValid flag
**/
void ExportDirectory::rebuild(std::vector<byte>& vBuffer, dword dwRva) const
{
unsigned int uiSizeDirectory = sizeof(PELIB_IMAGE_EXPORT_DIRECTORY);
unsigned int uiSizeNames = 0;
unsigned int uiSizeAddrFuncs = 0;
unsigned int uiSizeAddrNames = 0;
unsigned int uiSizeOrdinals = 0;
for (unsigned int i=0;i<m_ied.functions.size();i++)
{
uiSizeNames += (m_ied.functions[i].funcname.empty()) ? 0 : static_cast<unsigned int>(m_ied.functions[i].funcname.size()) + 1;
uiSizeAddrFuncs += sizeof(m_ied.functions[i].addroffunc);
uiSizeAddrNames += (m_ied.functions[i].funcname.empty()) ? 0 : sizeof(m_ied.functions[i].addrofname);
uiSizeOrdinals += (m_ied.functions[i].funcname.empty()) ? 0 : sizeof(m_ied.functions[i].ordinal);
}
unsigned int uiFilenameSize = static_cast<unsigned int>(m_ied.name.size()) + 1;
OutputBuffer obBuffer(vBuffer);
obBuffer << m_ied.ied.Characteristics;
obBuffer << m_ied.ied.TimeDateStamp;
obBuffer << m_ied.ied.MajorVersion;
obBuffer << m_ied.ied.MinorVersion;
obBuffer << dwRva + uiSizeDirectory;
obBuffer << m_ied.ied.Base;
obBuffer << static_cast<unsigned int>(m_ied.functions.size());
// TODO: Not correct but sufficient for now. (Update: I forgot what this comment refers to, but I'll leave it in)
obBuffer << static_cast<unsigned int>(m_ied.functions.size());
obBuffer << dwRva + uiSizeDirectory + uiFilenameSize;
obBuffer << dwRva + uiSizeDirectory + uiFilenameSize + uiSizeAddrFuncs;
obBuffer << dwRva + uiSizeDirectory + uiFilenameSize + uiSizeAddrFuncs + uiSizeAddrNames;
obBuffer.add(m_ied.name.c_str(), static_cast<unsigned int>(m_ied.name.size())+1);
for (unsigned int i=0;i<m_ied.functions.size();i++)
{
obBuffer << m_ied.functions[i].addroffunc;
}
unsigned int ulFuncCounter = dwRva + uiSizeDirectory + uiFilenameSize + uiSizeAddrFuncs + uiSizeAddrNames + uiSizeOrdinals;
for (unsigned int i=0;i<m_ied.functions.size();i++)
{
if (!m_ied.functions[i].funcname.empty())
{
obBuffer << ulFuncCounter;
ulFuncCounter += static_cast<unsigned int>(m_ied.functions[i].funcname.size()) + 1;
}
}
for (unsigned int i=0;i<m_ied.functions.size();i++)
{
if (!m_ied.functions[i].funcname.empty())
{
obBuffer << m_ied.functions[i].ordinal;
}
}
for (unsigned int i=0;i<m_ied.functions.size();i++)
{
if (m_ied.functions[i].funcname.empty() && m_ied.functions[i].addroffunc)
{
obBuffer << m_ied.functions[i].ordinal;
}
}
for (unsigned int i=0;i<m_ied.functions.size();i++)
{
if (!m_ied.functions[i].funcname.empty())
{
obBuffer.add(m_ied.functions[i].funcname.c_str(), static_cast<unsigned int>(m_ied.functions[i].funcname.size()) + 1);
}
}
}
/**
* @return Size of the current export directory.
**/
unsigned int ExportDirectory::size() const
{
return m_ied.size();
}
/**
* @param strFilename Name of the file.
* @param uiOffset File offset the export directory will be written to.
* @param uiRva RVA of the export directory.
* \todo Check if ofFile.write succeeded.
**/
int ExportDirectory::write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva) const
{
std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
if (!ofFile)
{
ofFile.clear();
ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
}
else
{
ofFile.close();
ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
}
if (!ofFile)
{
return ERROR_OPENING_FILE;
}
ofFile.seekp(uiOffset, std::ios::beg);
std::vector<unsigned char> vBuffer;
rebuild(vBuffer, uiRva);
ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
ofFile.close();
return NO_ERROR;
}
/**
* Changes the filename according to the export directory.
* @param strFilename New filename.
**/
void ExportDirectory::setNameString(const std::string& strFilename)
{
m_ied.name = strFilename;
}
std::string ExportDirectory::getNameString() const
{
return m_ied.name;
}
/**
* @param dwIndex Number which identifies an exported function.
* @return The name of that function.
**/
std::string ExportDirectory::getFunctionName(dword dwIndex) const
{
return m_ied.functions[dwIndex].funcname;
}
/**
* @param dwIndex Number which identifies an exported function.
* @return The ordinal of that function.
**/
word ExportDirectory::getFunctionOrdinal(dword dwIndex) const
{
return m_ied.functions[dwIndex].ordinal;
}
/**
* @param dwIndex Number which identifies an exported function.
* @return The RVA of the name string of that function.
**/
dword ExportDirectory::getAddressOfName(dword dwIndex) const
{
return m_ied.functions[dwIndex].addrofname;
}
/**
* @param dwIndex Number which identifies an exported function.
* @return The RVA of that function.
**/
dword ExportDirectory::getAddressOfFunction(dword dwIndex) const
{
return m_ied.functions[dwIndex].addroffunc;
}
/**
* @param dwIndex Number which identifies an exported function.
* @param strName The name of that function.
**/
void ExportDirectory::setFunctionName(dword dwIndex, const std::string& strName)
{
m_ied.functions[dwIndex].funcname = strName;
}
/**
* @param dwIndex Number which identifies an exported function.
* @param wValue The ordinal of that function.
**/
void ExportDirectory::setFunctionOrdinal(dword dwIndex, word wValue)
{
m_ied.functions[dwIndex].ordinal = wValue;
}
/**
* @param dwIndex Number which identifies an exported function.
* @param dwValue The RVA of the name string of that function.
**/
void ExportDirectory::setAddressOfName(dword dwIndex, dword dwValue)
{
m_ied.functions[dwIndex].addrofname = dwValue;
}
/**
* @param dwIndex Number which identifies an exported function.
* @param dwValue The RVA of that function.
**/
void ExportDirectory::setAddressOfFunction(dword dwIndex, dword dwValue)
{
m_ied.functions[dwIndex].addroffunc = dwValue;
}
/**
* @return The ordinal base of the export directory.
**/
dword ExportDirectory::getBase() const
{
return m_ied.ied.Base;
}
/**
* @return The characteristics of the export directory.
**/
dword ExportDirectory::getCharacteristics() const
{
return m_ied.ied.Characteristics;
}
/**
* @return The time/date stamp of the export directory.
**/
dword ExportDirectory::getTimeDateStamp() const
{
return m_ied.ied.TimeDateStamp;
}
/**
* @return The MajorVersion of the export directory.
**/
word ExportDirectory::getMajorVersion() const
{
return m_ied.ied.MajorVersion;
}
/**
* @return The MinorVersion of the export directory.
**/
word ExportDirectory::getMinorVersion() const
{
return m_ied.ied.MinorVersion;
}
/**
* @return The RVA of the name of the file.
**/
dword ExportDirectory::getName() const
{
return m_ied.ied.Name;
}
/**
* @return The NumberOfFunctions of the export directory.
**/
dword ExportDirectory::getNumberOfFunctions() const
{
return m_ied.ied.NumberOfFunctions;
}
/**
* @return The NumberOfNames of the export directory.
**/
dword ExportDirectory::getNumberOfNames() const
{
return m_ied.ied.NumberOfNames;
}
/**
* @return The AddressOfFunctions of the export directory.
**/
dword ExportDirectory::getAddressOfFunctions() const
{
return m_ied.ied.AddressOfFunctions;
}
/**
* @return The AddressOfNames of the export directory.
**/
dword ExportDirectory::getAddressOfNames() const
{
return m_ied.ied.AddressOfNames;
}
/* dword ExportDirectory::getNumberOfNameOrdinals() const
{
return static_cast<dword>(m_ied.functions.size());
}
dword ExportDirectory::getNumberOfAddressOfFunctionNames() const
{
return static_cast<dword>(m_ied.functions.size());
}
dword ExportDirectory::getNumberOfAddressOfFunctions() const
{
return static_cast<dword>(m_ied.functions.size());
}
*/
/**
* @return The AddressOfNameOrdinals of the export directory.
**/
dword ExportDirectory::getAddressOfNameOrdinals() const
{
return m_ied.ied.AddressOfNameOrdinals;
}
/**
* @param dwValue The ordinal base of the export directory.
**/
void ExportDirectory::setBase(dword dwValue)
{
m_ied.ied.Base = dwValue;
}
/**
* @param dwValue The Characteristics of the export directory.
**/
void ExportDirectory::setCharacteristics(dword dwValue)
{
m_ied.ied.Characteristics = dwValue;
}
/**
* @param dwValue The TimeDateStamp of the export directory.
**/
void ExportDirectory::setTimeDateStamp(dword dwValue)
{
m_ied.ied.TimeDateStamp = dwValue;
}
/**
* @param wValue The MajorVersion of the export directory.
**/
void ExportDirectory::setMajorVersion(word wValue)
{
m_ied.ied.MajorVersion = wValue;
}
/**
* @param wValue The MinorVersion of the export directory.
**/
void ExportDirectory::setMinorVersion(word wValue)
{
m_ied.ied.MinorVersion = wValue;
}
/**
* @param dwValue The Name of the export directory.
**/
void ExportDirectory::setName(dword dwValue)
{
m_ied.ied.Name = dwValue;
}
/**
* @param dwValue The NumberOfFunctions of the export directory.
**/
void ExportDirectory::setNumberOfFunctions(dword dwValue)
{
m_ied.ied.NumberOfFunctions = dwValue;
}
/**
* @param dwValue The NumberOfNames of the export directory.
**/
void ExportDirectory::setNumberOfNames(dword dwValue)
{
m_ied.ied.NumberOfNames = dwValue;
}
/**
* @param dwValue The AddressOfFunctions of the export directory.
**/
void ExportDirectory::setAddressOfFunctions(dword dwValue)
{
m_ied.ied.AddressOfFunctions = dwValue;
}
/**
* @param dwValue The AddressOfNames of the export directory.
**/
void ExportDirectory::setAddressOfNames(dword dwValue)
{
m_ied.ied.AddressOfNames = dwValue;
}
void ExportDirectory::setAddressOfNameOrdinals(dword value)
{
m_ied.ied.AddressOfNameOrdinals = value;
}
}

View file

@ -0,0 +1,133 @@
/*
* ExportDirectory.h - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#ifndef EXPORTDIRECTORY_H
#define EXPORTDIRECTORY_H
#include "PeHeader.h"
namespace PeLib
{
/// Class that handles the export directory.
/**
* This class handles the export directory.
* \todo getNameString
**/
// template<int bits>
class ExportDirectory
{
private:
/// Used to store all necessary information about a file's exported functions.
PELIB_IMAGE_EXP_DIRECTORY m_ied;
public:
/// Add another function to be exported.
void addFunction(const std::string& strFuncname, dword dwFuncAddr); // EXPORT
unsigned int calcNumberOfFunctions() const; // EXPORT
void clear(); // EXPORT
/// Identifies a function through it's name.
int getFunctionIndex(const std::string& strFunctionName) const; // EXPORT
/// Read a file's export directory.
int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, const PeHeader& pehHeader); // EXPORT
/// Rebuild the current export directory.
void rebuild(std::vector<byte>& vBuffer, dword dwRva) const; // EXPORT
void removeFunction(unsigned int index); // EXPORT
/// Returns the size of the current export directory.
unsigned int size() const; // EXPORT
/// Writes the current export directory to a file.
int write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva) const; // EXPORT
/// Changes the name of the file (according to the export directory).
void setNameString(const std::string& strFilename); // EXPORT
std::string getNameString() const; // EXPORT
/// Get the name of an exported function.
std::string getFunctionName(unsigned int index) const; // EXPORT
/// Get the ordinal of an exported function.
word getFunctionOrdinal(unsigned int index) const; // EXPORT
/// Get the address of the name of an exported function.
dword getAddressOfName(unsigned int index) const; // EXPORT
/// Get the address of an exported function.
dword getAddressOfFunction(unsigned int index) const; // EXPORT
/// Change the name of an exported function.
void setFunctionName(unsigned int index, const std::string& strName); // EXPORT
/// Change the ordinal of an exported function.
void setFunctionOrdinal(unsigned int index, word wValue); // EXPORT
/// Change the address of the name of an exported function.
void setAddressOfName(unsigned int index, dword dwValue); // EXPORT
/// Change the address of an exported function.
void setAddressOfFunction(unsigned int index, dword dwValue); // EXPORT
/*
word getFunctionOrdinal(std::string strFuncname) const;
dword getAddressOfName(std::string strFuncname) const;
dword getAddressOfFunction(std::string strFuncname) const;
void setFunctionOrdinal(std::string strFuncname, word wValue);
void setAddressOfName(std::string strFuncname, dword dwValue);
void setAddressOfFunction(std::string strFuncname, dword dwValue);
*/
/// Return the Base value of the export directory.
dword getBase() const; // EXPORT
/// Return the Characteristics value of the export directory.
dword getCharacteristics() const; // EXPORT
/// Return the TimeDateStamp value of the export directory.
dword getTimeDateStamp() const; // EXPORT
/// Return the MajorVersion value of the export directory.
word getMajorVersion() const; // EXPORT
/// Return the MinorVersion value of the export directory.
word getMinorVersion() const; // EXPORT
/// Return the Name value of the export directory.
dword getName() const; // EXPORT
/// Return the NumberOfFunctions value of the export directory.
dword getNumberOfFunctions() const; // EXPORT
/// Return the NumberOfNames value of the export directory.
dword getNumberOfNames() const; // EXPORT
/// Return the AddressOfFunctions value of the export directory.
dword getAddressOfFunctions() const; // EXPORT
/// Return the AddressOfNames value of the export directory.
dword getAddressOfNames() const; // EXPORT
/// Returns the AddressOfNameOrdinals value.
dword getAddressOfNameOrdinals() const; // EXPORT
/* /// Returns the number of NameOrdinals.
dword getNumberOfNameOrdinals() const; // EXPORT
/// Returns the number of AddressOfFunctionNames values.
dword getNumberOfAddressOfFunctionNames() const; // EXPORT
/// Returns the number of AddressOfFunction values.
dword getNumberOfAddressOfFunctions() const; // EXPORT
*/
/// Set the Base value of the export directory.
void setBase(dword dwValue); // EXPORT
/// Set the Characteristics value of the export directory.
void setCharacteristics(dword dwValue); // EXPORT
/// Set the TimeDateStamp value of the export directory.
void setTimeDateStamp(dword dwValue); // EXPORT
/// Set the MajorVersion value of the export directory.
void setMajorVersion(word wValue); // EXPORT
/// Set the MinorVersion value of the export directory.
void setMinorVersion(word wValue); // EXPORT
/// Set the Name value of the export directory.
void setName(dword dwValue); // EXPORT
/// Set the NumberOfFunctions value of the export directory.
void setNumberOfFunctions(dword dwValue); // EXPORT
/// Set the NumberOfNames value of the export directory.
void setNumberOfNames(dword dwValue); // EXPORT
/// Set the AddressOfFunctions value of the export directory.
void setAddressOfFunctions(dword dwValue); // EXPORT
/// Set the AddressOfNames value of the export directory.
void setAddressOfNames(dword dwValue); // EXPORT
void setAddressOfNameOrdinals(dword value); // EXPORT
};
}
#endif

View file

@ -0,0 +1,179 @@
/*
* IatDirectory.h - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#include "IatDirectory.h"
namespace PeLib
{
int IatDirectory::read(InputBuffer& inputBuffer, unsigned int size)
{
dword dwAddr;
std::vector<dword> vIat;
for (unsigned int i=0;i<size/sizeof(dword);i++)
{
inputBuffer >> dwAddr;
vIat.push_back(dwAddr);
}
std::swap(vIat, m_vIat);
return NO_ERROR;
}
/**
* Reads the Import Address table from a file.
* @param strFilename Name of the file.
* @param dwOffset File offset of the IAT (see #PeFile::PeHeader::getIDIatRVA).
* @param dwSize Size of the IAT (see #PeFile::PeHeader::getIDIatSize).
**/
int IatDirectory::read(const std::string& strFilename, unsigned int dwOffset, unsigned int dwSize)
{
std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
if (!ifFile)
{
return ERROR_OPENING_FILE;
}
if (fileSize(ifFile) < dwOffset + dwSize)
{
return ERROR_INVALID_FILE;
}
ifFile.seekg(dwOffset, std::ios::beg);
std::vector<byte> vBuffer(dwSize);
ifFile.read(reinterpret_cast<char*>(&vBuffer[0]), dwSize);
InputBuffer inpBuffer(vBuffer);
return read(inpBuffer, dwSize);
}
int IatDirectory::read(unsigned char* buffer, unsigned int buffersize)
{
std::vector<byte> vBuffer(buffer, buffer + buffersize);
InputBuffer inpBuffer(vBuffer);
return read(inpBuffer, buffersize);
}
/**
* Returns the number of fields in the IAT. This is equivalent to the number of
* imported functions.
* @return Number of fields in the IAT.
**/
unsigned int IatDirectory::calcNumberOfAddresses() const
{
return static_cast<unsigned int>(m_vIat.size());
}
/**
* Returns the dwValue of a field in the IAT.
* @param dwAddrnr Number identifying the field.
* @return dwValue of the field.
**/
dword IatDirectory::getAddress(unsigned int index) const
{
return m_vIat[index];
}
/**
* Updates the dwValue of a field in the IAT.
* @param dwAddrnr Number identifying the field.
* @param dwValue New dwValue of the field.
**/
void IatDirectory::setAddress(dword dwAddrnr, dword dwValue)
{
m_vIat[dwAddrnr] = dwValue;
}
/**
* Adds another field to the IAT.
* @param dwValue dwValue of the new field.
**/
void IatDirectory::addAddress(dword dwValue)
{
m_vIat.push_back(dwValue);
}
/**
* Removes an address from the IAT.
* @param dwAddrnr Number identifying the field.
**/
void IatDirectory::removeAddress(unsigned int index)
{
std::vector<dword>::iterator pos = m_vIat.begin() + index;
m_vIat.erase(pos);
}
/**
* Delete all entries from the IAT.
**/
void IatDirectory::clear()
{
m_vIat.clear();
}
/**
* Rebuilds the complete Import Address Table.
* @param vBuffer Buffer where the rebuilt IAT will be stored.
**/
void IatDirectory::rebuild(std::vector<byte>& vBuffer) const
{
vBuffer.reserve(size());
OutputBuffer obBuffer(vBuffer);
for (unsigned int i=0;i<m_vIat.size();i++)
{
obBuffer << m_vIat[i];
}
}
unsigned int IatDirectory::size() const
{
return static_cast<unsigned int>(m_vIat.size())* sizeof(dword);
}
/// Writes the current IAT to a file.
int IatDirectory::write(const std::string& strFilename, unsigned int uiOffset) const
{
std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
if (!ofFile)
{
ofFile.clear();
ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
}
else
{
ofFile.close();
ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
}
if (!ofFile)
{
return ERROR_OPENING_FILE;
}
ofFile.seekp(uiOffset, std::ios::beg);
std::vector<unsigned char> vBuffer;
rebuild(vBuffer);
ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
ofFile.close();
return NO_ERROR;
}
}

View file

@ -0,0 +1,58 @@
/*
* IatDirectory.h - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#ifndef IATDIRECTORY_H
#define IATDIRECTORY_H
#include "PeLibInc.h"
namespace PeLib
{
/// Class that handles the Import Address Table (IAT)
/**
* This class can read and modify the Import Address Table of a PE file.
**/
class IatDirectory
{
private:
std::vector<dword> m_vIat; ///< Stores the individual IAT fields.
int read(InputBuffer& inputBuffer, unsigned int size);
public:
/// Reads the Import Address Table from a PE file.
int read(const std::string& strFilename, unsigned int dwOffset, unsigned int dwSize); // EXPORT
int read(unsigned char* buffer, unsigned int buffersize); // EXPORT
/// Returns the number of fields in the IAT.
unsigned int calcNumberOfAddresses() const; // EXPORT
/// Adds another address to the IAT.
void addAddress(dword dwValue); // EXPORT
/// Removes an address from the IAT.
void removeAddress(unsigned int index); // EXPORT
/// Empties the IAT.
void clear(); // EXPORT
// Rebuilds the IAT.
void rebuild(std::vector<byte>& vBuffer) const; // EXPORT
/// Returns the size of the current IAT.
unsigned int size() const; // EXPORT
/// Writes the current IAT to a file.
int write(const std::string& strFilename, unsigned int uiOffset) const; // EXPORT
/// Retrieve the value of a field in the IAT.
dword getAddress(unsigned int index) const; // EXPORT
/// Change the value of a field in the IAT.
void setAddress(dword dwAddrnr, dword dwValue); // EXPORT
};
}
#endif

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,584 @@
/*
* MzHeader.cpp - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#include "MzHeader.h"
#include <iostream>
namespace PeLib
{
/**
* Reads data from an InputBuffer into the struct that represents the MZ header.
* It's required that the size of the input buffer is at least as big as the
* size of a MZ header. Otherwise we get undefined behaviour.
* @param ibBuffer InputBuffer that holds the data.
* @return A non-zero value is returned if a problem occured.
**/
void MzHeader::read(InputBuffer& ibBuffer)
{
ibBuffer >> m_idhHeader.e_magic;
ibBuffer >> m_idhHeader.e_cblp;
ibBuffer >> m_idhHeader.e_cp;
ibBuffer >> m_idhHeader.e_crlc;
ibBuffer >> m_idhHeader.e_cparhdr;
ibBuffer >> m_idhHeader.e_minalloc;
ibBuffer >> m_idhHeader.e_maxalloc;
ibBuffer >> m_idhHeader.e_ss;
ibBuffer >> m_idhHeader.e_sp;
ibBuffer >> m_idhHeader.e_csum;
ibBuffer >> m_idhHeader.e_ip;
ibBuffer >> m_idhHeader.e_cs;
ibBuffer >> m_idhHeader.e_lfarlc;
ibBuffer >> m_idhHeader.e_ovno;
for (unsigned int i=0;i<sizeof(m_idhHeader.e_res)/sizeof(m_idhHeader.e_res[0]);i++)
{
ibBuffer >> m_idhHeader.e_res[i];
}
ibBuffer >> m_idhHeader.e_oemid;
ibBuffer >> m_idhHeader.e_oeminfo;
for (unsigned int i=0;i<sizeof(m_idhHeader.e_res2)/sizeof(m_idhHeader.e_res2[0]);i++)
{
ibBuffer >> m_idhHeader.e_res2[i];
}
ibBuffer >> m_idhHeader.e_lfanew;
}
/**
* Tests if the currently loaded MZ header is a valid MZ header.
* Note that this function does not check if the address to the PE header is valid as this is not possible.
* Actually, the only thing this function checks is if the e_magic value is set to 0x5A4D (IMAGE_DOS_SIGNATURE).
* Everything else is not relevant for Windows 2000 and that's the system PeLib is focusing on for now.
* @return A boolean value that indicates if the MZ header is correct or not.
**/
bool MzHeader::isValid() const
{
// The only thing that matters on Windows 2K is the e_magic value. The entire rest is for DOS compatibility.
return isValid(e_magic);
}
bool MzHeader::isValid(Field f) const
{
if (f == e_magic)
{
return m_idhHeader.e_magic == PELIB_IMAGE_DOS_SIGNATURE;
}
else
{
return true;
}
}
/**
* Corrects all erroneous values of the current MZ header. Note that this function does not correct the
* pointer to the PE header.
* Actually, the only thing this function corrects is the e_magic value.
* Everything else is not relevant for Windows 2000 and that's the system PeLib is focusing on for now.
**/
void MzHeader::makeValid()
{
// The only thing that matters on Windows is the e_magic value. The entire rest is for DOS compatibility.
setMagicNumber(PELIB_IMAGE_DOS_SIGNATURE);
}
void MzHeader::makeValid(Field f)
{
if (f == e_magic)
{
setMagicNumber(PELIB_IMAGE_DOS_SIGNATURE);
}
}
/**
* Reads the MZ header from a file. Note that this function does not verify if a file is actually a MZ file.
* For this purpose see #PeFile::MzHeader::isValid. The reason for this is simple: Otherwise it might not
* be possible to load damaged PE files to repair them.
* @param strFilename Name of the file which will be read.
* @return A non-zero value is returned if a problem occured.
**/
int MzHeader::read(const std::string& strFilename)
{
std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
if (!ifFile)
{
return ERROR_OPENING_FILE;
}
if (fileSize(ifFile) < PELIB_IMAGE_DOS_HEADER::size())
{
return ERROR_INVALID_FILE;
}
ifFile.seekg(0, std::ios::beg);
originalOffset = 0;
std::vector<byte> vBuffer(PELIB_IMAGE_DOS_HEADER::size());
ifFile.read(reinterpret_cast<char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
ifFile.close();
InputBuffer ibBuffer(vBuffer);
read(ibBuffer);
return NO_ERROR;
}
/**
* Reads the MZ header from memory. A pointer to a location in memory is passed and the data
* at this location is treated like a MZ header structure. The MZ header does not need to be valid.
* @param pcBuffer Pointer to a MZ header.
* @param uiSize Length of the buffer.
* @return A non-zero value is returned if a problem occured.
**/
int MzHeader::read(unsigned char* pcBuffer, unsigned int uiSize, unsigned int originalOffs)
{
if (uiSize < PELIB_IMAGE_DOS_HEADER::size())
{
return ERROR_INVALID_FILE;
}
std::vector<byte> vBuffer(pcBuffer, pcBuffer + uiSize);
for (int i=0;i<0x40;i++) std::cout << std::hex << (int)vBuffer[i] << " ";
originalOffset = originalOffs;
InputBuffer ibBuffer(vBuffer);
read(ibBuffer);
return NO_ERROR;
}
/**
* Rebuilds the MZ header so that it can be written to a file. It's not guaranteed that the
* MZ header will be valid. If you want to make sure that the MZ header will be valid you
* must call #PeLib::MzHeader::makeValid first.
* @param vBuffer Buffer where the rebuilt MZ header will be stored.
**/
void MzHeader::rebuild(std::vector<byte>& vBuffer) const
{
OutputBuffer obBuffer(vBuffer);
obBuffer << m_idhHeader.e_magic;
obBuffer << m_idhHeader.e_cblp;
obBuffer << m_idhHeader.e_cp;
obBuffer << m_idhHeader.e_crlc;
obBuffer << m_idhHeader.e_cparhdr;
obBuffer << m_idhHeader.e_minalloc;
obBuffer << m_idhHeader.e_maxalloc;
obBuffer << m_idhHeader.e_ss;
obBuffer << m_idhHeader.e_sp;
obBuffer << m_idhHeader.e_csum;
obBuffer << m_idhHeader.e_ip;
obBuffer << m_idhHeader.e_cs;
obBuffer << m_idhHeader.e_lfarlc;
obBuffer << m_idhHeader.e_ovno;
for (unsigned int i=0;i<sizeof(m_idhHeader.e_res)/sizeof(m_idhHeader.e_res[0]);i++)
{
obBuffer << m_idhHeader.e_res[i];
}
obBuffer << m_idhHeader.e_oemid;
obBuffer << m_idhHeader.e_oeminfo;
for (unsigned int i=0;i<sizeof(m_idhHeader.e_res2)/sizeof(m_idhHeader.e_res2[0]);i++)
{
obBuffer << m_idhHeader.e_res2[i];
}
obBuffer << m_idhHeader.e_lfanew;
}
/**
* Returns the size of the MZ header. This size is actually always sizeof(IMAGE_DOS_HEADER) (== 0x40)
* because the MZ header is a header of constant size if you disregard the dos stub. If you want to know the
* size of the MZ header + the size of the dos stub check #PeLib::MzHeader::getAddressOfPeHeader.
* @return Size of the MZ header.
**/
unsigned int MzHeader::size() const
{
return sizeof(m_idhHeader);
}
/**
* Writes the current MZ header to a file. The file does not have to exist. If it doesn't exist
* it will be created.
* @param strFilename Name of the file the header will be written to.
* @param dwOffset Offset the header will be written to (defaults to 0).
* @return A non-zero value is returned if a problem occured.
**/
int MzHeader::write(const std::string& strFilename, dword dwOffset = 0) const
{
std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
if (!ofFile)
{
ofFile.clear();
ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
}
else
{
ofFile.close();
ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
}
if (!ofFile)
{
return ERROR_OPENING_FILE;
}
ofFile.seekp(dwOffset, std::ios::beg);
std::vector<unsigned char> vBuffer;
rebuild(vBuffer);
ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
ofFile.close();
return NO_ERROR;
}
/**
* Returns the MZ header's e_magic value.
**/
word MzHeader::getMagicNumber() const
{
return m_idhHeader.e_magic;
}
/**
* Returns the MZ header's e_cblp value.
**/
word MzHeader::getBytesOnLastPage() const
{
return m_idhHeader.e_cblp;
}
/**
* Returns the MZ header's e_cp value.
**/
word MzHeader::getPagesInFile() const
{
return m_idhHeader.e_cp;
}
/**
* Returns the MZ header's e_crlc value.
**/
word MzHeader::getRelocations() const
{
return m_idhHeader.e_crlc;
}
/**
* Returns the MZ header's e_cparhdr value.
**/
word MzHeader::getSizeOfHeader() const
{
return m_idhHeader.e_cparhdr;
}
/**
* Returns the MZ header's e_minalloc value.
**/
word MzHeader::getMinExtraParagraphs() const
{
return m_idhHeader.e_minalloc;
}
/**
* Returns the MZ header's e_maxalloc value.
**/
word MzHeader::getMaxExtraParagraphs() const
{
return m_idhHeader.e_maxalloc;
}
/**
* Returns the MZ header's e_ss value.
**/
word MzHeader::getSsValue() const
{
return m_idhHeader.e_ss;
}
/**
* Returns the MZ header's e_sp value.
**/
word MzHeader::getSpValue() const
{
return m_idhHeader.e_sp;
}
/**
* Returns the MZ header's e_csum value.
**/
word MzHeader::getChecksum() const
{
return m_idhHeader.e_csum;
}
/**
* Returns the MZ header's e_ip value.
**/
word MzHeader::getIpValue() const
{
return m_idhHeader.e_ip;
}
/**
* Returns the MZ header's e_cs value.
**/
word MzHeader::getCsValue() const
{
return m_idhHeader.e_cs;
}
/**
* Returns the MZ header's e_lfarlc value.
**/
word MzHeader::getAddrOfRelocationTable() const
{
return m_idhHeader.e_lfarlc;
}
/**
* Returns the MZ header's e_ovno value.
**/
word MzHeader::getOverlayNumber() const
{
return m_idhHeader.e_ovno;
}
/**
* Returns the MZ header's e_oemid value.
**/
word MzHeader::getOemIdentifier() const
{
return m_idhHeader.e_oemid;
}
/**
* Returns the MZ header's e_oeminfo value.
**/
word MzHeader::getOemInformation() const
{
return m_idhHeader.e_oeminfo;
}
/**
* Returns the MZ header's e_lfanew value.
**/
dword MzHeader::getAddressOfPeHeader() const
{
return m_idhHeader.e_lfanew;
}
/**
* Returns the MZ header's e_res[uiNr] value. If the parameter uiNr is out of range
* you will get undefined behaviour.
* @param uiNr The index of the word in the e_res array (valid range: 0-3)
**/
word MzHeader::getReservedWords1(unsigned int uiNr) const
{
return m_idhHeader.e_res[uiNr];
}
/**
* Returns the MZ header's e_res2[uiNr] value. If the parameter uiNr is out of range
* you will get undefined behaviour.
* @param uiNr The index of the word in the e_res array (valid range: 0-9)
**/
word MzHeader::getReservedWords2(unsigned int uiNr) const
{
return m_idhHeader.e_res2[uiNr];
}
/**
* Sets the MZ header's e_magic value.
* @param wValue The new value of e_magic.
**/
void MzHeader::setMagicNumber(word wValue)
{
m_idhHeader.e_magic = wValue;
}
/**
* Sets the MZ header's e_cblp value.
* @param wValue The new value of e_cblp.
**/
void MzHeader::setBytesOnLastPage(word wValue)
{
m_idhHeader.e_cblp = wValue;
}
/**
* Sets the MZ header's e_cp value.
* @param wValue The new value of e_cp.
**/
void MzHeader::setPagesInFile(word wValue)
{
m_idhHeader.e_cp = wValue;
}
/**
* Sets the MZ header's e_crlc value.
* @param wValue The new value of e_crlc.
**/
void MzHeader::setRelocations(word wValue)
{
m_idhHeader.e_crlc = wValue;
}
/**
* Sets the MZ header's e_cparhdr value.
* @param wValue The new value of e_cparhdr.
**/
void MzHeader::setSizeOfHeader(word wValue)
{
m_idhHeader.e_cparhdr = wValue;
}
/**
* Sets the MZ header's e_minalloc value.
* @param wValue The new value of e_minalloc.
**/
void MzHeader::setMinExtraParagraphs(word wValue)
{
m_idhHeader.e_minalloc = wValue;
}
/**
* Sets the MZ header's e_maxalloc value.
* @param wValue The new value of e_maxalloc.
**/
void MzHeader::setMaxExtraParagraphs(word wValue)
{
m_idhHeader.e_maxalloc = wValue;
}
/**
* Sets the MZ header's e_ss value.
* @param wValue The new value of e_ss.
**/
void MzHeader::setSsValue(word wValue)
{
m_idhHeader.e_ss = wValue;
}
/**
* Sets the MZ header's e_sp value.
* @param wValue The new value of e_sp.
**/
void MzHeader::setSpValue(word wValue)
{
m_idhHeader.e_sp = wValue;
}
/**
* Sets the MZ header's e_csum value.
* @param wValue The new value of e_csum.
**/
void MzHeader::setChecksum(word wValue)
{
m_idhHeader.e_csum = wValue;
}
/**
* Sets the MZ header's e_ip value.
* @param wValue The new value of e_ip.
**/
void MzHeader::setIpValue(word wValue)
{
m_idhHeader.e_ip = wValue;
}
/**
* Sets the MZ header's e_cs value.
* @param wValue The new value of e_cs.
**/
void MzHeader::setCsValue(word wValue)
{
m_idhHeader.e_cs = wValue;
}
/**
* Sets the MZ header's e_lfarlc value.
* @param wValue The new value of e_lfarlc.
**/
void MzHeader::setAddrOfRelocationTable(word wValue)
{
m_idhHeader.e_lfarlc = wValue;
}
/**
* Sets the MZ header's e_ovno value.
* @param wValue The new value of e_ovno.
**/
void MzHeader::setOverlayNumber(word wValue)
{
m_idhHeader.e_ovno = wValue;
}
/**
* Sets the MZ header's e_oemid value.
* @param wValue The new value of e_oemid.
**/
void MzHeader::setOemIdentifier(word wValue)
{
m_idhHeader.e_oemid = wValue;
}
/**
* Sets the MZ header's e_oeminfo value.
* @param wValue The new value of e_oeminfo.
**/
void MzHeader::setOemInformation(word wValue)
{
m_idhHeader.e_oeminfo = wValue;
}
/**
* Sets the MZ header's e_lfanew value.
* @param lValue The new value of e_lfanew.
**/
void MzHeader::setAddressOfPeHeader(dword lValue)
{
m_idhHeader.e_lfanew = lValue;
}
/**
* Sets the MZ header's e_res[uiNr] value. If the parameter uiNr is out of range
* you will get undefined behaviour.
* @param uiNr The index of the word in the e_res array (valid range: 0-3)
* @param wValue The new value of e_res[nr].
**/
void MzHeader::setReservedWords1(unsigned int uiNr, word wValue)
{
m_idhHeader.e_res[uiNr] = wValue;
}
/**
* Sets the MZ header's e_res2[uiNr] value. If the parameter uiNr is out of range
* you will get undefined behaviour.
* @param uiNr The index of the word in the e_res2 array (valid range: 0-9)
* @param wValue The new value of e_res[nr].
**/
void MzHeader::setReservedWords2(unsigned int uiNr, word wValue)
{
m_idhHeader.e_res2[uiNr] = wValue;
}
}

View file

@ -0,0 +1,148 @@
/*
* MzHeader.h - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#ifndef MZHEADER_H
#define MZHEADER_H
#include "PeLibInc.h"
namespace PeLib
{
/// Class that handles the MZ header of files.
/**
* This class can read and modify MZ headers. It provides set- and get functions to access
* all individual members of a MZ header. Furthermore it's possible to validate and rebuild
* MZ headers.
**/
class MzHeader
{
private:
PELIB_IMAGE_DOS_HEADER m_idhHeader; ///< Stores all MZ header information.
/// Reads data from an InputBuffer into a MZ header struct.
void read(InputBuffer& ibBuffer);
/// Offset of the MZ header in the original file.
unsigned int originalOffset;
public:
enum Field {e_magic, e_cblp, e_cp, e_crlc, e_cparhdr, e_minalloc, e_maxalloc,
e_ss, e_sp, e_csum, e_ip, e_cs, e_lfarlc, e_ovno, e_res, e_oemid,
e_oeminfo, e_res2, e_lfanew};
/// Checks if the current MZ header is valid.
bool isValid() const; // EXPORT
bool isValid(Field field) const; // EXPORT _field
/// Corrects the current MZ header.
void makeValid(); // EXPORT
void makeValid(Field field); // EXPORT _field
/// Reads the MZ header of a file.
int read(const std::string& strFilename); // EXPORT
/// Reads the MZ header from a memory location.
int read(unsigned char* pcBuffer, unsigned int uiSize, unsigned int originalOffs = 0); // EXPORT _fromMemory
/// Rebuild the MZ header.
void rebuild(std::vector<byte>& vBuffer) const; // EXPORT
/// Returns the size of the current MZ header.
unsigned int size() const; // EXPORT
/// Writes the current MZ header to offset 0 of a file.
int write(const std::string& strFilename, dword dwOffset) const; // EXPORT
/// Gets the e_magic value of the MZ header.
word getMagicNumber() const; // EXPORT
/// Gets the e_cblp value of the MZ header.
word getBytesOnLastPage() const; // EXPORT
/// Gets the e_cp value of the MZ header.
word getPagesInFile() const; // EXPORT
/// Gets the e_crlc value of the MZ header.
word getRelocations() const; // EXPORT
/// Gets the e_cparhdr value of the MZ header.
word getSizeOfHeader() const; // EXPORT
/// Gets the e_minalloc value of the MZ header.
word getMinExtraParagraphs() const; // EXPORT
/// Gets the e_maxalloc value of the MZ header.
word getMaxExtraParagraphs() const; // EXPORT
/// Gets the e_ss value of the MZ header.
word getSsValue() const; // EXPORT
/// Gets the e_sp value of the MZ header.
word getSpValue() const; // EXPORT
/// Gets the e_csum value of the MZ header.
word getChecksum() const; // EXPORT
/// Gets the e_ip value of the MZ header.
word getIpValue() const; // EXPORT
/// Gets the e_cs value of the MZ header.
word getCsValue() const; // EXPORT
/// Gets the e_lfarlc value of the MZ header.
word getAddrOfRelocationTable() const; // EXPORT
/// Gets the e_ovnovalue of the MZ header.
word getOverlayNumber() const; // EXPORT
/// Gets the e_oemid value of the MZ header.
word getOemIdentifier() const; // EXPORT
/// Gets the e_oeminfo value of the MZ header.
word getOemInformation() const; // EXPORT
/// Gets the e_lfanew value of the MZ header.
dword getAddressOfPeHeader() const; // EXPORT
/// Gets the e_res of the MZ header.
word getReservedWords1(unsigned int uiNr) const; // EXPORT
/// Gets the e_res2 of the MZ header.
word getReservedWords2(unsigned int uiNr) const; // EXPORT
/// Sets the e_magic value of the MZ header.
void setMagicNumber(word wValue); // EXPORT
/// Sets the e_cblp value of the MZ header.
void setBytesOnLastPage(word wValue); // EXPORT
/// Sets the e_cp value of the MZ header.
void setPagesInFile(word wValue); // EXPORT
/// Sets the e_crlc value of the MZ header.
void setRelocations(word wValue); // EXPORT
/// Sets the e_cparhdr value of the MZ header.
void setSizeOfHeader(word wValue); // EXPORT
/// Sets the e_minalloc value of the MZ header.
void setMinExtraParagraphs(word wValue); // EXPORT
/// Sets the e_maxalloc value of the MZ header.
void setMaxExtraParagraphs(word wValue); // EXPORT
/// Sets the e_ss value of the MZ header.
void setSsValue(word wValue); // EXPORT
/// Sets the e_sp value of the MZ header.
void setSpValue(word wValue); // EXPORT
/// Sets the e_csum value of the MZ header.
void setChecksum(word wValue); // EXPORT
/// Sets the e_ip value of the MZ header.
void setIpValue(word wValue); // EXPORT
/// Sets the e_cs value of the MZ header.
void setCsValue(word wValue); // EXPORT
/// Sets the e_lfarlc value of the MZ header.
void setAddrOfRelocationTable(word wValue); // EXPORT
/// Sets the e_ovno value of the MZ header.
void setOverlayNumber(word wValue); // EXPORT
/// Sets the e_oemid value of the MZ header.
void setOemIdentifier(word wValue); // EXPORT
/// Sets the e_oeminfo value of the MZ header.
void setOemInformation(word wValue); // EXPORT
/// Sets the e_lfanew value of the MZ header.
void setAddressOfPeHeader(dword dwValue); // EXPORT
/// Sets the e_res value of the MZ header.
void setReservedWords1(unsigned int uiNr, word wValue); // EXPORT
/// Sets the e_res2 value of the MZ header.
void setReservedWords2(unsigned int uiNr, word wValue); // EXPORT
};
}
#endif

View file

@ -0,0 +1,169 @@
/*
* PeLib.cpp - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#include "PeFile.h"
namespace PeLib
{
PeFile::~PeFile()
{
}
PeFile32::PeFile32() : PeFileT<32>()
{
}
PeFile32::PeFile32(const std::string& strFlename) : PeFileT<32>(strFlename)
{
}
PeFile64::PeFile64() : PeFileT<64>()
{
}
PeFile64::PeFile64(const std::string& strFlename) : PeFileT<64>(strFlename)
{
}
/**
* @return A reference to the file's MZ header.
**/
const MzHeader& PeFile::mzHeader() const
{
return m_mzh;
}
/**
* @return A reference to the file's MZ header.
**/
MzHeader& PeFile::mzHeader()
{
return m_mzh;
}
/**
* @return A reference to the file's export directory.
**/
const ExportDirectory& PeFile::expDir() const
{
return m_expdir;
}
/**
* @return A reference to the file's export directory.
**/
ExportDirectory& PeFile::expDir()
{
return m_expdir;
}
/**
* @return A reference to the file's bound import directory.
**/
const BoundImportDirectory& PeFile::boundImpDir() const
{
return m_boundimpdir;
}
/**
* @return A reference to the file's bound import directory.
**/
BoundImportDirectory& PeFile::boundImpDir()
{
return m_boundimpdir;
}
/**
* @return A reference to the file's resource directory.
**/
const ResourceDirectory& PeFile::resDir() const
{
return m_resdir;
}
/**
* @return A reference to the file's resource directory.
**/
ResourceDirectory& PeFile::resDir()
{
return m_resdir;
}
/**
* @return A reference to the file's relocations directory.
**/
const RelocationsDirectory& PeFile::relocDir() const
{
return m_relocs;
}
/**
* @return A reference to the file's relocations directory.
**/
RelocationsDirectory& PeFile::relocDir()
{
return m_relocs;
}
/**
* @return A reference to the file's COM+ descriptor directory.
**/
const ComHeaderDirectory& PeFile::comDir() const
{
return m_comdesc;
}
/**
* @return A reference to the file's COM+ descriptor directory.
**/
ComHeaderDirectory & PeFile::comDir()
{
return m_comdesc;
}
const IatDirectory& PeFile::iatDir() const
{
return m_iat;
}
IatDirectory& PeFile::iatDir()
{
return m_iat;
}
const DebugDirectory& PeFile::debugDir() const
{
return m_debugdir;
}
DebugDirectory& PeFile::debugDir()
{
return m_debugdir;
}
}

View file

@ -0,0 +1,451 @@
/*
* PeFile.h - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#ifndef PEFILE_H
#define PEFILE_H
#include "PeLibInc.h"
#include "MzHeader.h"
#include "PeHeader.h"
#include "ImportDirectory.h"
#include "ExportDirectory.h"
#include "BoundImportDirectory.h"
#include "ResourceDirectory.h"
#include "RelocationsDirectory.h"
#include "ComHeaderDirectory.h"
#include "IatDirectory.h"
#include "DebugDirectory.h"
#include "TlsDirectory.h"
namespace PeLib
{
class PeFile32;
class PeFile64;
/**
* Visitor base class for PeFiles.
**/
class PeFileVisitor
{
public:
virtual void callback(PeFile32 &file){}
virtual void callback(PeFile64 &file){}
virtual ~PeFileVisitor(){}
};
/**
* Traits class that's used to decide of what type the PeHeader in a PeFile is.
**/
template<int>
struct PeFile_Traits;
template<>
struct PeFile_Traits<32>
{
typedef PeHeader32 PeHeader32_64;
};
template<>
struct PeFile_Traits<64>
{
typedef PeHeader64 PeHeader32_64;
};
/**
* This class represents the common structures of PE and PE+ files.
**/
class PeFile
{
protected:
std::string m_filename; ///< Name of the current file.
MzHeader m_mzh; ///< MZ header of the current file.
ExportDirectory m_expdir; ///< Export directory of the current file.
BoundImportDirectory m_boundimpdir; ///< BoundImportDirectory of the current file.
ResourceDirectory m_resdir; ///< ResourceDirectory of the current file.
RelocationsDirectory m_relocs; ///< Relocations directory of the current file.
ComHeaderDirectory m_comdesc; ///< COM+ descriptor directory of the current file.
IatDirectory m_iat; ///< Import address table of the current file.
DebugDirectory m_debugdir;
public:
virtual ~PeFile();
/// Returns the name of the current file.
virtual std::string getFileName() const = 0; // EXPORT
/// Changes the name of the current file.
virtual void setFileName(std::string strFilename) = 0; // EXPORT
virtual void visit(PeFileVisitor &v) = 0;
/// Reads the MZ header of the current file from disc.
virtual int readMzHeader() = 0; // EXPORT
/// Reads the export directory of the current file from disc.
virtual int readExportDirectory() = 0; // EXPORT
/// Reads the PE header of the current file from disc.
virtual int readPeHeader() = 0; // EXPORT
/// Reads the import directory of the current file from disc.
virtual int readImportDirectory() = 0; // EXPORT
/// Reads the bound import directory of the current file from disc.
virtual int readBoundImportDirectory() = 0; // EXPORT
/// Reads the resource directory of the current file from disc.
virtual int readResourceDirectory() = 0; // EXPORT
/// Reads the relocations directory of the current file from disc.
virtual int readRelocationsDirectory() = 0; // EXPORT
/// Reads the COM+ descriptor directory of the current file from disc.
virtual int readComHeaderDirectory() = 0; // EXPORT
/// Reads the IAT directory of the current file from disc.
virtual int readIatDirectory() = 0; // EXPORT
/// Reads the Debug directory of the current file.
virtual int readDebugDirectory() = 0; // EXPORT
virtual int readTlsDirectory() = 0; // EXPORT
virtual unsigned int getBits() const = 0;
/// Accessor function for the MZ header.
const MzHeader& mzHeader() const;
/// Accessor function for the MZ header.
MzHeader& mzHeader(); // EXPORT
/// Accessor function for the export directory.
const ExportDirectory& expDir() const;
/// Accessor function for the export directory.
ExportDirectory& expDir(); // EXPORT
/// Accessor function for the bound import directory.
const BoundImportDirectory& boundImpDir() const;
/// Accessor function for the bound import directory.
BoundImportDirectory& boundImpDir(); // EXPORT
/// Accessor function for the resource directory.
const ResourceDirectory& resDir() const;
/// Accessor function for the resource directory.
ResourceDirectory& resDir(); // EXPORT
/// Accessor function for the relocations directory.
const RelocationsDirectory& relocDir() const;
/// Accessor function for the relocations directory.
RelocationsDirectory& relocDir(); // EXPORT
/// Accessor function for the COM+ descriptor directory.
const ComHeaderDirectory& comDir() const;
/// Accessor function for the COM+ descriptor directory.
ComHeaderDirectory& comDir(); // EXPORT
/// Accessor function for the IAT directory.
const IatDirectory& iatDir() const;
/// Accessor function for the IAT directory.
IatDirectory& iatDir(); // EXPORT
/// Accessor function for the debug directory.
const DebugDirectory& debugDir() const;
/// Accessor function for the debug directory.
DebugDirectory& debugDir(); // EXPORT
};
/**
* This class implements the common structures of PE and PE+ files.
**/
template<int bits>
class PeFileT : public PeFile
{
typedef typename PeFile_Traits<bits>::PeHeader32_64 PeHeader32_64;
private:
PeHeader32_64 m_peh; ///< PE header of the current file.
ImportDirectory<bits> m_impdir; ///< Import directory of the current file.
TlsDirectory<bits> m_tlsdir;
public:
/// Default constructor which exists only for the sake of allowing to construct files without filenames.
PeFileT();
virtual ~PeFileT() {}
/// Initializes a PeFile with a filename
explicit PeFileT(const std::string& strFilename);
/// Returns the name of the current file.
std::string getFileName() const;
/// Changes the name of the current file.
void setFileName(std::string strFilename);
/// Reads the MZ header of the current file from disc.
int readMzHeader() ;
/// Reads the export directory of the current file from disc.
int readExportDirectory() ;
/// Reads the PE header of the current file from disc.
int readPeHeader() ;
/// Reads the import directory of the current file from disc.
int readImportDirectory() ;
/// Reads the bound import directory of the current file from disc.
int readBoundImportDirectory() ;
/// Reads the resource directory of the current file from disc.
int readResourceDirectory() ;
/// Reads the relocations directory of the current file from disc.
int readRelocationsDirectory() ;
/// Reads the COM+ descriptor directory of the current file from disc.
int readComHeaderDirectory() ;
/// Reads the IAT directory of the current file from disc.
int readIatDirectory() ;
/// Reads the Debug directory of the current file.
int readDebugDirectory() ;
int readTlsDirectory() ;
unsigned int getBits() const
{
return bits;
}
/// Accessor function for the PE header.
const PeHeader32_64& peHeader() const;
/// Accessor function for the PE header.
PeHeader32_64& peHeader();
/// Accessor function for the import directory.
const ImportDirectory<bits>& impDir() const;
/// Accessor function for the import directory.
ImportDirectory<bits>& impDir();
const TlsDirectory<bits>& tlsDir() const;
TlsDirectory<bits>& tlsDir();
};
/**
* This class is the main class for handling PE files.
**/
class PeFile32 : public PeFileT<32>
{
public:
/// Default constructor which exists only for the sake of allowing to construct files without filenames.
PeFile32();
/// Initializes a PeFile with a filename
explicit PeFile32(const std::string& strFlename);
virtual void visit(PeFileVisitor &v) { v.callback( *this ); }
};
/**
* This class is the main class for handling PE+ files.
**/
class PeFile64 : public PeFileT<64>
{
public:
/// Default constructor which exists only for the sake of allowing to construct files without filenames.
PeFile64();
/// Initializes a PeFile with a filename
explicit PeFile64(const std::string& strFlename);
virtual void visit(PeFileVisitor &v) { v.callback( *this ); }
};
//typedef PeFileT<32> PeFile32;
//typedef PeFileT<64> PeFile64;
/**
* @param strFilename Name of the current file.
**/
template<int bits>
PeFileT<bits>::PeFileT(const std::string& strFilename)
{
m_filename = strFilename;
}
template<int bits>
PeFileT<bits>::PeFileT()
{
}
template<int bits>
int PeFileT<bits>::readPeHeader()
{
return peHeader().read(getFileName(), mzHeader().getAddressOfPeHeader());
}
template<int bits>
int PeFileT<bits>::readImportDirectory()
{
if (peHeader().calcNumberOfRvaAndSizes() >= 2
&& peHeader().getIddImportRva()
&& peHeader().getIddImportSize())
{
return impDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddImportRva())), peHeader().getIddImportSize(), peHeader());
}
return ERROR_DIRECTORY_DOES_NOT_EXIST;
}
/**
* @return A reference to the file's PE header.
**/
template<int bits>
const typename PeFile_Traits<bits>::PeHeader32_64& PeFileT<bits>::peHeader() const
{
return m_peh;
}
/**
* @return A reference to the file's PE header.
**/
template<int bits>
typename PeFile_Traits<bits>::PeHeader32_64& PeFileT<bits>::peHeader()
{
return m_peh;
}
/**
* @return A reference to the file's import directory.
**/
template<int bits>
const ImportDirectory<bits>& PeFileT<bits>::impDir() const
{
return m_impdir;
}
/**
* @return A reference to the file's import directory.
**/
template<int bits>
ImportDirectory<bits>& PeFileT<bits>::impDir()
{
return m_impdir;
}
template<int bits>
const TlsDirectory<bits>& PeFileT<bits>::tlsDir() const
{
return m_tlsdir;
}
template<int bits>
TlsDirectory<bits>& PeFileT<bits>::tlsDir()
{
return m_tlsdir;
}
/**
* @return Filename of the current file.
**/
template<int bits>
std::string PeFileT<bits>::getFileName() const
{
return m_filename;
}
/**
* @param strFilename New filename.
**/
template<int bits>
void PeFileT<bits>::setFileName(std::string strFilename)
{
m_filename = strFilename;
}
template<int bits>
int PeFileT<bits>::readMzHeader()
{
return mzHeader().read(getFileName());
}
template<int bits>
int PeFileT<bits>::readExportDirectory()
{
if (peHeader().calcNumberOfRvaAndSizes() >= 1
&& peHeader().getIddExportRva() && peHeader().getIddExportSize())
{
return expDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddExportRva())), peHeader().getIddExportSize(), peHeader());
}
return ERROR_DIRECTORY_DOES_NOT_EXIST;
}
template<int bits>
int PeFileT<bits>::readBoundImportDirectory()
{
if (peHeader().calcNumberOfRvaAndSizes() >= 12
&& peHeader().getIddBoundImportRva() && peHeader().getIddBoundImportSize())
{
return boundImpDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddBoundImportRva())), peHeader().getIddBoundImportSize());
}
return ERROR_DIRECTORY_DOES_NOT_EXIST;
}
template<int bits>
int PeFileT<bits>::readResourceDirectory()
{
if (peHeader().calcNumberOfRvaAndSizes() >= 3
&& peHeader().getIddResourceRva() && peHeader().getIddResourceSize())
{
return resDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddResourceRva())), peHeader().getIddResourceSize(), peHeader().getIddResourceRva());
}
return ERROR_DIRECTORY_DOES_NOT_EXIST;
}
template<int bits>
int PeFileT<bits>::readRelocationsDirectory()
{
if (peHeader().calcNumberOfRvaAndSizes() >= 6
&& peHeader().getIddBaseRelocRva() && peHeader().getIddBaseRelocSize())
{
return relocDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddBaseRelocRva())), peHeader().getIddBaseRelocSize());
}
return ERROR_DIRECTORY_DOES_NOT_EXIST;
}
template<int bits>
int PeFileT<bits>::readComHeaderDirectory()
{
if (peHeader().calcNumberOfRvaAndSizes() >= 15
&& peHeader().getIddComHeaderRva() && peHeader().getIddComHeaderSize())
{
return comDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddComHeaderRva())), peHeader().getIddComHeaderSize());
}
std::cout << peHeader().getIddComHeaderRva() << std::endl;
std::exit(0);
return ERROR_DIRECTORY_DOES_NOT_EXIST;
}
template<int bits>
int PeFileT<bits>::readIatDirectory()
{
if (peHeader().calcNumberOfRvaAndSizes() >= 13
&& peHeader().getIddIatRva() && peHeader().getIddIatSize())
{
return iatDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddIatRva())), peHeader().getIddIatSize());
}
return ERROR_DIRECTORY_DOES_NOT_EXIST;
}
template<int bits>
int PeFileT<bits>::readDebugDirectory()
{
if (peHeader().calcNumberOfRvaAndSizes() >= 7
&& peHeader().getIddDebugRva() && peHeader().getIddDebugSize())
{
return debugDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddDebugRva())), peHeader().getIddDebugSize());
}
return ERROR_DIRECTORY_DOES_NOT_EXIST;
}
template<int bits>
int PeFileT<bits>::readTlsDirectory()
{
if (peHeader().calcNumberOfRvaAndSizes() >= 10
&& peHeader().getIddTlsRva() && peHeader().getIddTlsSize())
{
return tlsDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddTlsRva())), peHeader().getIddTlsSize());
}
return ERROR_DIRECTORY_DOES_NOT_EXIST;
}
}
#endif

View file

@ -0,0 +1,90 @@
/*
* PeHeader.cpp - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#include "PeLibInc.h"
#include "PeHeader.h"
namespace PeLib
{
template<>
void PeHeaderT<32>::readBaseOfData(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<32>& header) const
{
ibBuffer >> header.OptionalHeader.BaseOfData;
}
template<>
void PeHeaderT<64>::readBaseOfData(InputBuffer&, PELIB_IMAGE_NT_HEADERS<64>&) const
{
}
template<>
void PeHeaderT<32>::rebuildBaseOfData(OutputBuffer& obBuffer) const
{
obBuffer << m_inthHeader.OptionalHeader.BaseOfData;
}
template<>
void PeHeaderT<64>::rebuildBaseOfData(OutputBuffer&) const
{
}
template<>
bool PeHeaderT<32>::isValid() const
{
return true;
}
template<>
bool PeHeaderT<64>::isValid() const
{
return true;
}
template<>
bool PeHeaderT<32>::isValid(unsigned int pehf) const
{
/*
if (pehf == NtSignature)
{
return m_inthHeader.Signature == IMAGE_NT_SIGNATURE;
}
else if (pehf == NumberOfSections)
{
return getNumberOfSections() == calcNumberOfSections();
} */
return false;
}
template<>
bool PeHeaderT<64>::isValid(unsigned int pehf) const
{
return false;
}
/**
* @return The BaseOfData value from the PE header.
**/
dword PeHeader32::getBaseOfData() const
{
return m_inthHeader.OptionalHeader.BaseOfData;
}
/**
* Changes the file's BaseOfData.
* @param dwValue New value.
**/
void PeHeader32::setBaseOfData(dword dwValue)
{
m_inthHeader.OptionalHeader.BaseOfData = dwValue;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,27 @@
/*
* PeLib.h - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
/** \mainpage PeLib - An open-source C++ library to modify PE files.
*
* \section intro Introduction
*
* <b>What is PeLib?</b><br>
* 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
*/
#ifndef PELIB_H
#define PELIB_H
#include "PeFile.h"
#endif

View file

@ -0,0 +1,275 @@
/*
* PeLibAux.cpp - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#include "PeLibInc.h"
#include "PeLibAux.h"
#include "PeFile.h"
#ifdef _MSC_VER
#include <ctype.h>
#endif
namespace PeLib
{
const qword PELIB_IMAGE_ORDINAL_FLAGS<64>::IMAGE_ORDINAL_FLAG = 0x8000000000000000ULL;
bool PELIB_IMAGE_SECTION_HEADER::biggerFileOffset(const PELIB_IMAGE_SECTION_HEADER& ish) const
{
return PointerToRawData < ish.PointerToRawData;
}
bool PELIB_IMAGE_SECTION_HEADER::biggerVirtualAddress(const PELIB_IMAGE_SECTION_HEADER& ish) const
{
return VirtualAddress < ish.VirtualAddress;
}
unsigned int alignOffset(unsigned int uiOffset, unsigned int uiAlignment)
{
if (!uiAlignment) return uiAlignment;
return (uiOffset % uiAlignment) ? uiOffset + (uiAlignment - uiOffset % uiAlignment) : uiOffset;
}
unsigned int fileSize(const std::string& filename)
{
std::fstream file(filename.c_str());
file.seekg(0, std::ios::end);
return file.tellg();
}
unsigned int fileSize(std::ifstream& file)
{
unsigned int oldpos = file.tellg();
file.seekg(0, std::ios::end);
unsigned int filesize = file.tellg();
file.seekg(oldpos, std::ios::beg);
return filesize;
}
unsigned int fileSize(std::fstream& file)
{
unsigned int oldpos = file.tellg();
file.seekg(0, std::ios::end);
unsigned int filesize = file.tellg();
file.seekg(oldpos, std::ios::beg);
return filesize;
}
unsigned int fileSize(std::ofstream& file)
{
unsigned int oldpos = file.tellp();
file.seekp(0, std::ios::end);
unsigned int filesize = file.tellp();
file.seekp(oldpos, std::ios::beg);
return filesize;
}
bool isEqualNc(const std::string& s1, const std::string& s2)
{
std::string t1 = s1;
std::string t2 = s2;
// No std:: to make VC++ happy
#ifdef _MSC_VER
std::transform(t1.begin(), t1.end(), t1.begin(), toupper);
std::transform(t2.begin(), t2.end(), t2.begin(), toupper);
#else
// Weird syntax to make Borland C++ happy
std::transform(t1.begin(), t1.end(), t1.begin(), (int(*)(int))std::toupper);
std::transform(t2.begin(), t2.end(), t2.begin(), (int(*)(int))std::toupper);
#endif
return t1 == t2;
}
PELIB_IMAGE_DOS_HEADER::PELIB_IMAGE_DOS_HEADER()
{
e_magic = 0;
e_cblp = 0;
e_cp = 0;
e_crlc = 0;
e_cparhdr = 0;
e_minalloc = 0;
e_maxalloc = 0;
e_ss = 0;
e_sp = 0;
e_csum = 0;
e_ip = 0;
e_cs = 0;
e_lfarlc = 0;
e_ovno = 0;
for (unsigned int i=0;i<sizeof(e_res)/sizeof(e_res[0]);i++)
{
e_res[i] = 0;
}
e_oemid = 0;
e_oeminfo = 0;
for (unsigned int i=0;i<sizeof(e_res2)/sizeof(e_res2[0]);i++)
{
e_res2[i] = 0;
}
e_lfanew = 0;
}
PELIB_EXP_FUNC_INFORMATION::PELIB_EXP_FUNC_INFORMATION()
{
addroffunc = 0;
addrofname = 0;
ordinal = 0;
}
PELIB_IMAGE_RESOURCE_DIRECTORY::PELIB_IMAGE_RESOURCE_DIRECTORY()
{
Characteristics = 0;
TimeDateStamp = 0;
MajorVersion = 0;
MinorVersion = 0;
NumberOfNamedEntries = 0;
NumberOfIdEntries = 0;
}
PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY::PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY()
{
Name = 0;
OffsetToData = 0;
}
bool PELIB_IMG_RES_DIR_ENTRY::operator<(const PELIB_IMG_RES_DIR_ENTRY& first) const
{
if (irde.Name & PELIB_IMAGE_RESOURCE_NAME_IS_STRING && first.irde.Name & PELIB_IMAGE_RESOURCE_NAME_IS_STRING)
{
return wstrName < first.wstrName;
}
else if (irde.Name & PELIB_IMAGE_RESOURCE_NAME_IS_STRING)
{
return true;
}
else if (first.irde.Name & PELIB_IMAGE_RESOURCE_NAME_IS_STRING)
{
return false;
}
else
{
return irde.Name < first.irde.Name;
}
}
PELIB_IMAGE_BASE_RELOCATION::PELIB_IMAGE_BASE_RELOCATION()
{
VirtualAddress = 0;
SizeOfBlock = 0;
}
PELIB_IMAGE_COR20_HEADER::PELIB_IMAGE_COR20_HEADER()
{
cb = 0;
MajorRuntimeVersion = 0;
MinorRuntimeVersion = 0;
MetaData.VirtualAddress = 0;
MetaData.Size = 0;
Flags = 0;
EntryPointToken = 0;
Resources.VirtualAddress = 0;
Resources.Size = 0;
StrongNameSignature.VirtualAddress = 0;
StrongNameSignature.Size = 0;
CodeManagerTable.VirtualAddress = 0;
CodeManagerTable.Size = 0;
VTableFixups.VirtualAddress = 0;
VTableFixups.Size = 0;
ExportAddressTableJumps.VirtualAddress = 0;
ExportAddressTableJumps.Size = 0;
ManagedNativeHeader.VirtualAddress = 0;
ManagedNativeHeader.Size = 0;
}
/** Compares the passed filename to the struct's filename.
* @param strModuleName A filename.
* @return True, if the passed filename equals the struct's filename. The comparison is case-sensitive.
**/
bool PELIB_IMAGE_BOUND_DIRECTORY::equal(const std::string strModuleName) const
{
return this->strModuleName == strModuleName;
}
bool PELIB_EXP_FUNC_INFORMATION::equal(const std::string strFunctionName) const
{
return isEqualNc(this->funcname, strFunctionName);
}
/**
* @param strFilename Name of a file.
* @return Either PEFILE32, PEFILE64 or PEFILE_UNKNOWN
**/
unsigned int getFileType(const std::string strFilename)
{
word machine, magic;
PeFile32 pef(strFilename);
if (pef.readMzHeader() != NO_ERROR) return PEFILE_UNKNOWN;
if (pef.readPeHeader() != NO_ERROR) return PEFILE_UNKNOWN;
machine = pef.peHeader().getMachine();
magic = pef.peHeader().getMagic();
if (machine == PELIB_IMAGE_FILE_MACHINE_I386 && magic == PELIB_IMAGE_NT_OPTIONAL_HDR32_MAGIC)
{
return PEFILE32;
}
// 0x8664 == AMD64; no named constant yet
else if ((machine == 0x8664 || machine == PELIB_IMAGE_FILE_MACHINE_IA64) && magic == PELIB_IMAGE_NT_OPTIONAL_HDR64_MAGIC)
{
return PEFILE64;
}
else
{
return PEFILE_UNKNOWN;
}
}
/**
* Opens a PE file. The return type is either PeFile32 or PeFile64 object. If an error occurs the return
* value is 0.
* @param strFilename Name of a file.
* @return Either a PeFile32 object, a PeFil64 object or 0.
**/
PeFile* openPeFile(const std::string& strFilename)
{
unsigned int type = getFileType(strFilename);
if (type == PEFILE32)
{
return new PeFile32(strFilename);
}
else if (type == PEFILE64)
{
return new PeFile64(strFilename);
}
else
{
return 0;
}
}
unsigned int PELIB_IMAGE_BOUND_DIRECTORY::size() const
{
unsigned int size = 0;
for (unsigned int i=0;i<moduleForwarders.size();i++)
{
size += moduleForwarders[i].size();
}
return size + PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size() + strModuleName.size() + 1;
}
}

View file

@ -0,0 +1,884 @@
/*
* PeLibAux.cpp - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#ifndef PELIBAUX_H
#define PELIBAUX_H
//#include "PeLibInc.h"
//#include "PeHeader.h"
#include "buffer/OutputBuffer.h"
#include "buffer/InputBuffer.h"
//#include "buffer/ResTree.h"
#include <numeric>
#include <limits>
namespace PeLib
{
enum errorCodes
{
NO_ERROR = 0,
ERROR_OPENING_FILE = -1,
ERROR_INVALID_FILE = -2,
ERROR_TOO_MANY_SECTIONS = -3,
ERROR_NOT_ENOUGH_SPACE = -4,
ERROR_NO_FILE_ALIGNMENT = -5,
ERROR_NO_SECTION_ALIGNMENT = -6,
ERROR_ENTRY_NOT_FOUND = -7,
ERROR_DUPLICATE_ENTRY = -8,
ERROR_DIRECTORY_DOES_NOT_EXIST = -9
};
class PeFile;
bool isEqualNc(const std::string& s1, const std::string& s2);
// It's necessary to make sure that a byte has 8 bits and that the platform has a 8 bit type,
// a 16bit type and a bit type. That's because binary PE files are pretty picky about their
// structure.
#if CHAR_BIT == 8
#if UCHAR_MAX == 255
typedef unsigned char byte;
// typedef std::bitset<8> byte;
#else
#error You need to change some typedefs (Code: 8). Please read the PeLib documentation.
#endif
#if USHRT_MAX == 65535U
typedef unsigned short word;
// typedef std::bitset<16> word;
#else
#error You need to change some typedefs (Code: 16). Please read the PeLib documentation.
#endif
#if UINT_MAX == 4294967295UL
typedef unsigned int dword;
// typedef std::bitset<32> dword;
#else
#error You need to change some typedefs (Code: 32). Please read the PeLib documentation.
#endif
typedef unsigned long long qword;
// #if ULLONG_MAX == 18446744073709551615
// typedef unsigned long long qword;
// #else
// #error You need to change some typedefs (Code: 32). Please read the PeLib documentation.
// #endif
#else
#error You need to change some typedefs. Please read the PeLib documentation.
#endif
/* enum bits {BITS_BYTE = 8, BITS_WORD = 16, BITS_DWORD = 32};
template<bits value>
class DataType
{
private:
std::bitset<value> bsValue;
unsigned long ulValue;
public:
void operator=(unsigned long ulValue)
{
bsValue = ulValue;
}
operator unsigned long() const
{
return bsValue.to_ulong();
}
const int operator&()
{
ulValue = bsValue;
return ulValue;
}
};
typedef DataType<BITS_BYTE> byte;
typedef DataType<BITS_WORD> word;
typedef DataType<BITS_DWORD> dword;
*/
enum {PEFILE32 = 32,
PEFILE64 = 64,
PEFILE_UNKNOWN = 0};
enum {BoundImportDirectoryId = 1,
ComHeaderDirectoryId,
ExportDirectoryId,
IatDirectoryId,
ImportDirectoryId,
MzHeaderId,
PeHeaderId,
RelocationsId,
PeFileId,
ResourceDirectoryId,
DebugDirectoryId,
TlsDirectoryId
};
const word PELIB_IMAGE_DOS_SIGNATURE = 0x5A4D;
const dword PELIB_IMAGE_NT_SIGNATURE = 0x00004550;
template<int bits>
struct PELIB_IMAGE_ORDINAL_FLAGS;
template<>
struct PELIB_IMAGE_ORDINAL_FLAGS<32>
{
static const dword IMAGE_ORDINAL_FLAG = 0x80000000;
};
template<>
struct PELIB_IMAGE_ORDINAL_FLAGS<64>
{
static const qword IMAGE_ORDINAL_FLAG;
};
const unsigned long PELIB_IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
const unsigned long PELIB_IMAGE_RESOURCE_NAME_IS_STRING = 0x80000000;
const unsigned long PELIB_IMAGE_RESOURCE_DATA_IS_DIRECTORY = 0x80000000;
enum
{
PELIB_IMAGE_DIRECTORY_ENTRY_EXPORT, // OK
PELIB_IMAGE_DIRECTORY_ENTRY_IMPORT, // OK
PELIB_IMAGE_DIRECTORY_ENTRY_RESOURCE, // OK
PELIB_IMAGE_DIRECTORY_ENTRY_EXCEPTION,
PELIB_IMAGE_DIRECTORY_ENTRY_SECURITY,
PELIB_IMAGE_DIRECTORY_ENTRY_BASERELOC, // OK
PELIB_IMAGE_DIRECTORY_ENTRY_DEBUG,
PELIB_IMAGE_DIRECTORY_ENTRY_ARCHITECTURE,
PELIB_IMAGE_DIRECTORY_ENTRY_GLOBALPTR,
PELIB_IMAGE_DIRECTORY_ENTRY_TLS,
PELIB_IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG,
PELIB_IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT, // OK
PELIB_IMAGE_DIRECTORY_ENTRY_IAT, // OK
PELIB_IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT,
PELIB_IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
};
enum
{
PELIB_IMAGE_SCN_TYPE_NO_PAD = 0x00000008,
PELIB_IMAGE_SCN_CNT_CODE = 0x00000020,
PELIB_IMAGE_SCN_CNT_INITIALIZED_DATA = 0x00000040,
PELIB_IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080,
PELIB_IMAGE_SCN_LNK_OTHER = 0x00000100,
PELIB_IMAGE_SCN_LNK_INFO = 0x00000200,
PELIB_IMAGE_SCN_LNK_REMOVE = 0x00000800,
PELIB_IMAGE_SCN_LNK_COMDAT = 0x00001000,
PELIB_IMAGE_SCN_NO_DEFER_SPEC_EXC = 0x00004000,
PELIB_IMAGE_SCN_GPREL = 0x00008000,
PELIB_IMAGE_SCN_MEM_FARDATA = 0x00008000,
PELIB_IMAGE_SCN_MEM_PURGEABLE = 0x00020000,
PELIB_IMAGE_SCN_MEM_16BIT = 0x00020000,
PELIB_IMAGE_SCN_MEM_LOCKED = 0x00040000,
PELIB_IMAGE_SCN_MEM_PRELOAD = 0x00080000,
PELIB_IMAGE_SCN_ALIGN_1BYTES = 0x00100000,
PELIB_IMAGE_SCN_ALIGN_2BYTES = 0x00200000,
PELIB_IMAGE_SCN_ALIGN_4BYTES = 0x00300000,
PELIB_IMAGE_SCN_ALIGN_8BYTES = 0x00400000,
PELIB_IMAGE_SCN_ALIGN_16BYTES = 0x00500000,
PELIB_IMAGE_SCN_ALIGN_BYTES = 0x00600000,
PELIB_IMAGE_SCN_ALIGN_64BYTES = 0x00700000,
PELIB_IMAGE_SCN_ALIGN_128BYTES = 0x00800000,
PELIB_IMAGE_SCN_ALIGN_256BYTES = 0x00900000,
PELIB_IMAGE_SCN_ALIGN_512BYTES = 0x00A00000,
PELIB_IMAGE_SCN_ALIGN_1024BYTES = 0x00B00000,
PELIB_IMAGE_SCN_ALIGN_2048BYTES = 0x00C00000,
PELIB_IMAGE_SCN_ALIGN_4096BYTES = 0x00D00000,
PELIB_IMAGE_SCN_ALIGN_8192BYTES = 0x00E00000,
PELIB_IMAGE_SCN_LNK_NRELOC_OVFL = 0x01000000,
PELIB_IMAGE_SCN_MEM_DISCARDABLE = 0x02000000,
PELIB_IMAGE_SCN_MEM_NOT_CACHED = 0x04000000,
PELIB_IMAGE_SCN_MEM_NOT_PAGED = 0x08000000,
PELIB_IMAGE_SCN_MEM_SHARED = 0x10000000,
PELIB_IMAGE_SCN_MEM_EXECUTE = 0x20000000,
PELIB_IMAGE_SCN_MEM_READ = 0x40000000,
PELIB_IMAGE_SCN_MEM_WRITE = 0x80000000
};
enum
{
PELIB_IMAGE_FILE_MACHINE_UNKNOWN = 0,
PELIB_IMAGE_FILE_MACHINE_I386 = 0x014c,
PELIB_IMAGE_FILE_MACHINE_R3000 = 0x0162,
PELIB_IMAGE_FILE_MACHINE_R4000 = 0x0166,
PELIB_IMAGE_FILE_MACHINE_R10000 = 0x0168,
PELIB_IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x0169,
PELIB_IMAGE_FILE_MACHINE_ALPHA = 0x0184,
PELIB_IMAGE_FILE_MACHINE_POWERPC = 0x01F0,
PELIB_IMAGE_FILE_MACHINE_SH3 = 0x01a2,
PELIB_IMAGE_FILE_MACHINE_SH3E = 0x01a4,
PELIB_IMAGE_FILE_MACHINE_SH4 = 0x01a6,
PELIB_IMAGE_FILE_MACHINE_ARM = 0x01c0,
PELIB_IMAGE_FILE_MACHINE_THUMB = 0x01c2,
PELIB_IMAGE_FILE_MACHINE_IA64 = 0x0200,
PELIB_IMAGE_FILE_MACHINE_MIPS16 = 0x0266,
PELIB_IMAGE_FILE_MACHINE_MIPSFPU = 0x0366,
PELIB_IMAGE_FILE_MACHINE_MIPSFPU16 = 0x0466,
PELIB_IMAGE_FILE_MACHINE_ALPHA64 = 0x0284,
PELIB_IMAGE_FILE_MACHINE_AXP64 = PELIB_IMAGE_FILE_MACHINE_ALPHA64
};
enum
{
PELIB_IMAGE_FILE_RELOCS_STRIPPED = 0x0001,
PELIB_IMAGE_FILE_EXECUTABLE_IMAGE = 0x0002,
PELIB_IMAGE_FILE_LINE_NUMS_STRIPPED = 0x0004,
PELIB_IMAGE_FILE_LOCAL_SYMS_STRIPPED = 0x0008,
PELIB_IMAGE_FILE_AGGRESIVE_WS_TRIM = 0x0010,
PELIB_IMAGE_FILE_LARGE_ADDRESS_AWARE = 0x0020,
PELIB_IMAGE_FILE_BYTES_REVERSED_LO = 0x0080,
PELIB_IMAGE_FILE_32BIT_MACHINE = 0x0100,
PELIB_IMAGE_FILE_DEBUG_STRIPPED = 0x0200,
PELIB_IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP = 0x0400,
PELIB_IMAGE_FILE_NET_RUN_FROM_SWAP = 0x0800,
PELIB_IMAGE_FILE_SYSTEM = 0x1000,
PELIB_IMAGE_FILE_DLL = 0x2000,
PELIB_IMAGE_FILE_UP_SYSTEM_ONLY = 0x4000,
PELIB_IMAGE_FILE_BYTES_REVERSED_HI = 0x8000
};
enum
{
PELIB_IMAGE_NT_OPTIONAL_HDR32_MAGIC = 0x10b,
PELIB_IMAGE_NT_OPTIONAL_HDR64_MAGIC = 0x20b,
PELIB_IMAGE_ROM_OPTIONAL_HDR_MAGIC = 0x107
};
enum
{
PELIB_IMAGE_SUBSYSTEM_UNKNOWN = 0,
PELIB_IMAGE_SUBSYSTEM_NATIVE = 1,
PELIB_IMAGE_SUBSYSTEM_WINDOWS_GUI = 2,
PELIB_IMAGE_SUBSYSTEM_WINDOWS_CUI = 3,
PELIB_IMAGE_SUBSYSTEM_OS2_CUI = 5,
PELIB_IMAGE_SUBSYSTEM_POSIX_CUI = 7,
PELIB_IMAGE_SUBSYSTEM_NATIVE_WINDOWS = 8,
PELIB_IMAGE_SUBSYSTEM_WINDOWS_CE_GUI = 9
};
enum
{
PELIB_RT_CURSOR = 1, // 1
PELIB_RT_BITMAP, // 2
PELIB_RT_ICON, // 3
PELIB_RT_MENU, // 4
PELIB_RT_DIALOG, // 5
PELIB_RT_STRING, // 6
PELIB_RT_FONTDIR, // 7
PELIB_RT_FONT, // 8
PELIB_RT_ACCELERATOR, // 9
PELIB_RT_RCDATA, // 10
PELIB_RT_MESSAGETABLE, // 11
PELIB_RT_GROUP_CURSOR, // 12
PELIB_RT_GROUP_ICON = 14, // 14
PELIB_RT_VERSION = 16,
PELIB_RT_DLGINCLUDE,
PELIB_RT_PLUGPLAY = 19,
PELIB_RT_VXD,
PELIB_RT_ANICURSOR,
PELIB_RT_ANIICON,
PELIB_RT_HTML,
PELIB_RT_MANIFEST
};
template<typename T>
unsigned int accumulate(unsigned int size, const T& v)
{
return size + v.size();
}
struct PELIB_IMAGE_DOS_HEADER
{
word e_magic;
word e_cblp;
word e_cp;
word e_crlc;
word e_cparhdr;
word e_minalloc;
word e_maxalloc;
word e_ss;
word e_sp;
word e_csum;
word e_ip;
word e_cs;
word e_lfarlc;
word e_ovno;
word e_res[4];
word e_oemid;
word e_oeminfo;
word e_res2[10];
dword e_lfanew;
PELIB_IMAGE_DOS_HEADER();
static inline unsigned int size() {return 64;}
};
struct PELIB_IMAGE_FILE_HEADER
{
word Machine;
word NumberOfSections;
dword TimeDateStamp;
dword PointerToSymbolTable;
dword NumberOfSymbols;
word SizeOfOptionalHeader;
word Characteristics;
PELIB_IMAGE_FILE_HEADER()
{
Machine = 0;
NumberOfSections = 0;
TimeDateStamp = 0;
PointerToSymbolTable = 0;
NumberOfSymbols = 0;
SizeOfOptionalHeader = 0;
Characteristics = 0;
}
static inline unsigned int size() {return 20;}
};
struct PELIB_IMAGE_DATA_DIRECTORY
{
dword VirtualAddress;
dword Size;
PELIB_IMAGE_DATA_DIRECTORY()
{
VirtualAddress = 0;
Size = 0;
}
static inline unsigned int size() {return 8;}
};
template<int>
struct FieldSizes;
template<>
struct FieldSizes<32>
{
typedef dword VAR4_8;
};
template<>
struct FieldSizes<64>
{
typedef qword VAR4_8;
};
template<int x>
struct PELIB_IMAGE_OPTIONAL_HEADER_BASE
{
typedef typename FieldSizes<x>::VAR4_8 VAR4_8;
word Magic;
byte MajorLinkerVersion;
byte MinorLinkerVersion;
dword SizeOfCode;
dword SizeOfInitializedData;
dword SizeOfUninitializedData;
dword AddressOfEntryPoint;
dword BaseOfCode;
dword BaseOfData;
VAR4_8 ImageBase;
dword SectionAlignment;
dword FileAlignment;
word MajorOperatingSystemVersion;
word MinorOperatingSystemVersion;
word MajorImageVersion;
word MinorImageVersion;
word MajorSubsystemVersion;
word MinorSubsystemVersion;
dword Win32VersionValue;
dword SizeOfImage;
dword SizeOfHeaders;
dword CheckSum;
word Subsystem;
word DllCharacteristics;
VAR4_8 SizeOfStackReserve;
VAR4_8 SizeOfStackCommit;
VAR4_8 SizeOfHeapReserve;
VAR4_8 SizeOfHeapCommit;
dword LoaderFlags;
dword NumberOfRvaAndSizes;
// PELIB_IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
PELIB_IMAGE_OPTIONAL_HEADER_BASE();
};
template<int x>
PELIB_IMAGE_OPTIONAL_HEADER_BASE<x>::PELIB_IMAGE_OPTIONAL_HEADER_BASE()
{
Magic = 0;
MajorLinkerVersion = 0;
MinorLinkerVersion = 0;
SizeOfCode = 0;
SizeOfInitializedData = 0;
SizeOfUninitializedData = 0;
AddressOfEntryPoint = 0;
BaseOfCode = 0;
// BaseOfData = 0;
ImageBase = 0;
SectionAlignment = 0;
FileAlignment = 0;
MajorOperatingSystemVersion = 0;
MinorOperatingSystemVersion = 0;
MajorImageVersion = 0;
MinorImageVersion = 0;
MajorSubsystemVersion = 0;
MinorSubsystemVersion = 0;
Win32VersionValue = 0;
SizeOfImage = 0;
SizeOfHeaders = 0;
CheckSum = 0;
Subsystem = 0;
DllCharacteristics = 0;
SizeOfStackReserve = 0;
SizeOfStackCommit = 0;
SizeOfHeapReserve = 0;
SizeOfHeapCommit = 0;
LoaderFlags = 0;
NumberOfRvaAndSizes = 0;
}
template<int>
struct PELIB_IMAGE_OPTIONAL_HEADER;
template<>
struct PELIB_IMAGE_OPTIONAL_HEADER<32> : public PELIB_IMAGE_OPTIONAL_HEADER_BASE<32>
{
dword BaseOfData;
static inline unsigned int size() {return 224 - 0x10 * 8;}
};
template<>
struct PELIB_IMAGE_OPTIONAL_HEADER<64> : public PELIB_IMAGE_OPTIONAL_HEADER_BASE<64>
{
static inline unsigned int size() {return 240 - 0x10 * 8;}
};
template<int x>
struct PELIB_IMAGE_NT_HEADERS
{
dword Signature;
PELIB_IMAGE_FILE_HEADER FileHeader;
PELIB_IMAGE_OPTIONAL_HEADER<x> OptionalHeader;
std::vector<PELIB_IMAGE_DATA_DIRECTORY> dataDirectories;
unsigned int size() const
{
return sizeof(dword)
+ PELIB_IMAGE_FILE_HEADER::size()
+ PELIB_IMAGE_OPTIONAL_HEADER<x>::size()
+ static_cast<unsigned int>(dataDirectories.size()) * PELIB_IMAGE_DATA_DIRECTORY::size();
}
PELIB_IMAGE_NT_HEADERS()
{
Signature = 0;
}
};
const unsigned int PELIB_IMAGE_SIZEOF_SHORT_NAME = 8;
struct PELIB_IMAGE_SECTION_HEADER
{
byte Name[PELIB_IMAGE_SIZEOF_SHORT_NAME];
dword VirtualSize;
dword VirtualAddress;
dword SizeOfRawData;
dword PointerToRawData;
dword PointerToRelocations;
dword PointerToLinenumbers;
word NumberOfRelocations;
word NumberOfLinenumbers;
dword Characteristics;
PELIB_IMAGE_SECTION_HEADER()
{
VirtualSize = 0;
VirtualAddress = 0;
SizeOfRawData = 0;
PointerToRawData = 0;
PointerToRelocations = 0;
PointerToLinenumbers = 0;
NumberOfRelocations = 0;
NumberOfLinenumbers = 0;
Characteristics = 0;
}
static inline unsigned int size() {return 40;}
bool biggerFileOffset(const PELIB_IMAGE_SECTION_HEADER& ish) const;
bool biggerVirtualAddress(const PELIB_IMAGE_SECTION_HEADER& ish) const;
};
template<int bits>
struct PELIB_IMAGE_THUNK_DATA
{
typename FieldSizes<bits>::VAR4_8 Ordinal;
PELIB_IMAGE_THUNK_DATA()
{
Ordinal = 0;
}
static inline unsigned int size() {return 4;}
};
struct PELIB_IMAGE_IMPORT_DESCRIPTOR
{
dword OriginalFirstThunk;
dword TimeDateStamp;
dword ForwarderChain;
dword Name;
dword FirstThunk;
PELIB_IMAGE_IMPORT_DESCRIPTOR()
{
OriginalFirstThunk = 0;
TimeDateStamp = 0;
ForwarderChain = 0;
Name = 0;
FirstThunk = 0;
}
static inline unsigned int size() {return 20;}
};
struct PELIB_IMAGE_EXPORT_DIRECTORY
{
dword Characteristics;
dword TimeDateStamp;
word MajorVersion;
word MinorVersion;
dword Name;
dword Base;
dword NumberOfFunctions;
dword NumberOfNames;
dword AddressOfFunctions;
dword AddressOfNames;
dword AddressOfNameOrdinals;
PELIB_IMAGE_EXPORT_DIRECTORY()
{
Characteristics = 0;
TimeDateStamp = 0;
MajorVersion = 0;
MinorVersion = 0;
Name = 0;
Base = 0;
NumberOfFunctions = 0;
NumberOfNames = 0;
AddressOfFunctions = 0;
NumberOfNames = 0;
AddressOfNameOrdinals = 0;
}
static inline unsigned int size() {return 40;}
};
struct PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR
{
dword TimeDateStamp;
word OffsetModuleName;
word NumberOfModuleForwarderRefs;
PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR()
{
TimeDateStamp = 0;
OffsetModuleName = 0;
NumberOfModuleForwarderRefs = 0;
}
static unsigned int size()
{
return 8;
}
};
// Stores all necessary information about a BoundImport field.
struct PELIB_IMAGE_BOUND_DIRECTORY
{
PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR ibdDescriptor; ///< Information about the imported file.
std::string strModuleName; ///< Name of the imported file.
std::vector<PELIB_IMAGE_BOUND_DIRECTORY> moduleForwarders;
// Will be used in std::find_if
// Passing by-reference not possible (see C++ Standard Core Language Defect Reports, Revision 29, Issue 106)
/// Compares the passed filename to the struct's filename.
bool equal(const std::string strModuleName) const;
unsigned int size() const;
};
struct PELIB_EXP_FUNC_INFORMATION
{
dword addroffunc;
dword addrofname;
word ordinal;
std::string funcname;
PELIB_EXP_FUNC_INFORMATION();
bool equal(const std::string strFunctionName) const;
inline unsigned int size() const
{
unsigned int uiSize = 4;
if (addroffunc) uiSize += 2;// + 4;
if (!funcname.empty()) uiSize += 4 + (unsigned int)funcname.size() + 1;
return uiSize;
}
};
struct PELIB_IMAGE_RESOURCE_DIRECTORY
{
dword Characteristics;
dword TimeDateStamp;
word MajorVersion;
word MinorVersion;
word NumberOfNamedEntries;
word NumberOfIdEntries;
PELIB_IMAGE_RESOURCE_DIRECTORY();
static inline unsigned int size() {return 16;}
};
struct PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY
{
dword Name;
dword OffsetToData;
PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY();
static inline unsigned int size() {return 8;}
};
const unsigned int PELIB_IMAGE_SIZEOF_BASE_RELOCATION = 8;
struct PELIB_IMG_RES_DIR_ENTRY
{
PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY irde;
std::string wstrName;
bool operator<(const PELIB_IMG_RES_DIR_ENTRY& first) const;
};
struct PELIB_IMAGE_BASE_RELOCATION
{
dword VirtualAddress;
dword SizeOfBlock;
PELIB_IMAGE_BASE_RELOCATION();
static inline unsigned int size() {return 8;}
};
struct PELIB_IMAGE_COR20_HEADER
{
dword cb;
word MajorRuntimeVersion;
word MinorRuntimeVersion;
PELIB_IMAGE_DATA_DIRECTORY MetaData;
dword Flags;
dword EntryPointToken;
PELIB_IMAGE_DATA_DIRECTORY Resources;
PELIB_IMAGE_DATA_DIRECTORY StrongNameSignature;
PELIB_IMAGE_DATA_DIRECTORY CodeManagerTable;
PELIB_IMAGE_DATA_DIRECTORY VTableFixups;
PELIB_IMAGE_DATA_DIRECTORY ExportAddressTableJumps;
PELIB_IMAGE_DATA_DIRECTORY ManagedNativeHeader;
PELIB_IMAGE_COR20_HEADER();
static inline unsigned int size() {return 72;}
};
// Used to store a file's export table.
struct PELIB_IMAGE_EXP_DIRECTORY
{
/// The IMAGE_EXPORTED_DIRECTORY of a file's export table.
PELIB_IMAGE_EXPORT_DIRECTORY ied;
/// The original filename of current file.
std::string name;
std::vector<PELIB_EXP_FUNC_INFORMATION> functions;
inline unsigned int size() const
{
return PELIB_IMAGE_EXPORT_DIRECTORY::size() + name.size() + 1 +
std::accumulate(functions.begin(), functions.end(), 0, accumulate<PELIB_EXP_FUNC_INFORMATION>);
}
};
// Used for parsing a file's import table. It combines the function name, the hint
// and the IMAGE_THUNK_DATA of an imported function.
template<int bits>
struct PELIB_THUNK_DATA
{
/// The IMAGE_THUNK_DATA struct of an imported function.
PELIB_IMAGE_THUNK_DATA<bits> itd;
/// The hint of an imported function.
word hint;
/// The function name of an imported function.
std::string fname;
bool equalHint(word wHint) const
{
return hint == wHint;
// return itd.Ordinal == (wHint | IMAGE_ORDINAL_FLAGS<bits>::IMAGE_ORDINAL_FLAG);
}
bool equalFunctionName(std::string strFunctionName) const
{
return isEqualNc(fname, strFunctionName);
}
unsigned int size() const {return PELIB_IMAGE_THUNK_DATA<bits>::size() + fname.size() + 1 + sizeof(hint);}
};
// Used to store a file's import table. Every struct of this sort
// can store import information of one DLL.
template<int bits>
struct PELIB_IMAGE_IMPORT_DIRECTORY
{
/// The IMAGE_IMPORT_DESCRIPTOR of an imported DLL.
PELIB_IMAGE_IMPORT_DESCRIPTOR impdesc;
/// The name of an imported DLL.
std::string name;
/// All original first thunk values of an imported DLL.
std::vector<PELIB_THUNK_DATA<bits> > originalfirstthunk;
/// All first thunk value of an imported DLL.
std::vector<PELIB_THUNK_DATA<bits> > firstthunk;
// bool operator==(std::string strFilename) const;
inline unsigned int size() const
{
return PELIB_IMAGE_IMPORT_DESCRIPTOR::size() + name.size() + 1 + // descriptor + dllname
std::accumulate(originalfirstthunk.begin(), originalfirstthunk.end(), 0, accumulate<PELIB_THUNK_DATA<bits> >) + // thunks (PeLib uses only one thunk)
PELIB_IMAGE_THUNK_DATA<bits>::size(); // zero-termination
}
bool operator==(std::string strFilename) const
{
return isEqualNc(this->name, strFilename);
}
};
struct PELIB_IMAGE_RESOURCE_DATA_ENTRY
{
dword OffsetToData;
dword Size;
dword CodePage;
dword Reserved;
static inline unsigned int size() {return 16;}
};
struct PELIB_IMAGE_RESOURCE_DATA
{
PELIB_IMAGE_RESOURCE_DATA_ENTRY irdEntry;
std::vector<byte> vData;
};
struct IMG_BASE_RELOC
{
PELIB_IMAGE_BASE_RELOCATION ibrRelocation;
std::vector<word> vRelocData;
};
struct PELIB_IMAGE_DEBUG_DIRECTORY
{
dword Characteristics;
dword TimeDateStamp;
word MajorVersion;
word MinorVersion;
dword Type;
dword SizeOfData;
dword AddressOfRawData;
dword PointerToRawData;
static unsigned int size() {return 28;}
};
struct PELIB_IMG_DEBUG_DIRECTORY
{
PELIB_IMAGE_DEBUG_DIRECTORY idd;
std::vector<byte> data;
};
template<int bits>
struct PELIB_IMAGE_TLS_DIRECTORY_BASE
{
typename FieldSizes<bits>::VAR4_8 StartAddressOfRawData;
typename FieldSizes<bits>::VAR4_8 EndAddressOfRawData;
typename FieldSizes<bits>::VAR4_8 AddressOfIndex;
typename FieldSizes<bits>::VAR4_8 AddressOfCallBacks;
dword SizeOfZeroFill;
dword Characteristics;
};
template<int bits>
struct PELIB_IMAGE_TLS_DIRECTORY;// : public PELIB_IMAGE_TLS_DIRECTORY_BASE<bits>
template<>
struct PELIB_IMAGE_TLS_DIRECTORY<32> : public PELIB_IMAGE_TLS_DIRECTORY_BASE<32>
{
// enum {size = 24};
static unsigned int size(){return 24;}
};
template<>
struct PELIB_IMAGE_TLS_DIRECTORY<64> : public PELIB_IMAGE_TLS_DIRECTORY_BASE<64>
{
// enum {size = 40};
static unsigned int size(){return 40;}
};
unsigned int fileSize(const std::string& filename);
unsigned int fileSize(std::ifstream& file);
unsigned int fileSize(std::ofstream& file);
unsigned int fileSize(std::fstream& file);
unsigned int alignOffset(unsigned int uiOffset, unsigned int uiAlignment);
/// Determines if a file is a 32bit or 64bit PE file.
unsigned int getFileType(const std::string strFilename);
/// Opens a PE file.
PeFile* openPeFile(const std::string& strFilename);
/* enum MzHeader_Field {e_magic, e_cblp, e_cp, e_crlc, e_cparhdr, e_minalloc, e_maxalloc,
e_ss, e_sp, e_csum, e_ip, e_cs, e_lfarlc, e_ovno, e_res, e_oemid,
e_oeminfo, e_res2, e_lfanew};
enum PeHeader_Field {NtSignature, Machine, NumberOfSections, TimeDateStamp, PointerToSymbolTable,
NumberOfSymbols, SizeOfOptionalHeader, Characteristics, Magic,
MajorLinkerVersion, MinorLinkerVersion, SizeOfCode, SizeOfInitializedData,
SizeOfUninitializedData, AddressOfEntryPoint, BaseOfCode, BaseOfData, ImageBase,
SectionAlignment, FileAlignment, MajorOperatingSystemVersion, MinorOperatingSystemVersion,
MajorImageVersion, MinorImageVersion, MajorSubsystemVersion, MinorSubsystemVersion,
Win32VersionValue, SizeOfImage, SizeOfHeaders, CheckSum, Subsystem, DllCharacteristics,
SizeOfStackReserve, SizeOfStackCommit, SizeOfHeapReserve, SizeOfHeapCommit,
LoaderFlags, NumberOfRvaAndSizes, DataDirectoryRva, DataDirectorySize};
enum Section_Field {SectionName, VirtualSize, VirtualAddress, SizeOfRawData, PointerToRawData, PointerToRelocations,
PointerToLinenumbers, NumberOfRelocations, NumberOfLinenumbers, SectionCharacteristics};
*/
}
#endif

View file

@ -0,0 +1,32 @@
/*
* PeLibInc.h - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#ifndef STD_H
#define STD_H
#ifdef _MSC_VER
#ifndef for
#define for if (0) {} else for
#endif
#endif
#include <algorithm>
#include <climits>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <functional>
// #include "PeLib.h"
#include "PeLibAux.h"
#endif

View file

@ -0,0 +1,211 @@
/*
* Relocations.cpp - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#include "PeLibInc.h"
#include "RelocationsDirectory.h"
namespace PeLib
{
void RelocationsDirectory::setRelocationData(unsigned int ulRelocation, unsigned int ulDataNumber, word wData)
{
m_vRelocations[ulRelocation].vRelocData[ulDataNumber] = wData;
}
void RelocationsDirectory::read(InputBuffer& inputbuffer, unsigned int uiSize)
{
IMG_BASE_RELOC ibrCurr;
std::vector<IMG_BASE_RELOC> vCurrReloc;
do
{
inputbuffer >> ibrCurr.ibrRelocation.VirtualAddress;
inputbuffer >> ibrCurr.ibrRelocation.SizeOfBlock;
ibrCurr.vRelocData.clear();
// That's not how to check if there are relocations, some DLLs start at VA 0.
// if (!ibrCurr.ibrRelocation.VirtualAddress) break;
for (unsigned int i=0;i<(ibrCurr.ibrRelocation.SizeOfBlock - PELIB_IMAGE_SIZEOF_BASE_RELOCATION) / sizeof(word);i++)
{
word wData;
inputbuffer >> wData;
ibrCurr.vRelocData.push_back(wData);
}
vCurrReloc.push_back(ibrCurr);
} while (ibrCurr.ibrRelocation.VirtualAddress && inputbuffer.get() < uiSize);
std::swap(vCurrReloc, m_vRelocations);
}
// TODO: Return value is wrong if buffer was too small.
int RelocationsDirectory::read(const unsigned char* buffer, unsigned int buffersize)
{
std::vector<unsigned char> vRelocDirectory(buffer, buffer + buffersize);
InputBuffer ibBuffer(vRelocDirectory);
read(ibBuffer, buffersize);
return NO_ERROR;
}
int RelocationsDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize)
{
std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
unsigned int ulFileSize = fileSize(ifFile);
if (!ifFile)
{
return ERROR_OPENING_FILE;
}
if (ulFileSize < uiOffset + uiSize)
{
return ERROR_INVALID_FILE;
}
ifFile.seekg(uiOffset, std::ios::beg);
std::vector<unsigned char> vRelocDirectory(uiSize);
ifFile.read(reinterpret_cast<char*>(&vRelocDirectory[0]), uiSize);
InputBuffer ibBuffer(vRelocDirectory);
read(ibBuffer, uiSize);
return NO_ERROR;
}
unsigned int RelocationsDirectory::size() const
{
unsigned int size = static_cast<unsigned int>(m_vRelocations.size()) * PELIB_IMAGE_BASE_RELOCATION::size();
for (unsigned int i=0;i<m_vRelocations.size();i++)
{
size += static_cast<unsigned int>(m_vRelocations[i].vRelocData.size()) * sizeof(word);
}
return size;
}
void RelocationsDirectory::rebuild(std::vector<byte>& vBuffer) const
{
OutputBuffer obBuffer(vBuffer);
for (unsigned int i=0;i<m_vRelocations.size();i++)
{
obBuffer << m_vRelocations[i].ibrRelocation.VirtualAddress;
obBuffer << m_vRelocations[i].ibrRelocation.SizeOfBlock;
for (unsigned int j=0;j<m_vRelocations[i].vRelocData.size();j++)
{
obBuffer << m_vRelocations[i].vRelocData[j];
}
}
}
unsigned int RelocationsDirectory::calcNumberOfRelocations() const
{
return static_cast<unsigned int>(m_vRelocations.size());
}
dword RelocationsDirectory::getVirtualAddress(unsigned int ulRelocation) const
{
return m_vRelocations[ulRelocation].ibrRelocation.VirtualAddress;
}
dword RelocationsDirectory::getSizeOfBlock(unsigned int ulRelocation) const
{
return m_vRelocations[ulRelocation].ibrRelocation.SizeOfBlock;
}
unsigned int RelocationsDirectory::calcNumberOfRelocationData(unsigned int ulRelocation) const
{
return static_cast<unsigned int>(m_vRelocations[ulRelocation].vRelocData.size());
}
word RelocationsDirectory::getRelocationData(unsigned int ulRelocation, unsigned int ulDataNumber) const
{
return m_vRelocations[ulRelocation].vRelocData[ulDataNumber];
}
void RelocationsDirectory::setVirtualAddress(unsigned int ulRelocation, dword dwValue)
{
m_vRelocations[ulRelocation].ibrRelocation.VirtualAddress = dwValue;
}
void RelocationsDirectory::setSizeOfBlock(unsigned int ulRelocation, dword dwValue)
{
m_vRelocations[ulRelocation].ibrRelocation.SizeOfBlock = dwValue;
}
void RelocationsDirectory::addRelocation()
{
IMG_BASE_RELOC newrelocation;
m_vRelocations.push_back(newrelocation);
}
void RelocationsDirectory::addRelocationData(unsigned int ulRelocation, word wValue)
{
m_vRelocations[ulRelocation].vRelocData.push_back(wValue);
}
/* void RelocationsDirectory::removeRelocationData(unsigned int ulRelocation, word wValue)
{
// If you get an error with Borland C++ here you have two options: Upgrade your compiler
// or use the commented line instead of the line below.
m_vRelocations[ulRelocation].vRelocData.erase(std::remove(m_vRelocations[ulRelocation].vRelocData.begin(), m_vRelocations[ulRelocation].vRelocData.end(), wValue), m_vRelocations[ulRelocation].vRelocData.end());
}
*/
void RelocationsDirectory::removeRelocation(unsigned int index)
{
m_vRelocations.erase(m_vRelocations.begin() + index);
}
void RelocationsDirectory::removeRelocationData(unsigned int relocindex, unsigned int dataindex)
{
m_vRelocations[relocindex].vRelocData.erase(m_vRelocations[relocindex].vRelocData.begin() + dataindex);
}
int RelocationsDirectory::write(const std::string& strFilename, unsigned int uiOffset) const
{
std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
if (!ofFile)
{
ofFile.clear();
ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
}
else
{
ofFile.close();
ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
}
if (!ofFile)
{
return ERROR_OPENING_FILE;
}
ofFile.seekp(uiOffset, std::ios::beg);
std::vector<unsigned char> vBuffer;
rebuild(vBuffer);
ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<std::streamsize>(vBuffer.size()));
ofFile.close();
return NO_ERROR;
}
}

View file

@ -0,0 +1,70 @@
/*
* Relocations.h - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#ifndef RELOCATIONSDIRECTORY_H
#define RELOCATIONSDIRECTORY_H
namespace PeLib
{
/// Class that handles the relocations directory.
/**
* This class handles the relocations directory.
**/
class RelocationsDirectory
{
private:
std::vector<IMG_BASE_RELOC> m_vRelocations; ///< Used to store the relocation data.
void read(InputBuffer& inputbuffer, unsigned int uiSize);
public:
/// Returns the number of relocations in the relocations directory.
unsigned int calcNumberOfRelocations() const; // EXPORT
/// Returns the number of relocation data entries of a specific relocation.
unsigned int calcNumberOfRelocationData(unsigned int ulRelocation) const; // EXPORT
/// Read a file's relocations directory.
int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize); // EXPORT
int read(const unsigned char* buffer, unsigned int buffersize); // EXPORT
/// Rebuilds the relocations directory.
void rebuild(std::vector<byte>& vBuffer) const; // EXPORT
/// Returns the size of the relocations directory.
unsigned int size() const; // EXPORT
/// Writes the relocations directory to a file.
int write(const std::string& strFilename, unsigned int dwOffset) const; // EXPORT
/// Returns the VA of a relocation.
dword getVirtualAddress(unsigned int ulRelocation) const; // EXPORT
/// Returns the SizeOfBlock value of a relocation.
dword getSizeOfBlock(unsigned int ulRelocation) const; // EXPORT
/// Returns the RelocationData of a relocation.
word getRelocationData(unsigned int ulRelocation, unsigned int ulDataNumber) const; // EXPORT
/// Changes the relocation data of a relocation.
void setRelocationData(unsigned int ulRelocation, unsigned int ulDataNumber, word wData); // EXPORT
/// Changes the VirtualAddress of a relocation.
void setVirtualAddress(unsigned int ulRelocation, dword dwValue); // EXPORT
/// Changes the SizeOfBlock of a relocation.
void setSizeOfBlock(unsigned int ulRelocation, dword dwValue); // EXPORT
void addRelocation(); // EXPORT
/// Adds new data to a relocation.
void addRelocationData(unsigned int ulRelocation, word wValue); // EXPORT
/// Removes data from a relocation.
// void removeRelocationData(unsigned int ulRelocation, word wValue); // EXPORT
void removeRelocation(unsigned int index); // EXPORT
void removeRelocationData(unsigned int relocindex, unsigned int dataindex); // EXPORT
};
}
#endif

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,735 @@
/*
* ResourceDirectory.cpp - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#ifndef RESOURCEDIRECTORY_H
#define RESOURCEDIRECTORY_H
#include "PeLibInc.h"
namespace PeLib
{
class ResourceElement;
/// The class ResourceChild is used to store information about a resource node.
class ResourceChild
{
friend class ResourceElement;
friend class ResourceDirectory;
friend class ResourceNode;
friend class ResourceLeaf;
/// Stores name and offset of a resource node.
PELIB_IMG_RES_DIR_ENTRY entry;
/// A pointer to one of the node's child nodes.
ResourceElement* child;
public:
/// Function which compares a resource ID to the node's resource ID.
bool equalId(dword wId) const; // EXPORT
/// Function which compares a string to the node's resource name.
bool equalName(std::string strName) const; // EXPORT
/// Predicate that determines if a child is identified by name or by ID.
bool isNamedResource() const; // EXPORT
/// Used for sorting a node's children.
bool operator<(const ResourceChild& rc) const; // EXPORT
/// Returns the size of a resource child.
// unsigned int size() const;
/// Standard constructor. Does absolutely nothing.
ResourceChild();
/// Makes a deep copy of a ResourceChild object.
ResourceChild(const ResourceChild& rhs);
/// Makes a deep copy of a ResourceChild object.
ResourceChild& operator=(const ResourceChild& rhs);
/// Deletes a ResourceChild object.
~ResourceChild();
};
/// Base class for ResourceNode and ResourceLeaf, the elements of the resource tree.
/// \todo write
class ResourceElement
{
friend class ResourceChild;
friend class ResourceNode;
friend class ResourceLeaf;
protected:
/// Stores RVA of the resource element in the file.
unsigned int uiElementRva;
/// Reads the next resource element from the InputBuffer.
virtual int read(InputBuffer&, unsigned int, unsigned int/*, const std::string&*/) = 0;
/// Writes the next resource element into the OutputBuffer.
virtual void rebuild(OutputBuffer&, unsigned int&, unsigned int, const std::string&) const = 0;
public:
/// Returns the RVA of the element in the file.
unsigned int getElementRva() const; // EXPORT
/// Indicates if the resource element is a leaf or a node.
virtual bool isLeaf() const = 0; // EXPORT
/// Corrects erroneous valeus in the ResourceElement.
virtual void makeValid() = 0; // EXPORT
/// Returns the size of a resource element.
// virtual unsigned int size() const = 0;
/// Necessary virtual destructor.
virtual ~ResourceElement() {}
};
/// ResourceLeafs represent the leafs of the resource tree: The actual resources.
class ResourceLeaf : public ResourceElement
{
friend class ResourceChild;
friend class ResourceDirectory;
template<typename T> friend struct fixNumberOfEntries;
private:
/// The resource data.
std::vector<byte> m_data;
/// PeLib equivalent of the Win32 structure IMAGE_RESOURCE_DATA_ENTRY
PELIB_IMAGE_RESOURCE_DATA_ENTRY entry;
protected:
int read(InputBuffer& inpBuffer, unsigned int uiOffset, unsigned int rva/*, const std::string&*/);
/// Writes the next resource leaf into the OutputBuffer.
void rebuild(OutputBuffer&, unsigned int& uiOffset, unsigned int uiRva, const std::string&) const;
public:
/// Indicates if the resource element is a leaf or a node.
bool isLeaf() const; // EXPORT
/// Corrects erroneous valeus in the ResourceLeaf.
void makeValid(); // EXPORT
/// Reads the next resource leaf from the InputBuffer.
/// Returns the size of a resource lead.
// unsigned int size() const;
/// Returns the resource data of this resource leaf.
std::vector<byte> getData() const; // EXPORT
/// Sets the resource data of this resource leaf.
void setData(const std::vector<byte>& vData); // EXPORT
/// Returns the OffsetToData value of this resource leaf.
dword getOffsetToData() const; // EXPORT
/// Returns the Size value of this resource leaf.
dword getSize() const; // EXPORT
/// Returns the CodePage value of this resource leaf.
dword getCodePage() const; // EXPORT
/// Returns the Reserved value of this resource leaf.
dword getReserved() const; // EXPORT
/// Sets the OffsetToData value of this resource leaf.
void setOffsetToData(dword dwValue); // EXPORT
/// Sets the Size value of this resource leaf.
void setSize(dword dwValue); // EXPORT
/// Sets the CodePage value of this resource leaf.
void setCodePage(dword dwValue); // EXPORT
/// Sets the Reserved value of this resource leaf.
void setReserved(dword dwValue); // EXPORT
};
/// ResourceNodes represent the nodes in the resource tree.
class ResourceNode : public ResourceElement
{
friend class ResourceChild;
friend class ResourceDirectory;
template<typename T> friend struct fixNumberOfEntries;
/// The node's children.
std::vector<ResourceChild> children;
/// The node's header. Equivalent to IMAGE_RESOURCE_DIRECTORY from the Win32 API.
PELIB_IMAGE_RESOURCE_DIRECTORY header;
protected:
/// Reads the next resource node.
int read(InputBuffer& inpBuffer, unsigned int uiOffset, unsigned int rva/*, const std::string&*/);
/// Writes the next resource node into the OutputBuffer.
void rebuild(OutputBuffer&, unsigned int& uiOffset, unsigned int uiRva, const std::string&) const;
public:
/// Indicates if the resource element is a leaf or a node.
bool isLeaf() const; // EXPORT
/// Corrects erroneous valeus in the ResourceNode.
void makeValid(); // EXPORT
/// Returns the node's number of children.
unsigned int getNumberOfChildren() const; // EXPORT
/// Adds another child to node.
void addChild(); // EXPORT
/// Returns a node's child.
ResourceElement* getChild(unsigned int uiIndex); // EXPORT
/// Removes a node's child.
void removeChild(unsigned int uiIndex); // EXPORT
/// Returns the name of one of the node's children.
std::string getChildName(unsigned int uiIndex) const; // EXPORT
/// Returns the Name value of one of the node's children.
dword getOffsetToChildName(unsigned int uiIndex) const; // EXPORT
/// Returns the OffsetToData value of one of the node's children.
dword getOffsetToChildData(unsigned int uiIndex) const; // EXPORT
/// Sets the name of one of the node's children.
void setChildName(unsigned int uiIndex, const std::string& strNewName); // EXPORT
/// Sets the Name value of one of the node's children.
void setOffsetToChildName(unsigned int uiIndex, dword dwNewOffset); // EXPORT
/// Sets the OffsetToData value of one of the node's children.
void setOffsetToChildData(unsigned int uiIndex, dword dwNewOffset); // EXPORT
/// Returns the node's Characteristics value.
dword getCharacteristics() const; // EXPORT
/// Returns the node's TimeDateStamp value.
dword getTimeDateStamp() const; // EXPORT
/// Returns the node's MajorVersion value.
word getMajorVersion() const; // EXPORT
/// Returns the node's MinorVersion value.
word getMinorVersion() const; // EXPORT
/// Returns the node's NumberOfNamedEntries value.
word getNumberOfNamedEntries() const; // EXPORT
/// Returns the node's NumberOfIdEntries value.
word getNumberOfIdEntries() const; // EXPORT
/// Sets the node's Characteristics value.
void setCharacteristics(dword value); // EXPORT
/// Sets the node's TimeDateStamp value.
void setTimeDateStamp(dword value); // EXPORT
/// Sets the node's MajorVersion value.
void setMajorVersion(word value); // EXPORT
/// Sets the node's MinorVersion value.
void setMinorVersion(word value); // EXPORT
/// Sets the node's NumberOfNamedEntries value.
void setNumberOfNamedEntries(word value); // EXPORT
/// Sets the node's NumberOfIdEntries value.
void setNumberOfIdEntries(word value); // EXPORT
/// Returns the size of a resource node.
// unsigned int size() const;
};
/// Auxiliary functor which is used to search through the resource tree.
/**
* Traits class for the template functions of ResourceDirectory.
* It's used to find out which function to use when searching for resource nodes or resource leafs
* in a node's children vector.
**/
template<typename T>
struct ResComparer
{
/// Pointer to a member function of ResourceChild
typedef bool(ResourceChild::*CompFunc)(T) const;
/// Return 0 for all unspecialized versions of ResComparer.
static CompFunc comp();
};
/// Auxiliary functor which is used to search through the resource tree.
/**
* ResComparer<dword> is used when a resource element is searched for by ID.
**/
template<>
struct ResComparer<dword>
{
/// Pointer to a member function of ResourceChild
typedef bool(ResourceChild::*CompFunc)(dword) const;
/// Return the address of the ResourceChild member function that compares the ids of resource elements.
static CompFunc comp()
{
return &ResourceChild::equalId;
}
};
/// Auxiliary functor which is used to search through the resource tree.
/**
* This specializd version of ResComparer is used when a resource element is searched for by name.
**/
template<>
struct ResComparer<std::string>
{
/// Pointer to a member function of ResourceChild
typedef bool(ResourceChild::*CompFunc)(std::string) const;
/// Return the address of the ResourceChild member function that compares the names of resource elements.
static CompFunc comp()
{
return &ResourceChild::equalName;
}
};
/// Unspecialized function that's used as base template for the specialized versions below.
template<typename T>
struct fixNumberOfEntries
{
/// Fixes a resource node's header.
static void fix(ResourceNode*);
};
/// Fixes NumberOfIdEntries value of a node.
template<>
struct fixNumberOfEntries<dword>
{
/// Fixes a resource node's NumberOfIdEntries value.
static void fix(ResourceNode* node)
{
node->header.NumberOfIdEntries = (unsigned int)node->children.size() - std::count_if(node->children.begin(), node->children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource));
}
};
/// Fixes NumberOfNamedEntries value of a node.
template<>
struct fixNumberOfEntries<std::string>
{
/// Fixes a resource node's NumberOfNamedEntries value.
static void fix(ResourceNode* node)
{
node->header.NumberOfNamedEntries = static_cast<PeLib::word>(std::count_if(node->children.begin(), node->children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource)));
}
};
/// Class that represents the resource directory of a PE file.
/**
* The class ResourceDirectory represents the resource directory of a PE file. This class is fundamentally
* different from the other classes of the PeLib library due to the structure of the ResourceDirectory.
* For once, it's possible to manipulate the ResourceDirectory through a set of "high level" functions and
* and through a set of "low level" functions. The "high level" functions are the functions inside the
* ResourceDirectory class with the exception of getRoot.<br><br>
* getRoot on the other hand is the first "low level" function. Use it to retrieve the root node of the
* resource tree. Then you can traverse through the tree and manipulate individual nodes and leafs
* directly using the functions provided by the classes ResourceNode and ResourceLeaf.<br><br>
* There's another difference between the ResourceDirectory class and the other PeLib classes, which is
* once again caused by the special structure of the PE resource directory. The nodes of the resource
* tree must be in a certain order. Manipulating the resource tree does not directly sort the nodes
* correctly as this would cause more trouble than it fixes. That means it's your responsibility to
* fix the resource tree after manipulating it. PeLib makes the job easy for you, just call the
* ResourceDirectory::makeValid function.<br><br>
* You might also wonder why there's no size() function in this class. I did not forget it. It's just
* that it's impossible to calculate the size of the resource directory without rebuilding it. So why
* should PeLib do this if you can do it just as easily by calling rebuild() and then checking the length
* of the returned vector.<br><br>
* There are also different ways to serialize (rebuild) the resource tree as it's not a fixed structure
* that can easily be minimized like most other PE directories.<br><br>
* This means it's entirely possible that the resource tree you read from a file differs from the one
* PeLib creates. This might cause a minor issue. The original resource tree might be smaller (due to
* different padding) so it's crucial that you check if there's enough space in the original resource
* directory before you write the rebuilt resource directory back to the file.
**/
class ResourceDirectory
{
private:
/// The root node of the resource directory.
ResourceNode m_rnRoot;
// Prepare for some crazy syntax below to make Digital Mars happy.
/// Retrieves an iterator to a specified resource child.
template<typename S, typename T>
std::vector<ResourceChild>::const_iterator locateResourceT(S restypeid, T resid) const;
/// Retrieves an iterator to a specified resource child.
template<typename S, typename T>
std::vector<ResourceChild>::iterator locateResourceT(S restypeid, T resid);
/// Adds a new resource.
template<typename S, typename T>
int addResourceT(S restypeid, T resid, ResourceChild& rc);
/// Removes new resource.
template<typename S, typename T>
int removeResourceT(S restypeid, T resid);
/// Returns the data of a resource.
template<typename S, typename T>
int getResourceDataT(S restypeid, T resid, std::vector<byte>& data) const;
/// Sets the data of a resource.
template<typename S, typename T>
int setResourceDataT(S restypeid, T resid, std::vector<byte>& data);
/// Returns the ID of a resource.
template<typename S, typename T>
dword getResourceIdT(S restypeid, T resid) const;
/// Sets the ID of a resource.
template<typename S, typename T>
int setResourceIdT(S restypeid, T resid, dword dwNewResId);
/// Returns the name of a resource.
template<typename S, typename T>
std::string getResourceNameT(S restypeid, T resid) const;
/// Sets the name of a resource.
template<typename S, typename T>
int setResourceNameT(S restypeid, T resid, std::string strNewResName);
public:
ResourceNode* getRoot();
/// Corrects a erroneous resource directory.
void makeValid();
/// Reads the resource directory from a file.
int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, unsigned int uiResDirRva);
/// Rebuilds the resource directory.
void rebuild(std::vector<byte>& vBuffer, unsigned int uiRva) const;
/// Returns the size of the rebuilt resource directory.
// unsigned int size() const;
/// Writes the resource directory to a file.
int write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva) const;
/// Adds a new resource type.
int addResourceType(dword dwResTypeId);
/// Adds a new resource type.
int addResourceType(const std::string& strResTypeName);
/// Removes a resource type and all of it's resources.
int removeResourceType(dword dwResTypeId);
/// Removes a resource type and all of it's resources.
int removeResourceType(const std::string& strResTypeName);
/// Removes a resource type and all of it's resources.
int removeResourceTypeByIndex(unsigned int uiIndex);
/// Adds a new resource.
int addResource(dword dwResTypeId, dword dwResId);
/// Adds a new resource.
int addResource(dword dwResTypeId, const std::string& strResName);
/// Adds a new resource.
int addResource(const std::string& strResTypeName, dword dwResId);
/// Adds a new resource.
int addResource(const std::string& strResTypeName, const std::string& strResName);
/// Removes a resource.
int removeResource(dword dwResTypeId, dword dwResId);
/// Removes a resource.
int removeResource(dword dwResTypeId, const std::string& strResName);
/// Removes a resource.
int removeResource(const std::string& strResTypeName, dword dwResId);
/// Removes a resource.
int removeResource(const std::string& strResTypeName, const std::string& strResName);
/// Returns the number of resource types.
unsigned int getNumberOfResourceTypes() const;
/// Returns the ID of a resource type.
dword getResourceTypeIdByIndex(unsigned int uiIndex) const;
/// Returns the name of a resource type.
std::string getResourceTypeNameByIndex(unsigned int uiIndex) const;
/// Converts a resource type ID to an index.
int resourceTypeIdToIndex(dword dwResTypeId) const;
/// Converts a resource type name to an index.
int resourceTypeNameToIndex(const std::string& strResTypeName) const;
/// Returns the number of resources of a certain resource type.
unsigned int getNumberOfResources(dword dwId) const;
/// Returns the number of resources of a certain resource type.
unsigned int getNumberOfResources(const std::string& strResTypeName) const;
/// Returns the number of resources of a certain resource type.
unsigned int getNumberOfResourcesByIndex(unsigned int uiIndex) const;
/// Returns the data of a certain resource.
void getResourceData(dword dwResTypeId, dword dwResId, std::vector<byte>& data) const;
/// Returns the data of a certain resource.
void getResourceData(dword dwResTypeId, const std::string& strResName, std::vector<byte>& data) const;
/// Returns the data of a certain resource.
void getResourceData(const std::string& strResTypeName, dword dwResId, std::vector<byte>& data) const;
/// Returns the data of a certain resource.
void getResourceData(const std::string& strResTypeName, const std::string& strResName, std::vector<byte>& data) const;
/// Returns the data of a certain resource.
void getResourceDataByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, std::vector<byte>& data) const;
/// Sets the data of a certain resource.
void setResourceData(dword dwResTypeId, dword dwResId, std::vector<byte>& data);
/// Sets the data of a certain resource.
void setResourceData(dword dwResTypeId, const std::string& strResName, std::vector<byte>& data);
/// Sets the data of a certain resource.
void setResourceData(const std::string& strResTypeName, dword dwResId, std::vector<byte>& data);
/// Sets the data of a certain resource.
void setResourceData(const std::string& strResTypeName, const std::string& strResName, std::vector<byte>& data);
/// Sets the data of a certain resource.
void setResourceDataByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, std::vector<byte>& data);
/// Returns the ID of a certain resource.
dword getResourceId(dword dwResTypeId, const std::string& strResName) const;
/// Returns the ID of a certain resource.
dword getResourceId(const std::string& strResTypeName, const std::string& strResName) const;
/// Returns the ID of a certain resource.
dword getResourceIdByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex) const;
/// Sets the ID of a certain resource.
void setResourceId(dword dwResTypeId, dword dwResId, dword dwNewResId);
/// Sets the ID of a certain resource.
void setResourceId(dword dwResTypeId, const std::string& strResName, dword dwNewResId);
/// Sets the ID of a certain resource.
void setResourceId(const std::string& strResTypeName, dword dwResId, dword dwNewResId);
/// Sets the ID of a certain resource.
void setResourceId(const std::string& strResTypeName, const std::string& strResName, dword dwNewResId);
/// Sets the ID of a certain resource.
void setResourceIdByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, dword dwNewResId);
/// Returns the name of a certain resource.
std::string getResourceName(dword dwResTypeId, dword dwResId) const;
/// Returns the name of a certain resource.
std::string getResourceName(const std::string& strResTypeName, dword dwResId) const;
/// Returns the name of a certain resource.
std::string getResourceNameByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex) const;
/// Sets the name of a certain resource.
void setResourceName(dword dwResTypeId, dword dwResId, const std::string& strNewResName);
/// Sets the name of a certain resource.
void setResourceName(dword dwResTypeId, const std::string& strResName, const std::string& strNewResName);
/// Sets the name of a certain resource.
void setResourceName(const std::string& strResTypeName, dword dwResId, const std::string& strNewResName);
/// Sets the name of a certain resource.
void setResourceName(const std::string& strResTypeName, const std::string& strResName, const std::string& strNewResName);
/// Sets the name of a certain resource.
void setResourceNameByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, const std::string& strNewResName);
};
/**
* Looks through the entire resource tree and returns a const_iterator to the resource specified
* by the parameters.
* @param restypeid Identifier of the resource type (either ID or name).
* @param resid Identifier of the resource (either ID or name).
* @return A const_iterator to the specified resource.
**/
template<typename S, typename T>
std::vector<ResourceChild>::const_iterator ResourceDirectory::locateResourceT(S restypeid, T resid) const
{
typedef bool(ResourceChild::*CompFunc1)(S) const;
typedef bool(ResourceChild::*CompFunc2)(T) const;
CompFunc1 comp1 = ResComparer<S>::comp();
CompFunc2 comp2 = ResComparer<T>::comp();
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));
if (Iter == m_rnRoot.children.end())
{
return Iter;
}
ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child);
std::vector<ResourceChild>::const_iterator ResIter = std::find_if(currNode->children.begin(), currNode->children.end(), std::bind2nd(std::mem_fun_ref(comp2), resid));
if (ResIter == currNode->children.end())
{
return ResIter;
}
return ResIter;
}
/**
* Looks through the entire resource tree and returns an iterator to the resource specified
* by the parameters.
* @param restypeid Identifier of the resource type (either ID or name).
* @param resid Identifier of the resource (either ID or name).
* @return An iterator to the specified resource.
**/
template<typename S, typename T>
std::vector<ResourceChild>::iterator ResourceDirectory::locateResourceT(S restypeid, T resid)
{
typedef bool(ResourceChild::*CompFunc1)(S) const;
typedef bool(ResourceChild::*CompFunc2)(T) const;
CompFunc1 comp1 = ResComparer<S>::comp();
CompFunc2 comp2 = ResComparer<T>::comp();
std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(comp1), restypeid));
if (Iter == m_rnRoot.children.end())
{
return Iter;
}
ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child);
std::vector<ResourceChild>::iterator ResIter = std::find_if(currNode->children.begin(), currNode->children.end(), std::bind2nd(std::mem_fun_ref(comp2), resid));
if (ResIter == currNode->children.end())
{
return ResIter;
}
return ResIter;
}
/**
* Adds a new resource, resource type and ID are specified by the parameters.
* @param restypeid Identifier of the resource type (either ID or name).
* @param resid Identifier of the resource (either ID or name).
* @param rc ResourceChild that will be added.
**/
template<typename S, typename T>
int ResourceDirectory::addResourceT(S restypeid, T resid, ResourceChild& rc)
{
typedef bool(ResourceChild::*CompFunc1)(S) const;
typedef bool(ResourceChild::*CompFunc2)(T) const;
CompFunc1 comp1 = ResComparer<S>::comp();
CompFunc2 comp2 = ResComparer<T>::comp();
std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(comp1), restypeid));
if (Iter == m_rnRoot.children.end())
{
return 1;
// throw Exceptions::ResourceTypeDoesNotExist(ResourceDirectoryId, __LINE__);
}
ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child);
std::vector<ResourceChild>::iterator ResIter = std::find_if(currNode->children.begin(), currNode->children.end(), std::bind2nd(std::mem_fun_ref(comp2), resid));
if (ResIter != currNode->children.end())
{
return 1;
// throw Exceptions::EntryAlreadyExists(ResourceDirectoryId, __LINE__);
}
rc.child = new ResourceNode;
ResourceChild rlnew;
rlnew.child = new ResourceLeaf;
ResourceNode* currNode2 = static_cast<ResourceNode*>(rc.child);
currNode2->children.push_back(rlnew);
currNode->children.push_back(rc);
fixNumberOfEntries<T>::fix(currNode);
fixNumberOfEntries<T>::fix(currNode2);
return 0;
}
/**
* Removes a resource, resource type and ID are specified by the parameters.
* @param restypeid Identifier of the resource type (either ID or name).
* @param resid Identifier of the resource (either ID or name).
**/
template<typename S, typename T>
int ResourceDirectory::removeResourceT(S restypeid, T resid)
{
typedef bool(ResourceChild::*CompFunc1)(S) const;
typedef bool(ResourceChild::*CompFunc2)(T) const;
CompFunc1 comp1 = ResComparer<S>::comp();
CompFunc2 comp2 = ResComparer<T>::comp();
std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(comp1), restypeid));
if (Iter == m_rnRoot.children.end())
{
return 1;
//throw Exceptions::ResourceTypeDoesNotExist(ResourceDirectoryId, __LINE__);
}
ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child);
std::vector<ResourceChild>::iterator ResIter = std::find_if(currNode->children.begin(), currNode->children.end(), std::bind2nd(std::mem_fun_ref(comp2), resid));
if (ResIter == currNode->children.end())
{
return 1;
// throw Exceptions::InvalidName(ResourceDirectoryId, __LINE__);
}
currNode->children.erase(ResIter);
fixNumberOfEntries<T>::fix(currNode);
return 0;
}
/**
* Returns the data of a resource, resource type and ID are specified by the parameters.
* @param restypeid Identifier of the resource type (either ID or name).
* @param resid Identifier of the resource (either ID or name).
* @param data The data of the resource will be written into this vector.
**/
template<typename S, typename T>
int ResourceDirectory::getResourceDataT(S restypeid, T resid, std::vector<byte>& data) const
{
std::vector<ResourceChild>::const_iterator ResIter = locateResourceT(restypeid, resid);
ResourceNode* currNode = static_cast<ResourceNode*>(ResIter->child);
ResourceLeaf* currLeaf = static_cast<ResourceLeaf*>(currNode->children[0].child);
data.assign(currLeaf->m_data.begin(), currLeaf->m_data.end());
return 0;
}
/**
* Sets the data of a resource, resource type and ID are specified by the parameters.
* @param restypeid Identifier of the resource type (either ID or name).
* @param resid Identifier of the resource (either ID or name).
* @param data The new data of the resource is taken from this vector.
**/
template<typename S, typename T>
int ResourceDirectory::setResourceDataT(S restypeid, T resid, std::vector<byte>& data)
{
std::vector<ResourceChild>::iterator ResIter = locateResourceT(restypeid, resid);
ResourceNode* currNode = static_cast<ResourceNode*>(ResIter->child);
ResourceLeaf* currLeaf = static_cast<ResourceLeaf*>(currNode->children[0].child);
currLeaf->m_data.assign(data.begin(), data.end());
return 0;
}
/**
* Returns the id of a resource, resource type and ID are specified by the parameters.
* Note: Calling this function with resid == the ID of the resource makes no sense at all.
* @param restypeid Identifier of the resource type (either ID or name).
* @param resid Identifier of the resource (either ID or name).
* @return The ID of the specified resource.
**/
template<typename S, typename T>
dword ResourceDirectory::getResourceIdT(S restypeid, T resid) const
{
std::vector<ResourceChild>::const_iterator ResIter = locateResourceT(restypeid, resid);
return ResIter->entry.irde.Name;
}
/**
* Sets the id of a resource, resource type and ID are specified by the parameters.
* @param restypeid Identifier of the resource type (either ID or name).
* @param resid Identifier of the resource (either ID or name).
* @param dwNewResId New ID of the resource.
**/
template<typename S, typename T>
int ResourceDirectory::setResourceIdT(S restypeid, T resid, dword dwNewResId)
{
std::vector<ResourceChild>::iterator ResIter = locateResourceT(restypeid, resid);
ResIter->entry.irde.Name = dwNewResId;
return 0;
}
/**
* Returns the name of a resource, resource type and ID are specified by the parameters.
* Note: Calling this function with resid == the name of the resource makes no sense at all.
* @param restypeid Identifier of the resource type (either ID or name).
* @param resid Identifier of the resource (either ID or name).
* @return The name of the specified resource.
**/
template<typename S, typename T>
std::string ResourceDirectory::getResourceNameT(S restypeid, T resid) const
{
std::vector<ResourceChild>::const_iterator ResIter = locateResourceT(restypeid, resid);
return ResIter->entry.wstrName;
}
/**
* Sets the name of a resource, resource type and ID are specified by the parameters.
* @param restypeid Identifier of the resource type (either ID or name).
* @param resid Identifier of the resource (either ID or name).
* @param strNewResName The new name of the resource.
**/
template<typename S, typename T>
int ResourceDirectory::setResourceNameT(S restypeid, T resid, std::string strNewResName)
{
std::vector<ResourceChild>::iterator ResIter = locateResourceT(restypeid, resid);
ResIter->entry.wstrName = strNewResName;
return 0;
}
}
#endif

View file

@ -0,0 +1,304 @@
/*
* TlsDirectory.h - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#ifndef TLSDIRECTORY_H
#define TLSDIRECTORY_H
namespace PeLib
{
/// Class that handles the TLS directory.
/**
* This class handles the TLS (Thread Local Storage) directory.
**/
template<int bits>
class TlsDirectory
{
private:
PELIB_IMAGE_TLS_DIRECTORY<bits> m_tls; ///< Structure that holds all information about the directory.
void read(InputBuffer& inputbuffer);
public:
/// Reads a file's TLS directory.
int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize); // EXPORT
int read(unsigned char* buffer, unsigned int buffersize); // EXPORT
/// Rebuilds the TLS directory.
void rebuild(std::vector<byte>& vBuffer) const; // EXPORT
/// Returns the size of the TLS Directory.
unsigned int size() const; // EXPORT
/// Writes the TLS directory to a file.
int write(const std::string& strFilename, unsigned int dwOffset) const; // EXPORT
/// Returns the StartAddressOfRawData value of the TLS header.
dword getStartAddressOfRawData() const; // EXPORT
/// Returns the EndAddressOfRawData value of the TLS header.
dword getEndAddressOfRawData() const; // EXPORT
/// Returns the AddressOfIndex value of the TLS header.
dword getAddressOfIndex() const; // EXPORT
/// Returns the AddressOfCallBacks value of the TLS header.
dword getAddressOfCallBacks() const; // EXPORT
/// Returns the SizeOfZeroFill value of the TLS header.
dword getSizeOfZeroFill() const; // EXPORT
/// Returns the Characteristics value of the TLS header.
dword getCharacteristics() const; // EXPORT
/// Sets the StartAddressOfRawData value of the TLS header.
void setStartAddressOfRawData(dword dwValue); // EXPORT
/// Sets the EndAddressOfRawData value of the TLS header.
void setEndAddressOfRawData(dword dwValue); // EXPORT
/// Sets the AddressOfIndex value of the TLS header.
void setAddressOfIndex(dword dwValue); // EXPORT
/// Sets the AddressOfCallBacks value of the TLS header.
void setAddressOfCallBacks(dword dwValue); // EXPORT
/// Sets the SizeOfZeroFill value of the TLS header.
void setSizeOfZeroFill(dword dwValue); // EXPORT
/// Sets the Characteristics value of the TLS header.
void setCharacteristics(dword dwValue); // EXPORT
};
template<int bits>
void TlsDirectory<bits>::read(InputBuffer& inputBuffer)
{
PELIB_IMAGE_TLS_DIRECTORY<bits> itdCurr;
inputBuffer >> itdCurr.StartAddressOfRawData;
inputBuffer >> itdCurr.EndAddressOfRawData;
inputBuffer >> itdCurr.AddressOfIndex;
inputBuffer >> itdCurr.AddressOfCallBacks;
inputBuffer >> itdCurr.SizeOfZeroFill;
inputBuffer >> itdCurr.Characteristics;
std::swap(itdCurr, m_tls);
}
template<int bits>
int TlsDirectory<bits>::read(unsigned char* buffer, unsigned int buffersize)
{
if (buffersize < PELIB_IMAGE_TLS_DIRECTORY<bits>::size())
{
return ERROR_INVALID_FILE;
}
std::vector<byte> vTlsDirectory(buffer, buffer + buffersize);
InputBuffer ibBuffer(vTlsDirectory);
read(ibBuffer);
return NO_ERROR;
}
/**
* Reads a file's TLS directory.
* @param strFilename Name of the file.
* @param uiOffset File offset of the TLS directory.
* @param uiSize Size of the TLS directory.
**/
template<int bits>
int TlsDirectory<bits>::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize)
{
std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
unsigned int ulFileSize = fileSize(ifFile);
if (!ifFile)
{
return ERROR_OPENING_FILE;
}
if (ulFileSize < uiOffset + uiSize)
{
return ERROR_INVALID_FILE;
}
ifFile.seekg(uiOffset, std::ios::beg);
std::vector<byte> vTlsDirectory(uiSize);
ifFile.read(reinterpret_cast<char*>(&vTlsDirectory[0]), uiSize);
InputBuffer ibBuffer(vTlsDirectory);
read(ibBuffer);
return NO_ERROR;
}
/**
* Rebuilds the current TLS Directory.
* @param vBuffer Buffer where the TLS directory will be written to.
**/
template<int bits>
void TlsDirectory<bits>::rebuild(std::vector<byte>& vBuffer) const
{
OutputBuffer obBuffer(vBuffer);
obBuffer << m_tls.StartAddressOfRawData;
obBuffer << m_tls.EndAddressOfRawData;
obBuffer << m_tls.AddressOfIndex;
obBuffer << m_tls.AddressOfCallBacks;
obBuffer << m_tls.SizeOfZeroFill;
obBuffer << m_tls.Characteristics;
}
/**
* Returns the size of the TLS directory. Due to the static nature of this structure the return value
* will always be 24.
* @return Size in bytes.
**/
template<int bits>
unsigned int TlsDirectory<bits>::size() const
{
return PELIB_IMAGE_TLS_DIRECTORY<bits>::size();
}
/**
* @param strFilename Name of the file.
* @param dwOffset File offset the TLS Directory will be written to.
**/
template<int bits>
int TlsDirectory<bits>::write(const std::string& strFilename, unsigned int dwOffset) const
{
std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
if (!ofFile)
{
ofFile.clear();
ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
}
else
{
ofFile.close();
ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
}
if (!ofFile)
{
return ERROR_OPENING_FILE;
}
ofFile.seekp(dwOffset, std::ios::beg);
std::vector<unsigned char> vBuffer;
rebuild(vBuffer);
ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), vBuffer.size());
ofFile.close();
return NO_ERROR;
}
/**
* @return The StartAddressOfRawData value of the TLS directory.
**/
template<int bits>
dword TlsDirectory<bits>::getStartAddressOfRawData() const
{
return m_tls.StartAddressOfRawData;
}
/**
* @return The EndAddressOfRawData value of the TLS directory.
**/
template<int bits>
dword TlsDirectory<bits>::getEndAddressOfRawData() const
{
return m_tls.EndAddressOfRawData;
}
/**
* @return The AddressOfIndex value of the TLS directory.
**/
template<int bits>
dword TlsDirectory<bits>::getAddressOfIndex() const
{
return m_tls.AddressOfIndex;
}
/**
* @return The AddressOfCallBacks value of the TLS directory.
**/
template<int bits>
dword TlsDirectory<bits>::getAddressOfCallBacks() const
{
return m_tls.AddressOfCallBacks;
}
/**
* @return The SizeOfZeroFill value of the TLS directory.
**/
template<int bits>
dword TlsDirectory<bits>::getSizeOfZeroFill() const
{
return m_tls.SizeOfZeroFill;
}
/**
* @return The Characteristics value of the TLS directory.
**/
template<int bits>
dword TlsDirectory<bits>::getCharacteristics() const
{
return m_tls.Characteristics;
}
/**
* @param dwValue The new StartAddressOfRawData value of the TLS directory.
**/
template<int bits>
void TlsDirectory<bits>::setStartAddressOfRawData(dword dwValue)
{
m_tls.StartAddressOfRawData = dwValue;
}
/**
* @param dwValue The new EndAddressOfRawData value of the TLS directory.
**/
template<int bits>
void TlsDirectory<bits>::setEndAddressOfRawData(dword dwValue)
{
m_tls.EndAddressOfRawData = dwValue;
}
/**
* @param dwValue The new AddressOfIndex value of the TLS directory.
**/
template<int bits>
void TlsDirectory<bits>::setAddressOfIndex(dword dwValue)
{
m_tls.AddressOfIndex = dwValue;
}
/**
* @param dwValue The new AddressOfCallBacks value of the TLS directory.
**/
template<int bits>
void TlsDirectory<bits>::setAddressOfCallBacks(dword dwValue)
{
m_tls.AddressOfCallBacks = dwValue;
}
/**
* @param dwValue The new SizeOfZeroFill value of the TLS directory.
**/
template<int bits>
void TlsDirectory<bits>::setSizeOfZeroFill(dword dwValue)
{
m_tls.SizeOfZeroFill = dwValue;
}
/**
* @param dwValue The new Characteristics value of the TLS directory.
**/
template<int bits>
void TlsDirectory<bits>::setCharacteristics(dword dwValue)
{
m_tls.Characteristics = dwValue;
}
}
#endif

View file

@ -0,0 +1,58 @@
/*
* InputBuffer.cpp - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#include "InputBuffer.h"
namespace PeLib
{
unsigned long InputBuffer::get()
{
return ulIndex;
}
InputBuffer::InputBuffer(std::vector<unsigned char>& vBuffer) : m_vBuffer(vBuffer), ulIndex(0)
{
}
const unsigned char* InputBuffer::data() const
{
return &m_vBuffer[0];
}
unsigned long InputBuffer::size()
{
return static_cast<unsigned long>(m_vBuffer.size());
}
void InputBuffer::read(char* lpBuffer, unsigned long ulSize)
{
std::copy(&m_vBuffer[ulIndex], &m_vBuffer[ulIndex + ulSize], lpBuffer);
ulIndex += ulSize;
}
void InputBuffer::reset()
{
m_vBuffer.clear();
}
void InputBuffer::set(unsigned long ulIndex)
{
this->ulIndex = ulIndex;
}
void InputBuffer::setBuffer(std::vector<unsigned char>& vBuffer)
{
m_vBuffer = vBuffer;
ulIndex = 0;
}
}

View file

@ -0,0 +1,52 @@
/*
* InputBuffer.h - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#ifndef INPUTBUFFER_H
#define INPUTBUFFER_H
#include <vector>
#include <iterator>
#include <cassert>
namespace PeLib
{
class InputBuffer
{
private:
std::vector<unsigned char>& m_vBuffer;
unsigned long ulIndex;
public:
InputBuffer(std::vector<unsigned char>& vBuffer);
const unsigned char* data() const;
unsigned long size();
template<typename T>
InputBuffer& operator>>(T& value)
{
assert(ulIndex + sizeof(value) <= m_vBuffer.size());
value = *(T*)(&m_vBuffer[ulIndex]);//reinterpret_cast<T*>(&m_vBuffer[ulIndex]);
ulIndex += sizeof(T);
return *this;
}
void read(char* lpBuffer, unsigned long ulSize);
void reset();
void set(unsigned long ulIndex);
unsigned long get();
void setBuffer(std::vector<unsigned char>& vBuffer);
// void updateData(unsigned long ulIndex,
};
}
#endif

View file

@ -0,0 +1,41 @@
/*
* OutputBuffer.cpp - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#include "OutputBuffer.h"
namespace PeLib
{
OutputBuffer::OutputBuffer(std::vector<unsigned char>& vBuffer) : m_vBuffer(vBuffer)
{
m_vBuffer.clear();
}
const unsigned char* OutputBuffer::data() const
{
return &m_vBuffer[0];
}
unsigned long OutputBuffer::size()
{
return static_cast<unsigned long>(m_vBuffer.size());
}
void OutputBuffer::add(const char* lpBuffer, unsigned long ulSize)
{
std::copy(lpBuffer, lpBuffer + ulSize, std::back_inserter(m_vBuffer));
}
void OutputBuffer::reset()
{
m_vBuffer.clear();
}
}

View file

@ -0,0 +1,51 @@
/*
* OutputBuffer.h - Part of the PeLib library.
*
* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
* All rights reserved.
*
* This software is licensed under the zlib/libpng License.
* For more details see http://www.opensource.org/licenses/zlib-license.php
* or the license information file (license.htm) in the root directory
* of PeLib.
*/
#ifndef OUTPUTBUFFER_H
#define OUTPUTBUFFER_H
#include <vector>
#include <iterator>
namespace PeLib
{
class OutputBuffer
{
private:
std::vector<unsigned char>& m_vBuffer;
public:
OutputBuffer(std::vector<unsigned char>& vBuffer);
const unsigned char* data() const;
unsigned long size();
template<typename T>
OutputBuffer& operator<<(const T& value)
{
const unsigned char* p = reinterpret_cast<const unsigned char*>(&value);
std::copy(p, p + sizeof(value), std::back_inserter(m_vBuffer));
return *this;
}
void add(const char* lpBuffer, unsigned long ulSize);
void reset();
void resize(unsigned int uiSize);
void set(unsigned int uiPosition);
template<typename T>
void update(unsigned long ulIndex, const T& value)
{
*(T*)(&m_vBuffer[ulIndex]) = value;
}
};
}
#endif

View file

@ -0,0 +1,321 @@
PeLib 0.09 alpha (February 09, 2005)
Added:
- Added PeHeaderT<x>::setIddBaseRelocRva(dword value)
- Added PeHeaderT<x>::setIddBaseRelocSize(dword value)
- Added PeHeaderT<x>::setIddArchitectureRva(dword value)
- Added PeHeaderT<x>::setIddArchitectureSize(dword value)
- Added PeHeaderT<x>::setIddComHeaderRva(dword value)
- Added PeHeaderT<x>::setIddComHeaderSize(dword value)
- Added void PeHeaderT<x>::setImageDataDirectoryRva(dword dwDirectory, dword value)
- Added void PeHeaderT<x>::setImageDataDirectorySize(dword dwDirectory, dword value)
- Added bool PeHeaderT<x>::isValid() const
- Added int PeHeaderT<x>::read(const unsigned char* pcBuffer, unsigned int uiSize, unsigned int uiOffset);
- Added int BoundImportDirectory::read(unsigned char* pcBuffer, unsigned int uiSize);
- Added int BoundImportDirectory::read(InputBuffer& inpBuffer, unsigned char* data, unsigned int dwSize);
- Added unsigned int BoundImportDirectory::totalModules()
- Added DebugDirectory::setData to set the debug data of individual entries in the DebugDirectory.
- Added DebugDirectory::getData to get the debug data of individual entries in the DebugDirectory.
- Added int IatDirectory::read(unsigned char* buffer, unsigned int buffersize)
- Optimized the size and rebuild methods to avoid duplicate strings for files that appear
more than once in the BoundImport Directory.
- Added two read functions to TlsDirectory and updated the return values of the old read function.
- Added two read functions to ComHeaderDirectory and updated the return values of the old read function.
- Added two read functions to RelocationsDirectory and updated the return values of the old read function.
- Added void RelocationsDirectory::addRelocation()
- Added void RelocationsDirectory::removeRelocation(unsigned int index)
- Added void DebugDirectory::clear()
- Added void ExportDirectory::removeFunction(unsigned int index)
- Added void ExportDirectory::clear()
- Added unsigned int ExportDirectory::calcNumberOfFunctions()
- Added void ExportDirectory::setAddressOfNameOrdinals(dword value)
Bugfixes:
- Fixed a bug in TlsDirectory<bits>::size()
- Fixed a bug in PeHeaderT<64>::isValid(dword)
- Fixed a bug in PeHeaderT<bits>::removeDataDirectory(dword)
- Fixed a bug in BoundImportDirectory::rebuild()
- Fixed a bug in BoundImportDirectory::read() (Potential buffer overflow)
- Fixed a bug in BoundImportDirectory::read() (Bug caused incorrect results when reading the directory more than once)
- Fixed a bug when reading the debug data of individual DebugDirectory entries.
- Fixed a bug that caused non-existing data directories to be read (PeFile).
- Fixed a bug that caused problems when reading import directories that were located close to the end of the file (ImportDirectory).
- Fixed a minor bug in PeHeader::calcSizeOfImage
- Fixed some return values and removed all exception handling blocks.
Changes:
- Changed return values of PeHeader::addSection
- Changed return values of PeHeader::read
- Changed behaviour: PeHeader::m_uiOffset is initialized to 0 in default constructors.
- Changed return value of BoundImportDirectory::getNumberOfModules() from int to unsigned int
- Changed name of BoundImportDirectory::getNumberOfModules to calcNumberOfModules
- Changed the return values of the PeFile::read* functions.
- Renamed IatDirectory::removeAll to IatDirectory::clear
- Renamed IatDirectory::numberOfAddresses to IatDirectory::calcNumberOfAddresses
- Changed the parameter types of IatDirectory::getAddress from dword to unsigned int
- Changed the parameter types of IatDirectory::removeAddress from dword to unsigned int
- All constants taken from windows.h that were redefined in PeLibAux.h now have the prefix PELIB_ to avoid
conflicts with windows.h if both files are included to a project.
- Changed PELIB_IMAGE_TLS_DIRECTORY<bits>::size from an enum to a function.
- Changed the name of RelocationsDirectory::getNumberOfRelocationData to calcNumberOfRelocationData
- Changed void RelocationsDirectory::removeRelocationData(unsigned int ulRelocation, word wValue)
to void RelocationsDirectory::removeRelocationData(unsigned int relocindex, unsigned int dataindex)
- Removed dword ExportDirectory::getNumberOfNameOrdinals()
- Removed dword ExportDirectory::getNumberOfAddressOfFunctionNames()
- Removed dword ExportDirectory::getNumberOfAddressOfFunctions()
- Changed the parameters of some functions in ExportDirectory from dword to unsigned int.
January 16, 2005 PeLib 0.08 alpha
Added:
- Added std::string ExportDirectory::getNameString()
- Added resource type RT_MANIFEST to PeLibAux.h
- Added the following functions of PeHeaderT<int x>: setIddDebugRva, setIddDebugSize,
setIddDelayImportRva, setIddDelayImportSize, setIddExceptionRva, setIddExceptionSize, setIddGlobalPtrRva,
setIddGlobalPtrSize, setIddIatRva, setIddIatSize, setIddLoadConfigRva, setIddLoadConfigSize,
setIddResourceRva, setIddResourceSize, setIddResourceRva, setIddResourceSize, setIddSecurityRva,
setIddSecuritySize, setIddTlsRva, setIddTlsSize
- ImportDirectory32 and ImportDirectory64 are now available.
- Added ImportDirectory<bits>::setFileName(dword, currdir, const std::string&)
- Added ImportDirectory<bits>::setFirstThunk(dword, currdir, dword)
- Added ImportDirectory<bits>::setForwarderChain(dword, currdir, dword)
- Added ImportDirectory<bits>::setRvaOfName(dword, currdir, dword)
- Added ImportDirectory<bits>::setOriginalFirstThunk(dword, currdir, dword)
- Added ImportDirectory<bits>::setTimeDateStamp(dword, currdir, dword)
- Added ImportDirectory<bits>::setOriginalFirstThunk(dword, dword, currdir, dword)
- Added ImportDirectory<bits>::setFirstThunk(dword, dword, currdir, dword)
- Added ImportDirectory<bits>::setFunctionHint(dword, dword, currdir, word)
- Added ImportDirectory<bits>::setFunctionName(dword, dword, currdir, const std::string&)
- Added dword BoundImportDirectory::getTimeDateStamp(dword dwBidnr, dword forwardedModule) const
- Added word BoundImportDirectory::getOffsetModuleName(dword dwBidnr, dword forwardedModule) const
- Added word BoundImportDirectory::getNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule) const
- Added std::string BoundImportDirectory::getModuleName(dword dwBidnr, dword forwardedModule) const
- Added void BoundImportDirectory::setTimeDateStamp(dword dwBidnr, dword forwardedModule, dword dwTds)
- Added void BoundImportDirectory::setOffsetModuleName(dword dwBidnr, dword forwardedModule, word wOmn)
- Added void BoundImportDirectory::setNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule, word wMfr)
- Added void BoundImportDirectory::setModuleName(dword dwBidnr, dword forwardedModule, const std::string& strModuleName)
- Added word calcNumberOfModuleForwarderRefs(dword dwBidnr) const
- Added void addForwardedModule(dword dwBidnr, const std::string& name, dword timeStamp = 0, word offsetModuleName = 0, word forwardedModules = 0)
- Added void removeForwardedModule(dword dwBidnr, word forwardedModule)
- Added PeHeaderT<x>::addDataDirectory()
- Added PeHeaderT<x>::removeDataDirectory(dword)
Bugfixes:
- Fixed a bug in MzHeader::isValid
- Fixed a bug in PeHeaderT<x>::size()
- Fixed a bug in PeHeaderT<x>::calcRva()
- Fixed a bug in PeHeaderT<x>::calcSizeOfImage()
- Fixed a bug in PeHeaderT<x>::getSectionName(dword)
- Fixed a bug in PeHeaderT<x>::calcStartOfCode()
- Fixed a bug in PELIB_THUNK_DATA<bits>::bool equalHint(word wHint) const
- Fixed a bug in PELIB_IMAGE_THUNK_DATA<bits>::bool equalHint(word wHint) const
- Fixed a bug in int ImportDirectory<bits>::removeFunction(const std::string& strFilename, word wHint)
- Fixed a bug in int ImportDirectory<bits>::removeFile(const std::string& strFilename)
- Function hints are now properly added when rebuilding import directories.
- Reading and rebuilding bound import directories now works with forwarded modules.
Changes:
- Changed behaviour: Removed all exceptions from the MzHeader class. The functions work with return values now.
- Changed behaviour: The MzHeader::read() functions stopped checking if the MzHeader begins with "MZ".
- Changed behaviour: PeHeaderT<int x>::addSection(std::string, dword) doesn't use exceptions anymore.
Return values now indicate if the function succeeded or failed.
- Changed behaviour: PeHeaderT<int x>::getSectionWithOffset(dword) doesn't use exceptions anymore.
Return values now indicate if the function succeeded or failed.
- Changed behaviour: PeHeaderT<int x>::getSectionWithRva(dword) doesn't use exceptions anymore.
Return values now indicate if the function succeeded or failed.
- Changed behaviour: PeHeaderT<int x>::rvaToOffset(dword) doesn't use exceptions anymore.
Return values now indicate if the function succeeded or failed.
- Changed behaviour: PeHeaderT<int x>::write(std::string, unsigned int) doesn't use exceptions anymore.
Return values now indicate if the function succeeded or failed.
- Changed behaviour: PeHeaderT<int x>::writeSectionData(const std::string& strFilename, word wSecnr,
const std::vector<byte>& vBuffer) doesn't use exceptions anymore.
Return values now indicate if the function succeeded or failed.
- Changed behaviour: PeHeaderT<int x>::writeSections(std::string) doesn't use exceptions anymore.
Return values now indicate if the function succeeded or failed.
- Changed behaviour: Return value of PeHeaderT<x>::calcSpaceAfterHeader() changed from unsigned long
to unsigned int.
- Changed behaviour: Return value of PeHeaderT<x>::calcStartOfCode() changed from unsigned long
to unsigned int.
- Changed behaviour: Return value of PeHeaderT<x>::calcOffset() changed from unsigned long
to unsigned int.
- Changed behaviour: Return value of PeHeaderT<x>::offsetToRva(dword) changed from unsigned long
to unsigned int.
- Changed behaviour: Return value of PeHeaderT<x>::offsetToVa(dword) changed from unsigned long
to unsigned int.
- Renamed ExportDirectory::setName(std::string) to ExportDirectory::setNameString(std::string)
- Renamed the PeHeaderT::getId* functions to PeHeaderT::getIdd*
- Renamed PeHeaderT::getImageDirectoryRva to PeHeaderT::getImageDataDirectoryRva
- Renamed PeHeaderT::getImageDirectorySize to PeHeaderT::getImageDataDirectorySize
- Renamed void PeHeaderT<x>::setWinVersionValue(dword dwValue) to void PeHeaderT<x>::setWin32VersionValue(dword dwValue)
- Renamed the following functions of PeHeaderT<int x>: setIdImportRva to setIddImportRva,
setIdImportSize to setIddImportSize, setIdExportRva to setIddExportRva, setIdExportSize to setIddExportSize
- Renamed dword ImportDirectory<bits>::getName to dword ImportDirectory<bits>::getRvaOfName
- Changed behaviour: All removeFunction and removeFile functions from ImportDirectory.h return int instead
of void now.
- Changed behavior: ResourceDirectory::resourceTypeNameToIndex returns int instead of unsigned int.
-------------------------------------------------------------------------------------------------------------
July 18, 2004 PeLib 0.07 alpha
Added:
- Full support of the PE+ format.
- ImportDirectory::getName(string, currdir)
- ImportDirectory::getFirstThunk(dword, currdir)
- ImportDirectory::getOriginalFirstThunk(dword, currdir)
- ImportDirectory::getForwarderChain(dword, currdir)
- ImportDirectory::getName(dword, currdir)
- ImportDirectory::getTimeDateStamp(dword, currdir)
- PeLib::getFileType(string)
- PeLib::openPeFile(string)
- Added class PeFileVisitor
- Added PeFile::visit(PeFileVisitor&)
Bugfixes:
- Fixed a bug in PeHeader::rvaToOffset
Changes:
- Renamed ImportDirectory::OLD to PeLib::OLDDIR and ImportDirectory::NEW to PeLib::NEWDIR
- Renamed Relocations to RelocationsDirectory
- Renamed ImportAddressTable to IatDirectory
- Renamed ComDescriptor to ComHeader
- Renamed PeFile::comDescDir to PeFile::comDir
- Changed unsigned long ExportDirectory::getFunctionIndex to unsigned int ExportDirectory::getFunctionIndex
-------------------------------------------------------------------------------------------------------------
July 4, 2004 PeLib 0.06 alpha
Added:
- TlsDirectory class
Changes:
- ResourceElement::read and ResourceElement::rebuild are now protected.
Bugfixes:
- Fixed a bug in PeHeader::rvaToOffset
-------------------------------------------------------------------------------------------------------------
June 26, 2004 PeLib 0.05 alpha
Added:
- Constructor, Copy constructor, assignment operator and destructor for ResourceChild.
- ResourceDirectory::getRoot()
- ResourceElement::isLeaf()
- ResourceElement::getElementRva
- 10 new functions in ResourceLeaf.
- 22 new functions in ResourceNode.
- Added the RT_* constants which identify resource types to PeLibAux.h
- Added a new example (examples/ResourceTree) which shows how to use low level ResourceDirectory functions.
- Added PELIB_IMAGE_DEBUG_DIRECTORY and PELIB_IMG_DEBUG_DIRECTORY
- Added the new class DebugDirectory which handles the debug directory of PE files.
- Added readDebugDirectory() and debugDir() to PeFile.
Removed:
- ~ResourceNode()
-------------------------------------------------------------------------------------------------------------
June 12, 2004 PeLib 0.04 alpha
New:
- Finally implemented the class ResourceDirectory. That means lots of new functions I won't explicitly list here.
Check the documentation.
Removed:
- The files buffer/ResTree.cpp and buffer/ResTree.h are obsolete and were removed.
Bugfixes:
- Fixed PeHeader::calcStartOfCode
- Fixed PeHeader::getSectionWithRva
Changes:
- Changed PeHeader::read to throw an exception if the NT signature is not 'PE'\0\0
- Changed the 2nd parameter of void MzHeader::read(unsigned char*, unsigned long) from unsigned long to unsigned int.
- Changed the return value of MzHeader::size from long to int.
- Changed parameters of MzHeader::getReservedWords1, MzHeader::getReservedWords2, MzHeader::setReservedWords1 and
MzHeader::setReservedWords2 from long to int.
- Changed MzHeader::read(std::string) to MzHeader::read(const std::string&)
- Changed return value of BoundImportDirectory::getModuleIndex from long to int.
- Changed return value of BoundImportDirectory::size from long to int.
- Changed return value of ComDescriptor::size from long to int.
- Changed return value of ImportAddressTable::size from long to int.
- Changed return value of Relocations::getNumberOfRelocations from long to int.
- Changed return value of Relocations::getNumberOfRelocationData from long to int.
- Changed return value of Relocations::size from long to int.
- Changed parameter of Relocations::getVirtualAddress from long to int.
- Changed parameter of Relocations::getSizeOfBlock from long to int.
- Changed parameter of Relocations::getRelocationData from long to int.
- Changed parameters of Relocations::setRelocationData from long to int.
- Changed parameters of Relocations::setVirtualAddress from long to int.
- Changed parameters of Relocations::setSizeOfBlock from long to int.
- Changed parameters of Relocations::addRelocationData from long to int.
- Changed parameters of Relocations::removeRelocationData from long to int.
- Changed return value of ExportDirectory::getFunctionIndex(const std::string&) const from unsigned int to int.
-------------------------------------------------------------------------------------------------------------
May 31, 2004: PeLib 0.03 alpha
Bugfixes:
- Fixed some bugs in FileDump.cpp
Changes:
- Modified PeLibAux.cpp to make PeLib VC++ 7.1 compatible.
- Changed vector access from .at to operator[] all over the project.
Real undefined behaviour is probably better than spontaniously terminating applications.
New:
- Added makefiles for Borland C++ commandline tools (tested on version 5.6.4)
- Added makefiles for Digital Mars Compiler (tested on version 8.38n)
Note that support for DMC is not yet complete. PeLib compiles though, the examples don't yet but the
reason for this is that I am unable to correctly specifiy the PeLib object files when compiling.
- Added makefiles for Visual C++ 7.1 (tested on compiler Version 13.10.3052)
-------------------------------------------------------------------------------------------------------------
Mai 1, 2004: PeLib 0.02 alpha
Bugfixes:
- Fixed a bug in FileDump's and OON2's makefile.g++
- Fixed ImportDirectory::size
- Changed parameter of PELIB_THUNK_DATA::equalHint from dword to word
- Fixed a bug in PeHeader::read (PeLib always assumed 0x10 data directories in version 0.01 alpha)
Changes:
- Slightly changed ImportDirectory::removeFile (Changed function's signature)
- Moved the definitions of byte, word and dword into the PeLib namespace.
- Renamed PELIB_THUNK_DATA::equalName to PELIB_THUNK_DATA::equalFunctionName
- Started to add size() functions to structs defined in PeLibAux.h
- Moved PeFile::writeSectionData to PeHeader::writeSectionData
- Moved PeFile::writeSections to PeHeader::writeSections
New:
- Added ImportDirectory::hasFunction
- Wrote BoundImportDirectory::size
- Added accumulate function to PeLibAux.h
- Added PELIB_IMAGE_SECTION_HEADER::biggerFileOffset
- Added PELIB_IMAGE_SECTION_HEADER::biggerVirtualAddress
- Added PeHeader::calcSizeOfImage
- Added PeHeader::enlargeLastSection
Removed:
- Removed PeFile::write
- Removed PeFile::writeImportDirectory
Other changes:
- Rewrote parts of ImportDirectory::read
- Rewrote ImportDirectory::removeFunction (both version).
- Changed std::ios:: to std::ios_base:: in ImportDirectory
- Changed ImportDirectory::addFunction (both versions)
- Changed ExportDirectory::rebuild
- Changed ExportDirectory::size
- Rewrote ImportDirectory::size
- Rewrote PeHeader::size
- Rewrote ComDescriptor::size
-------------------------------------------------------------------------------------------------------------
April 9, 2004: PeLib 0.01 alpha Initial release

View file

@ -0,0 +1,35 @@
<html>
<body>
<h1>The zlib/libpng License</h1>
<tt>
<p>Copyright (c) 2004 - Sebastian Porst</p>
<p>This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.</p>
<p>Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:</p>
<blockquote>
<p>1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.</p>
<p>2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.</p>
<p>3. This notice may not be removed or altered from any source
distribution.</p>
</blockquote>
</tt>
</body>
</html>

View file

@ -0,0 +1,44 @@
PeLib - Version 0.09 (alpha release)
=========================================
Copyright 2004 by Sebastian Porst
WWW: http://www.pelib.com
E-Mail: webmaster@the-interweb.com
=========================================
1. What is PeLib?
2. Where can I find a documentation of PeLib DLL?
3. Which license is used for PeLib?
4. Which compilers are being supported?
5. How do I compile PeLib?
1. What is PeLib DLL?
PeLib is an open-source C++ library to modify
PE files. See http://www.pelib.com for more details.
2. Where can I find a documentation of PeLib DLL?
http://www.pelib.com
3. All parts of PeLib are distributed under the zlib/libpng license.
See license.htm for details.
4. The following compilers have been tested:
MingW with g++ 3.2.3
Visual C++ 7.1 / Compiler version 13.10.3052
Borland C++ 5.6.4 (currently not supported)
Digital Mars Compiler 8.38n (currently not supported)
5. Go into the PeLib/source directory and enter the following lines
depending on which compiler you use.
g++: make -f makefile.g++
Borland C++: make -f makefile.bcc (currently not supported)
Visual C++ 7.1: nmake makefile.vc7
Digital Mars: make makefile.dmc (currently not supported)
If the compilation is succesful there should be some *.o/*.obj files
and (if you used g++) a PeLib.a file in the lib directory.
Then go to the examples directory and pick one example (I
suggest FileDump) and try to build it with the same make
command as above.

View file

@ -0,0 +1,19 @@
PROJECT(zlib)
# source files for zlib
SET(zlib_src
zlib/adler32.c
zlib/compress.c
zlib/crc32.c
zlib/deflate.c
zlib/gzio.c
zlib/infback.c
zlib/inffast.c
zlib/inflate.c
zlib/inftrees.c
zlib/trees.c
zlib/uncompr.c
zlib/zutil.c
)
ADD_LIBRARY(zlib ${zlib_src})

View file

@ -0,0 +1,855 @@
ChangeLog file for zlib
Changes in 1.2.3 (18 July 2005)
- Apply security vulnerability fixes to contrib/infback9 as well
- Clean up some text files (carriage returns, trailing space)
- Update testzlib, vstudio, masmx64, and masmx86 in contrib [Vollant]
Changes in 1.2.2.4 (11 July 2005)
- Add inflatePrime() function for starting inflation at bit boundary
- Avoid some Visual C warnings in deflate.c
- Avoid more silly Visual C warnings in inflate.c and inftrees.c for 64-bit
compile
- Fix some spelling errors in comments [Betts]
- Correct inflateInit2() error return documentation in zlib.h
- Added zran.c example of compressed data random access to examples
directory, shows use of inflatePrime()
- Fix cast for assignments to strm->state in inflate.c and infback.c
- Fix zlibCompileFlags() in zutil.c to use 1L for long shifts [Oberhumer]
- Move declarations of gf2 functions to right place in crc32.c [Oberhumer]
- Add cast in trees.c t avoid a warning [Oberhumer]
- Avoid some warnings in fitblk.c, gun.c, gzjoin.c in examples [Oberhumer]
- Update make_vms.com [Zinser]
- Initialize state->write in inflateReset() since copied in inflate_fast()
- Be more strict on incomplete code sets in inflate_table() and increase
ENOUGH and MAXD -- this repairs a possible security vulnerability for
invalid inflate input. Thanks to Tavis Ormandy and Markus Oberhumer for
discovering the vulnerability and providing test cases.
- Add ia64 support to configure for HP-UX [Smith]
- Add error return to gzread() for format or i/o error [Levin]
- Use malloc.h for OS/2 [Necasek]
Changes in 1.2.2.3 (27 May 2005)
- Replace 1U constants in inflate.c and inftrees.c for 64-bit compile
- Typecast fread() return values in gzio.c [Vollant]
- Remove trailing space in minigzip.c outmode (VC++ can't deal with it)
- Fix crc check bug in gzread() after gzungetc() [Heiner]
- Add the deflateTune() function to adjust internal compression parameters
- Add a fast gzip decompressor, gun.c, to examples (use of inflateBack)
- Remove an incorrect assertion in examples/zpipe.c
- Add C++ wrapper in infback9.h [Donais]
- Fix bug in inflateCopy() when decoding fixed codes
- Note in zlib.h how much deflateSetDictionary() actually uses
- Remove USE_DICT_HEAD in deflate.c (would mess up inflate if used)
- Add _WIN32_WCE to define WIN32 in zconf.in.h [Spencer]
- Don't include stderr.h or errno.h for _WIN32_WCE in zutil.h [Spencer]
- Add gzdirect() function to indicate transparent reads
- Update contrib/minizip [Vollant]
- Fix compilation of deflate.c when both ASMV and FASTEST [Oberhumer]
- Add casts in crc32.c to avoid warnings [Oberhumer]
- Add contrib/masmx64 [Vollant]
- Update contrib/asm586, asm686, masmx86, testzlib, vstudio [Vollant]
Changes in 1.2.2.2 (30 December 2004)
- Replace structure assignments in deflate.c and inflate.c with zmemcpy to
avoid implicit memcpy calls (portability for no-library compilation)
- Increase sprintf() buffer size in gzdopen() to allow for large numbers
- Add INFLATE_STRICT to check distances against zlib header
- Improve WinCE errno handling and comments [Chang]
- Remove comment about no gzip header processing in FAQ
- Add Z_FIXED strategy option to deflateInit2() to force fixed trees
- Add updated make_vms.com [Coghlan], update README
- Create a new "examples" directory, move gzappend.c there, add zpipe.c,
fitblk.c, gzlog.[ch], gzjoin.c, and zlib_how.html.
- Add FAQ entry and comments in deflate.c on uninitialized memory access
- Add Solaris 9 make options in configure [Gilbert]
- Allow strerror() usage in gzio.c for STDC
- Fix DecompressBuf in contrib/delphi/ZLib.pas [ManChesTer]
- Update contrib/masmx86/inffas32.asm and gvmat32.asm [Vollant]
- Use z_off_t for adler32_combine() and crc32_combine() lengths
- Make adler32() much faster for small len
- Use OS_CODE in deflate() default gzip header
Changes in 1.2.2.1 (31 October 2004)
- Allow inflateSetDictionary() call for raw inflate
- Fix inflate header crc check bug for file names and comments
- Add deflateSetHeader() and gz_header structure for custom gzip headers
- Add inflateGetheader() to retrieve gzip headers
- Add crc32_combine() and adler32_combine() functions
- Add alloc_func, free_func, in_func, out_func to Z_PREFIX list
- Use zstreamp consistently in zlib.h (inflate_back functions)
- Remove GUNZIP condition from definition of inflate_mode in inflate.h
and in contrib/inflate86/inffast.S [Truta, Anderson]
- Add support for AMD64 in contrib/inflate86/inffas86.c [Anderson]
- Update projects/README.projects and projects/visualc6 [Truta]
- Update win32/DLL_FAQ.txt [Truta]
- Avoid warning under NO_GZCOMPRESS in gzio.c; fix typo [Truta]
- Deprecate Z_ASCII; use Z_TEXT instead [Truta]
- Use a new algorithm for setting strm->data_type in trees.c [Truta]
- Do not define an exit() prototype in zutil.c unless DEBUG defined
- Remove prototype of exit() from zutil.c, example.c, minigzip.c [Truta]
- Add comment in zlib.h for Z_NO_FLUSH parameter to deflate()
- Fix Darwin build version identification [Peterson]
Changes in 1.2.2 (3 October 2004)
- Update zlib.h comments on gzip in-memory processing
- Set adler to 1 in inflateReset() to support Java test suite [Walles]
- Add contrib/dotzlib [Ravn]
- Update win32/DLL_FAQ.txt [Truta]
- Update contrib/minizip [Vollant]
- Move contrib/visual-basic.txt to old/ [Truta]
- Fix assembler builds in projects/visualc6/ [Truta]
Changes in 1.2.1.2 (9 September 2004)
- Update INDEX file
- Fix trees.c to update strm->data_type (no one ever noticed!)
- Fix bug in error case in inflate.c, infback.c, and infback9.c [Brown]
- Add "volatile" to crc table flag declaration (for DYNAMIC_CRC_TABLE)
- Add limited multitasking protection to DYNAMIC_CRC_TABLE
- Add NO_vsnprintf for VMS in zutil.h [Mozilla]
- Don't declare strerror() under VMS [Mozilla]
- Add comment to DYNAMIC_CRC_TABLE to use get_crc_table() to initialize
- Update contrib/ada [Anisimkov]
- Update contrib/minizip [Vollant]
- Fix configure to not hardcode directories for Darwin [Peterson]
- Fix gzio.c to not return error on empty files [Brown]
- Fix indentation; update version in contrib/delphi/ZLib.pas and
contrib/pascal/zlibpas.pas [Truta]
- Update mkasm.bat in contrib/masmx86 [Truta]
- Update contrib/untgz [Truta]
- Add projects/README.projects [Truta]
- Add project for MS Visual C++ 6.0 in projects/visualc6 [Cadieux, Truta]
- Update win32/DLL_FAQ.txt [Truta]
- Update list of Z_PREFIX symbols in zconf.h [Randers-Pehrson, Truta]
- Remove an unnecessary assignment to curr in inftrees.c [Truta]
- Add OS/2 to exe builds in configure [Poltorak]
- Remove err dummy parameter in zlib.h [Kientzle]
Changes in 1.2.1.1 (9 January 2004)
- Update email address in README
- Several FAQ updates
- Fix a big fat bug in inftrees.c that prevented decoding valid
dynamic blocks with only literals and no distance codes --
Thanks to "Hot Emu" for the bug report and sample file
- Add a note to puff.c on no distance codes case.
Changes in 1.2.1 (17 November 2003)
- Remove a tab in contrib/gzappend/gzappend.c
- Update some interfaces in contrib for new zlib functions
- Update zlib version number in some contrib entries
- Add Windows CE definition for ptrdiff_t in zutil.h [Mai, Truta]
- Support shared libraries on Hurd and KFreeBSD [Brown]
- Fix error in NO_DIVIDE option of adler32.c
Changes in 1.2.0.8 (4 November 2003)
- Update version in contrib/delphi/ZLib.pas and contrib/pascal/zlibpas.pas
- Add experimental NO_DIVIDE #define in adler32.c
- Possibly faster on some processors (let me know if it is)
- Correct Z_BLOCK to not return on first inflate call if no wrap
- Fix strm->data_type on inflate() return to correctly indicate EOB
- Add deflatePrime() function for appending in the middle of a byte
- Add contrib/gzappend for an example of appending to a stream
- Update win32/DLL_FAQ.txt [Truta]
- Delete Turbo C comment in README [Truta]
- Improve some indentation in zconf.h [Truta]
- Fix infinite loop on bad input in configure script [Church]
- Fix gzeof() for concatenated gzip files [Johnson]
- Add example to contrib/visual-basic.txt [Michael B.]
- Add -p to mkdir's in Makefile.in [vda]
- Fix configure to properly detect presence or lack of printf functions
- Add AS400 support [Monnerat]
- Add a little Cygwin support [Wilson]
Changes in 1.2.0.7 (21 September 2003)
- Correct some debug formats in contrib/infback9
- Cast a type in a debug statement in trees.c
- Change search and replace delimiter in configure from % to # [Beebe]
- Update contrib/untgz to 0.2 with various fixes [Truta]
- Add build support for Amiga [Nikl]
- Remove some directories in old that have been updated to 1.2
- Add dylib building for Mac OS X in configure and Makefile.in
- Remove old distribution stuff from Makefile
- Update README to point to DLL_FAQ.txt, and add comment on Mac OS X
- Update links in README
Changes in 1.2.0.6 (13 September 2003)
- Minor FAQ updates
- Update contrib/minizip to 1.00 [Vollant]
- Remove test of gz functions in example.c when GZ_COMPRESS defined [Truta]
- Update POSTINC comment for 68060 [Nikl]
- Add contrib/infback9 with deflate64 decoding (unsupported)
- For MVS define NO_vsnprintf and undefine FAR [van Burik]
- Add pragma for fdopen on MVS [van Burik]
Changes in 1.2.0.5 (8 September 2003)
- Add OF to inflateBackEnd() declaration in zlib.h
- Remember start when using gzdopen in the middle of a file
- Use internal off_t counters in gz* functions to properly handle seeks
- Perform more rigorous check for distance-too-far in inffast.c
- Add Z_BLOCK flush option to return from inflate at block boundary
- Set strm->data_type on return from inflate
- Indicate bits unused, if at block boundary, and if in last block
- Replace size_t with ptrdiff_t in crc32.c, and check for correct size
- Add condition so old NO_DEFLATE define still works for compatibility
- FAQ update regarding the Windows DLL [Truta]
- INDEX update: add qnx entry, remove aix entry [Truta]
- Install zlib.3 into mandir [Wilson]
- Move contrib/zlib_dll_FAQ.txt to win32/DLL_FAQ.txt; update [Truta]
- Adapt the zlib interface to the new DLL convention guidelines [Truta]
- Introduce ZLIB_WINAPI macro to allow the export of functions using
the WINAPI calling convention, for Visual Basic [Vollant, Truta]
- Update msdos and win32 scripts and makefiles [Truta]
- Export symbols by name, not by ordinal, in win32/zlib.def [Truta]
- Add contrib/ada [Anisimkov]
- Move asm files from contrib/vstudio/vc70_32 to contrib/asm386 [Truta]
- Rename contrib/asm386 to contrib/masmx86 [Truta, Vollant]
- Add contrib/masm686 [Truta]
- Fix offsets in contrib/inflate86 and contrib/masmx86/inffas32.asm
[Truta, Vollant]
- Update contrib/delphi; rename to contrib/pascal; add example [Truta]
- Remove contrib/delphi2; add a new contrib/delphi [Truta]
- Avoid inclusion of the nonstandard <memory.h> in contrib/iostream,
and fix some method prototypes [Truta]
- Fix the ZCR_SEED2 constant to avoid warnings in contrib/minizip
[Truta]
- Avoid the use of backslash (\) in contrib/minizip [Vollant]
- Fix file time handling in contrib/untgz; update makefiles [Truta]
- Update contrib/vstudio/vc70_32 to comply with the new DLL guidelines
[Vollant]
- Remove contrib/vstudio/vc15_16 [Vollant]
- Rename contrib/vstudio/vc70_32 to contrib/vstudio/vc7 [Truta]
- Update README.contrib [Truta]
- Invert the assignment order of match_head and s->prev[...] in
INSERT_STRING [Truta]
- Compare TOO_FAR with 32767 instead of 32768, to avoid 16-bit warnings
[Truta]
- Compare function pointers with 0, not with NULL or Z_NULL [Truta]
- Fix prototype of syncsearch in inflate.c [Truta]
- Introduce ASMINF macro to be enabled when using an ASM implementation
of inflate_fast [Truta]
- Change NO_DEFLATE to NO_GZCOMPRESS [Truta]
- Modify test_gzio in example.c to take a single file name as a
parameter [Truta]
- Exit the example.c program if gzopen fails [Truta]
- Add type casts around strlen in example.c [Truta]
- Remove casting to sizeof in minigzip.c; give a proper type
to the variable compared with SUFFIX_LEN [Truta]
- Update definitions of STDC and STDC99 in zconf.h [Truta]
- Synchronize zconf.h with the new Windows DLL interface [Truta]
- Use SYS16BIT instead of __32BIT__ to distinguish between
16- and 32-bit platforms [Truta]
- Use far memory allocators in small 16-bit memory models for
Turbo C [Truta]
- Add info about the use of ASMV, ASMINF and ZLIB_WINAPI in
zlibCompileFlags [Truta]
- Cygwin has vsnprintf [Wilson]
- In Windows16, OS_CODE is 0, as in MSDOS [Truta]
- In Cygwin, OS_CODE is 3 (Unix), not 11 (Windows32) [Wilson]
Changes in 1.2.0.4 (10 August 2003)
- Minor FAQ updates
- Be more strict when checking inflateInit2's windowBits parameter
- Change NO_GUNZIP compile option to NO_GZIP to cover deflate as well
- Add gzip wrapper option to deflateInit2 using windowBits
- Add updated QNX rule in configure and qnx directory [Bonnefoy]
- Make inflate distance-too-far checks more rigorous
- Clean up FAR usage in inflate
- Add casting to sizeof() in gzio.c and minigzip.c
Changes in 1.2.0.3 (19 July 2003)
- Fix silly error in gzungetc() implementation [Vollant]
- Update contrib/minizip and contrib/vstudio [Vollant]
- Fix printf format in example.c
- Correct cdecl support in zconf.in.h [Anisimkov]
- Minor FAQ updates
Changes in 1.2.0.2 (13 July 2003)
- Add ZLIB_VERNUM in zlib.h for numerical preprocessor comparisons
- Attempt to avoid warnings in crc32.c for pointer-int conversion
- Add AIX to configure, remove aix directory [Bakker]
- Add some casts to minigzip.c
- Improve checking after insecure sprintf() or vsprintf() calls
- Remove #elif's from crc32.c
- Change leave label to inf_leave in inflate.c and infback.c to avoid
library conflicts
- Remove inflate gzip decoding by default--only enable gzip decoding by
special request for stricter backward compatibility
- Add zlibCompileFlags() function to return compilation information
- More typecasting in deflate.c to avoid warnings
- Remove leading underscore from _Capital #defines [Truta]
- Fix configure to link shared library when testing
- Add some Windows CE target adjustments [Mai]
- Remove #define ZLIB_DLL in zconf.h [Vollant]
- Add zlib.3 [Rodgers]
- Update RFC URL in deflate.c and algorithm.txt [Mai]
- Add zlib_dll_FAQ.txt to contrib [Truta]
- Add UL to some constants [Truta]
- Update minizip and vstudio [Vollant]
- Remove vestigial NEED_DUMMY_RETURN from zconf.in.h
- Expand use of NO_DUMMY_DECL to avoid all dummy structures
- Added iostream3 to contrib [Schwardt]
- Replace rewind() with fseek() for WinCE [Truta]
- Improve setting of zlib format compression level flags
- Report 0 for huffman and rle strategies and for level == 0 or 1
- Report 2 only for level == 6
- Only deal with 64K limit when necessary at compile time [Truta]
- Allow TOO_FAR check to be turned off at compile time [Truta]
- Add gzclearerr() function [Souza]
- Add gzungetc() function
Changes in 1.2.0.1 (17 March 2003)
- Add Z_RLE strategy for run-length encoding [Truta]
- When Z_RLE requested, restrict matches to distance one
- Update zlib.h, minigzip.c, gzopen(), gzdopen() for Z_RLE
- Correct FASTEST compilation to allow level == 0
- Clean up what gets compiled for FASTEST
- Incorporate changes to zconf.in.h [Vollant]
- Refine detection of Turbo C need for dummy returns
- Refine ZLIB_DLL compilation
- Include additional header file on VMS for off_t typedef
- Try to use _vsnprintf where it supplants vsprintf [Vollant]
- Add some casts in inffast.c
- Enchance comments in zlib.h on what happens if gzprintf() tries to
write more than 4095 bytes before compression
- Remove unused state from inflateBackEnd()
- Remove exit(0) from minigzip.c, example.c
- Get rid of all those darn tabs
- Add "check" target to Makefile.in that does the same thing as "test"
- Add "mostlyclean" and "maintainer-clean" targets to Makefile.in
- Update contrib/inflate86 [Anderson]
- Update contrib/testzlib, contrib/vstudio, contrib/minizip [Vollant]
- Add msdos and win32 directories with makefiles [Truta]
- More additions and improvements to the FAQ
Changes in 1.2.0 (9 March 2003)
- New and improved inflate code
- About 20% faster
- Does not allocate 32K window unless and until needed
- Automatically detects and decompresses gzip streams
- Raw inflate no longer needs an extra dummy byte at end
- Added inflateBack functions using a callback interface--even faster
than inflate, useful for file utilities (gzip, zip)
- Added inflateCopy() function to record state for random access on
externally generated deflate streams (e.g. in gzip files)
- More readable code (I hope)
- New and improved crc32()
- About 50% faster, thanks to suggestions from Rodney Brown
- Add deflateBound() and compressBound() functions
- Fix memory leak in deflateInit2()
- Permit setting dictionary for raw deflate (for parallel deflate)
- Fix const declaration for gzwrite()
- Check for some malloc() failures in gzio.c
- Fix bug in gzopen() on single-byte file 0x1f
- Fix bug in gzread() on concatenated file with 0x1f at end of buffer
and next buffer doesn't start with 0x8b
- Fix uncompress() to return Z_DATA_ERROR on truncated input
- Free memory at end of example.c
- Remove MAX #define in trees.c (conflicted with some libraries)
- Fix static const's in deflate.c, gzio.c, and zutil.[ch]
- Declare malloc() and free() in gzio.c if STDC not defined
- Use malloc() instead of calloc() in zutil.c if int big enough
- Define STDC for AIX
- Add aix/ with approach for compiling shared library on AIX
- Add HP-UX support for shared libraries in configure
- Add OpenUNIX support for shared libraries in configure
- Use $cc instead of gcc to build shared library
- Make prefix directory if needed when installing
- Correct Macintosh avoidance of typedef Byte in zconf.h
- Correct Turbo C memory allocation when under Linux
- Use libz.a instead of -lz in Makefile (assure use of compiled library)
- Update configure to check for snprintf or vsnprintf functions and their
return value, warn during make if using an insecure function
- Fix configure problem with compile-time knowledge of HAVE_UNISTD_H that
is lost when library is used--resolution is to build new zconf.h
- Documentation improvements (in zlib.h):
- Document raw deflate and inflate
- Update RFCs URL
- Point out that zlib and gzip formats are different
- Note that Z_BUF_ERROR is not fatal
- Document string limit for gzprintf() and possible buffer overflow
- Note requirement on avail_out when flushing
- Note permitted values of flush parameter of inflate()
- Add some FAQs (and even answers) to the FAQ
- Add contrib/inflate86/ for x86 faster inflate
- Add contrib/blast/ for PKWare Data Compression Library decompression
- Add contrib/puff/ simple inflate for deflate format description
Changes in 1.1.4 (11 March 2002)
- ZFREE was repeated on same allocation on some error conditions.
This creates a security problem described in
http://www.zlib.org/advisory-2002-03-11.txt
- Returned incorrect error (Z_MEM_ERROR) on some invalid data
- Avoid accesses before window for invalid distances with inflate window
less than 32K.
- force windowBits > 8 to avoid a bug in the encoder for a window size
of 256 bytes. (A complete fix will be available in 1.1.5).
Changes in 1.1.3 (9 July 1998)
- fix "an inflate input buffer bug that shows up on rare but persistent
occasions" (Mark)
- fix gzread and gztell for concatenated .gz files (Didier Le Botlan)
- fix gzseek(..., SEEK_SET) in write mode
- fix crc check after a gzeek (Frank Faubert)
- fix miniunzip when the last entry in a zip file is itself a zip file
(J Lillge)
- add contrib/asm586 and contrib/asm686 (Brian Raiter)
See http://www.muppetlabs.com/~breadbox/software/assembly.html
- add support for Delphi 3 in contrib/delphi (Bob Dellaca)
- add support for C++Builder 3 and Delphi 3 in contrib/delphi2 (Davide Moretti)
- do not exit prematurely in untgz if 0 at start of block (Magnus Holmgren)
- use macro EXTERN instead of extern to support DLL for BeOS (Sander Stoks)
- added a FAQ file
- Support gzdopen on Mac with Metrowerks (Jason Linhart)
- Do not redefine Byte on Mac (Brad Pettit & Jason Linhart)
- define SEEK_END too if SEEK_SET is not defined (Albert Chin-A-Young)
- avoid some warnings with Borland C (Tom Tanner)
- fix a problem in contrib/minizip/zip.c for 16-bit MSDOS (Gilles Vollant)
- emulate utime() for WIN32 in contrib/untgz (Gilles Vollant)
- allow several arguments to configure (Tim Mooney, Frodo Looijaard)
- use libdir and includedir in Makefile.in (Tim Mooney)
- support shared libraries on OSF1 V4 (Tim Mooney)
- remove so_locations in "make clean" (Tim Mooney)
- fix maketree.c compilation error (Glenn, Mark)
- Python interface to zlib now in Python 1.5 (Jeremy Hylton)
- new Makefile.riscos (Rich Walker)
- initialize static descriptors in trees.c for embedded targets (Nick Smith)
- use "foo-gz" in example.c for RISCOS and VMS (Nick Smith)
- add the OS/2 files in Makefile.in too (Andrew Zabolotny)
- fix fdopen and halloc macros for Microsoft C 6.0 (Tom Lane)
- fix maketree.c to allow clean compilation of inffixed.h (Mark)
- fix parameter check in deflateCopy (Gunther Nikl)
- cleanup trees.c, use compressed_len only in debug mode (Christian Spieler)
- Many portability patches by Christian Spieler:
. zutil.c, zutil.h: added "const" for zmem*
. Make_vms.com: fixed some typos
. Make_vms.com: msdos/Makefile.*: removed zutil.h from some dependency lists
. msdos/Makefile.msc: remove "default rtl link library" info from obj files
. msdos/Makefile.*: use model-dependent name for the built zlib library
. msdos/Makefile.emx, nt/Makefile.emx, nt/Makefile.gcc:
new makefiles, for emx (DOS/OS2), emx&rsxnt and mingw32 (Windows 9x / NT)
- use define instead of typedef for Bytef also for MSC small/medium (Tom Lane)
- replace __far with _far for better portability (Christian Spieler, Tom Lane)
- fix test for errno.h in configure (Tim Newsham)
Changes in 1.1.2 (19 March 98)
- added contrib/minzip, mini zip and unzip based on zlib (Gilles Vollant)
See http://www.winimage.com/zLibDll/unzip.html
- preinitialize the inflate tables for fixed codes, to make the code
completely thread safe (Mark)
- some simplifications and slight speed-up to the inflate code (Mark)
- fix gzeof on non-compressed files (Allan Schrum)
- add -std1 option in configure for OSF1 to fix gzprintf (Martin Mokrejs)
- use default value of 4K for Z_BUFSIZE for 16-bit MSDOS (Tim Wegner + Glenn)
- added os2/Makefile.def and os2/zlib.def (Andrew Zabolotny)
- add shared lib support for UNIX_SV4.2MP (MATSUURA Takanori)
- do not wrap extern "C" around system includes (Tom Lane)
- mention zlib binding for TCL in README (Andreas Kupries)
- added amiga/Makefile.pup for Amiga powerUP SAS/C PPC (Andreas Kleinert)
- allow "make install prefix=..." even after configure (Glenn Randers-Pehrson)
- allow "configure --prefix $HOME" (Tim Mooney)
- remove warnings in example.c and gzio.c (Glenn Randers-Pehrson)
- move Makefile.sas to amiga/Makefile.sas
Changes in 1.1.1 (27 Feb 98)
- fix macros _tr_tally_* in deflate.h for debug mode (Glenn Randers-Pehrson)
- remove block truncation heuristic which had very marginal effect for zlib
(smaller lit_bufsize than in gzip 1.2.4) and degraded a little the
compression ratio on some files. This also allows inlining _tr_tally for
matches in deflate_slow.
- added msdos/Makefile.w32 for WIN32 Microsoft Visual C++ (Bob Frazier)
Changes in 1.1.0 (24 Feb 98)
- do not return STREAM_END prematurely in inflate (John Bowler)
- revert to the zlib 1.0.8 inflate to avoid the gcc 2.8.0 bug (Jeremy Buhler)
- compile with -DFASTEST to get compression code optimized for speed only
- in minigzip, try mmap'ing the input file first (Miguel Albrecht)
- increase size of I/O buffers in minigzip.c and gzio.c (not a big gain
on Sun but significant on HP)
- add a pointer to experimental unzip library in README (Gilles Vollant)
- initialize variable gcc in configure (Chris Herborth)
Changes in 1.0.9 (17 Feb 1998)
- added gzputs and gzgets functions
- do not clear eof flag in gzseek (Mark Diekhans)
- fix gzseek for files in transparent mode (Mark Diekhans)
- do not assume that vsprintf returns the number of bytes written (Jens Krinke)
- replace EXPORT with ZEXPORT to avoid conflict with other programs
- added compress2 in zconf.h, zlib.def, zlib.dnt
- new asm code from Gilles Vollant in contrib/asm386
- simplify the inflate code (Mark):
. Replace ZALLOC's in huft_build() with single ZALLOC in inflate_blocks_new()
. ZALLOC the length list in inflate_trees_fixed() instead of using stack
. ZALLOC the value area for huft_build() instead of using stack
. Simplify Z_FINISH check in inflate()
- Avoid gcc 2.8.0 comparison bug a little differently than zlib 1.0.8
- in inftrees.c, avoid cc -O bug on HP (Farshid Elahi)
- in zconf.h move the ZLIB_DLL stuff earlier to avoid problems with
the declaration of FAR (Gilles VOllant)
- install libz.so* with mode 755 (executable) instead of 644 (Marc Lehmann)
- read_buf buf parameter of type Bytef* instead of charf*
- zmemcpy parameters are of type Bytef*, not charf* (Joseph Strout)
- do not redeclare unlink in minigzip.c for WIN32 (John Bowler)
- fix check for presence of directories in "make install" (Ian Willis)
Changes in 1.0.8 (27 Jan 1998)
- fixed offsets in contrib/asm386/gvmat32.asm (Gilles Vollant)
- fix gzgetc and gzputc for big endian systems (Markus Oberhumer)
- added compress2() to allow setting the compression level
- include sys/types.h to get off_t on some systems (Marc Lehmann & QingLong)
- use constant arrays for the static trees in trees.c instead of computing
them at run time (thanks to Ken Raeburn for this suggestion). To create
trees.h, compile with GEN_TREES_H and run "make test".
- check return code of example in "make test" and display result
- pass minigzip command line options to file_compress
- simplifying code of inflateSync to avoid gcc 2.8 bug
- support CC="gcc -Wall" in configure -s (QingLong)
- avoid a flush caused by ftell in gzopen for write mode (Ken Raeburn)
- fix test for shared library support to avoid compiler warnings
- zlib.lib -> zlib.dll in msdos/zlib.rc (Gilles Vollant)
- check for TARGET_OS_MAC in addition to MACOS (Brad Pettit)
- do not use fdopen for Metrowerks on Mac (Brad Pettit))
- add checks for gzputc and gzputc in example.c
- avoid warnings in gzio.c and deflate.c (Andreas Kleinert)
- use const for the CRC table (Ken Raeburn)
- fixed "make uninstall" for shared libraries
- use Tracev instead of Trace in infblock.c
- in example.c use correct compressed length for test_sync
- suppress +vnocompatwarnings in configure for HPUX (not always supported)
Changes in 1.0.7 (20 Jan 1998)
- fix gzseek which was broken in write mode
- return error for gzseek to negative absolute position
- fix configure for Linux (Chun-Chung Chen)
- increase stack space for MSC (Tim Wegner)
- get_crc_table and inflateSyncPoint are EXPORTed (Gilles Vollant)
- define EXPORTVA for gzprintf (Gilles Vollant)
- added man page zlib.3 (Rick Rodgers)
- for contrib/untgz, fix makedir() and improve Makefile
- check gzseek in write mode in example.c
- allocate extra buffer for seeks only if gzseek is actually called
- avoid signed/unsigned comparisons (Tim Wegner, Gilles Vollant)
- add inflateSyncPoint in zconf.h
- fix list of exported functions in nt/zlib.dnt and mdsos/zlib.def
Changes in 1.0.6 (19 Jan 1998)
- add functions gzprintf, gzputc, gzgetc, gztell, gzeof, gzseek, gzrewind and
gzsetparams (thanks to Roland Giersig and Kevin Ruland for some of this code)
- Fix a deflate bug occurring only with compression level 0 (thanks to
Andy Buckler for finding this one).
- In minigzip, pass transparently also the first byte for .Z files.
- return Z_BUF_ERROR instead of Z_OK if output buffer full in uncompress()
- check Z_FINISH in inflate (thanks to Marc Schluper)
- Implement deflateCopy (thanks to Adam Costello)
- make static libraries by default in configure, add --shared option.
- move MSDOS or Windows specific files to directory msdos
- suppress the notion of partial flush to simplify the interface
(but the symbol Z_PARTIAL_FLUSH is kept for compatibility with 1.0.4)
- suppress history buffer provided by application to simplify the interface
(this feature was not implemented anyway in 1.0.4)
- next_in and avail_in must be initialized before calling inflateInit or
inflateInit2
- add EXPORT in all exported functions (for Windows DLL)
- added Makefile.nt (thanks to Stephen Williams)
- added the unsupported "contrib" directory:
contrib/asm386/ by Gilles Vollant <info@winimage.com>
386 asm code replacing longest_match().
contrib/iostream/ by Kevin Ruland <kevin@rodin.wustl.edu>
A C++ I/O streams interface to the zlib gz* functions
contrib/iostream2/ by Tyge Løvset <Tyge.Lovset@cmr.no>
Another C++ I/O streams interface
contrib/untgz/ by "Pedro A. Aranda Guti\irrez" <paag@tid.es>
A very simple tar.gz file extractor using zlib
contrib/visual-basic.txt by Carlos Rios <c_rios@sonda.cl>
How to use compress(), uncompress() and the gz* functions from VB.
- pass params -f (filtered data), -h (huffman only), -1 to -9 (compression
level) in minigzip (thanks to Tom Lane)
- use const for rommable constants in deflate
- added test for gzseek and gztell in example.c
- add undocumented function inflateSyncPoint() (hack for Paul Mackerras)
- add undocumented function zError to convert error code to string
(for Tim Smithers)
- Allow compilation of gzio with -DNO_DEFLATE to avoid the compression code.
- Use default memcpy for Symantec MSDOS compiler.
- Add EXPORT keyword for check_func (needed for Windows DLL)
- add current directory to LD_LIBRARY_PATH for "make test"
- create also a link for libz.so.1
- added support for FUJITSU UXP/DS (thanks to Toshiaki Nomura)
- use $(SHAREDLIB) instead of libz.so in Makefile.in (for HPUX)
- added -soname for Linux in configure (Chun-Chung Chen,
- assign numbers to the exported functions in zlib.def (for Windows DLL)
- add advice in zlib.h for best usage of deflateSetDictionary
- work around compiler bug on Atari (cast Z_NULL in call of s->checkfn)
- allow compilation with ANSI keywords only enabled for TurboC in large model
- avoid "versionString"[0] (Borland bug)
- add NEED_DUMMY_RETURN for Borland
- use variable z_verbose for tracing in debug mode (L. Peter Deutsch).
- allow compilation with CC
- defined STDC for OS/2 (David Charlap)
- limit external names to 8 chars for MVS (Thomas Lund)
- in minigzip.c, use static buffers only for 16-bit systems
- fix suffix check for "minigzip -d foo.gz"
- do not return an error for the 2nd of two consecutive gzflush() (Felix Lee)
- use _fdopen instead of fdopen for MSC >= 6.0 (Thomas Fanslau)
- added makelcc.bat for lcc-win32 (Tom St Denis)
- in Makefile.dj2, use copy and del instead of install and rm (Frank Donahoe)
- Avoid expanded $Id$. Use "rcs -kb" or "cvs admin -kb" to avoid Id expansion.
- check for unistd.h in configure (for off_t)
- remove useless check parameter in inflate_blocks_free
- avoid useless assignment of s->check to itself in inflate_blocks_new
- do not flush twice in gzclose (thanks to Ken Raeburn)
- rename FOPEN as F_OPEN to avoid clash with /usr/include/sys/file.h
- use NO_ERRNO_H instead of enumeration of operating systems with errno.h
- work around buggy fclose on pipes for HP/UX
- support zlib DLL with BORLAND C++ 5.0 (thanks to Glenn Randers-Pehrson)
- fix configure if CC is already equal to gcc
Changes in 1.0.5 (3 Jan 98)
- Fix inflate to terminate gracefully when fed corrupted or invalid data
- Use const for rommable constants in inflate
- Eliminate memory leaks on error conditions in inflate
- Removed some vestigial code in inflate
- Update web address in README
Changes in 1.0.4 (24 Jul 96)
- In very rare conditions, deflate(s, Z_FINISH) could fail to produce an EOF
bit, so the decompressor could decompress all the correct data but went
on to attempt decompressing extra garbage data. This affected minigzip too.
- zlibVersion and gzerror return const char* (needed for DLL)
- port to RISCOS (no fdopen, no multiple dots, no unlink, no fileno)
- use z_error only for DEBUG (avoid problem with DLLs)
Changes in 1.0.3 (2 Jul 96)
- use z_streamp instead of z_stream *, which is now a far pointer in MSDOS
small and medium models; this makes the library incompatible with previous
versions for these models. (No effect in large model or on other systems.)
- return OK instead of BUF_ERROR if previous deflate call returned with
avail_out as zero but there is nothing to do
- added memcmp for non STDC compilers
- define NO_DUMMY_DECL for more Mac compilers (.h files merged incorrectly)
- define __32BIT__ if __386__ or i386 is defined (pb. with Watcom and SCO)
- better check for 16-bit mode MSC (avoids problem with Symantec)
Changes in 1.0.2 (23 May 96)
- added Windows DLL support
- added a function zlibVersion (for the DLL support)
- fixed declarations using Bytef in infutil.c (pb with MSDOS medium model)
- Bytef is define's instead of typedef'd only for Borland C
- avoid reading uninitialized memory in example.c
- mention in README that the zlib format is now RFC1950
- updated Makefile.dj2
- added algorithm.doc
Changes in 1.0.1 (20 May 96) [1.0 skipped to avoid confusion]
- fix array overlay in deflate.c which sometimes caused bad compressed data
- fix inflate bug with empty stored block
- fix MSDOS medium model which was broken in 0.99
- fix deflateParams() which could generated bad compressed data.
- Bytef is define'd instead of typedef'ed (work around Borland bug)
- added an INDEX file
- new makefiles for DJGPP (Makefile.dj2), 32-bit Borland (Makefile.b32),
Watcom (Makefile.wat), Amiga SAS/C (Makefile.sas)
- speed up adler32 for modern machines without auto-increment
- added -ansi for IRIX in configure
- static_init_done in trees.c is an int
- define unlink as delete for VMS
- fix configure for QNX
- add configure branch for SCO and HPUX
- avoid many warnings (unused variables, dead assignments, etc...)
- no fdopen for BeOS
- fix the Watcom fix for 32 bit mode (define FAR as empty)
- removed redefinition of Byte for MKWERKS
- work around an MWKERKS bug (incorrect merge of all .h files)
Changes in 0.99 (27 Jan 96)
- allow preset dictionary shared between compressor and decompressor
- allow compression level 0 (no compression)
- add deflateParams in zlib.h: allow dynamic change of compression level
and compression strategy.
- test large buffers and deflateParams in example.c
- add optional "configure" to build zlib as a shared library
- suppress Makefile.qnx, use configure instead
- fixed deflate for 64-bit systems (detected on Cray)
- fixed inflate_blocks for 64-bit systems (detected on Alpha)
- declare Z_DEFLATED in zlib.h (possible parameter for deflateInit2)
- always return Z_BUF_ERROR when deflate() has nothing to do
- deflateInit and inflateInit are now macros to allow version checking
- prefix all global functions and types with z_ with -DZ_PREFIX
- make falloc completely reentrant (inftrees.c)
- fixed very unlikely race condition in ct_static_init
- free in reverse order of allocation to help memory manager
- use zlib-1.0/* instead of zlib/* inside the tar.gz
- make zlib warning-free with "gcc -O3 -Wall -Wwrite-strings -Wpointer-arith
-Wconversion -Wstrict-prototypes -Wmissing-prototypes"
- allow gzread on concatenated .gz files
- deflateEnd now returns Z_DATA_ERROR if it was premature
- deflate is finally (?) fully deterministic (no matches beyond end of input)
- Document Z_SYNC_FLUSH
- add uninstall in Makefile
- Check for __cpluplus in zlib.h
- Better test in ct_align for partial flush
- avoid harmless warnings for Borland C++
- initialize hash_head in deflate.c
- avoid warning on fdopen (gzio.c) for HP cc -Aa
- include stdlib.h for STDC compilers
- include errno.h for Cray
- ignore error if ranlib doesn't exist
- call ranlib twice for NeXTSTEP
- use exec_prefix instead of prefix for libz.a
- renamed ct_* as _tr_* to avoid conflict with applications
- clear z->msg in inflateInit2 before any error return
- initialize opaque in example.c, gzio.c, deflate.c and inflate.c
- fixed typo in zconf.h (_GNUC__ => __GNUC__)
- check for WIN32 in zconf.h and zutil.c (avoid farmalloc in 32-bit mode)
- fix typo in Make_vms.com (f$trnlnm -> f$getsyi)
- in fcalloc, normalize pointer if size > 65520 bytes
- don't use special fcalloc for 32 bit Borland C++
- use STDC instead of __GO32__ to avoid redeclaring exit, calloc, etc...
- use Z_BINARY instead of BINARY
- document that gzclose after gzdopen will close the file
- allow "a" as mode in gzopen.
- fix error checking in gzread
- allow skipping .gz extra-field on pipes
- added reference to Perl interface in README
- put the crc table in FAR data (I dislike more and more the medium model :)
- added get_crc_table
- added a dimension to all arrays (Borland C can't count).
- workaround Borland C bug in declaration of inflate_codes_new & inflate_fast
- guard against multiple inclusion of *.h (for precompiled header on Mac)
- Watcom C pretends to be Microsoft C small model even in 32 bit mode.
- don't use unsized arrays to avoid silly warnings by Visual C++:
warning C4746: 'inflate_mask' : unsized array treated as '__far'
(what's wrong with far data in far model?).
- define enum out of inflate_blocks_state to allow compilation with C++
Changes in 0.95 (16 Aug 95)
- fix MSDOS small and medium model (now easier to adapt to any compiler)
- inlined send_bits
- fix the final (:-) bug for deflate with flush (output was correct but
not completely flushed in rare occasions).
- default window size is same for compression and decompression
(it's now sufficient to set MAX_WBITS in zconf.h).
- voidp -> voidpf and voidnp -> voidp (for consistency with other
typedefs and because voidnp was not near in large model).
Changes in 0.94 (13 Aug 95)
- support MSDOS medium model
- fix deflate with flush (could sometimes generate bad output)
- fix deflateReset (zlib header was incorrectly suppressed)
- added support for VMS
- allow a compression level in gzopen()
- gzflush now calls fflush
- For deflate with flush, flush even if no more input is provided.
- rename libgz.a as libz.a
- avoid complex expression in infcodes.c triggering Turbo C bug
- work around a problem with gcc on Alpha (in INSERT_STRING)
- don't use inline functions (problem with some gcc versions)
- allow renaming of Byte, uInt, etc... with #define.
- avoid warning about (unused) pointer before start of array in deflate.c
- avoid various warnings in gzio.c, example.c, infblock.c, adler32.c, zutil.c
- avoid reserved word 'new' in trees.c
Changes in 0.93 (25 June 95)
- temporarily disable inline functions
- make deflate deterministic
- give enough lookahead for PARTIAL_FLUSH
- Set binary mode for stdin/stdout in minigzip.c for OS/2
- don't even use signed char in inflate (not portable enough)
- fix inflate memory leak for segmented architectures
Changes in 0.92 (3 May 95)
- don't assume that char is signed (problem on SGI)
- Clear bit buffer when starting a stored block
- no memcpy on Pyramid
- suppressed inftest.c
- optimized fill_window, put longest_match inline for gcc
- optimized inflate on stored blocks.
- untabify all sources to simplify patches
Changes in 0.91 (2 May 95)
- Default MEM_LEVEL is 8 (not 9 for Unix) as documented in zlib.h
- Document the memory requirements in zconf.h
- added "make install"
- fix sync search logic in inflateSync
- deflate(Z_FULL_FLUSH) now works even if output buffer too short
- after inflateSync, don't scare people with just "lo world"
- added support for DJGPP
Changes in 0.9 (1 May 95)
- don't assume that zalloc clears the allocated memory (the TurboC bug
was Mark's bug after all :)
- let again gzread copy uncompressed data unchanged (was working in 0.71)
- deflate(Z_FULL_FLUSH), inflateReset and inflateSync are now fully implemented
- added a test of inflateSync in example.c
- moved MAX_WBITS to zconf.h because users might want to change that.
- document explicitly that zalloc(64K) on MSDOS must return a normalized
pointer (zero offset)
- added Makefiles for Microsoft C, Turbo C, Borland C++
- faster crc32()
Changes in 0.8 (29 April 95)
- added fast inflate (inffast.c)
- deflate(Z_FINISH) now returns Z_STREAM_END when done. Warning: this
is incompatible with previous versions of zlib which returned Z_OK.
- work around a TurboC compiler bug (bad code for b << 0, see infutil.h)
(actually that was not a compiler bug, see 0.81 above)
- gzread no longer reads one extra byte in certain cases
- In gzio destroy(), don't reference a freed structure
- avoid many warnings for MSDOS
- avoid the ERROR symbol which is used by MS Windows
Changes in 0.71 (14 April 95)
- Fixed more MSDOS compilation problems :( There is still a bug with
TurboC large model.
Changes in 0.7 (14 April 95)
- Added full inflate support.
- Simplified the crc32() interface. The pre- and post-conditioning
(one's complement) is now done inside crc32(). WARNING: this is
incompatible with previous versions; see zlib.h for the new usage.
Changes in 0.61 (12 April 95)
- workaround for a bug in TurboC. example and minigzip now work on MSDOS.
Changes in 0.6 (11 April 95)
- added minigzip.c
- added gzdopen to reopen a file descriptor as gzFile
- added transparent reading of non-gziped files in gzread.
- fixed bug in gzread (don't read crc as data)
- fixed bug in destroy (gzio.c) (don't return Z_STREAM_END for gzclose).
- don't allocate big arrays in the stack (for MSDOS)
- fix some MSDOS compilation problems
Changes in 0.5:
- do real compression in deflate.c. Z_PARTIAL_FLUSH is supported but
not yet Z_FULL_FLUSH.
- support decompression but only in a single step (forced Z_FINISH)
- added opaque object for zalloc and zfree.
- added deflateReset and inflateReset
- added a variable zlib_version for consistency checking.
- renamed the 'filter' parameter of deflateInit2 as 'strategy'.
Added Z_FILTERED and Z_HUFFMAN_ONLY constants.
Changes in 0.4:
- avoid "zip" everywhere, use zlib instead of ziplib.
- suppress Z_BLOCK_FLUSH, interpret Z_PARTIAL_FLUSH as block flush
if compression method == 8.
- added adler32 and crc32
- renamed deflateOptions as deflateInit2, call one or the other but not both
- added the method parameter for deflateInit2.
- added inflateInit2
- simplied considerably deflateInit and inflateInit by not supporting
user-provided history buffer. This is supported only in deflateInit2
and inflateInit2.
Changes in 0.3:
- prefix all macro names with Z_
- use Z_FINISH instead of deflateEnd to finish compression.
- added Z_HUFFMAN_ONLY
- added gzerror()

View file

@ -0,0 +1,339 @@
Frequently Asked Questions about zlib
If your question is not there, please check the zlib home page
http://www.zlib.org which may have more recent information.
The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html
1. Is zlib Y2K-compliant?
Yes. zlib doesn't handle dates.
2. Where can I get a Windows DLL version?
The zlib sources can be compiled without change to produce a DLL.
See the file win32/DLL_FAQ.txt in the zlib distribution.
Pointers to the precompiled DLL are found in the zlib web site at
http://www.zlib.org.
3. Where can I get a Visual Basic interface to zlib?
See
* http://www.dogma.net/markn/articles/zlibtool/zlibtool.htm
* contrib/visual-basic.txt in the zlib distribution
* win32/DLL_FAQ.txt in the zlib distribution
4. compress() returns Z_BUF_ERROR.
Make sure that before the call of compress, the length of the compressed
buffer is equal to the total size of the compressed buffer and not
zero. For Visual Basic, check that this parameter is passed by reference
("as any"), not by value ("as long").
5. deflate() or inflate() returns Z_BUF_ERROR.
Before making the call, make sure that avail_in and avail_out are not
zero. When setting the parameter flush equal to Z_FINISH, also make sure
that avail_out is big enough to allow processing all pending input.
Note that a Z_BUF_ERROR is not fatal--another call to deflate() or
inflate() can be made with more input or output space. A Z_BUF_ERROR
may in fact be unavoidable depending on how the functions are used, since
it is not possible to tell whether or not there is more output pending
when strm.avail_out returns with zero.
6. Where's the zlib documentation (man pages, etc.)?
It's in zlib.h for the moment, and Francis S. Lin has converted it to a
web page zlib.html. Volunteers to transform this to Unix-style man pages,
please contact us (zlib@gzip.org). Examples of zlib usage are in the files
example.c and minigzip.c.
7. Why don't you use GNU autoconf or libtool or ...?
Because we would like to keep zlib as a very small and simple
package. zlib is rather portable and doesn't need much configuration.
8. I found a bug in zlib.
Most of the time, such problems are due to an incorrect usage of
zlib. Please try to reproduce the problem with a small program and send
the corresponding source to us at zlib@gzip.org . Do not send
multi-megabyte data files without prior agreement.
9. Why do I get "undefined reference to gzputc"?
If "make test" produces something like
example.o(.text+0x154): undefined reference to `gzputc'
check that you don't have old files libz.* in /usr/lib, /usr/local/lib or
/usr/X11R6/lib. Remove any old versions, then do "make install".
10. I need a Delphi interface to zlib.
See the contrib/delphi directory in the zlib distribution.
11. Can zlib handle .zip archives?
Not by itself, no. See the directory contrib/minizip in the zlib
distribution.
12. Can zlib handle .Z files?
No, sorry. You have to spawn an uncompress or gunzip subprocess, or adapt
the code of uncompress on your own.
13. How can I make a Unix shared library?
make clean
./configure -s
make
14. How do I install a shared zlib library on Unix?
After the above, then:
make install
However, many flavors of Unix come with a shared zlib already installed.
Before going to the trouble of compiling a shared version of zlib and
trying to install it, you may want to check if it's already there! If you
can #include <zlib.h>, it's there. The -lz option will probably link to it.
15. I have a question about OttoPDF.
We are not the authors of OttoPDF. The real author is on the OttoPDF web
site: Joel Hainley, jhainley@myndkryme.com.
16. Can zlib decode Flate data in an Adobe PDF file?
Yes. See http://www.fastio.com/ (ClibPDF), or http://www.pdflib.com/ .
To modify PDF forms, see http://sourceforge.net/projects/acroformtool/ .
17. Why am I getting this "register_frame_info not found" error on Solaris?
After installing zlib 1.1.4 on Solaris 2.6, running applications using zlib
generates an error such as:
ld.so.1: rpm: fatal: relocation error: file /usr/local/lib/libz.so:
symbol __register_frame_info: referenced symbol not found
The symbol __register_frame_info is not part of zlib, it is generated by
the C compiler (cc or gcc). You must recompile applications using zlib
which have this problem. This problem is specific to Solaris. See
http://www.sunfreeware.com for Solaris versions of zlib and applications
using zlib.
18. Why does gzip give an error on a file I make with compress/deflate?
The compress and deflate functions produce data in the zlib format, which
is different and incompatible with the gzip format. The gz* functions in
zlib on the other hand use the gzip format. Both the zlib and gzip
formats use the same compressed data format internally, but have different
headers and trailers around the compressed data.
19. Ok, so why are there two different formats?
The gzip format was designed to retain the directory information about
a single file, such as the name and last modification date. The zlib
format on the other hand was designed for in-memory and communication
channel applications, and has a much more compact header and trailer and
uses a faster integrity check than gzip.
20. Well that's nice, but how do I make a gzip file in memory?
You can request that deflate write the gzip format instead of the zlib
format using deflateInit2(). You can also request that inflate decode
the gzip format using inflateInit2(). Read zlib.h for more details.
21. Is zlib thread-safe?
Yes. However any library routines that zlib uses and any application-
provided memory allocation routines must also be thread-safe. zlib's gz*
functions use stdio library routines, and most of zlib's functions use the
library memory allocation routines by default. zlib's Init functions allow
for the application to provide custom memory allocation routines.
Of course, you should only operate on any given zlib or gzip stream from a
single thread at a time.
22. Can I use zlib in my commercial application?
Yes. Please read the license in zlib.h.
23. Is zlib under the GNU license?
No. Please read the license in zlib.h.
24. The license says that altered source versions must be "plainly marked". So
what exactly do I need to do to meet that requirement?
You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h. In
particular, the final version number needs to be changed to "f", and an
identification string should be appended to ZLIB_VERSION. Version numbers
x.x.x.f are reserved for modifications to zlib by others than the zlib
maintainers. For example, if the version of the base zlib you are altering
is "1.2.3.4", then in zlib.h you should change ZLIB_VERNUM to 0x123f, and
ZLIB_VERSION to something like "1.2.3.f-zachary-mods-v3". You can also
update the version strings in deflate.c and inftrees.c.
For altered source distributions, you should also note the origin and
nature of the changes in zlib.h, as well as in ChangeLog and README, along
with the dates of the alterations. The origin should include at least your
name (or your company's name), and an email address to contact for help or
issues with the library.
Note that distributing a compiled zlib library along with zlib.h and
zconf.h is also a source distribution, and so you should change
ZLIB_VERSION and ZLIB_VERNUM and note the origin and nature of the changes
in zlib.h as you would for a full source distribution.
25. Will zlib work on a big-endian or little-endian architecture, and can I
exchange compressed data between them?
Yes and yes.
26. Will zlib work on a 64-bit machine?
It should. It has been tested on 64-bit machines, and has no dependence
on any data types being limited to 32-bits in length. If you have any
difficulties, please provide a complete problem report to zlib@gzip.org
27. Will zlib decompress data from the PKWare Data Compression Library?
No. The PKWare DCL uses a completely different compressed data format
than does PKZIP and zlib. However, you can look in zlib's contrib/blast
directory for a possible solution to your problem.
28. Can I access data randomly in a compressed stream?
No, not without some preparation. If when compressing you periodically
use Z_FULL_FLUSH, carefully write all the pending data at those points,
and keep an index of those locations, then you can start decompression
at those points. You have to be careful to not use Z_FULL_FLUSH too
often, since it can significantly degrade compression.
29. Does zlib work on MVS, OS/390, CICS, etc.?
We don't know for sure. We have heard occasional reports of success on
these systems. If you do use it on one of these, please provide us with
a report, instructions, and patches that we can reference when we get
these questions. Thanks.
30. Is there some simpler, easier to read version of inflate I can look at
to understand the deflate format?
First off, you should read RFC 1951. Second, yes. Look in zlib's
contrib/puff directory.
31. Does zlib infringe on any patents?
As far as we know, no. In fact, that was originally the whole point behind
zlib. Look here for some more information:
http://www.gzip.org/#faq11
32. Can zlib work with greater than 4 GB of data?
Yes. inflate() and deflate() will process any amount of data correctly.
Each call of inflate() or deflate() is limited to input and output chunks
of the maximum value that can be stored in the compiler's "unsigned int"
type, but there is no limit to the number of chunks. Note however that the
strm.total_in and strm_total_out counters may be limited to 4 GB. These
counters are provided as a convenience and are not used internally by
inflate() or deflate(). The application can easily set up its own counters
updated after each call of inflate() or deflate() to count beyond 4 GB.
compress() and uncompress() may be limited to 4 GB, since they operate in a
single call. gzseek() and gztell() may be limited to 4 GB depending on how
zlib is compiled. See the zlibCompileFlags() function in zlib.h.
The word "may" appears several times above since there is a 4 GB limit
only if the compiler's "long" type is 32 bits. If the compiler's "long"
type is 64 bits, then the limit is 16 exabytes.
33. Does zlib have any security vulnerabilities?
The only one that we are aware of is potentially in gzprintf(). If zlib
is compiled to use sprintf() or vsprintf(), then there is no protection
against a buffer overflow of a 4K string space, other than the caller of
gzprintf() assuring that the output will not exceed 4K. On the other
hand, if zlib is compiled to use snprintf() or vsnprintf(), which should
normally be the case, then there is no vulnerability. The ./configure
script will display warnings if an insecure variation of sprintf() will
be used by gzprintf(). Also the zlibCompileFlags() function will return
information on what variant of sprintf() is used by gzprintf().
If you don't have snprintf() or vsnprintf() and would like one, you can
find a portable implementation here:
http://www.ijs.si/software/snprintf/
Note that you should be using the most recent version of zlib. Versions
1.1.3 and before were subject to a double-free vulnerability.
34. Is there a Java version of zlib?
Probably what you want is to use zlib in Java. zlib is already included
as part of the Java SDK in the java.util.zip package. If you really want
a version of zlib written in the Java language, look on the zlib home
page for links: http://www.zlib.org/
35. I get this or that compiler or source-code scanner warning when I crank it
up to maximally-pedantic. Can't you guys write proper code?
Many years ago, we gave up attempting to avoid warnings on every compiler
in the universe. It just got to be a waste of time, and some compilers
were downright silly. So now, we simply make sure that the code always
works.
36. Valgrind (or some similar memory access checker) says that deflate is
performing a conditional jump that depends on an uninitialized value.
Isn't that a bug?
No. That is intentional for performance reasons, and the output of
deflate is not affected. This only started showing up recently since
zlib 1.2.x uses malloc() by default for allocations, whereas earlier
versions used calloc(), which zeros out the allocated memory.
37. Will zlib read the (insert any ancient or arcane format here) compressed
data format?
Probably not. Look in the comp.compression FAQ for pointers to various
formats and associated software.
38. How can I encrypt/decrypt zip files with zlib?
zlib doesn't support encryption. The original PKZIP encryption is very weak
and can be broken with freely available programs. To get strong encryption,
use GnuPG, http://www.gnupg.org/ , which already includes zlib compression.
For PKZIP compatible "encryption", look at http://www.info-zip.org/
39. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings?
"gzip" is the gzip format, and "deflate" is the zlib format. They should
probably have called the second one "zlib" instead to avoid confusion
with the raw deflate compressed data format. While the HTTP 1.1 RFC 2616
correctly points to the zlib specification in RFC 1950 for the "deflate"
transfer encoding, there have been reports of servers and browsers that
incorrectly produce or expect raw deflate data per the deflate
specficiation in RFC 1951, most notably Microsoft. So even though the
"deflate" transfer encoding using the zlib format would be the more
efficient approach (and in fact exactly what the zlib format was designed
for), using the "gzip" transfer encoding is probably more reliable due to
an unfortunate choice of name on the part of the HTTP 1.1 authors.
Bottom line: use the gzip format for HTTP 1.1 encoding.
40. Does zlib support the new "Deflate64" format introduced by PKWare?
No. PKWare has apparently decided to keep that format proprietary, since
they have not documented it as they have previous compression formats.
In any case, the compression improvements are so modest compared to other
more modern approaches, that it's not worth the effort to implement.
41. Can you please sign these lengthy legal documents and fax them back to us
so that we can use your software in our product?
No. Go away. Shoo.

View file

@ -0,0 +1,51 @@
ChangeLog history of changes
FAQ Frequently Asked Questions about zlib
INDEX this file
Makefile makefile for Unix (generated by configure)
Makefile.in makefile for Unix (template for configure)
README guess what
algorithm.txt description of the (de)compression algorithm
configure configure script for Unix
zconf.in.h template for zconf.h (used by configure)
amiga/ makefiles for Amiga SAS C
as400/ makefiles for IBM AS/400
msdos/ makefiles for MSDOS
old/ makefiles for various architectures and zlib documentation
files that have not yet been updated for zlib 1.2.x
projects/ projects for various Integrated Development Environments
qnx/ makefiles for QNX
win32/ makefiles for Windows
zlib public header files (must be kept):
zconf.h
zlib.h
private source files used to build the zlib library:
adler32.c
compress.c
crc32.c
crc32.h
deflate.c
deflate.h
gzio.c
infback.c
inffast.c
inffast.h
inffixed.h
inflate.c
inflate.h
inftrees.c
inftrees.h
trees.c
trees.h
uncompr.c
zutil.c
zutil.h
source files for sample programs:
example.c
minigzip.c
unsupported contribution by third parties
See contrib/README.contrib

View file

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

View file

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

View file

@ -0,0 +1,125 @@
ZLIB DATA COMPRESSION LIBRARY
zlib 1.2.3 is a general purpose data compression library. All the code is
thread safe. The data format used by the zlib library is described by RFCs
(Request for Comments) 1950 to 1952 in the files
http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format)
and rfc1952.txt (gzip format). These documents are also available in other
formats from ftp://ftp.uu.net/graphics/png/documents/zlib/zdoc-index.html
All functions of the compression library are documented in the file zlib.h
(volunteer to write man pages welcome, contact zlib@gzip.org). A usage example
of the library is given in the file example.c which also tests that the library
is working correctly. Another example is given in the file minigzip.c. The
compression library itself is composed of all source files except example.c and
minigzip.c.
To compile all files and run the test program, follow the instructions given at
the top of Makefile. In short "make test; make install" should work for most
machines. For Unix: "./configure; make test; make install". For MSDOS, use one
of the special makefiles such as Makefile.msc. For VMS, use make_vms.com.
Questions about zlib should be sent to <zlib@gzip.org>, or to Gilles Vollant
<info@winimage.com> for the Windows DLL version. The zlib home page is
http://www.zlib.org or http://www.gzip.org/zlib/ Before reporting a problem,
please check this site to verify that you have the latest version of zlib;
otherwise get the latest version and check whether the problem still exists or
not.
PLEASE read the zlib FAQ http://www.gzip.org/zlib/zlib_faq.html before asking
for help.
Mark Nelson <markn@ieee.org> wrote an article about zlib for the Jan. 1997
issue of Dr. Dobb's Journal; a copy of the article is available in
http://dogma.net/markn/articles/zlibtool/zlibtool.htm
The changes made in version 1.2.3 are documented in the file ChangeLog.
Unsupported third party contributions are provided in directory "contrib".
A Java implementation of zlib is available in the Java Development Kit
http://java.sun.com/j2se/1.4.2/docs/api/java/util/zip/package-summary.html
See the zlib home page http://www.zlib.org for details.
A Perl interface to zlib written by Paul Marquess <pmqs@cpan.org> is in the
CPAN (Comprehensive Perl Archive Network) sites
http://www.cpan.org/modules/by-module/Compress/
A Python interface to zlib written by A.M. Kuchling <amk@amk.ca> is
available in Python 1.5 and later versions, see
http://www.python.org/doc/lib/module-zlib.html
A zlib binding for TCL written by Andreas Kupries <a.kupries@westend.com> is
availlable at http://www.oche.de/~akupries/soft/trf/trf_zip.html
An experimental package to read and write files in .zip format, written on top
of zlib by Gilles Vollant <info@winimage.com>, is available in the
contrib/minizip directory of zlib.
Notes for some targets:
- For Windows DLL versions, please see win32/DLL_FAQ.txt
- For 64-bit Irix, deflate.c must be compiled without any optimization. With
-O, one libpng test fails. The test works in 32 bit mode (with the -n32
compiler flag). The compiler bug has been reported to SGI.
- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works
when compiled with cc.
- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is
necessary to get gzprintf working correctly. This is done by configure.
- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with
other compilers. Use "make test" to check your compiler.
- gzdopen is not supported on RISCOS, BEOS and by some Mac compilers.
- For PalmOs, see http://palmzlib.sourceforge.net/
- When building a shared, i.e. dynamic library on Mac OS X, the library must be
installed before testing (do "make install" before "make test"), since the
library location is specified in the library.
Acknowledgments:
The deflate format used by zlib was defined by Phil Katz. The deflate
and zlib specifications were written by L. Peter Deutsch. Thanks to all the
people who reported problems and suggested various improvements in zlib;
they are too numerous to cite here.
Copyright notice:
(C) 1995-2004 Jean-loup Gailly and Mark Adler
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jean-loup Gailly Mark Adler
jloup@gzip.org madler@alumni.caltech.edu
If you use the zlib library in a product, we would appreciate *not*
receiving lengthy legal documents to sign. The sources are provided
for free but without warranty of any kind. The library has been
entirely written by Jean-loup Gailly and Mark Adler; it does not
include third-party code.
If you redistribute modified sources, we would appreciate that you include
in the file ChangeLog history information documenting your changes. Please
read the FAQ for more information on the distribution of modified source
versions.

View file

@ -0,0 +1,149 @@
/* adler32.c -- compute the Adler-32 checksum of a data stream
* Copyright (C) 1995-2004 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* @(#) $Id$ */
#define ZLIB_INTERNAL
#include "zlib.h"
#define BASE 65521UL /* largest prime smaller than 65536 */
#define NMAX 5552
/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
#define DO16(buf) DO8(buf,0); DO8(buf,8);
/* use NO_DIVIDE if your processor does not do division in hardware */
#ifdef NO_DIVIDE
# define MOD(a) \
do { \
if (a >= (BASE << 16)) a -= (BASE << 16); \
if (a >= (BASE << 15)) a -= (BASE << 15); \
if (a >= (BASE << 14)) a -= (BASE << 14); \
if (a >= (BASE << 13)) a -= (BASE << 13); \
if (a >= (BASE << 12)) a -= (BASE << 12); \
if (a >= (BASE << 11)) a -= (BASE << 11); \
if (a >= (BASE << 10)) a -= (BASE << 10); \
if (a >= (BASE << 9)) a -= (BASE << 9); \
if (a >= (BASE << 8)) a -= (BASE << 8); \
if (a >= (BASE << 7)) a -= (BASE << 7); \
if (a >= (BASE << 6)) a -= (BASE << 6); \
if (a >= (BASE << 5)) a -= (BASE << 5); \
if (a >= (BASE << 4)) a -= (BASE << 4); \
if (a >= (BASE << 3)) a -= (BASE << 3); \
if (a >= (BASE << 2)) a -= (BASE << 2); \
if (a >= (BASE << 1)) a -= (BASE << 1); \
if (a >= BASE) a -= BASE; \
} while (0)
# define MOD4(a) \
do { \
if (a >= (BASE << 4)) a -= (BASE << 4); \
if (a >= (BASE << 3)) a -= (BASE << 3); \
if (a >= (BASE << 2)) a -= (BASE << 2); \
if (a >= (BASE << 1)) a -= (BASE << 1); \
if (a >= BASE) a -= BASE; \
} while (0)
#else
# define MOD(a) a %= BASE
# define MOD4(a) a %= BASE
#endif
/* ========================================================================= */
uLong ZEXPORT adler32(adler, buf, len)
uLong adler;
const Bytef *buf;
uInt len;
{
unsigned long sum2;
unsigned n;
/* split Adler-32 into component sums */
sum2 = (adler >> 16) & 0xffff;
adler &= 0xffff;
/* in case user likes doing a byte at a time, keep it fast */
if (len == 1) {
adler += buf[0];
if (adler >= BASE)
adler -= BASE;
sum2 += adler;
if (sum2 >= BASE)
sum2 -= BASE;
return adler | (sum2 << 16);
}
/* initial Adler-32 value (deferred check for len == 1 speed) */
if (buf == Z_NULL)
return 1L;
/* in case short lengths are provided, keep it somewhat fast */
if (len < 16) {
while (len--) {
adler += *buf++;
sum2 += adler;
}
if (adler >= BASE)
adler -= BASE;
MOD4(sum2); /* only added so many BASE's */
return adler | (sum2 << 16);
}
/* do length NMAX blocks -- requires just one modulo operation */
while (len >= NMAX) {
len -= NMAX;
n = NMAX / 16; /* NMAX is divisible by 16 */
do {
DO16(buf); /* 16 sums unrolled */
buf += 16;
} while (--n);
MOD(adler);
MOD(sum2);
}
/* do remaining bytes (less than NMAX, still just one modulo) */
if (len) { /* avoid modulos if none remaining */
while (len >= 16) {
len -= 16;
DO16(buf);
buf += 16;
}
while (len--) {
adler += *buf++;
sum2 += adler;
}
MOD(adler);
MOD(sum2);
}
/* return recombined sums */
return adler | (sum2 << 16);
}
/* ========================================================================= */
uLong ZEXPORT adler32_combine(adler1, adler2, len2)
uLong adler1;
uLong adler2;
z_off_t len2;
{
unsigned long sum1;
unsigned long sum2;
unsigned rem;
/* the derivation of this formula is left as an exercise for the reader */
rem = (unsigned)(len2 % BASE);
sum1 = adler1 & 0xffff;
sum2 = rem * sum1;
MOD(sum2);
sum1 += (adler2 & 0xffff) + BASE - 1;
sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
if (sum1 > BASE) sum1 -= BASE;
if (sum1 > BASE) sum1 -= BASE;
if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
if (sum2 > BASE) sum2 -= BASE;
return sum1 | (sum2 << 16);
}

View file

@ -0,0 +1,209 @@
1. Compression algorithm (deflate)
The deflation algorithm used by gzip (also zip and zlib) is a variation of
LZ77 (Lempel-Ziv 1977, see reference below). It finds duplicated strings in
the input data. The second occurrence of a string is replaced by a
pointer to the previous string, in the form of a pair (distance,
length). Distances are limited to 32K bytes, and lengths are limited
to 258 bytes. When a string does not occur anywhere in the previous
32K bytes, it is emitted as a sequence of literal bytes. (In this
description, `string' must be taken as an arbitrary sequence of bytes,
and is not restricted to printable characters.)
Literals or match lengths are compressed with one Huffman tree, and
match distances are compressed with another tree. The trees are stored
in a compact form at the start of each block. The blocks can have any
size (except that the compressed data for one block must fit in
available memory). A block is terminated when deflate() determines that
it would be useful to start another block with fresh trees. (This is
somewhat similar to the behavior of LZW-based _compress_.)
Duplicated strings are found using a hash table. All input strings of
length 3 are inserted in the hash table. A hash index is computed for
the next 3 bytes. If the hash chain for this index is not empty, all
strings in the chain are compared with the current input string, and
the longest match is selected.
The hash chains are searched starting with the most recent strings, to
favor small distances and thus take advantage of the Huffman encoding.
The hash chains are singly linked. There are no deletions from the
hash chains, the algorithm simply discards matches that are too old.
To avoid a worst-case situation, very long hash chains are arbitrarily
truncated at a certain length, determined by a runtime option (level
parameter of deflateInit). So deflate() does not always find the longest
possible match but generally finds a match which is long enough.
deflate() also defers the selection of matches with a lazy evaluation
mechanism. After a match of length N has been found, deflate() searches for
a longer match at the next input byte. If a longer match is found, the
previous match is truncated to a length of one (thus producing a single
literal byte) and the process of lazy evaluation begins again. Otherwise,
the original match is kept, and the next match search is attempted only N
steps later.
The lazy match evaluation is also subject to a runtime parameter. If
the current match is long enough, deflate() reduces the search for a longer
match, thus speeding up the whole process. If compression ratio is more
important than speed, deflate() attempts a complete second search even if
the first match is already long enough.
The lazy match evaluation is not performed for the fastest compression
modes (level parameter 1 to 3). For these fast modes, new strings
are inserted in the hash table only when no match was found, or
when the match is not too long. This degrades the compression ratio
but saves time since there are both fewer insertions and fewer searches.
2. Decompression algorithm (inflate)
2.1 Introduction
The key question is how to represent a Huffman code (or any prefix code) so
that you can decode fast. The most important characteristic is that shorter
codes are much more common than longer codes, so pay attention to decoding the
short codes fast, and let the long codes take longer to decode.
inflate() sets up a first level table that covers some number of bits of
input less than the length of longest code. It gets that many bits from the
stream, and looks it up in the table. The table will tell if the next
code is that many bits or less and how many, and if it is, it will tell
the value, else it will point to the next level table for which inflate()
grabs more bits and tries to decode a longer code.
How many bits to make the first lookup is a tradeoff between the time it
takes to decode and the time it takes to build the table. If building the
table took no time (and if you had infinite memory), then there would only
be a first level table to cover all the way to the longest code. However,
building the table ends up taking a lot longer for more bits since short
codes are replicated many times in such a table. What inflate() does is
simply to make the number of bits in the first table a variable, and then
to set that variable for the maximum speed.
For inflate, which has 286 possible codes for the literal/length tree, the size
of the first table is nine bits. Also the distance trees have 30 possible
values, and the size of the first table is six bits. Note that for each of
those cases, the table ended up one bit longer than the ``average'' code
length, i.e. the code length of an approximately flat code which would be a
little more than eight bits for 286 symbols and a little less than five bits
for 30 symbols.
2.2 More details on the inflate table lookup
Ok, you want to know what this cleverly obfuscated inflate tree actually
looks like. You are correct that it's not a Huffman tree. It is simply a
lookup table for the first, let's say, nine bits of a Huffman symbol. The
symbol could be as short as one bit or as long as 15 bits. If a particular
symbol is shorter than nine bits, then that symbol's translation is duplicated
in all those entries that start with that symbol's bits. For example, if the
symbol is four bits, then it's duplicated 32 times in a nine-bit table. If a
symbol is nine bits long, it appears in the table once.
If the symbol is longer than nine bits, then that entry in the table points
to another similar table for the remaining bits. Again, there are duplicated
entries as needed. The idea is that most of the time the symbol will be short
and there will only be one table look up. (That's whole idea behind data
compression in the first place.) For the less frequent long symbols, there
will be two lookups. If you had a compression method with really long
symbols, you could have as many levels of lookups as is efficient. For
inflate, two is enough.
So a table entry either points to another table (in which case nine bits in
the above example are gobbled), or it contains the translation for the symbol
and the number of bits to gobble. Then you start again with the next
ungobbled bit.
You may wonder: why not just have one lookup table for how ever many bits the
longest symbol is? The reason is that if you do that, you end up spending
more time filling in duplicate symbol entries than you do actually decoding.
At least for deflate's output that generates new trees every several 10's of
kbytes. You can imagine that filling in a 2^15 entry table for a 15-bit code
would take too long if you're only decoding several thousand symbols. At the
other extreme, you could make a new table for every bit in the code. In fact,
that's essentially a Huffman tree. But then you spend two much time
traversing the tree while decoding, even for short symbols.
So the number of bits for the first lookup table is a trade of the time to
fill out the table vs. the time spent looking at the second level and above of
the table.
Here is an example, scaled down:
The code being decoded, with 10 symbols, from 1 to 6 bits long:
A: 0
B: 10
C: 1100
D: 11010
E: 11011
F: 11100
G: 11101
H: 11110
I: 111110
J: 111111
Let's make the first table three bits long (eight entries):
000: A,1
001: A,1
010: A,1
011: A,1
100: B,2
101: B,2
110: -> table X (gobble 3 bits)
111: -> table Y (gobble 3 bits)
Each entry is what the bits decode as and how many bits that is, i.e. how
many bits to gobble. Or the entry points to another table, with the number of
bits to gobble implicit in the size of the table.
Table X is two bits long since the longest code starting with 110 is five bits
long:
00: C,1
01: C,1
10: D,2
11: E,2
Table Y is three bits long since the longest code starting with 111 is six
bits long:
000: F,2
001: F,2
010: G,2
011: G,2
100: H,2
101: H,2
110: I,3
111: J,3
So what we have here are three tables with a total of 20 entries that had to
be constructed. That's compared to 64 entries for a single table. Or
compared to 16 entries for a Huffman tree (six two entry tables and one four
entry table). Assuming that the code ideally represents the probability of
the symbols, it takes on the average 1.25 lookups per symbol. That's compared
to one lookup for the single table, or 1.66 lookups per symbol for the
Huffman tree.
There, I think that gives you a picture of what's going on. For inflate, the
meaning of a particular symbol is often more than just a letter. It can be a
byte (a "literal"), or it can be either a length or a distance which
indicates a base value and a number of bits to fetch after the code that is
added to the base value. Or it might be the special end-of-block code. The
data structures created in inftrees.c try to encode all that information
compactly in the tables.
Jean-loup Gailly Mark Adler
jloup@gzip.org madler@alumni.caltech.edu
References:
[LZ77] Ziv J., Lempel A., ``A Universal Algorithm for Sequential Data
Compression,'' IEEE Transactions on Information Theory, Vol. 23, No. 3,
pp. 337-343.
``DEFLATE Compressed Data Format Specification'' available in
http://www.ietf.org/rfc/rfc1951.txt

View file

@ -0,0 +1,79 @@
/* compress.c -- compress a memory buffer
* Copyright (C) 1995-2003 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* @(#) $Id$ */
#define ZLIB_INTERNAL
#include "zlib.h"
/* ===========================================================================
Compresses the source buffer into the destination buffer. The level
parameter has the same meaning as in deflateInit. sourceLen is the byte
length of the source buffer. Upon entry, destLen is the total size of the
destination buffer, which must be at least 0.1% larger than sourceLen plus
12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
memory, Z_BUF_ERROR if there was not enough room in the output buffer,
Z_STREAM_ERROR if the level parameter is invalid.
*/
int ZEXPORT compress2 (dest, destLen, source, sourceLen, level)
Bytef *dest;
uLongf *destLen;
const Bytef *source;
uLong sourceLen;
int level;
{
z_stream stream;
int err;
stream.next_in = (Bytef*)source;
stream.avail_in = (uInt)sourceLen;
#ifdef MAXSEG_64K
/* Check for source > 64K on 16-bit machine: */
if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
#endif
stream.next_out = dest;
stream.avail_out = (uInt)*destLen;
if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
stream.zalloc = (alloc_func)0;
stream.zfree = (free_func)0;
stream.opaque = (voidpf)0;
err = deflateInit(&stream, level);
if (err != Z_OK) return err;
err = deflate(&stream, Z_FINISH);
if (err != Z_STREAM_END) {
deflateEnd(&stream);
return err == Z_OK ? Z_BUF_ERROR : err;
}
*destLen = stream.total_out;
err = deflateEnd(&stream);
return err;
}
/* ===========================================================================
*/
int ZEXPORT compress (dest, destLen, source, sourceLen)
Bytef *dest;
uLongf *destLen;
const Bytef *source;
uLong sourceLen;
{
return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
}
/* ===========================================================================
If the default memLevel or windowBits for deflateInit() is changed, then
this function needs to be updated.
*/
uLong ZEXPORT compressBound (sourceLen)
uLong sourceLen;
{
return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
}

View file

@ -0,0 +1,459 @@
#!/bin/sh
# configure script for zlib. This script is needed only if
# you wish to build a shared library and your system supports them,
# of if you need special compiler, flags or install directory.
# Otherwise, you can just use directly "make test; make install"
#
# To create a shared library, use "configure --shared"; by default a static
# library is created. If the primitive shared library support provided here
# does not work, use ftp://prep.ai.mit.edu/pub/gnu/libtool-*.tar.gz
#
# To impose specific compiler or flags or install directory, use for example:
# prefix=$HOME CC=cc CFLAGS="-O4" ./configure
# or for csh/tcsh users:
# (setenv prefix $HOME; setenv CC cc; setenv CFLAGS "-O4"; ./configure)
# LDSHARED is the command to be used to create a shared library
# Incorrect settings of CC or CFLAGS may prevent creating a shared library.
# If you have problems, try without defining CC and CFLAGS before reporting
# an error.
LIBS=libz.a
LDFLAGS="-L. ${LIBS}"
VER=`sed -n -e '/VERSION "/s/.*"\(.*\)".*/\1/p' < zlib.h`
VER2=`sed -n -e '/VERSION "/s/.*"\([0-9]*\\.[0-9]*\)\\..*/\1/p' < zlib.h`
VER1=`sed -n -e '/VERSION "/s/.*"\([0-9]*\)\\..*/\1/p' < zlib.h`
AR=${AR-"ar rc"}
RANLIB=${RANLIB-"ranlib"}
prefix=${prefix-/usr/local}
exec_prefix=${exec_prefix-'${prefix}'}
libdir=${libdir-'${exec_prefix}/lib'}
includedir=${includedir-'${prefix}/include'}
mandir=${mandir-'${prefix}/share/man'}
shared_ext='.so'
shared=0
gcc=0
old_cc="$CC"
old_cflags="$CFLAGS"
while test $# -ge 1
do
case "$1" in
-h* | --h*)
echo 'usage:'
echo ' configure [--shared] [--prefix=PREFIX] [--exec_prefix=EXPREFIX]'
echo ' [--libdir=LIBDIR] [--includedir=INCLUDEDIR]'
exit 0;;
-p*=* | --p*=*) prefix=`echo $1 | sed 's/[-a-z_]*=//'`; shift;;
-e*=* | --e*=*) exec_prefix=`echo $1 | sed 's/[-a-z_]*=//'`; shift;;
-l*=* | --libdir=*) libdir=`echo $1 | sed 's/[-a-z_]*=//'`; shift;;
-i*=* | --includedir=*) includedir=`echo $1 | sed 's/[-a-z_]*=//'`;shift;;
-p* | --p*) prefix="$2"; shift; shift;;
-e* | --e*) exec_prefix="$2"; shift; shift;;
-l* | --l*) libdir="$2"; shift; shift;;
-i* | --i*) includedir="$2"; shift; shift;;
-s* | --s*) shared=1; shift;;
*) echo "unknown option: $1"; echo "$0 --help for help"; exit 1;;
esac
done
test=ztest$$
cat > $test.c <<EOF
extern int getchar();
int hello() {return getchar();}
EOF
test -z "$CC" && echo Checking for gcc...
cc=${CC-gcc}
cflags=${CFLAGS-"-O3"}
# to force the asm version use: CFLAGS="-O3 -DASMV" ./configure
case "$cc" in
*gcc*) gcc=1;;
esac
if test "$gcc" -eq 1 && ($cc -c $cflags $test.c) 2>/dev/null; then
CC="$cc"
SFLAGS=${CFLAGS-"-fPIC -O3"}
CFLAGS="$cflags"
case `(uname -s || echo unknown) 2>/dev/null` in
Linux | linux | GNU | GNU/*) LDSHARED=${LDSHARED-"$cc -shared -Wl,-soname,libz.so.1"};;
CYGWIN* | Cygwin* | cygwin* | OS/2* )
EXE='.exe';;
QNX*) # This is for QNX6. I suppose that the QNX rule below is for QNX2,QNX4
# (alain.bonnefoy@icbt.com)
LDSHARED=${LDSHARED-"$cc -shared -Wl,-hlibz.so.1"};;
HP-UX*)
LDSHARED=${LDSHARED-"$cc -shared $SFLAGS"}
case `(uname -m || echo unknown) 2>/dev/null` in
ia64)
shared_ext='.so'
SHAREDLIB='libz.so';;
*)
shared_ext='.sl'
SHAREDLIB='libz.sl';;
esac;;
Darwin*) shared_ext='.dylib'
SHAREDLIB=libz$shared_ext
SHAREDLIBV=libz.$VER$shared_ext
SHAREDLIBM=libz.$VER1$shared_ext
LDSHARED=${LDSHARED-"$cc -dynamiclib -install_name $libdir/$SHAREDLIBM -compatibility_version $VER1 -current_version $VER"};;
*) LDSHARED=${LDSHARED-"$cc -shared"};;
esac
else
# find system name and corresponding cc options
CC=${CC-cc}
case `(uname -sr || echo unknown) 2>/dev/null` in
HP-UX*) SFLAGS=${CFLAGS-"-O +z"}
CFLAGS=${CFLAGS-"-O"}
# LDSHARED=${LDSHARED-"ld -b +vnocompatwarnings"}
LDSHARED=${LDSHARED-"ld -b"}
case `(uname -m || echo unknown) 2>/dev/null` in
ia64)
shared_ext='.so'
SHAREDLIB='libz.so';;
*)
shared_ext='.sl'
SHAREDLIB='libz.sl';;
esac;;
IRIX*) SFLAGS=${CFLAGS-"-ansi -O2 -rpath ."}
CFLAGS=${CFLAGS-"-ansi -O2"}
LDSHARED=${LDSHARED-"cc -shared"};;
OSF1\ V4*) SFLAGS=${CFLAGS-"-O -std1"}
CFLAGS=${CFLAGS-"-O -std1"}
LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so -Wl,-msym -Wl,-rpath,$(libdir) -Wl,-set_version,${VER}:1.0"};;
OSF1*) SFLAGS=${CFLAGS-"-O -std1"}
CFLAGS=${CFLAGS-"-O -std1"}
LDSHARED=${LDSHARED-"cc -shared"};;
QNX*) SFLAGS=${CFLAGS-"-4 -O"}
CFLAGS=${CFLAGS-"-4 -O"}
LDSHARED=${LDSHARED-"cc"}
RANLIB=${RANLIB-"true"}
AR="cc -A";;
SCO_SV\ 3.2*) SFLAGS=${CFLAGS-"-O3 -dy -KPIC "}
CFLAGS=${CFLAGS-"-O3"}
LDSHARED=${LDSHARED-"cc -dy -KPIC -G"};;
SunOS\ 5*) SFLAGS=${CFLAGS-"-fast -xcg89 -KPIC -R."}
CFLAGS=${CFLAGS-"-fast -xcg89"}
LDSHARED=${LDSHARED-"cc -G"};;
SunOS\ 4*) SFLAGS=${CFLAGS-"-O2 -PIC"}
CFLAGS=${CFLAGS-"-O2"}
LDSHARED=${LDSHARED-"ld"};;
SunStudio\ 9*) SFLAGS=${CFLAGS-"-DUSE_MMAP -fast -xcode=pic32 -xtarget=ultra3 -xarch=v9b"}
CFLAGS=${CFLAGS-"-DUSE_MMAP -fast -xtarget=ultra3 -xarch=v9b"}
LDSHARED=${LDSHARED-"cc -xarch=v9b"};;
UNIX_System_V\ 4.2.0)
SFLAGS=${CFLAGS-"-KPIC -O"}
CFLAGS=${CFLAGS-"-O"}
LDSHARED=${LDSHARED-"cc -G"};;
UNIX_SV\ 4.2MP)
SFLAGS=${CFLAGS-"-Kconform_pic -O"}
CFLAGS=${CFLAGS-"-O"}
LDSHARED=${LDSHARED-"cc -G"};;
OpenUNIX\ 5)
SFLAGS=${CFLAGS-"-KPIC -O"}
CFLAGS=${CFLAGS-"-O"}
LDSHARED=${LDSHARED-"cc -G"};;
AIX*) # Courtesy of dbakker@arrayasolutions.com
SFLAGS=${CFLAGS-"-O -qmaxmem=8192"}
CFLAGS=${CFLAGS-"-O -qmaxmem=8192"}
LDSHARED=${LDSHARED-"xlc -G"};;
# send working options for other systems to support@gzip.org
*) SFLAGS=${CFLAGS-"-O"}
CFLAGS=${CFLAGS-"-O"}
LDSHARED=${LDSHARED-"cc -shared"};;
esac
fi
SHAREDLIB=${SHAREDLIB-"libz$shared_ext"}
SHAREDLIBV=${SHAREDLIBV-"libz$shared_ext.$VER"}
SHAREDLIBM=${SHAREDLIBM-"libz$shared_ext.$VER1"}
if test $shared -eq 1; then
echo Checking for shared library support...
# we must test in two steps (cc then ld), required at least on SunOS 4.x
if test "`($CC -c $SFLAGS $test.c) 2>&1`" = "" &&
test "`($LDSHARED -o $test$shared_ext $test.o) 2>&1`" = ""; then
CFLAGS="$SFLAGS"
LIBS="$SHAREDLIBV"
echo Building shared library $SHAREDLIBV with $CC.
elif test -z "$old_cc" -a -z "$old_cflags"; then
echo No shared library support.
shared=0;
else
echo 'No shared library support; try without defining CC and CFLAGS'
shared=0;
fi
fi
if test $shared -eq 0; then
LDSHARED="$CC"
echo Building static library $LIBS version $VER with $CC.
else
LDFLAGS="-L. ${SHAREDLIBV}"
fi
cat > $test.c <<EOF
#include <unistd.h>
int main() { return 0; }
EOF
if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
sed < zconf.in.h "/HAVE_UNISTD_H/s%0%1%" > zconf.h
echo "Checking for unistd.h... Yes."
else
cp -p zconf.in.h zconf.h
echo "Checking for unistd.h... No."
fi
cat > $test.c <<EOF
#include <stdio.h>
#include <stdarg.h>
#include "zconf.h"
int main()
{
#ifndef STDC
choke me
#endif
return 0;
}
EOF
if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
echo "Checking whether to use vs[n]printf() or s[n]printf()... using vs[n]printf()"
cat > $test.c <<EOF
#include <stdio.h>
#include <stdarg.h>
int mytest(char *fmt, ...)
{
char buf[20];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
return 0;
}
int main()
{
return (mytest("Hello%d\n", 1));
}
EOF
if test "`($CC $CFLAGS -o $test $test.c) 2>&1`" = ""; then
echo "Checking for vsnprintf() in stdio.h... Yes."
cat >$test.c <<EOF
#include <stdio.h>
#include <stdarg.h>
int mytest(char *fmt, ...)
{
int n;
char buf[20];
va_list ap;
va_start(ap, fmt);
n = vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
return n;
}
int main()
{
return (mytest("Hello%d\n", 1));
}
EOF
if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
echo "Checking for return value of vsnprintf()... Yes."
else
CFLAGS="$CFLAGS -DHAS_vsnprintf_void"
echo "Checking for return value of vsnprintf()... No."
echo " WARNING: apparently vsnprintf() does not return a value. zlib"
echo " can build but will be open to possible string-format security"
echo " vulnerabilities."
fi
else
CFLAGS="$CFLAGS -DNO_vsnprintf"
echo "Checking for vsnprintf() in stdio.h... No."
echo " WARNING: vsnprintf() not found, falling back to vsprintf(). zlib"
echo " can build but will be open to possible buffer-overflow security"
echo " vulnerabilities."
cat >$test.c <<EOF
#include <stdio.h>
#include <stdarg.h>
int mytest(char *fmt, ...)
{
int n;
char buf[20];
va_list ap;
va_start(ap, fmt);
n = vsprintf(buf, fmt, ap);
va_end(ap);
return n;
}
int main()
{
return (mytest("Hello%d\n", 1));
}
EOF
if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
echo "Checking for return value of vsprintf()... Yes."
else
CFLAGS="$CFLAGS -DHAS_vsprintf_void"
echo "Checking for return value of vsprintf()... No."
echo " WARNING: apparently vsprintf() does not return a value. zlib"
echo " can build but will be open to possible string-format security"
echo " vulnerabilities."
fi
fi
else
echo "Checking whether to use vs[n]printf() or s[n]printf()... using s[n]printf()"
cat >$test.c <<EOF
#include <stdio.h>
int mytest()
{
char buf[20];
snprintf(buf, sizeof(buf), "%s", "foo");
return 0;
}
int main()
{
return (mytest());
}
EOF
if test "`($CC $CFLAGS -o $test $test.c) 2>&1`" = ""; then
echo "Checking for snprintf() in stdio.h... Yes."
cat >$test.c <<EOF
#include <stdio.h>
int mytest()
{
char buf[20];
return snprintf(buf, sizeof(buf), "%s", "foo");
}
int main()
{
return (mytest());
}
EOF
if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
echo "Checking for return value of snprintf()... Yes."
else
CFLAGS="$CFLAGS -DHAS_snprintf_void"
echo "Checking for return value of snprintf()... No."
echo " WARNING: apparently snprintf() does not return a value. zlib"
echo " can build but will be open to possible string-format security"
echo " vulnerabilities."
fi
else
CFLAGS="$CFLAGS -DNO_snprintf"
echo "Checking for snprintf() in stdio.h... No."
echo " WARNING: snprintf() not found, falling back to sprintf(). zlib"
echo " can build but will be open to possible buffer-overflow security"
echo " vulnerabilities."
cat >$test.c <<EOF
#include <stdio.h>
int mytest()
{
char buf[20];
return sprintf(buf, "%s", "foo");
}
int main()
{
return (mytest());
}
EOF
if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
echo "Checking for return value of sprintf()... Yes."
else
CFLAGS="$CFLAGS -DHAS_sprintf_void"
echo "Checking for return value of sprintf()... No."
echo " WARNING: apparently sprintf() does not return a value. zlib"
echo " can build but will be open to possible string-format security"
echo " vulnerabilities."
fi
fi
fi
cat >$test.c <<EOF
#include <errno.h>
int main() { return 0; }
EOF
if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
echo "Checking for errno.h... Yes."
else
echo "Checking for errno.h... No."
CFLAGS="$CFLAGS -DNO_ERRNO_H"
fi
cat > $test.c <<EOF
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
caddr_t hello() {
return mmap((caddr_t)0, (off_t)0, PROT_READ, MAP_SHARED, 0, (off_t)0);
}
EOF
if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
CFLAGS="$CFLAGS -DUSE_MMAP"
echo Checking for mmap support... Yes.
else
echo Checking for mmap support... No.
fi
CPP=${CPP-"$CC -E"}
case $CFLAGS in
*ASMV*)
if test "`nm $test.o | grep _hello`" = ""; then
CPP="$CPP -DNO_UNDERLINE"
echo Checking for underline in external names... No.
else
echo Checking for underline in external names... Yes.
fi;;
esac
rm -f $test.[co] $test $test$shared_ext
# udpate Makefile
sed < Makefile.in "
/^CC *=/s#=.*#=$CC#
/^CFLAGS *=/s#=.*#=$CFLAGS#
/^CPP *=/s#=.*#=$CPP#
/^LDSHARED *=/s#=.*#=$LDSHARED#
/^LIBS *=/s#=.*#=$LIBS#
/^SHAREDLIB *=/s#=.*#=$SHAREDLIB#
/^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV#
/^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM#
/^AR *=/s#=.*#=$AR#
/^RANLIB *=/s#=.*#=$RANLIB#
/^EXE *=/s#=.*#=$EXE#
/^prefix *=/s#=.*#=$prefix#
/^exec_prefix *=/s#=.*#=$exec_prefix#
/^libdir *=/s#=.*#=$libdir#
/^includedir *=/s#=.*#=$includedir#
/^mandir *=/s#=.*#=$mandir#
/^LDFLAGS *=/s#=.*#=$LDFLAGS#
" > Makefile

View file

@ -0,0 +1,423 @@
/* crc32.c -- compute the CRC-32 of a data stream
* Copyright (C) 1995-2005 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*
* Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster
* CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing
* tables for updating the shift register in one step with three exclusive-ors
* instead of four steps with four exclusive-ors. This results in about a
* factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3.
*/
/* @(#) $Id$ */
/*
Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
protection on the static variables used to control the first-use generation
of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
first call get_crc_table() to initialize the tables before allowing more than
one thread to use crc32().
*/
#ifdef MAKECRCH
# include <stdio.h>
# ifndef DYNAMIC_CRC_TABLE
# define DYNAMIC_CRC_TABLE
# endif /* !DYNAMIC_CRC_TABLE */
#endif /* MAKECRCH */
#include "zutil.h" /* for STDC and FAR definitions */
#define local static
/* Find a four-byte integer type for crc32_little() and crc32_big(). */
#ifndef NOBYFOUR
# ifdef STDC /* need ANSI C limits.h to determine sizes */
# include <limits.h>
# define BYFOUR
# if (UINT_MAX == 0xffffffffUL)
typedef unsigned int u4;
# else
# if (ULONG_MAX == 0xffffffffUL)
typedef unsigned long u4;
# else
# if (USHRT_MAX == 0xffffffffUL)
typedef unsigned short u4;
# else
# undef BYFOUR /* can't find a four-byte integer type! */
# endif
# endif
# endif
# endif /* STDC */
#endif /* !NOBYFOUR */
/* Definitions for doing the crc four data bytes at a time. */
#ifdef BYFOUR
# define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
(((w)&0xff00)<<8)+(((w)&0xff)<<24))
local unsigned long crc32_little OF((unsigned long,
const unsigned char FAR *, unsigned));
local unsigned long crc32_big OF((unsigned long,
const unsigned char FAR *, unsigned));
# define TBLS 8
#else
# define TBLS 1
#endif /* BYFOUR */
/* Local functions for crc concatenation */
local unsigned long gf2_matrix_times OF((unsigned long *mat,
unsigned long vec));
local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
#ifdef DYNAMIC_CRC_TABLE
local volatile int crc_table_empty = 1;
local unsigned long FAR crc_table[TBLS][256];
local void make_crc_table OF((void));
#ifdef MAKECRCH
local void write_table OF((FILE *, const unsigned long FAR *));
#endif /* MAKECRCH */
/*
Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
Polynomials over GF(2) are represented in binary, one bit per coefficient,
with the lowest powers in the most significant bit. Then adding polynomials
is just exclusive-or, and multiplying a polynomial by x is a right shift by
one. If we call the above polynomial p, and represent a byte as the
polynomial q, also with the lowest power in the most significant bit (so the
byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
where a mod b means the remainder after dividing a by b.
This calculation is done using the shift-register method of multiplying and
taking the remainder. The register is initialized to zero, and for each
incoming bit, x^32 is added mod p to the register if the bit is a one (where
x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
x (which is shifting right by one and adding x^32 mod p if the bit shifted
out is a one). We start with the highest power (least significant bit) of
q and repeat for all eight bits of q.
The first table is simply the CRC of all possible eight bit values. This is
all the information needed to generate CRCs on data a byte at a time for all
combinations of CRC register values and incoming bytes. The remaining tables
allow for word-at-a-time CRC calculation for both big-endian and little-
endian machines, where a word is four bytes.
*/
local void make_crc_table()
{
unsigned long c;
int n, k;
unsigned long poly; /* polynomial exclusive-or pattern */
/* terms of polynomial defining this crc (except x^32): */
static volatile int first = 1; /* flag to limit concurrent making */
static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
/* See if another task is already doing this (not thread-safe, but better
than nothing -- significantly reduces duration of vulnerability in
case the advice about DYNAMIC_CRC_TABLE is ignored) */
if (first) {
first = 0;
/* make exclusive-or pattern from polynomial (0xedb88320UL) */
poly = 0UL;
for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
poly |= 1UL << (31 - p[n]);
/* generate a crc for every 8-bit value */
for (n = 0; n < 256; n++) {
c = (unsigned long)n;
for (k = 0; k < 8; k++)
c = c & 1 ? poly ^ (c >> 1) : c >> 1;
crc_table[0][n] = c;
}
#ifdef BYFOUR
/* generate crc for each value followed by one, two, and three zeros,
and then the byte reversal of those as well as the first table */
for (n = 0; n < 256; n++) {
c = crc_table[0][n];
crc_table[4][n] = REV(c);
for (k = 1; k < 4; k++) {
c = crc_table[0][c & 0xff] ^ (c >> 8);
crc_table[k][n] = c;
crc_table[k + 4][n] = REV(c);
}
}
#endif /* BYFOUR */
crc_table_empty = 0;
}
else { /* not first */
/* wait for the other guy to finish (not efficient, but rare) */
while (crc_table_empty)
;
}
#ifdef MAKECRCH
/* write out CRC tables to crc32.h */
{
FILE *out;
out = fopen("crc32.h", "w");
if (out == NULL) return;
fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
fprintf(out, "local const unsigned long FAR ");
fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
write_table(out, crc_table[0]);
# ifdef BYFOUR
fprintf(out, "#ifdef BYFOUR\n");
for (k = 1; k < 8; k++) {
fprintf(out, " },\n {\n");
write_table(out, crc_table[k]);
}
fprintf(out, "#endif\n");
# endif /* BYFOUR */
fprintf(out, " }\n};\n");
fclose(out);
}
#endif /* MAKECRCH */
}
#ifdef MAKECRCH
local void write_table(out, table)
FILE *out;
const unsigned long FAR *table;
{
int n;
for (n = 0; n < 256; n++)
fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
}
#endif /* MAKECRCH */
#else /* !DYNAMIC_CRC_TABLE */
/* ========================================================================
* Tables of CRC-32s of all single-byte values, made by make_crc_table().
*/
#include "crc32.h"
#endif /* DYNAMIC_CRC_TABLE */
/* =========================================================================
* This function can be used by asm versions of crc32()
*/
const unsigned long FAR * ZEXPORT get_crc_table()
{
#ifdef DYNAMIC_CRC_TABLE
if (crc_table_empty)
make_crc_table();
#endif /* DYNAMIC_CRC_TABLE */
return (const unsigned long FAR *)crc_table;
}
/* ========================================================================= */
#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
/* ========================================================================= */
unsigned long ZEXPORT crc32(crc, buf, len)
unsigned long crc;
const unsigned char FAR *buf;
unsigned len;
{
if (buf == Z_NULL) return 0UL;
#ifdef DYNAMIC_CRC_TABLE
if (crc_table_empty)
make_crc_table();
#endif /* DYNAMIC_CRC_TABLE */
#ifdef BYFOUR
if (sizeof(void *) == sizeof(ptrdiff_t)) {
u4 endian;
endian = 1;
if (*((unsigned char *)(&endian)))
return crc32_little(crc, buf, len);
else
return crc32_big(crc, buf, len);
}
#endif /* BYFOUR */
crc = crc ^ 0xffffffffUL;
while (len >= 8) {
DO8;
len -= 8;
}
if (len) do {
DO1;
} while (--len);
return crc ^ 0xffffffffUL;
}
#ifdef BYFOUR
/* ========================================================================= */
#define DOLIT4 c ^= *buf4++; \
c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
/* ========================================================================= */
local unsigned long crc32_little(crc, buf, len)
unsigned long crc;
const unsigned char FAR *buf;
unsigned len;
{
register u4 c;
register const u4 FAR *buf4;
c = (u4)crc;
c = ~c;
while (len && ((ptrdiff_t)buf & 3)) {
c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
len--;
}
buf4 = (const u4 FAR *)(const void FAR *)buf;
while (len >= 32) {
DOLIT32;
len -= 32;
}
while (len >= 4) {
DOLIT4;
len -= 4;
}
buf = (const unsigned char FAR *)buf4;
if (len) do {
c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
} while (--len);
c = ~c;
return (unsigned long)c;
}
/* ========================================================================= */
#define DOBIG4 c ^= *++buf4; \
c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
/* ========================================================================= */
local unsigned long crc32_big(crc, buf, len)
unsigned long crc;
const unsigned char FAR *buf;
unsigned len;
{
register u4 c;
register const u4 FAR *buf4;
c = REV((u4)crc);
c = ~c;
while (len && ((ptrdiff_t)buf & 3)) {
c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
len--;
}
buf4 = (const u4 FAR *)(const void FAR *)buf;
buf4--;
while (len >= 32) {
DOBIG32;
len -= 32;
}
while (len >= 4) {
DOBIG4;
len -= 4;
}
buf4++;
buf = (const unsigned char FAR *)buf4;
if (len) do {
c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
} while (--len);
c = ~c;
return (unsigned long)(REV(c));
}
#endif /* BYFOUR */
#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
/* ========================================================================= */
local unsigned long gf2_matrix_times(mat, vec)
unsigned long *mat;
unsigned long vec;
{
unsigned long sum;
sum = 0;
while (vec) {
if (vec & 1)
sum ^= *mat;
vec >>= 1;
mat++;
}
return sum;
}
/* ========================================================================= */
local void gf2_matrix_square(square, mat)
unsigned long *square;
unsigned long *mat;
{
int n;
for (n = 0; n < GF2_DIM; n++)
square[n] = gf2_matrix_times(mat, mat[n]);
}
/* ========================================================================= */
uLong ZEXPORT crc32_combine(crc1, crc2, len2)
uLong crc1;
uLong crc2;
z_off_t len2;
{
int n;
unsigned long row;
unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
/* degenerate case */
if (len2 == 0)
return crc1;
/* put operator for one zero bit in odd */
odd[0] = 0xedb88320L; /* CRC-32 polynomial */
row = 1;
for (n = 1; n < GF2_DIM; n++) {
odd[n] = row;
row <<= 1;
}
/* put operator for two zero bits in even */
gf2_matrix_square(even, odd);
/* put operator for four zero bits in odd */
gf2_matrix_square(odd, even);
/* apply len2 zeros to crc1 (first square will put the operator for one
zero byte, eight zero bits, in even) */
do {
/* apply zeros operator for this bit of len2 */
gf2_matrix_square(even, odd);
if (len2 & 1)
crc1 = gf2_matrix_times(even, crc1);
len2 >>= 1;
/* if no more bits set, then done */
if (len2 == 0)
break;
/* another iteration of the loop with odd and even swapped */
gf2_matrix_square(odd, even);
if (len2 & 1)
crc1 = gf2_matrix_times(odd, crc1);
len2 >>= 1;
/* if no more bits set, then done */
} while (len2 != 0);
/* return combined crc */
crc1 ^= crc2;
return crc1;
}

View file

@ -0,0 +1,441 @@
/* crc32.h -- tables for rapid CRC calculation
* Generated automatically by crc32.c
*/
local const unsigned long FAR crc_table[TBLS][256] =
{
{
0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
0x2d02ef8dUL
#ifdef BYFOUR
},
{
0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
0x9324fd72UL
},
{
0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
0xbe9834edUL
},
{
0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
0xde0506f1UL
},
{
0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
0x8def022dUL
},
{
0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
0x72fd2493UL
},
{
0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
0xed3498beUL
},
{
0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
0xf10605deUL
#endif
}
};

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,331 @@
/* deflate.h -- internal compression state
* Copyright (C) 1995-2004 Jean-loup Gailly
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* WARNING: this file should *not* be used by applications. It is
part of the implementation of the compression library and is
subject to change. Applications should only use zlib.h.
*/
/* @(#) $Id$ */
#ifndef DEFLATE_H
#define DEFLATE_H
#include "zutil.h"
/* define NO_GZIP when compiling if you want to disable gzip header and
trailer creation by deflate(). NO_GZIP would be used to avoid linking in
the crc code when it is not needed. For shared libraries, gzip encoding
should be left enabled. */
#ifndef NO_GZIP
# define GZIP
#endif
/* ===========================================================================
* Internal compression state.
*/
#define LENGTH_CODES 29
/* number of length codes, not counting the special END_BLOCK code */
#define LITERALS 256
/* number of literal bytes 0..255 */
#define L_CODES (LITERALS+1+LENGTH_CODES)
/* number of Literal or Length codes, including the END_BLOCK code */
#define D_CODES 30
/* number of distance codes */
#define BL_CODES 19
/* number of codes used to transfer the bit lengths */
#define HEAP_SIZE (2*L_CODES+1)
/* maximum heap size */
#define MAX_BITS 15
/* All codes must not exceed MAX_BITS bits */
#define INIT_STATE 42
#define EXTRA_STATE 69
#define NAME_STATE 73
#define COMMENT_STATE 91
#define HCRC_STATE 103
#define BUSY_STATE 113
#define FINISH_STATE 666
/* Stream status */
/* Data structure describing a single value and its code string. */
typedef struct ct_data_s {
union {
ush freq; /* frequency count */
ush code; /* bit string */
} fc;
union {
ush dad; /* father node in Huffman tree */
ush len; /* length of bit string */
} dl;
} FAR ct_data;
#define Freq fc.freq
#define Code fc.code
#define Dad dl.dad
#define Len dl.len
typedef struct static_tree_desc_s static_tree_desc;
typedef struct tree_desc_s {
ct_data *dyn_tree; /* the dynamic tree */
int max_code; /* largest code with non zero frequency */
static_tree_desc *stat_desc; /* the corresponding static tree */
} FAR tree_desc;
typedef ush Pos;
typedef Pos FAR Posf;
typedef unsigned IPos;
/* A Pos is an index in the character window. We use short instead of int to
* save space in the various tables. IPos is used only for parameter passing.
*/
typedef struct internal_state {
z_streamp strm; /* pointer back to this zlib stream */
int status; /* as the name implies */
Bytef *pending_buf; /* output still pending */
ulg pending_buf_size; /* size of pending_buf */
Bytef *pending_out; /* next pending byte to output to the stream */
uInt pending; /* nb of bytes in the pending buffer */
int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
gz_headerp gzhead; /* gzip header information to write */
uInt gzindex; /* where in extra, name, or comment */
Byte method; /* STORED (for zip only) or DEFLATED */
int last_flush; /* value of flush param for previous deflate call */
/* used by deflate.c: */
uInt w_size; /* LZ77 window size (32K by default) */
uInt w_bits; /* log2(w_size) (8..16) */
uInt w_mask; /* w_size - 1 */
Bytef *window;
/* Sliding window. Input bytes are read into the second half of the window,
* and move to the first half later to keep a dictionary of at least wSize
* bytes. With this organization, matches are limited to a distance of
* wSize-MAX_MATCH bytes, but this ensures that IO is always
* performed with a length multiple of the block size. Also, it limits
* the window size to 64K, which is quite useful on MSDOS.
* To do: use the user input buffer as sliding window.
*/
ulg window_size;
/* Actual size of window: 2*wSize, except when the user input buffer
* is directly used as sliding window.
*/
Posf *prev;
/* Link to older string with same hash index. To limit the size of this
* array to 64K, this link is maintained only for the last 32K strings.
* An index in this array is thus a window index modulo 32K.
*/
Posf *head; /* Heads of the hash chains or NIL. */
uInt ins_h; /* hash index of string to be inserted */
uInt hash_size; /* number of elements in hash table */
uInt hash_bits; /* log2(hash_size) */
uInt hash_mask; /* hash_size-1 */
uInt hash_shift;
/* Number of bits by which ins_h must be shifted at each input
* step. It must be such that after MIN_MATCH steps, the oldest
* byte no longer takes part in the hash key, that is:
* hash_shift * MIN_MATCH >= hash_bits
*/
long block_start;
/* Window position at the beginning of the current output block. Gets
* negative when the window is moved backwards.
*/
uInt match_length; /* length of best match */
IPos prev_match; /* previous match */
int match_available; /* set if previous match exists */
uInt strstart; /* start of string to insert */
uInt match_start; /* start of matching string */
uInt lookahead; /* number of valid bytes ahead in window */
uInt prev_length;
/* Length of the best match at previous step. Matches not greater than this
* are discarded. This is used in the lazy match evaluation.
*/
uInt max_chain_length;
/* To speed up deflation, hash chains are never searched beyond this
* length. A higher limit improves compression ratio but degrades the
* speed.
*/
uInt max_lazy_match;
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
*/
# define max_insert_length max_lazy_match
/* Insert new strings in the hash table only if the match length is not
* greater than this length. This saves time but degrades compression.
* max_insert_length is used only for compression levels <= 3.
*/
int level; /* compression level (1..9) */
int strategy; /* favor or force Huffman coding*/
uInt good_match;
/* Use a faster search when the previous match is longer than this */
int nice_match; /* Stop searching when current match exceeds this */
/* used by trees.c: */
/* Didn't use ct_data typedef below to supress compiler warning */
struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
struct tree_desc_s l_desc; /* desc. for literal tree */
struct tree_desc_s d_desc; /* desc. for distance tree */
struct tree_desc_s bl_desc; /* desc. for bit length tree */
ush bl_count[MAX_BITS+1];
/* number of codes at each bit length for an optimal tree */
int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
int heap_len; /* number of elements in the heap */
int heap_max; /* element of largest frequency */
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
* The same heap array is used to build all trees.
*/
uch depth[2*L_CODES+1];
/* Depth of each subtree used as tie breaker for trees of equal frequency
*/
uchf *l_buf; /* buffer for literals or lengths */
uInt lit_bufsize;
/* Size of match buffer for literals/lengths. There are 4 reasons for
* limiting lit_bufsize to 64K:
* - frequencies can be kept in 16 bit counters
* - if compression is not successful for the first block, all input
* data is still in the window so we can still emit a stored block even
* when input comes from standard input. (This can also be done for
* all blocks if lit_bufsize is not greater than 32K.)
* - if compression is not successful for a file smaller than 64K, we can
* even emit a stored file instead of a stored block (saving 5 bytes).
* This is applicable only for zip (not gzip or zlib).
* - creating new Huffman trees less frequently may not provide fast
* adaptation to changes in the input data statistics. (Take for
* example a binary file with poorly compressible code followed by
* a highly compressible string table.) Smaller buffer sizes give
* fast adaptation but have of course the overhead of transmitting
* trees more frequently.
* - I can't count above 4
*/
uInt last_lit; /* running index in l_buf */
ushf *d_buf;
/* Buffer for distances. To simplify the code, d_buf and l_buf have
* the same number of elements. To use different lengths, an extra flag
* array would be necessary.
*/
ulg opt_len; /* bit length of current block with optimal trees */
ulg static_len; /* bit length of current block with static trees */
uInt matches; /* number of string matches in current block */
int last_eob_len; /* bit length of EOB code for last block */
#ifdef DEBUG
ulg compressed_len; /* total bit length of compressed file mod 2^32 */
ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
#endif
ush bi_buf;
/* Output buffer. bits are inserted starting at the bottom (least
* significant bits).
*/
int bi_valid;
/* Number of valid bits in bi_buf. All bits above the last valid bit
* are always zero.
*/
} FAR deflate_state;
/* Output a byte on the stream.
* IN assertion: there is enough room in pending_buf.
*/
#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
/* Minimum amount of lookahead, except at the end of the input file.
* See deflate.c for comments about the MIN_MATCH+1.
*/
#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
/* In order to simplify the code, particularly on 16 bit machines, match
* distances are limited to MAX_DIST instead of WSIZE.
*/
/* in trees.c */
void _tr_init OF((deflate_state *s));
int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
int eof));
void _tr_align OF((deflate_state *s));
void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
int eof));
#define d_code(dist) \
((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
/* Mapping from a distance to a distance code. dist is the distance - 1 and
* must not have side effects. _dist_code[256] and _dist_code[257] are never
* used.
*/
#ifndef DEBUG
/* Inline versions of _tr_tally for speed: */
#if defined(GEN_TREES_H) || !defined(STDC)
extern uch _length_code[];
extern uch _dist_code[];
#else
extern const uch _length_code[];
extern const uch _dist_code[];
#endif
# define _tr_tally_lit(s, c, flush) \
{ uch cc = (c); \
s->d_buf[s->last_lit] = 0; \
s->l_buf[s->last_lit++] = cc; \
s->dyn_ltree[cc].Freq++; \
flush = (s->last_lit == s->lit_bufsize-1); \
}
# define _tr_tally_dist(s, distance, length, flush) \
{ uch len = (length); \
ush dist = (distance); \
s->d_buf[s->last_lit] = dist; \
s->l_buf[s->last_lit++] = len; \
dist--; \
s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
s->dyn_dtree[d_code(dist)].Freq++; \
flush = (s->last_lit == s->lit_bufsize-1); \
}
#else
# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
# define _tr_tally_dist(s, distance, length, flush) \
flush = _tr_tally(s, distance, length)
#endif
#endif /* DEFLATE_H */

View file

@ -0,0 +1,565 @@
/* example.c -- usage example of the zlib compression library
* Copyright (C) 1995-2004 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* @(#) $Id$ */
#include <stdio.h>
#include "zlib.h"
#ifdef STDC
# include <string.h>
# include <stdlib.h>
#endif
#if defined(VMS) || defined(RISCOS)
# define TESTFILE "foo-gz"
#else
# define TESTFILE "foo.gz"
#endif
#define CHECK_ERR(err, msg) { \
if (err != Z_OK) { \
fprintf(stderr, "%s error: %d\n", msg, err); \
exit(1); \
} \
}
const char hello[] = "hello, hello!";
/* "hello world" would be more standard, but the repeated "hello"
* stresses the compression code better, sorry...
*/
const char dictionary[] = "hello";
uLong dictId; /* Adler32 value of the dictionary */
void test_compress OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen));
void test_gzio OF((const char *fname,
Byte *uncompr, uLong uncomprLen));
void test_deflate OF((Byte *compr, uLong comprLen));
void test_inflate OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen));
void test_large_deflate OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen));
void test_large_inflate OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen));
void test_flush OF((Byte *compr, uLong *comprLen));
void test_sync OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen));
void test_dict_deflate OF((Byte *compr, uLong comprLen));
void test_dict_inflate OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen));
int main OF((int argc, char *argv[]));
/* ===========================================================================
* Test compress() and uncompress()
*/
void test_compress(compr, comprLen, uncompr, uncomprLen)
Byte *compr, *uncompr;
uLong comprLen, uncomprLen;
{
int err;
uLong len = (uLong)strlen(hello)+1;
err = compress(compr, &comprLen, (const Bytef*)hello, len);
CHECK_ERR(err, "compress");
strcpy((char*)uncompr, "garbage");
err = uncompress(uncompr, &uncomprLen, compr, comprLen);
CHECK_ERR(err, "uncompress");
if (strcmp((char*)uncompr, hello)) {
fprintf(stderr, "bad uncompress\n");
exit(1);
} else {
printf("uncompress(): %s\n", (char *)uncompr);
}
}
/* ===========================================================================
* Test read/write of .gz files
*/
void test_gzio(fname, uncompr, uncomprLen)
const char *fname; /* compressed file name */
Byte *uncompr;
uLong uncomprLen;
{
#ifdef NO_GZCOMPRESS
fprintf(stderr, "NO_GZCOMPRESS -- gz* functions cannot compress\n");
#else
int err;
int len = (int)strlen(hello)+1;
gzFile file;
z_off_t pos;
file = gzopen(fname, "wb");
if (file == NULL) {
fprintf(stderr, "gzopen error\n");
exit(1);
}
gzputc(file, 'h');
if (gzputs(file, "ello") != 4) {
fprintf(stderr, "gzputs err: %s\n", gzerror(file, &err));
exit(1);
}
if (gzprintf(file, ", %s!", "hello") != 8) {
fprintf(stderr, "gzprintf err: %s\n", gzerror(file, &err));
exit(1);
}
gzseek(file, 1L, SEEK_CUR); /* add one zero byte */
gzclose(file);
file = gzopen(fname, "rb");
if (file == NULL) {
fprintf(stderr, "gzopen error\n");
exit(1);
}
strcpy((char*)uncompr, "garbage");
if (gzread(file, uncompr, (unsigned)uncomprLen) != len) {
fprintf(stderr, "gzread err: %s\n", gzerror(file, &err));
exit(1);
}
if (strcmp((char*)uncompr, hello)) {
fprintf(stderr, "bad gzread: %s\n", (char*)uncompr);
exit(1);
} else {
printf("gzread(): %s\n", (char*)uncompr);
}
pos = gzseek(file, -8L, SEEK_CUR);
if (pos != 6 || gztell(file) != pos) {
fprintf(stderr, "gzseek error, pos=%ld, gztell=%ld\n",
(long)pos, (long)gztell(file));
exit(1);
}
if (gzgetc(file) != ' ') {
fprintf(stderr, "gzgetc error\n");
exit(1);
}
if (gzungetc(' ', file) != ' ') {
fprintf(stderr, "gzungetc error\n");
exit(1);
}
gzgets(file, (char*)uncompr, (int)uncomprLen);
if (strlen((char*)uncompr) != 7) { /* " hello!" */
fprintf(stderr, "gzgets err after gzseek: %s\n", gzerror(file, &err));
exit(1);
}
if (strcmp((char*)uncompr, hello + 6)) {
fprintf(stderr, "bad gzgets after gzseek\n");
exit(1);
} else {
printf("gzgets() after gzseek: %s\n", (char*)uncompr);
}
gzclose(file);
#endif
}
/* ===========================================================================
* Test deflate() with small buffers
*/
void test_deflate(compr, comprLen)
Byte *compr;
uLong comprLen;
{
z_stream c_stream; /* compression stream */
int err;
uLong len = (uLong)strlen(hello)+1;
c_stream.zalloc = (alloc_func)0;
c_stream.zfree = (free_func)0;
c_stream.opaque = (voidpf)0;
err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);
CHECK_ERR(err, "deflateInit");
c_stream.next_in = (Bytef*)hello;
c_stream.next_out = compr;
while (c_stream.total_in != len && c_stream.total_out < comprLen) {
c_stream.avail_in = c_stream.avail_out = 1; /* force small buffers */
err = deflate(&c_stream, Z_NO_FLUSH);
CHECK_ERR(err, "deflate");
}
/* Finish the stream, still forcing small buffers: */
for (;;) {
c_stream.avail_out = 1;
err = deflate(&c_stream, Z_FINISH);
if (err == Z_STREAM_END) break;
CHECK_ERR(err, "deflate");
}
err = deflateEnd(&c_stream);
CHECK_ERR(err, "deflateEnd");
}
/* ===========================================================================
* Test inflate() with small buffers
*/
void test_inflate(compr, comprLen, uncompr, uncomprLen)
Byte *compr, *uncompr;
uLong comprLen, uncomprLen;
{
int err;
z_stream d_stream; /* decompression stream */
strcpy((char*)uncompr, "garbage");
d_stream.zalloc = (alloc_func)0;
d_stream.zfree = (free_func)0;
d_stream.opaque = (voidpf)0;
d_stream.next_in = compr;
d_stream.avail_in = 0;
d_stream.next_out = uncompr;
err = inflateInit(&d_stream);
CHECK_ERR(err, "inflateInit");
while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen) {
d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */
err = inflate(&d_stream, Z_NO_FLUSH);
if (err == Z_STREAM_END) break;
CHECK_ERR(err, "inflate");
}
err = inflateEnd(&d_stream);
CHECK_ERR(err, "inflateEnd");
if (strcmp((char*)uncompr, hello)) {
fprintf(stderr, "bad inflate\n");
exit(1);
} else {
printf("inflate(): %s\n", (char *)uncompr);
}
}
/* ===========================================================================
* Test deflate() with large buffers and dynamic change of compression level
*/
void test_large_deflate(compr, comprLen, uncompr, uncomprLen)
Byte *compr, *uncompr;
uLong comprLen, uncomprLen;
{
z_stream c_stream; /* compression stream */
int err;
c_stream.zalloc = (alloc_func)0;
c_stream.zfree = (free_func)0;
c_stream.opaque = (voidpf)0;
err = deflateInit(&c_stream, Z_BEST_SPEED);
CHECK_ERR(err, "deflateInit");
c_stream.next_out = compr;
c_stream.avail_out = (uInt)comprLen;
/* At this point, uncompr is still mostly zeroes, so it should compress
* very well:
*/
c_stream.next_in = uncompr;
c_stream.avail_in = (uInt)uncomprLen;
err = deflate(&c_stream, Z_NO_FLUSH);
CHECK_ERR(err, "deflate");
if (c_stream.avail_in != 0) {
fprintf(stderr, "deflate not greedy\n");
exit(1);
}
/* Feed in already compressed data and switch to no compression: */
deflateParams(&c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY);
c_stream.next_in = compr;
c_stream.avail_in = (uInt)comprLen/2;
err = deflate(&c_stream, Z_NO_FLUSH);
CHECK_ERR(err, "deflate");
/* Switch back to compressing mode: */
deflateParams(&c_stream, Z_BEST_COMPRESSION, Z_FILTERED);
c_stream.next_in = uncompr;
c_stream.avail_in = (uInt)uncomprLen;
err = deflate(&c_stream, Z_NO_FLUSH);
CHECK_ERR(err, "deflate");
err = deflate(&c_stream, Z_FINISH);
if (err != Z_STREAM_END) {
fprintf(stderr, "deflate should report Z_STREAM_END\n");
exit(1);
}
err = deflateEnd(&c_stream);
CHECK_ERR(err, "deflateEnd");
}
/* ===========================================================================
* Test inflate() with large buffers
*/
void test_large_inflate(compr, comprLen, uncompr, uncomprLen)
Byte *compr, *uncompr;
uLong comprLen, uncomprLen;
{
int err;
z_stream d_stream; /* decompression stream */
strcpy((char*)uncompr, "garbage");
d_stream.zalloc = (alloc_func)0;
d_stream.zfree = (free_func)0;
d_stream.opaque = (voidpf)0;
d_stream.next_in = compr;
d_stream.avail_in = (uInt)comprLen;
err = inflateInit(&d_stream);
CHECK_ERR(err, "inflateInit");
for (;;) {
d_stream.next_out = uncompr; /* discard the output */
d_stream.avail_out = (uInt)uncomprLen;
err = inflate(&d_stream, Z_NO_FLUSH);
if (err == Z_STREAM_END) break;
CHECK_ERR(err, "large inflate");
}
err = inflateEnd(&d_stream);
CHECK_ERR(err, "inflateEnd");
if (d_stream.total_out != 2*uncomprLen + comprLen/2) {
fprintf(stderr, "bad large inflate: %ld\n", d_stream.total_out);
exit(1);
} else {
printf("large_inflate(): OK\n");
}
}
/* ===========================================================================
* Test deflate() with full flush
*/
void test_flush(compr, comprLen)
Byte *compr;
uLong *comprLen;
{
z_stream c_stream; /* compression stream */
int err;
uInt len = (uInt)strlen(hello)+1;
c_stream.zalloc = (alloc_func)0;
c_stream.zfree = (free_func)0;
c_stream.opaque = (voidpf)0;
err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);
CHECK_ERR(err, "deflateInit");
c_stream.next_in = (Bytef*)hello;
c_stream.next_out = compr;
c_stream.avail_in = 3;
c_stream.avail_out = (uInt)*comprLen;
err = deflate(&c_stream, Z_FULL_FLUSH);
CHECK_ERR(err, "deflate");
compr[3]++; /* force an error in first compressed block */
c_stream.avail_in = len - 3;
err = deflate(&c_stream, Z_FINISH);
if (err != Z_STREAM_END) {
CHECK_ERR(err, "deflate");
}
err = deflateEnd(&c_stream);
CHECK_ERR(err, "deflateEnd");
*comprLen = c_stream.total_out;
}
/* ===========================================================================
* Test inflateSync()
*/
void test_sync(compr, comprLen, uncompr, uncomprLen)
Byte *compr, *uncompr;
uLong comprLen, uncomprLen;
{
int err;
z_stream d_stream; /* decompression stream */
strcpy((char*)uncompr, "garbage");
d_stream.zalloc = (alloc_func)0;
d_stream.zfree = (free_func)0;
d_stream.opaque = (voidpf)0;
d_stream.next_in = compr;
d_stream.avail_in = 2; /* just read the zlib header */
err = inflateInit(&d_stream);
CHECK_ERR(err, "inflateInit");
d_stream.next_out = uncompr;
d_stream.avail_out = (uInt)uncomprLen;
inflate(&d_stream, Z_NO_FLUSH);
CHECK_ERR(err, "inflate");
d_stream.avail_in = (uInt)comprLen-2; /* read all compressed data */
err = inflateSync(&d_stream); /* but skip the damaged part */
CHECK_ERR(err, "inflateSync");
err = inflate(&d_stream, Z_FINISH);
if (err != Z_DATA_ERROR) {
fprintf(stderr, "inflate should report DATA_ERROR\n");
/* Because of incorrect adler32 */
exit(1);
}
err = inflateEnd(&d_stream);
CHECK_ERR(err, "inflateEnd");
printf("after inflateSync(): hel%s\n", (char *)uncompr);
}
/* ===========================================================================
* Test deflate() with preset dictionary
*/
void test_dict_deflate(compr, comprLen)
Byte *compr;
uLong comprLen;
{
z_stream c_stream; /* compression stream */
int err;
c_stream.zalloc = (alloc_func)0;
c_stream.zfree = (free_func)0;
c_stream.opaque = (voidpf)0;
err = deflateInit(&c_stream, Z_BEST_COMPRESSION);
CHECK_ERR(err, "deflateInit");
err = deflateSetDictionary(&c_stream,
(const Bytef*)dictionary, sizeof(dictionary));
CHECK_ERR(err, "deflateSetDictionary");
dictId = c_stream.adler;
c_stream.next_out = compr;
c_stream.avail_out = (uInt)comprLen;
c_stream.next_in = (Bytef*)hello;
c_stream.avail_in = (uInt)strlen(hello)+1;
err = deflate(&c_stream, Z_FINISH);
if (err != Z_STREAM_END) {
fprintf(stderr, "deflate should report Z_STREAM_END\n");
exit(1);
}
err = deflateEnd(&c_stream);
CHECK_ERR(err, "deflateEnd");
}
/* ===========================================================================
* Test inflate() with a preset dictionary
*/
void test_dict_inflate(compr, comprLen, uncompr, uncomprLen)
Byte *compr, *uncompr;
uLong comprLen, uncomprLen;
{
int err;
z_stream d_stream; /* decompression stream */
strcpy((char*)uncompr, "garbage");
d_stream.zalloc = (alloc_func)0;
d_stream.zfree = (free_func)0;
d_stream.opaque = (voidpf)0;
d_stream.next_in = compr;
d_stream.avail_in = (uInt)comprLen;
err = inflateInit(&d_stream);
CHECK_ERR(err, "inflateInit");
d_stream.next_out = uncompr;
d_stream.avail_out = (uInt)uncomprLen;
for (;;) {
err = inflate(&d_stream, Z_NO_FLUSH);
if (err == Z_STREAM_END) break;
if (err == Z_NEED_DICT) {
if (d_stream.adler != dictId) {
fprintf(stderr, "unexpected dictionary");
exit(1);
}
err = inflateSetDictionary(&d_stream, (const Bytef*)dictionary,
sizeof(dictionary));
}
CHECK_ERR(err, "inflate with dict");
}
err = inflateEnd(&d_stream);
CHECK_ERR(err, "inflateEnd");
if (strcmp((char*)uncompr, hello)) {
fprintf(stderr, "bad inflate with dict\n");
exit(1);
} else {
printf("inflate with dictionary: %s\n", (char *)uncompr);
}
}
/* ===========================================================================
* Usage: example [output.gz [input.gz]]
*/
int main(argc, argv)
int argc;
char *argv[];
{
Byte *compr, *uncompr;
uLong comprLen = 10000*sizeof(int); /* don't overflow on MSDOS */
uLong uncomprLen = comprLen;
static const char* myVersion = ZLIB_VERSION;
if (zlibVersion()[0] != myVersion[0]) {
fprintf(stderr, "incompatible zlib version\n");
exit(1);
} else if (strcmp(zlibVersion(), ZLIB_VERSION) != 0) {
fprintf(stderr, "warning: different zlib version\n");
}
printf("zlib version %s = 0x%04x, compile flags = 0x%lx\n",
ZLIB_VERSION, ZLIB_VERNUM, zlibCompileFlags());
compr = (Byte*)calloc((uInt)comprLen, 1);
uncompr = (Byte*)calloc((uInt)uncomprLen, 1);
/* compr and uncompr are cleared to avoid reading uninitialized
* data and to ensure that uncompr compresses well.
*/
if (compr == Z_NULL || uncompr == Z_NULL) {
printf("out of memory\n");
exit(1);
}
test_compress(compr, comprLen, uncompr, uncomprLen);
test_gzio((argc > 1 ? argv[1] : TESTFILE),
uncompr, uncomprLen);
test_deflate(compr, comprLen);
test_inflate(compr, comprLen, uncompr, uncomprLen);
test_large_deflate(compr, comprLen, uncompr, uncomprLen);
test_large_inflate(compr, comprLen, uncompr, uncomprLen);
test_flush(compr, &comprLen);
test_sync(compr, comprLen, uncompr, uncomprLen);
comprLen = uncomprLen;
test_dict_deflate(compr, comprLen);
test_dict_inflate(compr, comprLen, uncompr, uncomprLen);
free(compr);
free(uncompr);
return 0;
}

File diff suppressed because it is too large Load diff

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