summaryrefslogtreecommitdiff
path: root/utils
diff options
context:
space:
mode:
Diffstat (limited to 'utils')
-rwxr-xr-xutils/zenutils/CMakeLists.txt13
-rwxr-xr-xutils/zenutils/COPYING339
-rwxr-xr-xutils/zenutils/bin/firmware_extract.exebin0 -> 86016 bytes
-rwxr-xr-xutils/zenutils/bin/firmware_make.exebin0 -> 69632 bytes
-rwxr-xr-xutils/zenutils/bin/update_extract.exebin0 -> 163840 bytes
-rwxr-xr-xutils/zenutils/bin/update_patch.exebin0 -> 180224 bytes
-rwxr-xr-xutils/zenutils/bin/zen_crypt.exebin0 -> 81920 bytes
-rwxr-xr-xutils/zenutils/libraries/CMakeLists.txt3
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/CMakeLists.txt14
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/AUTHORS11
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BENCHMARKS73
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BUGS69
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/CONTRIBUTORS19
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING336
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING.LIB504
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/ChangeLog0
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/INSTALL187
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/NEWS184
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README143
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.DLL37
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.WIN3243
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/api.h89
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/beecrypt.h799
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.c137
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.h92
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.c509
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.h132
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfishopt.h82
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.c94
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.h128
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/gnu.h67
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.c123
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.h53
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.c77
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.h60
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/memchunk.h53
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.c1537
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.h691
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpnumber.h115
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpopt.h205
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/rsa.h121
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.c329
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.h120
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1opt.h65
-rwxr-xr-xutils/zenutils/libraries/beecrypt-4.1.2/beecrypt/win.h139
-rwxr-xr-xutils/zenutils/libraries/getpot-c++-1.1.17/getpot/GetPot2433
-rwxr-xr-xutils/zenutils/libraries/getpot-c++-1.1.17/getpot/LPGL.txt504
-rwxr-xr-xutils/zenutils/libraries/getpot-c++-1.1.17/getpot/README50
-rwxr-xr-xutils/zenutils/libraries/getpot-c++-1.1.17/getpot/getpot.hpp2435
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/CMakeLists.txt20
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.cpp511
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.h87
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.cpp467
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.h120
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.cpp383
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.h84
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.cpp692
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.h133
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.cpp179
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.h58
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/ImportDirectory.h1139
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/MzHeader.cpp584
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/MzHeader.h148
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/PeFile.cpp169
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/PeFile.h451
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/PeHeader.cpp90
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/PeHeader.h2685
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/PeLib.h27
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/PeLibAux.cpp275
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/PeLibAux.h884
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/PeLibInc.h32
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/RelocationsDirectory.cpp211
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/RelocationsDirectory.h70
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/ResourceDirectory.cpp1497
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/ResourceDirectory.h735
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/TlsDirectory.h304
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/buffer/InputBuffer.cpp58
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/buffer/InputBuffer.h52
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/buffer/OutputBuffer.cpp41
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/buffer/OutputBuffer.h51
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/changelog.txt321
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/license.htm35
-rwxr-xr-xutils/zenutils/libraries/pelib-0.9/pelib/readme.txt44
-rwxr-xr-xutils/zenutils/libraries/zlib123/CMakeLists.txt19
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/ChangeLog855
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/FAQ339
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/INDEX51
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/Makefile154
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/Makefile.in154
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/README125
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/adler32.c149
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/algorithm.txt209
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/compress.c79
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/configure459
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/crc32.c423
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/crc32.h441
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/deflate.c1736
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/deflate.h331
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/example.c565
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/gzio.c1026
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/infback.c623
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/inffast.c318
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/inffast.h11
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/inffixed.h94
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/inflate.c1368
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/inflate.h115
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/inftrees.c329
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/inftrees.h55
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/make_vms.com461
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/minigzip.c322
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/trees.c1219
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/trees.h128
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/uncompr.c61
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/zconf.h332
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/zconf.in.h332
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/zlib.3159
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/zlib.h1357
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/zutil.c318
-rwxr-xr-xutils/zenutils/libraries/zlib123/zlib/zutil.h269
-rwxr-xr-xutils/zenutils/notes.txt77
-rwxr-xr-xutils/zenutils/source/CMakeLists.txt6
-rwxr-xr-xutils/zenutils/source/firmware_extract/CMakeLists.txt3
-rwxr-xr-xutils/zenutils/source/firmware_extract/main.cpp243
-rwxr-xr-xutils/zenutils/source/firmware_make/CMakeLists.txt3
-rwxr-xr-xutils/zenutils/source/firmware_make/main.cpp261
-rwxr-xr-xutils/zenutils/source/shared/CMakeLists.txt16
-rwxr-xr-xutils/zenutils/source/shared/cenc.cpp333
-rwxr-xr-xutils/zenutils/source/shared/cenc.h29
-rwxr-xr-xutils/zenutils/source/shared/crypt.cpp91
-rwxr-xr-xutils/zenutils/source/shared/crypt.h30
-rwxr-xr-xutils/zenutils/source/shared/file.cpp106
-rwxr-xr-xutils/zenutils/source/shared/file.h36
-rwxr-xr-xutils/zenutils/source/shared/firmware.cpp387
-rwxr-xr-xutils/zenutils/source/shared/firmware.h92
-rwxr-xr-xutils/zenutils/source/shared/pe.cpp128
-rwxr-xr-xutils/zenutils/source/shared/pe.h142
-rwxr-xr-xutils/zenutils/source/shared/shared.cpp0
-rwxr-xr-xutils/zenutils/source/shared/updater.cpp151
-rwxr-xr-xutils/zenutils/source/shared/updater.h32
-rwxr-xr-xutils/zenutils/source/shared/utils.cpp211
-rwxr-xr-xutils/zenutils/source/shared/utils.h68
-rwxr-xr-xutils/zenutils/source/update_extract/CMakeLists.txt3
-rwxr-xr-xutils/zenutils/source/update_extract/main.cpp279
-rwxr-xr-xutils/zenutils/source/update_patch/CMakeLists.txt3
-rwxr-xr-xutils/zenutils/source/update_patch/main.cpp409
-rwxr-xr-xutils/zenutils/source/zen_crypt/CMakeLists.txt4
-rwxr-xr-xutils/zenutils/source/zen_crypt/main.cpp687
147 files changed, 44667 insertions, 0 deletions
diff --git a/utils/zenutils/CMakeLists.txt b/utils/zenutils/CMakeLists.txt
new file mode 100755
index 0000000000..32798747cd
--- /dev/null
+++ b/utils/zenutils/CMakeLists.txt
@@ -0,0 +1,13 @@
1PROJECT(zenutils)
2
3SET(EXECUTABLE_OUTPUT_PATH ${zenutils_SOURCE_DIR}/bin/${CMAKE_SYSTEM_NAME})
4
5SUBDIRS(source libraries)
6
7INCLUDE_DIRECTORIES(
8 ${zenutils_SOURCE_DIR}/libraries/beecrypt-4.1.2
9 ${zenutils_SOURCE_DIR}/libraries/getpot-c++-1.1.17
10 ${zenutils_SOURCE_DIR}/libraries/pelib-0.9
11 ${zenutils_SOURCE_DIR}/libraries/zlib123
12 ${zenutils_SOURCE_DIR}/source/shared
13)
diff --git a/utils/zenutils/COPYING b/utils/zenutils/COPYING
new file mode 100755
index 0000000000..d511905c16
--- /dev/null
+++ b/utils/zenutils/COPYING
@@ -0,0 +1,339 @@
1 GNU GENERAL PUBLIC LICENSE
2 Version 2, June 1991
3
4 Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 Everyone is permitted to copy and distribute verbatim copies
7 of this license document, but changing it is not allowed.
8
9 Preamble
10
11 The licenses for most software are designed to take away your
12freedom to share and change it. By contrast, the GNU General Public
13License is intended to guarantee your freedom to share and change free
14software--to make sure the software is free for all its users. This
15General Public License applies to most of the Free Software
16Foundation's software and to any other program whose authors commit to
17using it. (Some other Free Software Foundation software is covered by
18the GNU Lesser General Public License instead.) You can apply it to
19your programs, too.
20
21 When we speak of free software, we are referring to freedom, not
22price. Our General Public Licenses are designed to make sure that you
23have the freedom to distribute copies of free software (and charge for
24this service if you wish), that you receive source code or can get it
25if you want it, that you can change the software or use pieces of it
26in new free programs; and that you know you can do these things.
27
28 To protect your rights, we need to make restrictions that forbid
29anyone to deny you these rights or to ask you to surrender the rights.
30These restrictions translate to certain responsibilities for you if you
31distribute copies of the software, or if you modify it.
32
33 For example, if you distribute copies of such a program, whether
34gratis or for a fee, you must give the recipients all the rights that
35you have. You must make sure that they, too, receive or can get the
36source code. And you must show them these terms so they know their
37rights.
38
39 We protect your rights with two steps: (1) copyright the software, and
40(2) offer you this license which gives you legal permission to copy,
41distribute and/or modify the software.
42
43 Also, for each author's protection and ours, we want to make certain
44that everyone understands that there is no warranty for this free
45software. If the software is modified by someone else and passed on, we
46want its recipients to know that what they have is not the original, so
47that any problems introduced by others will not reflect on the original
48authors' reputations.
49
50 Finally, any free program is threatened constantly by software
51patents. We wish to avoid the danger that redistributors of a free
52program will individually obtain patent licenses, in effect making the
53program proprietary. To prevent this, we have made it clear that any
54patent must be licensed for everyone's free use or not licensed at all.
55
56 The precise terms and conditions for copying, distribution and
57modification follow.
58
59 GNU GENERAL PUBLIC LICENSE
60 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61
62 0. This License applies to any program or other work which contains
63a notice placed by the copyright holder saying it may be distributed
64under the terms of this General Public License. The "Program", below,
65refers to any such program or work, and a "work based on the Program"
66means either the Program or any derivative work under copyright law:
67that is to say, a work containing the Program or a portion of it,
68either verbatim or with modifications and/or translated into another
69language. (Hereinafter, translation is included without limitation in
70the term "modification".) Each licensee is addressed as "you".
71
72Activities other than copying, distribution and modification are not
73covered by this License; they are outside its scope. The act of
74running the Program is not restricted, and the output from the Program
75is covered only if its contents constitute a work based on the
76Program (independent of having been made by running the Program).
77Whether that is true depends on what the Program does.
78
79 1. You may copy and distribute verbatim copies of the Program's
80source code as you receive it, in any medium, provided that you
81conspicuously and appropriately publish on each copy an appropriate
82copyright notice and disclaimer of warranty; keep intact all the
83notices that refer to this License and to the absence of any warranty;
84and give any other recipients of the Program a copy of this License
85along with the Program.
86
87You may charge a fee for the physical act of transferring a copy, and
88you may at your option offer warranty protection in exchange for a fee.
89
90 2. You may modify your copy or copies of the Program or any portion
91of it, thus forming a work based on the Program, and copy and
92distribute such modifications or work under the terms of Section 1
93above, provided that you also meet all of these conditions:
94
95 a) You must cause the modified files to carry prominent notices
96 stating that you changed the files and the date of any change.
97
98 b) You must cause any work that you distribute or publish, that in
99 whole or in part contains or is derived from the Program or any
100 part thereof, to be licensed as a whole at no charge to all third
101 parties under the terms of this License.
102
103 c) If the modified program normally reads commands interactively
104 when run, you must cause it, when started running for such
105 interactive use in the most ordinary way, to print or display an
106 announcement including an appropriate copyright notice and a
107 notice that there is no warranty (or else, saying that you provide
108 a warranty) and that users may redistribute the program under
109 these conditions, and telling the user how to view a copy of this
110 License. (Exception: if the Program itself is interactive but
111 does not normally print such an announcement, your work based on
112 the Program is not required to print an announcement.)
113
114These requirements apply to the modified work as a whole. If
115identifiable sections of that work are not derived from the Program,
116and can be reasonably considered independent and separate works in
117themselves, then this License, and its terms, do not apply to those
118sections when you distribute them as separate works. But when you
119distribute the same sections as part of a whole which is a work based
120on the Program, the distribution of the whole must be on the terms of
121this License, whose permissions for other licensees extend to the
122entire whole, and thus to each and every part regardless of who wrote it.
123
124Thus, it is not the intent of this section to claim rights or contest
125your rights to work written entirely by you; rather, the intent is to
126exercise the right to control the distribution of derivative or
127collective works based on the Program.
128
129In addition, mere aggregation of another work not based on the Program
130with the Program (or with a work based on the Program) on a volume of
131a storage or distribution medium does not bring the other work under
132the scope of this License.
133
134 3. You may copy and distribute the Program (or a work based on it,
135under Section 2) in object code or executable form under the terms of
136Sections 1 and 2 above provided that you also do one of the following:
137
138 a) Accompany it with the complete corresponding machine-readable
139 source code, which must be distributed under the terms of Sections
140 1 and 2 above on a medium customarily used for software interchange; or,
141
142 b) Accompany it with a written offer, valid for at least three
143 years, to give any third party, for a charge no more than your
144 cost of physically performing source distribution, a complete
145 machine-readable copy of the corresponding source code, to be
146 distributed under the terms of Sections 1 and 2 above on a medium
147 customarily used for software interchange; or,
148
149 c) Accompany it with the information you received as to the offer
150 to distribute corresponding source code. (This alternative is
151 allowed only for noncommercial distribution and only if you
152 received the program in object code or executable form with such
153 an offer, in accord with Subsection b above.)
154
155The source code for a work means the preferred form of the work for
156making modifications to it. For an executable work, complete source
157code means all the source code for all modules it contains, plus any
158associated interface definition files, plus the scripts used to
159control compilation and installation of the executable. However, as a
160special exception, the source code distributed need not include
161anything that is normally distributed (in either source or binary
162form) with the major components (compiler, kernel, and so on) of the
163operating system on which the executable runs, unless that component
164itself accompanies the executable.
165
166If distribution of executable or object code is made by offering
167access to copy from a designated place, then offering equivalent
168access to copy the source code from the same place counts as
169distribution of the source code, even though third parties are not
170compelled to copy the source along with the object code.
171
172 4. You may not copy, modify, sublicense, or distribute the Program
173except as expressly provided under this License. Any attempt
174otherwise to copy, modify, sublicense or distribute the Program is
175void, and will automatically terminate your rights under this License.
176However, parties who have received copies, or rights, from you under
177this License will not have their licenses terminated so long as such
178parties remain in full compliance.
179
180 5. You are not required to accept this License, since you have not
181signed it. However, nothing else grants you permission to modify or
182distribute the Program or its derivative works. These actions are
183prohibited by law if you do not accept this License. Therefore, by
184modifying or distributing the Program (or any work based on the
185Program), you indicate your acceptance of this License to do so, and
186all its terms and conditions for copying, distributing or modifying
187the Program or works based on it.
188
189 6. Each time you redistribute the Program (or any work based on the
190Program), the recipient automatically receives a license from the
191original licensor to copy, distribute or modify the Program subject to
192these terms and conditions. You may not impose any further
193restrictions on the recipients' exercise of the rights granted herein.
194You are not responsible for enforcing compliance by third parties to
195this License.
196
197 7. If, as a consequence of a court judgment or allegation of patent
198infringement or for any other reason (not limited to patent issues),
199conditions are imposed on you (whether by court order, agreement or
200otherwise) that contradict the conditions of this License, they do not
201excuse you from the conditions of this License. If you cannot
202distribute so as to satisfy simultaneously your obligations under this
203License and any other pertinent obligations, then as a consequence you
204may not distribute the Program at all. For example, if a patent
205license would not permit royalty-free redistribution of the Program by
206all those who receive copies directly or indirectly through you, then
207the only way you could satisfy both it and this License would be to
208refrain entirely from distribution of the Program.
209
210If any portion of this section is held invalid or unenforceable under
211any particular circumstance, the balance of the section is intended to
212apply and the section as a whole is intended to apply in other
213circumstances.
214
215It is not the purpose of this section to induce you to infringe any
216patents or other property right claims or to contest validity of any
217such claims; this section has the sole purpose of protecting the
218integrity of the free software distribution system, which is
219implemented by public license practices. Many people have made
220generous contributions to the wide range of software distributed
221through that system in reliance on consistent application of that
222system; it is up to the author/donor to decide if he or she is willing
223to distribute software through any other system and a licensee cannot
224impose that choice.
225
226This section is intended to make thoroughly clear what is believed to
227be a consequence of the rest of this License.
228
229 8. If the distribution and/or use of the Program is restricted in
230certain countries either by patents or by copyrighted interfaces, the
231original copyright holder who places the Program under this License
232may add an explicit geographical distribution limitation excluding
233those countries, so that distribution is permitted only in or among
234countries not thus excluded. In such case, this License incorporates
235the limitation as if written in the body of this License.
236
237 9. The Free Software Foundation may publish revised and/or new versions
238of the General Public License from time to time. Such new versions will
239be similar in spirit to the present version, but may differ in detail to
240address new problems or concerns.
241
242Each version is given a distinguishing version number. If the Program
243specifies a version number of this License which applies to it and "any
244later version", you have the option of following the terms and conditions
245either of that version or of any later version published by the Free
246Software Foundation. If the Program does not specify a version number of
247this License, you may choose any version ever published by the Free Software
248Foundation.
249
250 10. If you wish to incorporate parts of the Program into other free
251programs whose distribution conditions are different, write to the author
252to ask for permission. For software which is copyrighted by the Free
253Software Foundation, write to the Free Software Foundation; we sometimes
254make exceptions for this. Our decision will be guided by the two goals
255of preserving the free status of all derivatives of our free software and
256of promoting the sharing and reuse of software generally.
257
258 NO WARRANTY
259
260 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268REPAIR OR CORRECTION.
269
270 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278POSSIBILITY OF SUCH DAMAGES.
279
280 END OF TERMS AND CONDITIONS
281
282 How to Apply These Terms to Your New Programs
283
284 If you develop a new program, and you want it to be of the greatest
285possible use to the public, the best way to achieve this is to make it
286free software which everyone can redistribute and change under these terms.
287
288 To do so, attach the following notices to the program. It is safest
289to attach them to the start of each source file to most effectively
290convey the exclusion of warranty; and each file should have at least
291the "copyright" line and a pointer to where the full notice is found.
292
293 <one line to give the program's name and a brief idea of what it does.>
294 Copyright (C) <year> <name of author>
295
296 This program is free software; you can redistribute it and/or modify
297 it under the terms of the GNU General Public License as published by
298 the Free Software Foundation; either version 2 of the License, or
299 (at your option) any later version.
300
301 This program is distributed in the hope that it will be useful,
302 but WITHOUT ANY WARRANTY; without even the implied warranty of
303 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 GNU General Public License for more details.
305
306 You should have received a copy of the GNU General Public License along
307 with this program; if not, write to the Free Software Foundation, Inc.,
308 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309
310Also add information on how to contact you by electronic and paper mail.
311
312If the program is interactive, make it output a short notice like this
313when it starts in an interactive mode:
314
315 Gnomovision version 69, Copyright (C) year name of author
316 Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 This is free software, and you are welcome to redistribute it
318 under certain conditions; type `show c' for details.
319
320The hypothetical commands `show w' and `show c' should show the appropriate
321parts of the General Public License. Of course, the commands you use may
322be called something other than `show w' and `show c'; they could even be
323mouse-clicks or menu items--whatever suits your program.
324
325You should also get your employer (if you work as a programmer) or your
326school, if any, to sign a "copyright disclaimer" for the program, if
327necessary. Here is a sample; alter the names:
328
329 Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 `Gnomovision' (which makes passes at compilers) written by James Hacker.
331
332 <signature of Ty Coon>, 1 April 1989
333 Ty Coon, President of Vice
334
335This General Public License does not permit incorporating your program into
336proprietary programs. If your program is a subroutine library, you may
337consider it more useful to permit linking proprietary applications with the
338library. If this is what you want to do, use the GNU Lesser General
339Public License instead of this License.
diff --git a/utils/zenutils/bin/firmware_extract.exe b/utils/zenutils/bin/firmware_extract.exe
new file mode 100755
index 0000000000..834adefc30
--- /dev/null
+++ b/utils/zenutils/bin/firmware_extract.exe
Binary files differ
diff --git a/utils/zenutils/bin/firmware_make.exe b/utils/zenutils/bin/firmware_make.exe
new file mode 100755
index 0000000000..df62304226
--- /dev/null
+++ b/utils/zenutils/bin/firmware_make.exe
Binary files differ
diff --git a/utils/zenutils/bin/update_extract.exe b/utils/zenutils/bin/update_extract.exe
new file mode 100755
index 0000000000..752cf2d083
--- /dev/null
+++ b/utils/zenutils/bin/update_extract.exe
Binary files differ
diff --git a/utils/zenutils/bin/update_patch.exe b/utils/zenutils/bin/update_patch.exe
new file mode 100755
index 0000000000..c3a6a808bf
--- /dev/null
+++ b/utils/zenutils/bin/update_patch.exe
Binary files differ
diff --git a/utils/zenutils/bin/zen_crypt.exe b/utils/zenutils/bin/zen_crypt.exe
new file mode 100755
index 0000000000..a5dce080de
--- /dev/null
+++ b/utils/zenutils/bin/zen_crypt.exe
Binary files differ
diff --git a/utils/zenutils/libraries/CMakeLists.txt b/utils/zenutils/libraries/CMakeLists.txt
new file mode 100755
index 0000000000..19297d7a2e
--- /dev/null
+++ b/utils/zenutils/libraries/CMakeLists.txt
@@ -0,0 +1,3 @@
1ADD_SUBDIRECTORY(beecrypt-4.1.2)
2ADD_SUBDIRECTORY(pelib-0.9)
3ADD_SUBDIRECTORY(zlib123)
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/CMakeLists.txt b/utils/zenutils/libraries/beecrypt-4.1.2/CMakeLists.txt
new file mode 100755
index 0000000000..83836af99d
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/CMakeLists.txt
@@ -0,0 +1,14 @@
1PROJECT(beecrypt)
2
3# source files for beecrypt
4SET(beecrypt_srcs
5 beecrypt/blockmode.c
6 beecrypt/blowfish.c
7 beecrypt/endianness.c
8 beecrypt/hmac.c
9 beecrypt/hmacsha1.c
10 beecrypt/mp.c
11 beecrypt/sha1.c
12)
13
14ADD_LIBRARY(beecrypt ${beecrypt_srcs})
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/AUTHORS b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/AUTHORS
new file mode 100755
index 0000000000..878abf5a3f
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/AUTHORS
@@ -0,0 +1,11 @@
1BeeCrypt Cryptograpy Library:
2
3Bob Deblier <bob.deblier@pandora.be>
4
5C++ Interface:
6
7Bob Deblier <bob.deblier@pandora.be>
8
9Python Interface:
10
11Jeff Johson <jbj@redhat.com>
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BENCHMARKS b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BENCHMARKS
new file mode 100755
index 0000000000..7919f340db
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BENCHMARKS
@@ -0,0 +1,73 @@
1Note: timings are average values and may vary under different conditions,
2i.e. the amount of free memory, swapped memory, amount of cpu cache, etc.
3I've tried to make them as accurate as possible, within limits.
4
5Note: many of the testing systems were provided by HP's testdrive program;
6many thanks to them for giving me access to their systems. Also thanks to
7SourceForge for their compile farm!
8
9Note: to avoid religious wars, in the table below read GNU/Linux for
10Linux - I'm just a little cramped for space...
11
12BENCHmark Modular Exponentation (more is better):
13
14BeeCrypt 4.0.0 | gcc-3.3.3 | Fedora Core 2 | Athlon 64 3000+| 1 GB: 24870
15BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 24566
16BeeCrypt 4.0.0 | gcc-3.2.2 | SuSE 8 EL | Opteron 1600 | 1 GB: 19460
17BeeCrypt 3.0.0 | gcc-3.x | RedHat Linux | Opteron MP 1600 | : 17230
18BeeCrypt 3.1.0 | gcc-2.96 | RedHat AS 2.1 | Itanium 2 1400 | 1 GB: 11453
19BeeCrypt 3.0.0 | gcc-3.2.2 | Debian Linux 3.0 | Itanium 2 900 | 12 GB: 7317
20BeeCrypt 3.0.0 | gcc-3.3 | RedHat AS 2.1 | P4 Xeon 2400 | 4 GB: 6920 [--with-arch=pentium4]
21BeeCrypt 4.1.0 | gcc-3.3.3 | Fedora Core 2 | P4 Xeon 2400 | 1 GB: 6811 [--with-arch=pentium4]
22BeeCrypt 4.1.0 | gcc-3.3.3 | SuSE Enterprise 9 | POWER4 1000 | 16 GB: 5858
23BeeCrypt 3.0.0 | gcc-2.95.4 | Debian Linux 3.0 | Alpha EV6.7 666 | 2 GB: 5742
24BeeCrypt 3.0.0 | gcc-2.96 | RedHat AS 2.1 | P4 Xeon 2400 | 4 GB: 3280 [--with-arch=pentiumpro]
25BeeCrypt 3.0.0 | gcc-3.x | RedHat Linux | POWER4+ 1200 | : 2592
26BeeCrypt 3.0.0 | gcc-3.x | RedHat Linux | P3 Xeon 900 | : 2169
27BeeCrypt 3.0.0 | gcc-3.2.2 | AIX 5.1 | POWER3-II 333 | 512 MB: 1782 [--with-arch=powerpc64]
28BeeCrypt 3.0.0 | gcc-3.x | RedHat Linux | zSeries 900 | : 1687 (s390x)
29BeeCrypt 3.0.0 | gcc-3.3 | SuSE Linux 8.2 | Pentium 3 600 | 512 MB: 1447 [--with-arch=pentium3]
30BeeCrypt 3.0.0 | gcc-3.2.2 | AIX 5.1 | POWER3-II 333 | 512 MB: 756
31BeeCrypt 3.0.0 | Forte C 5.1 | Solaris 8 | UltraSparc II 400 | 4 GB: 425 [--with-arch=sparcv8plus]
32BeeCrypt 3.0.0 | | Debian Linux 3.0 | StrongARM 1110 128 | 32 MB: 341
33BeeCrypt 3.0.0 | gcc-2.95.4 | Debian Linux 3.0r1 | M68040 33 | 52 MB: 24
34BeeCrypt 3.0.0 | gcc-2.95.4 | Debian Linux 3.0r1 | M68030 25 | 36 MB: 8
35
36BENCHmark Hash Function (more is better):
37
38MD5
39BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 190.5 MB/s
40BeeCrypt 3.0.0 | gcc-2.96 | RedHat AS 2.1 | P4 Xeon 2400 | 4 GB: 137.0 MB/s [--with-arch=pentiumpro]
41BeeCrypt 4.1.0 | gcc-3.3.3 | Fedora Core 2 | P4 Xeon 2400 | 1 GB: 97.2 MB/s [--with-arch=pentium4]
42BeeCrypt 4.1.0 | gcc-3.3.3 | SuSE Enterprise 9 | POWER4 1000 | 16 GB: 38.8 MB/s
43
44SHA-1
45BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 117.4 MB/s
46BeeCrypt 4.1.0 | gcc-3.3.3 | Fedora Core 2 | P4 Xeon 2400 | 1 GB: 81.9 MB/s [--with-arch=pentium4]
47BeeCrypt 3.0.0 | gcc-2.96 | RedHat AS 2.1 | P4 Xeon 2400 | 4 GB: 77.0 MB/s [--with-arch=pentiumpro]
48BeeCrypt 4.1.0 | gcc-3.3.3 | SuSE Enterprise 9 | POWER4 1000 | 16 GB: 51.2 MB/s
49
50SHA-256
51BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 85.1 MB/s
52BeeCrypt 4.1.0 | gcc-3.3.3 | Fedora Core 2 | P4 Xeon 2400 | 1 GB: 42.4 MB/s [--with-arch=pentium4]
53BeeCrypt 3.0.0 | gcc-2.96 | RedHat AS 2.1 | P4 Xeon 2400 | 4 GB: 37.8 MB/s [--with-arch=pentiumpro]
54BeeCrypt 4.1.0 | gcc-3.3.3 | SuSE Enterprise 9 | POWER4 1000 | 16 GB: 33.0 MB/s
55
56SHA-512
57BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 129.6 MB/s
58BeeCrypt 4.1.0 | gcc-3.3.3 | SuSE Enterprise 9 | POWER4 1000 | 16 GB: 57.6 MB/s
59BeeCrypt 4.1.0 | gcc-3.3.3 | Fedora Core 2 | P4 Xeon 2400 | 1 GB: 46.3 MB/s [--with-arch=pentium4]
60
61BENCHmark Block Cipher (more is better):
62
63AES, 128 bits
64BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 97.0 MB/s [ECB encrypt]
65BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 93.5 MB/s [CBC encrypt]
66BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 104.6 MB/s [ECB decrypt]
67BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 99.2 MB/s [CBC decrypt]
68
69Blowfish, 128 bits
70BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 59.4 MB/s [ECB encrypt]
71BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 57.7 MB/s [CBC encrypt]
72BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 61.4 MB/s [ECB decrypt]
73BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 59.3 MB/s [CBC decrypt]
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BUGS b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BUGS
new file mode 100755
index 0000000000..577c5adac5
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BUGS
@@ -0,0 +1,69 @@
1Legend:
2 - = open bug
3 * = fixed bug
4
54.1.0:
6 - SuSE 9.2 (x86) compiler is buggy: the MMX-optimized version fails all
7 test vectors. Since all other Linux distro's handle this perfectly it's
8 up to them to fix this bug.
9
103.1.0:
11 * Error in final result computation of mpextgcd_w in certain circumstances.
12 * PowerPC 64-bit assembler symbols aren't defined according to LSB 1.3.
13
143.0.0:
15 - Can't seem to generate 64-bit shared libraries on AIX; use
16 --disable-shared on this platform for now.
17 - Intel icc can't cope with gcj headers. There's also a problem in
18 combination with aio.h; solution should be to not test gcj when using
19 this compiler. As a workaround, you can specify --without-javaglue.
20 - GCC 3.3 produces faster output for Blowfish on Pentium 4 than the
21 included assembler source; try coding two Blowfish rounds (without swap)
22 in C and compile to assembler to see how GCC accomplishes this.
23
242.3.0pre:
25 * bug in certain instances of computing modular inverse.
26 * incorrectly translated intel-style assembler version of x86 mp32odd
27 and mp32even routines into gnu assembler format.
28 * base64 decoding of '+' and '/' characters is wrong.
29 * incorrect testing of the result of the gcd operation in mp32prndconone.
30 * Chinese Remainer Theorem for RSA private key operation doesn't work
31 * incorrect header file inclusion when --disable-threads is selected or
32 when no multithreading is available.
33
342.2.0:
35 [ Released by Jeff Johnson of RedHat, Inc.; lint & doxygen enhanced version
36 of 2.1.0. ]
37
382.1.0:
39 * Entropy gathering from /dev/dsp contained error; size in words of entropy
40 data to gather was overwritten with audio sample size - which resulted in
41 much less entropy.
42
432.0.0:
44 - Chinese Remainder Theorem for RSA private key operation doesn't work; it
45 needs fixing.
46
471.1.2:
48 * SHA-1 i586 assembler code uses local variables below the current stack
49 frame.
50
511.1.1:
52 * discrete logarithm domain parameter generator calculations contains bugs
53 - was detected in this release but present since the first release.
54
551.1.0:
56 * The javaglue produces a NullPointerException when initializing with a
57 null IV; this should be treated correctly, i.e. as an all zero IV.
58
591.0.2:
60
611.0.1:
62 * The Windows 2000 bug is still around
63
641.0.0:
65 * On Windows 2000, the entropy system gets error WAVERR_BADFORMAT in
66 waveInOpen; So far I've been unable to determine why the system does this
67 for format WAVE_FORMAT_PCM. Suggestions to fix this problem are more than
68 welcome.
69 * The assembler code for SHA-1 in gnu/fips180opt.gas.i586.s contains bugs.
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/CONTRIBUTORS b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/CONTRIBUTORS
new file mode 100755
index 0000000000..7f61011475
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/CONTRIBUTORS
@@ -0,0 +1,19 @@
1I would like to thank the following people (in alphabetical order):
2
3- Seth Arnold, for contributing to the documentation.
4- Jan-Rudolph Bührmann, for helping me get started on the 64-bit multi-
5 precision integer library.
6- Luca Filipozzi, maintainer/packager of BeeCrypt for Debian GNU/Linux.
7- Jeff Johnson, the guy behind RedHat's Package Manager, who has inspired
8 and contributed to many of the changes for version 3.0.0; 73 de Bob.
9- Jon Sturgeon, bug hunter extraordinaire.
10
11Further thanks go to:
12- AMD, for donating a copy of "AMD x86-64 Architecture Programmer's Manual".
13- ARM Ltd, for donating a copy of "ARM Architecture Reference Manual".
14- HP/Compaq, for their testdrive program, which gave me the opportunity to
15 test and BeeCrypt on many new platforms.
16- SourceForge, for their excellent open source development platform!
17
18Last but not least: thanks to everyone who provided bits of information,
19reported bugs and provided feedback.
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING
new file mode 100755
index 0000000000..a6d7d0188a
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING
@@ -0,0 +1,336 @@
1 GNU GENERAL PUBLIC LICENSE
2 Version 2, June 1991
3
4 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
5 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
6 Everyone is permitted to copy and distribute verbatim copies
7 of this license document, but changing it is not allowed.
8
9 Preamble
10
11 The licenses for most software are designed to take away your
12freedom to share and change it. By contrast, the GNU General Public
13License is intended to guarantee your freedom to share and change free
14software--to make sure the software is free for all its users. This
15General Public License applies to most of the Free Software
16Foundation's software and to any other program whose authors commit to
17using it. (Some other Free Software Foundation software is covered by
18the GNU Library General Public License instead.) You can apply it to
19your programs, too.
20
21 When we speak of free software, we are referring to freedom, not
22price. Our General Public Licenses are designed to make sure that you
23have the freedom to distribute copies of free software (and charge for
24this service if you wish), that you receive source code or can get it
25if you want it, that you can change the software or use pieces of it
26in new free programs; and that you know you can do these things.
27
28 To protect your rights, we need to make restrictions that forbid
29anyone to deny you these rights or to ask you to surrender the rights.
30These restrictions translate to certain responsibilities for you if you
31distribute copies of the software, or if you modify it.
32
33 For example, if you distribute copies of such a program, whether
34gratis or for a fee, you must give the recipients all the rights that
35you have. You must make sure that they, too, receive or can get the
36source code. And you must show them these terms so they know their
37rights.
38
39 We protect your rights with two steps: (1) copyright the software, and
40(2) offer you this license which gives you legal permission to copy,
41distribute and/or modify the software.
42
43 Also, for each author's protection and ours, we want to make certain
44that everyone understands that there is no warranty for this free
45software. If the software is modified by someone else and passed on, we
46want its recipients to know that what they have is not the original, so
47that any problems introduced by others will not reflect on the original
48authors' reputations.
49
50 Finally, any free program is threatened constantly by software
51patents. We wish to avoid the danger that redistributors of a free
52program will individually obtain patent licenses, in effect making the
53program proprietary. To prevent this, we have made it clear that any
54patent must be licensed for everyone's free use or not licensed at all.
55
56 The precise terms and conditions for copying, distribution and
57modification follow.
58
59 GNU GENERAL PUBLIC LICENSE
60 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61
62 0. This License applies to any program or other work which contains
63a notice placed by the copyright holder saying it may be distributed
64under the terms of this General Public License. The "Program", below,
65refers to any such program or work, and a "work based on the Program"
66means either the Program or any derivative work under copyright law:
67that is to say, a work containing the Program or a portion of it,
68either verbatim or with modifications and/or translated into another
69language. (Hereinafter, translation is included without limitation in
70the term "modification".) Each licensee is addressed as "you".
71
72Activities other than copying, distribution and modification are not
73covered by this License; they are outside its scope. The act of
74running the Program is not restricted, and the output from the Program
75is covered only if its contents constitute a work based on the
76Program (independent of having been made by running the Program).
77Whether that is true depends on what the Program does.
78
79 1. You may copy and distribute verbatim copies of the Program's
80source code as you receive it, in any medium, provided that you
81conspicuously and appropriately publish on each copy an appropriate
82copyright notice and disclaimer of warranty; keep intact all the
83notices that refer to this License and to the absence of any warranty;
84and give any other recipients of the Program a copy of this License
85along with the Program.
86
87You may charge a fee for the physical act of transferring a copy, and
88you may at your option offer warranty protection in exchange for a fee.
89
90 2. You may modify your copy or copies of the Program or any portion
91of it, thus forming a work based on the Program, and copy and
92distribute such modifications or work under the terms of Section 1
93above, provided that you also meet all of these conditions:
94
95 a) You must cause the modified files to carry prominent notices
96 stating that you changed the files and the date of any change.
97
98 b) You must cause any work that you distribute or publish, that in
99 whole or in part contains or is derived from the Program or any
100 part thereof, to be licensed as a whole at no charge to all third
101 parties under the terms of this License.
102
103 c) If the modified program normally reads commands interactively
104 when run, you must cause it, when started running for such
105 interactive use in the most ordinary way, to print or display an
106 announcement including an appropriate copyright notice and a
107 notice that there is no warranty (or else, saying that you provide
108 a warranty) and that users may redistribute the program under
109 these conditions, and telling the user how to view a copy of this
110 License. (Exception: if the Program itself is interactive but
111 does not normally print such an announcement, your work based on
112 the Program is not required to print an announcement.)
113
114These requirements apply to the modified work as a whole. If
115identifiable sections of that work are not derived from the Program,
116and can be reasonably considered independent and separate works in
117themselves, then this License, and its terms, do not apply to those
118sections when you distribute them as separate works. But when you
119distribute the same sections as part of a whole which is a work based
120on the Program, the distribution of the whole must be on the terms of
121this License, whose permissions for other licensees extend to the
122entire whole, and thus to each and every part regardless of who wrote it.
123
124Thus, it is not the intent of this section to claim rights or contest
125your rights to work written entirely by you; rather, the intent is to
126exercise the right to control the distribution of derivative or
127collective works based on the Program.
128
129In addition, mere aggregation of another work not based on the Program
130with the Program (or with a work based on the Program) on a volume of
131a storage or distribution medium does not bring the other work under
132the scope of this License.
133
134 3. You may copy and distribute the Program (or a work based on it,
135under Section 2) in object code or executable form under the terms of
136Sections 1 and 2 above provided that you also do one of the following:
137
138 a) Accompany it with the complete corresponding machine-readable
139 source code, which must be distributed under the terms of Sections
140 1 and 2 above on a medium customarily used for software interchange; or,
141
142 b) Accompany it with a written offer, valid for at least three
143 years, to give any third party, for a charge no more than your
144 cost of physically performing source distribution, a complete
145 machine-readable copy of the corresponding source code, to be
146 distributed under the terms of Sections 1 and 2 above on a medium
147 customarily used for software interchange; or,
148
149 c) Accompany it with the information you received as to the offer
150 to distribute corresponding source code. (This alternative is
151 allowed only for noncommercial distribution and only if you
152 received the program in object code or executable form with such
153 an offer, in accord with Subsection b above.)
154
155The source code for a work means the preferred form of the work for
156making modifications to it. For an executable work, complete source
157code means all the source code for all modules it contains, plus any
158associated interface definition files, plus the scripts used to
159control compilation and installation of the executable. However, as a
160special exception, the source code distributed need not include
161anything that is normally distributed (in either source or binary
162form) with the major components (compiler, kernel, and so on) of the
163operating system on which the executable runs, unless that component
164itself accompanies the executable.
165
166If distribution of executable or object code is made by offering
167access to copy from a designated place, then offering equivalent
168access to copy the source code from the same place counts as
169distribution of the source code, even though third parties are not
170compelled to copy the source along with the object code.
171
172 4. You may not copy, modify, sublicense, or distribute the Program
173except as expressly provided under this License. Any attempt
174otherwise to copy, modify, sublicense or distribute the Program is
175void, and will automatically terminate your rights under this License.
176However, parties who have received copies, or rights, from you under
177this License will not have their licenses terminated so long as such
178parties remain in full compliance.
179
180 5. You are not required to accept this License, since you have not
181signed it. However, nothing else grants you permission to modify or
182distribute the Program or its derivative works. These actions are
183prohibited by law if you do not accept this License. Therefore, by
184modifying or distributing the Program (or any work based on the
185Program), you indicate your acceptance of this License to do so, and
186all its terms and conditions for copying, distributing or modifying
187the Program or works based on it.
188
189 6. Each time you redistribute the Program (or any work based on the
190Program), the recipient automatically receives a license from the
191original licensor to copy, distribute or modify the Program subject to
192these terms and conditions. You may not impose any further
193restrictions on the recipients' exercise of the rights granted herein.
194You are not responsible for enforcing compliance by third parties to
195this License.
196
197 7. If, as a consequence of a court judgment or allegation of patent
198infringement or for any other reason (not limited to patent issues),
199conditions are imposed on you (whether by court order, agreement or
200otherwise) that contradict the conditions of this License, they do not
201excuse you from the conditions of this License. If you cannot
202distribute so as to satisfy simultaneously your obligations under this
203License and any other pertinent obligations, then as a consequence you
204may not distribute the Program at all. For example, if a patent
205license would not permit royalty-free redistribution of the Program by
206all those who receive copies directly or indirectly through you, then
207the only way you could satisfy both it and this License would be to
208refrain entirely from distribution of the Program.
209
210If any portion of this section is held invalid or unenforceable under
211any particular circumstance, the balance of the section is intended to
212apply and the section as a whole is intended to apply in other
213circumstances.
214
215It is not the purpose of this section to induce you to infringe any
216patents or other property right claims or to contest validity of any
217such claims; this section has the sole purpose of protecting the
218integrity of the free software distribution system, which is
219implemented by public license practices. Many people have made
220generous contributions to the wide range of software distributed
221through that system in reliance on consistent application of that
222system; it is up to the author/donor to decide if he or she is willing
223to distribute software through any other system and a licensee cannot
224impose that choice.
225
226This section is intended to make thoroughly clear what is believed to
227be a consequence of the rest of this License.
228
229 8. If the distribution and/or use of the Program is restricted in
230certain countries either by patents or by copyrighted interfaces, the
231original copyright holder who places the Program under this License
232may add an explicit geographical distribution limitation excluding
233those countries, so that distribution is permitted only in or among
234countries not thus excluded. In such case, this License incorporates
235the limitation as if written in the body of this License.
236
237 9. The Free Software Foundation may publish revised and/or new versions
238of the General Public License from time to time. Such new versions will
239be similar in spirit to the present version, but may differ in detail to
240address new problems or concerns.
241
242Each version is given a distinguishing version number. If the Program
243specifies a version number of this License which applies to it and "any
244later version", you have the option of following the terms and conditions
245either of that version or of any later version published by the Free
246Software Foundation. If the Program does not specify a version number of
247this License, you may choose any version ever published by the Free Software
248Foundation.
249
250 10. If you wish to incorporate parts of the Program into other free
251programs whose distribution conditions are different, write to the author
252to ask for permission. For software which is copyrighted by the Free
253Software Foundation, write to the Free Software Foundation; we sometimes
254make exceptions for this. Our decision will be guided by the two goals
255of preserving the free status of all derivatives of our free software and
256of promoting the sharing and reuse of software generally.
257
258 NO WARRANTY
259
260 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268REPAIR OR CORRECTION.
269
270 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278POSSIBILITY OF SUCH DAMAGES.
279
280 END OF TERMS AND CONDITIONS
281
282 How to Apply These Terms to Your New Programs
283
284 If you develop a new program, and you want it to be of the greatest
285possible use to the public, the best way to achieve this is to make it
286free software which everyone can redistribute and change under these terms.
287
288 To do so, attach the following notices to the program. It is safest
289to attach them to the start of each source file to most effectively
290convey the exclusion of warranty; and each file should have at least
291the "copyright" line and a pointer to where the full notice is found.
292
293 <one line to give the program's name and a brief idea of what it does.>
294 Copyright (C) <year> <name of author>
295
296 This program is free software; you can redistribute it and/or modify
297 it under the terms of the GNU General Public License as published by
298 the Free Software Foundation; either version 2 of the License, or
299 (at your option) any later version.
300
301 This program is distributed in the hope that it will be useful,
302 but WITHOUT ANY WARRANTY; without even the implied warranty of
303 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 GNU General Public License for more details.
305
306 You should have received a copy of the GNU General Public License
307 along with this program; if not, write to the Free Software
308 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
309
310
311Also add information on how to contact you by electronic and paper mail.
312
313If the program is interactive, make it output a short notice like this
314when it starts in an interactive mode:
315
316 Gnomovision version 69, Copyright (C) year name of author
317 Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
318 This is free software, and you are welcome to redistribute it
319 under certain conditions; type `show c' for details.
320
321The hypothetical commands `show w' and `show c' should show the appropriate
322parts of the General Public License. Of course, the commands you use may
323be called something other than `show w' and `show c'; they could even be
324mouse-clicks or menu items--whatever suits your program.
325
326You should also get your employer (if you work as a programmer) or your
327school, if any, to sign a "copyright disclaimer" for the program, if
328necessary. Hereny it with the complete corresponding machine-readable
329 source code, which must be distributed under the terms of Sections
330 1 and 2 above on a medium customarily used for software interchange; or,
331
332 b) Accompany it with a written offer, valid for at least three
333 years, to give any third party, for a charge no more than your
334 cost of physically performing source distribution, a complete
335 machine-readable copy of the corresponding source code, to be
336 distributed under the terms of Section
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING.LIB b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING.LIB
new file mode 100755
index 0000000000..223ede7de3
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING.LIB
@@ -0,0 +1,504 @@
1 GNU LESSER GENERAL PUBLIC LICENSE
2 Version 2.1, February 1999
3
4 Copyright (C) 1991, 1999 Free Software Foundation, Inc.
5 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
6 Everyone is permitted to copy and distribute verbatim copies
7 of this license document, but changing it is not allowed.
8
9[This is the first released version of the Lesser GPL. It also counts
10 as the successor of the GNU Library Public License, version 2, hence
11 the version number 2.1.]
12
13 Preamble
14
15 The licenses for most software are designed to take away your
16freedom to share and change it. By contrast, the GNU General Public
17Licenses are intended to guarantee your freedom to share and change
18free software--to make sure the software is free for all its users.
19
20 This license, the Lesser General Public License, applies to some
21specially designated software packages--typically libraries--of the
22Free Software Foundation and other authors who decide to use it. You
23can use it too, but we suggest you first think carefully about whether
24this license or the ordinary General Public License is the better
25strategy to use in any particular case, based on the explanations below.
26
27 When we speak of free software, we are referring to freedom of use,
28not price. Our General Public Licenses are designed to make sure that
29you have the freedom to distribute copies of free software (and charge
30for this service if you wish); that you receive source code or can get
31it if you want it; that you can change the software and use pieces of
32it in new free programs; and that you are informed that you can do
33these things.
34
35 To protect your rights, we need to make restrictions that forbid
36distributors to deny you these rights or to ask you to surrender these
37rights. These restrictions translate to certain responsibilities for
38you if you distribute copies of the library or if you modify it.
39
40 For example, if you distribute copies of the library, whether gratis
41or for a fee, you must give the recipients all the rights that we gave
42you. You must make sure that they, too, receive or can get the source
43code. If you link other code with the library, you must provide
44complete object files to the recipients, so that they can relink them
45with the library after making changes to the library and recompiling
46it. And you must show them these terms so they know their rights.
47
48 We protect your rights with a two-step method: (1) we copyright the
49library, and (2) we offer you this license, which gives you legal
50permission to copy, distribute and/or modify the library.
51
52 To protect each distributor, we want to make it very clear that
53there is no warranty for the free library. Also, if the library is
54modified by someone else and passed on, the recipients should know
55that what they have is not the original version, so that the original
56author's reputation will not be affected by problems that might be
57introduced by others.
58
59 Finally, software patents pose a constant threat to the existence of
60any free program. We wish to make sure that a company cannot
61effectively restrict the users of a free program by obtaining a
62restrictive license from a patent holder. Therefore, we insist that
63any patent license obtained for a version of the library must be
64consistent with the full freedom of use specified in this license.
65
66 Most GNU software, including some libraries, is covered by the
67ordinary GNU General Public License. This license, the GNU Lesser
68General Public License, applies to certain designated libraries, and
69is quite different from the ordinary General Public License. We use
70this license for certain libraries in order to permit linking those
71libraries into non-free programs.
72
73 When a program is linked with a library, whether statically or using
74a shared library, the combination of the two is legally speaking a
75combined work, a derivative of the original library. The ordinary
76General Public License therefore permits such linking only if the
77entire combination fits its criteria of freedom. The Lesser General
78Public License permits more lax criteria for linking other code with
79the library.
80
81 We call this license the "Lesser" General Public License because it
82does Less to protect the user's freedom than the ordinary General
83Public License. It also provides other free software developers Less
84of an advantage over competing non-free programs. These disadvantages
85are the reason we use the ordinary General Public License for many
86libraries. However, the Lesser license provides advantages in certain
87special circumstances.
88
89 For example, on rare occasions, there may be a special need to
90encourage the widest possible use of a certain library, so that it becomes
91a de-facto standard. To achieve this, non-free programs must be
92allowed to use the library. A more frequent case is that a free
93library does the same job as widely used non-free libraries. In this
94case, there is little to gain by limiting the free library to free
95software only, so we use the Lesser General Public License.
96
97 In other cases, permission to use a particular library in non-free
98programs enables a greater number of people to use a large body of
99free software. For example, permission to use the GNU C Library in
100non-free programs enables many more people to use the whole GNU
101operating system, as well as its variant, the GNU/Linux operating
102system.
103
104 Although the Lesser General Public License is Less protective of the
105users' freedom, it does ensure that the user of a program that is
106linked with the Library has the freedom and the wherewithal to run
107that program using a modified version of the Library.
108
109 The precise terms and conditions for copying, distribution and
110modification follow. Pay close attention to the difference between a
111"work based on the library" and a "work that uses the library". The
112former contains code derived from the library, whereas the latter must
113be combined with the library in order to run.
114
115 GNU LESSER GENERAL PUBLIC LICENSE
116 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
117
118 0. This License Agreement applies to any software library or other
119program which contains a notice placed by the copyright holder or
120other authorized party saying it may be distributed under the terms of
121this Lesser General Public License (also called "this License").
122Each licensee is addressed as "you".
123
124 A "library" means a collection of software functions and/or data
125prepared so as to be conveniently linked with application programs
126(which use some of those functions and data) to form executables.
127
128 The "Library", below, refers to any such software library or work
129which has been distributed under these terms. A "work based on the
130Library" means either the Library or any derivative work under
131copyright law: that is to say, a work containing the Library or a
132portion of it, either verbatim or with modifications and/or translated
133straightforwardly into another language. (Hereinafter, translation is
134included without limitation in the term "modification".)
135
136 "Source code" for a work means the preferred form of the work for
137making modifications to it. For a library, complete source code means
138all the source code for all modules it contains, plus any associated
139interface definition files, plus the scripts used to control compilation
140and installation of the library.
141
142 Activities other than copying, distribution and modification are not
143covered by this License; they are outside its scope. The act of
144running a program using the Library is not restricted, and output from
145such a program is covered only if its contents constitute a work based
146on the Library (independent of the use of the Library in a tool for
147writing it). Whether that is true depends on what the Library does
148and what the program that uses the Library does.
149
150 1. You may copy and distribute verbatim copies of the Library's
151complete source code as you receive it, in any medium, provided that
152you conspicuously and appropriately publish on each copy an
153appropriate copyright notice and disclaimer of warranty; keep intact
154all the notices that refer to this License and to the absence of any
155warranty; and distribute a copy of this License along with the
156Library.
157
158 You may charge a fee for the physical act of transferring a copy,
159and you may at your option offer warranty protection in exchange for a
160fee.
161
162 2. You may modify your copy or copies of the Library or any portion
163of it, thus forming a work based on the Library, and copy and
164distribute such modifications or work under the terms of Section 1
165above, provided that you also meet all of these conditions:
166
167 a) The modified work must itself be a software library.
168
169 b) You must cause the files modified to carry prominent notices
170 stating that you changed the files and the date of any change.
171
172 c) You must cause the whole of the work to be licensed at no
173 charge to all third parties under the terms of this License.
174
175 d) If a facility in the modified Library refers to a function or a
176 table of data to be supplied by an application program that uses
177 the facility, other than as an argument passed when the facility
178 is invoked, then you must make a good faith effort to ensure that,
179 in the event an application does not supply such function or
180 table, the facility still operates, and performs whatever part of
181 its purpose remains meaningful.
182
183 (For example, a function in a library to compute square roots has
184 a purpose that is entirely well-defined independent of the
185 application. Therefore, Subsection 2d requires that any
186 application-supplied function or table used by this function must
187 be optional: if the application does not supply it, the square
188 root function must still compute square roots.)
189
190These requirements apply to the modified work as a whole. If
191identifiable sections of that work are not derived from the Library,
192and can be reasonably considered independent and separate works in
193themselves, then this License, and its terms, do not apply to those
194sections when you distribute them as separate works. But when you
195distribute the same sections as part of a whole which is a work based
196on the Library, the distribution of the whole must be on the terms of
197this License, whose permissions for other licensees extend to the
198entire whole, and thus to each and every part regardless of who wrote
199it.
200
201Thus, it is not the intent of this section to claim rights or contest
202your rights to work written entirely by you; rather, the intent is to
203exercise the right to control the distribution of derivative or
204collective works based on the Library.
205
206In addition, mere aggregation of another work not based on the Library
207with the Library (or with a work based on the Library) on a volume of
208a storage or distribution medium does not bring the other work under
209the scope of this License.
210
211 3. You may opt to apply the terms of the ordinary GNU General Public
212License instead of this License to a given copy of the Library. To do
213this, you must alter all the notices that refer to this License, so
214that they refer to the ordinary GNU General Public License, version 2,
215instead of to this License. (If a newer version than version 2 of the
216ordinary GNU General Public License has appeared, then you can specify
217that version instead if you wish.) Do not make any other change in
218these notices.
219
220 Once this change is made in a given copy, it is irreversible for
221that copy, so the ordinary GNU General Public License applies to all
222subsequent copies and derivative works made from that copy.
223
224 This option is useful when you wish to copy part of the code of
225the Library into a program that is not a library.
226
227 4. You may copy and distribute the Library (or a portion or
228derivative of it, under Section 2) in object code or executable form
229under the terms of Sections 1 and 2 above provided that you accompany
230it with the complete corresponding machine-readable source code, which
231must be distributed under the terms of Sections 1 and 2 above on a
232medium customarily used for software interchange.
233
234 If distribution of object code is made by offering access to copy
235from a designated place, then offering equivalent access to copy the
236source code from the same place satisfies the requirement to
237distribute the source code, even though third parties are not
238compelled to copy the source along with the object code.
239
240 5. A program that contains no derivative of any portion of the
241Library, but is designed to work with the Library by being compiled or
242linked with it, is called a "work that uses the Library". Such a
243work, in isolation, is not a derivative work of the Library, and
244therefore falls outside the scope of this License.
245
246 However, linking a "work that uses the Library" with the Library
247creates an executable that is a derivative of the Library (because it
248contains portions of the Library), rather than a "work that uses the
249library". The executable is therefore covered by this License.
250Section 6 states terms for distribution of such executables.
251
252 When a "work that uses the Library" uses material from a header file
253that is part of the Library, the object code for the work may be a
254derivative work of the Library even though the source code is not.
255Whether this is true is especially significant if the work can be
256linked without the Library, or if the work is itself a library. The
257threshold for this to be true is not precisely defined by law.
258
259 If such an object file uses only numerical parameters, data
260structure layouts and accessors, and small macros and small inline
261functions (ten lines or less in length), then the use of the object
262file is unrestricted, regardless of whether it is legally a derivative
263work. (Executables containing this object code plus portions of the
264Library will still fall under Section 6.)
265
266 Otherwise, if the work is a derivative of the Library, you may
267distribute the object code for the work under the terms of Section 6.
268Any executables containing that work also fall under Section 6,
269whether or not they are linked directly with the Library itself.
270
271 6. As an exception to the Sections above, you may also combine or
272link a "work that uses the Library" with the Library to produce a
273work containing portions of the Library, and distribute that work
274under terms of your choice, provided that the terms permit
275modification of the work for the customer's own use and reverse
276engineering for debugging such modifications.
277
278 You must give prominent notice with each copy of the work that the
279Library is used in it and that the Library and its use are covered by
280this License. You must supply a copy of this License. If the work
281during execution displays copyright notices, you must include the
282copyright notice for the Library among them, as well as a reference
283directing the user to the copy of this License. Also, you must do one
284of these things:
285
286 a) Accompany the work with the complete corresponding
287 machine-readable source code for the Library including whatever
288 changes were used in the work (which must be distributed under
289 Sections 1 and 2 above); and, if the work is an executable linked
290 with the Library, with the complete machine-readable "work that
291 uses the Library", as object code and/or source code, so that the
292 user can modify the Library and then relink to produce a modified
293 executable containing the modified Library. (It is understood
294 that the user who changes the contents of definitions files in the
295 Library will not necessarily be able to recompile the application
296 to use the modified definitions.)
297
298 b) Use a suitable shared library mechanism for linking with the
299 Library. A suitable mechanism is one that (1) uses at run time a
300 copy of the library already present on the user's computer system,
301 rather than copying library functions into the executable, and (2)
302 will operate properly with a modified version of the library, if
303 the user installs one, as long as the modified version is
304 interface-compatible with the version that the work was made with.
305
306 c) Accompany the work with a written offer, valid for at
307 least three years, to give the same user the materials
308 specified in Subsection 6a, above, for a charge no more
309 than the cost of performing this distribution.
310
311 d) If distribution of the work is made by offering access to copy
312 from a designated place, offer equivalent access to copy the above
313 specified materials from the same place.
314
315 e) Verify that the user has already received a copy of these
316 materials or that you have already sent this user a copy.
317
318 For an executable, the required form of the "work that uses the
319Library" must include any data and utility programs needed for
320reproducing the executable from it. However, as a special exception,
321the materials to be distributed need not include anything that is
322normally distributed (in either source or binary form) with the major
323components (compiler, kernel, and so on) of the operating system on
324which the executable runs, unless that component itself accompanies
325the executable.
326
327 It may happen that this requirement contradicts the license
328restrictions of other proprietary libraries that do not normally
329accompany the operating system. Such a contradiction means you cannot
330use both them and the Library together in an executable that you
331distribute.
332
333 7. You may place library facilities that are a work based on the
334Library side-by-side in a single library together with other library
335facilities not covered by this License, and distribute such a combined
336library, provided that the separate distribution of the work based on
337the Library and of the other library facilities is otherwise
338permitted, and provided that you do these two things:
339
340 a) Accompany the combined library with a copy of the same work
341 based on the Library, uncombined with any other library
342 facilities. This must be distributed under the terms of the
343 Sections above.
344
345 b) Give prominent notice with the combined library of the fact
346 that part of it is a work based on the Library, and explaining
347 where to find the accompanying uncombined form of the same work.
348
349 8. You may not copy, modify, sublicense, link with, or distribute
350the Library except as expressly provided under this License. Any
351attempt otherwise to copy, modify, sublicense, link with, or
352distribute the Library is void, and will automatically terminate your
353rights under this License. However, parties who have received copies,
354or rights, from you under this License will not have their licenses
355terminated so long as such parties remain in full compliance.
356
357 9. You are not required to accept this License, since you have not
358signed it. However, nothing else grants you permission to modify or
359distribute the Library or its derivative works. These actions are
360prohibited by law if you do not accept this License. Therefore, by
361modifying or distributing the Library (or any work based on the
362Library), you indicate your acceptance of this License to do so, and
363all its terms and conditions for copying, distributing or modifying
364the Library or works based on it.
365
366 10. Each time you redistribute the Library (or any work based on the
367Library), the recipient automatically receives a license from the
368original licensor to copy, distribute, link with or modify the Library
369subject to these terms and conditions. You may not impose any further
370restrictions on the recipients' exercise of the rights granted herein.
371You are not responsible for enforcing compliance by third parties with
372this License.
373
374 11. If, as a consequence of a court judgment or allegation of patent
375infringement or for any other reason (not limited to patent issues),
376conditions are imposed on you (whether by court order, agreement or
377otherwise) that contradict the conditions of this License, they do not
378excuse you from the conditions of this License. If you cannot
379distribute so as to satisfy simultaneously your obligations under this
380License and any other pertinent obligations, then as a consequence you
381may not distribute the Library at all. For example, if a patent
382license would not permit royalty-free redistribution of the Library by
383all those who receive copies directly or indirectly through you, then
384the only way you could satisfy both it and this License would be to
385refrain entirely from distribution of the Library.
386
387If any portion of this section is held invalid or unenforceable under any
388particular circumstance, the balance of the section is intended to apply,
389and the section as a whole is intended to apply in other circumstances.
390
391It is not the purpose of this section to induce you to infringe any
392patents or other property right claims or to contest validity of any
393such claims; this section has the sole purpose of protecting the
394integrity of the free software distribution system which is
395implemented by public license practices. Many people have made
396generous contributions to the wide range of software distributed
397through that system in reliance on consistent application of that
398system; it is up to the author/donor to decide if he or she is willing
399to distribute software through any other system and a licensee cannot
400impose that choice.
401
402This section is intended to make thoroughly clear what is believed to
403be a consequence of the rest of this License.
404
405 12. If the distribution and/or use of the Library is restricted in
406certain countries either by patents or by copyrighted interfaces, the
407original copyright holder who places the Library under this License may add
408an explicit geographical distribution limitation excluding those countries,
409so that distribution is permitted only in or among countries not thus
410excluded. In such case, this License incorporates the limitation as if
411written in the body of this License.
412
413 13. The Free Software Foundation may publish revised and/or new
414versions of the Lesser General Public License from time to time.
415Such new versions will be similar in spirit to the present version,
416but may differ in detail to address new problems or concerns.
417
418Each version is given a distinguishing version number. If the Library
419specifies a version number of this License which applies to it and
420"any later version", you have the option of following the terms and
421conditions either of that version or of any later version published by
422the Free Software Foundation. If the Library does not specify a
423license version number, you may choose any version ever published by
424the Free Software Foundation.
425
426 14. If you wish to incorporate parts of the Library into other free
427programs whose distribution conditions are incompatible with these,
428write to the author to ask for permission. For software which is
429copyrighted by the Free Software Foundation, write to the Free
430Software Foundation; we sometimes make exceptions for this. Our
431decision will be guided by the two goals of preserving the free status
432of all derivatives of our free software and of promoting the sharing
433and reuse of software generally.
434
435 NO WARRANTY
436
437 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
438WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
439EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
440OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
441KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
442IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
443PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
444LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
445THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
446
447 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
448WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
449AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
450FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
451CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
452LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
453RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
454FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
455SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
456DAMAGES.
457
458 END OF TERMS AND CONDITIONS
459
460 How to Apply These Terms to Your New Libraries
461
462 If you develop a new library, and you want it to be of the greatest
463possible use to the public, we recommend making it free software that
464everyone can redistribute and change. You can do so by permitting
465redistribution under these terms (or, alternatively, under the terms of the
466ordinary General Public License).
467
468 To apply these terms, attach the following notices to the library. It is
469safest to attach them to the start of each source file to most effectively
470convey the exclusion of warranty; and each file should have at least the
471"copyright" line and a pointer to where the full notice is found.
472
473 <one line to give the library's name and a brief idea of what it does.>
474 Copyright (C) <year> <name of author>
475
476 This library is free software; you can redistribute it and/or
477 modify it under the terms of the GNU Lesser General Public
478 License as published by the Free Software Foundation; either
479 version 2 of the License, or (at your option) any later version.
480
481 This library is distributed in the hope that it will be useful,
482 but WITHOUT ANY WARRANTY; without even the implied warranty of
483 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
484 Lesser General Public License for more details.
485
486 You should have received a copy of the GNU Lesser General Public
487 License along with this library; if not, write to the Free Software
488 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
489
490Also add information on how to contact you by electronic and paper mail.
491
492You should also get your employer (if you work as a programmer) or your
493school, if any, to sign a "copyright disclaimer" for the library, if
494necessary. Here is a sample; alter the names:
495
496 Yoyodyne, Inc., hereby disclaims all copyright interest in the
497 library `Frob' (a library for tweaking knobs) written by James Random Hacker.
498
499 <signature of Ty Coon>, 1 April 1990
500 Ty Coon, President of Vice
501
502That's all there is to it!
503
504
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/ChangeLog b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/ChangeLog
new file mode 100755
index 0000000000..e69de29bb2
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/ChangeLog
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/INSTALL b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/INSTALL
new file mode 100755
index 0000000000..bca44d042e
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/INSTALL
@@ -0,0 +1,187 @@
1Basic Installation
2==================
3
4 The `configure' shell script attempts to guess correct values for
5various system-dependent variables used during compilation. It uses
6those values to create a `Makefile' in each directory of the package.
7It may also create one or more `.h' files containing system-dependent
8definitions. Finally, it creates a shell script `config.status' that
9you can run in the future to recreate the current configuration, a file
10`config.cache' that saves the results of its tests to speed up
11reconfiguring, and a file `config.log' containing compiler output
12(useful mainly for debugging `configure').
13
14 If you need to do unusual things to compile the package, please try
15to figure out how `configure' could check whether to do them, and mail
16diffs or instructions to the address given in the `README' so they can
17be considered for the next release. If at some point `config.cache'
18contains results you don't want to keep, you may remove or edit it.
19
20 The file `configure.in' is used to create `configure' by a program
21called `autoconf'. You only need `configure.in' if you want to change
22it or regenerate `configure' using a newer version of `autoconf'.
23
24The simplest way to compile this package is:
25
26 1. `cd' to the directory containing the package's source code and type
27 `./configure' to configure the package for your system. If you're
28 using `csh' on an old version of System V, you might need to type
29 `sh ./configure' instead to prevent `csh' from trying to execute
30 `configure' itself.
31
32 Running `configure' takes awhile. While running, it prints some
33 messages telling which features it is checking for.
34
35 2. Type `make' to compile the package.
36
37 If you're building GNU make on a system which does not already have
38 a `make', you can use the build.sh shell script to compile. Run
39 `sh ./build.sh'. This should compile the program in the current
40 directory. Then you will have a Make program that you can use for
41 `make install', or whatever else.
42
43 3. Optionally, type `./make check' to run any self-tests that come with
44 the package.
45
46 4. Type `make install' to install the programs and any data files and
47 documentation.
48
49 5. You can remove the program binaries and object files from the
50 source code directory by typing `make clean'. To also remove the
51 files that `configure' created (so you can compile the package for
52 a different kind of computer), type `make distclean'. There is
53 also a `make maintainer-clean' target, but that is intended mainly
54 for the package's developers. If you use it, you may have to get
55 all sorts of other programs in order to regenerate files that came
56 with the distribution.
57
58Compilers and Options
59=====================
60
61 Some systems require unusual options for compilation or linking that
62the `configure' script does not know about. You can give `configure'
63initial values for variables by setting them in the environment. Using
64a Bourne-compatible shell, you can do that on the command line like
65this:
66 CC=c89 CFLAGS=-O2 LIBS=-lposix ./configure
67
68Or on systems that have the `env' program, you can do it like this:
69 env CPPFLAGS=-I/usr/local/include LDFLAGS=-s ./configure
70
71Compiling For Multiple Architectures
72====================================
73
74 You can compile the package for more than one kind of computer at the
75same time, by placing the object files for each architecture in their
76own directory. To do this, you must use a version of `make' that
77supports the `VPATH' variable, such as GNU `make'. `cd' to the
78directory where you want the object files and executables to go and run
79the `configure' script. `configure' automatically checks for the
80source code in the directory that `configure' is in and in `..'.
81
82 If you have to use a `make' that does not supports the `VPATH'
83variable, you have to compile the package for one architecture at a time
84in the source code directory. After you have installed the package for
85one architecture, use `make distclean' before reconfiguring for another
86architecture.
87
88Installation Names
89==================
90
91 By default, `make install' will install the package's files in
92`/usr/local/bin', `/usr/local/man', etc. You can specify an
93installation prefix other than `/usr/local' by giving `configure' the
94option `--prefix=PATH'.
95
96 You can specify separate installation prefixes for
97architecture-specific files and architecture-independent files. If you
98give `configure' the option `--exec-prefix=PATH', the package will use
99PATH as the prefix for installing programs and libraries.
100Documentation and other data files will still use the regular prefix.
101
102 In addition, if you use an unusual directory layout you can give
103options like `--bindir=PATH' to specify different values for particular
104kinds of files. Run `configure --help' for a list of the directories
105you can set and what kinds of files go in them.
106
107 If the package supports it, you can cause programs to be installed
108with an extra prefix or suffix on their names by giving `configure' the
109option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'.
110
111Optional Features
112=================
113
114 Some packages pay attention to `--enable-FEATURE' options to
115`configure', where FEATURE indicates an optional part of the package.
116They may also pay attention to `--with-PACKAGE' options, where PACKAGE
117is something like `gnu-as' or `x' (for the X Window System). The
118`README' should mention any `--enable-' and `--with-' options that the
119package recognizes.
120
121 For packages that use the X Window System, `configure' can usually
122find the X include and library files automatically, but if it doesn't,
123you can use the `configure' options `--x-includes=DIR' and
124`--x-libraries=DIR' to specify their locations.
125
126Specifying the System Type
127==========================
128
129 There may be some features `configure' can not figure out
130automatically, but needs to determine by the type of host the package
131will run on. Usually `configure' can figure that out, but if it prints
132a message saying it can not guess the host type, give it the
133`--host=TYPE' option. TYPE can either be a short name for the system
134type, such as `sun4', or a canonical name with three fields:
135 CPU-COMPANY-SYSTEM
136
137See the file `config.sub' for the possible values of each field. If
138`config.sub' isn't included in this package, then this package doesn't
139need to know the host type.
140
141 If you are building compiler tools for cross-compiling, you can also
142use the `--target=TYPE' option to select the type of system they will
143produce code for and the `--build=TYPE' option to select the type of
144system on which you are compiling the package.
145
146Sharing Defaults
147================
148
149 If you want to set default values for `configure' scripts to share,
150you can create a site shell script called `config.site' that gives
151default values for variables like `CC', `cache_file', and `prefix'.
152`configure' looks for `PREFIX/share/config.site' if it exists, then
153`PREFIX/etc/config.site' if it exists. Or, you can set the
154`CONFIG_SITE' environment variable to the location of the site script.
155A warning: not all `configure' scripts look for a site script.
156
157Operation Controls
158==================
159
160 `configure' recognizes the following options to control how it
161operates.
162
163`--cache-file=FILE'
164 Use and save the results of the tests in FILE instead of
165 `./config.cache'. Set FILE to `/dev/null' to disable caching, for
166 debugging `configure'.
167
168`--help'
169 Print a summary of the options to `configure', and exit.
170
171`--quiet'
172`--silent'
173`-q'
174 Do not print messages saying which checks are being made. To
175 suppress all normal output, redirect it to `/dev/null' (any error
176 messages will still be shown).
177
178`--srcdir=DIR'
179 Look for the package's source code in directory DIR. Usually
180 `configure' can determine that directory automatically.
181
182`--version'
183 Print the version of Autoconf used to generate the `configure'
184 script, and exit.
185
186`configure' also accepts some other, not widely useful, options.
187
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/NEWS b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/NEWS
new file mode 100755
index 0000000000..6c6bbd0175
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/NEWS
@@ -0,0 +1,184 @@
14.1.2:
2 - Fixed Cygwin DLL missing symbols problem.
3 - Fixed GNU-stack assembler section on some platforms (Debian-ARM).
4 - Fixed problem cause by include of <asm/byteorder.h>.
5 - Fixed SHA-384 and SHA-512 code Visual C++ compatibility.
6 - Improved detection of IBM ICU library version; has to be >= 2.8.
7
84.1.1:
9 - Fixed shared library version info.
10
114.1.0:
12 - Added SHA-384 and SHA-512 algorithms.
13 - Added HMAC-SHA-384 and HMAC-SHA-512 algorithms.
14 - Added generic SSE2 optimization for the above algorithms.
15 - Added more digest algorithms for PKCS#1 EMSA.
16 - Optimized swap32 and swap64 routines on Linux.
17 - Fixed missing definition in mpopt.h for s390x.
18 - Fixed nostackexec configuration bug.
19 - Fixed problem in Date::toString.
20 - Fixed deadlock problem which occured in certain cases where security
21 or crypto SPI constructor called getInstance for another security or
22 crypto SPI.
23 - Fixed a bug in the generic CBC encryption code; when called with
24 nblocks == 1, the feedback was set incorrectly.
25 - Fixed a bug in mpbsubmod; sometimes it takes multiple additions of
26 the modulus to get a positive number.
27 - Fixed PowerPC 64-bit configuration problem on Linux.
28
294.0.0:
30 - Added a C++ API interface, modeled after Java's security & crypto API.
31 - Added the new GNU noexecstack feature.
32 - Added more x86_64 and s390x assembler routines.
33 - Modified i2osp, so that it only requires as many octets as there are
34 significant bytes in the multi-precision integers.
35 - Fixed a bug in the creation of rsa keypairs; code was not correctly
36 migrated to new calling sequence. The code now implements the method
37 described in IEEE P.1363.
38 - Fixed another bug in mpextgcd_w which sometimes returned incorrect
39 results.
40 - Fixed a bug in mprshiftlsz, which didn't work correctly when size = 1.
41 - Fixed a configuration problem on Tru64 Unix.
42
433.1.0:
44 - Added wiping of private key components of keypairs before freeing.
45 - Fixed bug in mpextgcd_w which sometimes returned incorrect result.
46 - Fixed error in PowerPC 64-bit assembler symbol definitions.
47
483.0.0:
49 - Cleaned up installed header files.
50 - Modified the API so that all keys can be passed as arrays of bytes.
51 - Modified the API so that all key sizes are given in bits.
52 - Modified the multi-precision integer library to work better on 64-bit
53 machines.
54 - Modified the assembly source generation mechanism, employing the m4
55 macro processor.
56 - Added multi-precision integer vectorized assembler routines for
57 Itanium.
58 - Added multi-precision integer assembler routines for PowerPC 64-bit.
59 - Added multi-precision integer assembler routines for Alpha.
60 - Added multi-precision integer assembler routines for Opteron.
61 - Added multi-precision integer assembler routines for IBM zSeries 64-bit.
62 - Added multi-precision integer assembler routines for M68K.
63 - Added Jeff Johnson's python bindings.
64 - Added new unit tests.
65 - Added new benchmarking programs.
66
672.3.0pre:
68 - 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).
69 - Added the AES algorithm, with assembler routines for i586 and powerpc.
70 - Added the DSA signature algorithm.
71 - Added PowerPC assembler routines for blowfish.
72 - Added Pentium4 SSE2 assembler multiplication routines.
73 - Fixed the RSA CRT algorithm.
74 - Fixed the gas/i386 mp32even and mp32odd routines.
75 - Fixed a bug in modular inverse computation; thanks to Jeff Johnson of RedHat for pointing this out.
76 - Fixed a bug in testing the result of a gcd operation in the mp32prndconone routine.
77 - Fixed an ugly bug in base64 decoding.
78 - Fixed compatibility with the latest automake & autoconf versions.
79 - Replaces CPU optimization mechanism in configure script.
80
812.1.0:
82 - Added support for automake, autoheader and libtool, which should make compiling the library even easier.
83 - Changed DHAES API to conform to IEEE P.1363 submission and to allow for uneven key splitting.
84 - Improved PKCS#5 padding routines.
85 - Added a hash reset to the hashFunctionContextInit function. This was pointed out by Marko Kreen.
86 - Fixed problem with configuring on i486-pc-linux-gnu. This was pointed out Steve O'Neill.
87 - Fixed problem in the C version of mp32sub where carry would sometimes be missed. This was pointed out by Jon Sturgeon.
88 - 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.
89 - Changed mp32opt i386 assembler routines for slight performance improvement.
90 - Changed mp32opt powerpc assembler routines for slight performance improvement.
91 - Changed mp32opt sparcv9 assembler routines for slight performance improvement.
92 - Added sparcv8 assembler routines for multi-precision integer multiplication.
93 - Added arm assembler routines for multi-precision integer multiplication.
94 - Added prototype 64-bit ia64 assembler routines for multi-precision integer operations.
95 - Started writing the long-awaited documentation.
96
972.0.0:
98 - Changed mp32barrett struct and operations to be multithread-safe; this required a change in API.
99 - Changed hashFunction struct to incorporate internal block size parameter.
100 - Changed HMAC algorithm and file names to match names in RFC 2104.
101 - Changed SHA-1 C code for slightly faster results.
102 - Changed detection of entropy devices.
103 - Changed most void-returning functions to return int for error conditions.
104 - Changed beecrypt-java class names in javaglue.
105 - Added RSA keypair generation.
106 - Added RSA private & public key operations.
107 - Added SHA-256 hash function.
108 - Added HMAC-MD5 and HMAC-SHA-256 keyed hash functions.
109 - Added PKCS#5 padding.
110 - Added DHAES encryption scheme.
111 - Added Microsoft Visual C support, added Makefile.mak for this purpose.
112 - Added Solaris/Sparc Forte C 64 bit support.
113 - Added configure --disable-optimized option (disables assembler & processor-specific optimizations).
114 - 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.
115 - Fixed bug in (certain cases of) modular inverse computation.
116 - Fixed buffer overrun in base64 encoding. This was pointed out by Jon Sturgeon.
117 - Fixed various minor bugs.
118 - Renamed text files to match automake conventions.
119
1201.1.2:
121 - 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.
122 - Added MD5 hash function.
123
1241.1.1:
125 - Changed autoconfig script for easier porting.
126 - Changed sources for easier compilation on Microsoft Visual C++; no assembler-optimization on this platform yet.
127 - Fixed bug in javaglue when passing null IV to blockcipher.
128 - Shared library is now linked dynamically, with shared object name and version.
129 - Tested on Alpha Linux.
130 - Tested on Alpha FreeBSD.
131 - Added support for Compaq Alpha Tru64 Unix.
132 - Added initial support for QNX.
133
1341.1.0:
135 - Added glue for interfacing from BeeCrypt Java Cryptography Provider.
136 - Changed blockcipher struct to support interfacing with Java.
137 - Added better blockcipher IV handling.
138 - Multi-pass block processing is now possible with blockEncrypt/blockDecrypt.
139 - Updated config.sub and config.guess to latest version from sources.redhat.com
140 - Changed opening of entropy devices to blocking read-only mode instead of non-blocking read-write.
141 - Added win32 'wincrypt' entropy source.
142 - Added win32 'console' entropy source.
143 - Added FreeBSD support.
144 - Added PowerPC assembler optimized multiprecision subtraction routines.
145 - Added initial ia64 support.
146 - Added initial Darwin support (everything compiles, but the shared library doesn't build yet).
147
1481.0.2:
149 - Fixed Windows 2000 entropy bug; instead of using the first waveIn device, entropy now uses WAVE_MAPPER.
150 - Added sparcv9 mp32addsqrtrc GNU assembler routine.
151 - Added more hashFunctionContext and keyedHashFunctionContext functions.
152
1531.0.1:
154 - Added a sliding window modular exponentiation, about 30% faster than left-to-right exponentiation.
155 - Fixed bugs in fips180opt.gas.i586.s (Linux SHA-1 assembler code for Pentium/Pentium Pro) - the Windows/Metrowerks version was okay.
156
1571.0.0:
158 - 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.
159 - Global code overhaul to support Win32
160 - Added more assembler routines, including SHA-1 for Pentium Pro (60% faster)
161 - Added cleanup function to randomGenerator
162 - Added missing functions in endianness.c
163 - Fixed bug in entropy.c where devices might stay open
164 - 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.
165
1660.9.5:
167 - Added PowerPC assembler optimization for multiprecision integers, 80% faster on our PowerMac 7200/90
168 - Fixed /dev/random entropy provider
169 - Changed name SHA1 to SHA-1 in fips180 for consistency
170
1710.9.4a:
172 - Added missing file 'blowfishopt.o'
173
1740.9.4:
175 - Changes to configure script, to distinguish between different processors of the x86 family
176 - Changes to blowfish code, 586/686 assembler optimization added, 30% faster on Pentium/PentiumPro
177 - Changes to blowfish code, eliminated static blowfishSetupEncrypt; incorporated into regular encrypt
178 - Changes to Makefile to selectively use blowfish assember code, depending on cpu type
179 - Added missing routines 'mp32bzero' and 'mp32bnpowmod' to mp32barrett.c
180 - Fixed 'const register' to 'register const' in mp32.c
181 - Minor fixes in included header files
182
1830.9.3:
184 - Initial public release
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README
new file mode 100755
index 0000000000..d875372c39
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README
@@ -0,0 +1,143 @@
1Welcome to the BeeCrypt crypto library!
2
3Copyright (c) 1997, 1998, 1999, 2000, 2001 Virtual Unlimited B.V.
4Copyright (c) 2002, 2003, Bob Deblier (for certain parts)
5
6Author: Bob Deblier <bob.deblier@pandora.be>
7
8This library is free software; you can redistribute it and/or
9modify it under the terms of the GNU Lesser General Public
10License as published by the Free Software Foundation; either
11version 2.1 of the License, or (at your option) any later version.
12
13This library is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16Lesser General Public License for more details.
17
18You should have received a copy of the GNU Lesser General Public
19License along with this library; if not, write to the Free Software
20Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21
22For the specifics of this license, see file 'COPYING.LIB', included in
23this distribution.
24
25
26
27Welcome to version 3.0.0 of BeeCrypt:
28
29AES support has been added, and the library has been thoroughly debugged,
30with the addition of unit tests. Once you've built the library, you can
31verify the correct functioning with 'make check'.
32
33Multi-precision integer routines should now perform dramatically better
34an 64-bit processors, especially Alpha and Itanium.
35
36Benchmarks can be obtained with 'make bench'.
37
38As usual, your comments are welcome.
39
40
41
42About BeeCrypt:
43
44This library is an ongoing project of Virtual Unlimited B.V. Its goal is
45to provide strong and fast cryptography for use by our products, but
46we're not limiting the use to that. We're releasing it under the LGPL
47license, because we feel that cryptography should be open to inspection
48by everybody, and available for use by everybody to safeguard privacy.
49
50Note that depending on where you are, the use of cryptography may be
51limited or forbidden by law. Before using this library, make sure you
52are legally entitled to do so.
53
54
55For more on Virtual Unlimited B.V. and our products please consult our
56website: http://www.virtualunlimited.com/
57
58
59<plug>
60Most of the algorithms are implemented from reliable sources such as:
61
62"Handbook of Applied Cryptography"
63 Alfred J. Menezes, Paul C. van Oorschot, Scott A. Vanstone
64 CRC Press
65
66"Applied Cryptography", second edition
67 Bruce Schneier
68 Wiley
69
70
71For crypto enthusiasts these books are invaluable background material.
72
73IEEE P1363 "Standard Specifications for Public Key Cryptography" is a
74very interesting draft standard, which we will try to comply with.
75</plug>
76
77The structures in the library are geared towards exchange with Java
78and its security and cryptography classes. This library can also be
79accessed from Java by installing BeeCrypt for Java, a JCE 1.2 crypto
80provider and the counterpart of this library.
81
82
83Included in the library are:
84 - entropy sources for initializing pseudo-random generators
85 - pseudo-random generators: FIPS-186, Mersenne Twister
86 - block ciphers: AES, Blowfish
87 - hash functions: MD5, SHA-1, SHA-256
88 - keyed hash functions: HMAC-MD5, HMAC-SHA-1, HMAC-SHA-256
89 - multi-precision integer library, with assembler-optimized routines
90 for several processors
91 - probabilistic primality testing, with optimized small prime trial
92 division
93 - discrete logarithm parameter generation over a prime field
94 - Diffie-Hellman key agreement
95 - DSA signature scheme
96 - ElGamal signature scheme (two variants)
97 - RSA keypair generation with chinese remainder theorem variables
98 - RSA public & private key operations
99 - DHAES encryption scheme
100
101Planned for the near future are:
102 - compliance with and compliance statements for IEEE P1363
103 - more blockciphers (Twofish, ... )
104 - more hash functions (RIPEMD-160, SHA-384, SHA-512, HAVAL, Tiger)
105 - RSA signatures as specified by RFC-2440.
106 - Elliptic Curves (ECDSA, ... )
107 - more blockcipher modes (OFB, ... )
108
109The library has been tested on the following platforms:
110 - AIX 5.1 ppc
111 - AIX 5.1 ppc64
112 - Darwin 6.5 (a.k.a. MacOS X 10.2)
113 - FreeBSD 4.0 alpha
114 - FreeBSD 4.0, 4.2 x86
115 - Linux glibc 2.x alpha
116 - Linux glibc 2.x arm
117 - Linux glibc 2.x ia64
118 - Linux glibc 2.x ppc
119 - Linux glibc 2.x sparc
120 - Linux glibc 2.x x86
121 - Solaris 2.6/2.7/2.8/2.9 sparc (with Forte or gnu compilers)
122 - Solaris 2.7/2.8 x86 (with Forte or GNU compilers)
123 - Tru64 Unix alpha
124 - Win32 (Windows 95, 98, NT 4.0, 2000, XP)
125
126The library is currently in the process of being ported to:
127 - Cygwin (Can't seem to get the DLL to build properly with the current
128 version of the autotools)
129 - HP/UX is a pain in the backside; I'll try getting it working, but the
130 configure script doesn't seem capable of properly detecting gettimeofday.
131
132For more information, refer to the HTML documentation in the docs directory.
133
134If you want to report bugs, make suggestions, contribute fixes or
135enhancements, please see the beecrypt-specific website:
136
137http://sourceforge.net/projects/beecrypt
138
139or contact me at mailto:bob.deblier@pandora.be
140
141Sincerely,
142
143Bob Deblier
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.DLL b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.DLL
new file mode 100755
index 0000000000..2131f87ce2
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.DLL
@@ -0,0 +1,37 @@
1File beetest.exe is a compiled version of the test program included in
2the source distribution, which you can find on our website:
3http://beecrypt.virtualunlimited.com/
4
5To run, it needs file beecrypt.dll present in the same directory.
6
7For Developers:
8
9Files beecrypt.dll and beecrypt.lib are a pre-compiled version of the
10BeeCrypt library for Pentium Pro processors.
11
12If you want to develop applications with this library, you'll also need
13the header files, included in the source distribution (see higher).
14
15Please make sure you respect the term of the license under which the
16BeeCrypt library is released:
17
18Copyright (c) 1997, 1998, 1999, 2000, 2001 Virtual Unlimited B.V.
19
20Author: Bob Deblier <bob@virtualunlimited.com>
21
22This library is free software; you can redistribute it and/or
23modify it under the terms of the GNU Lesser General Public
24License as published by the Free Software Foundation; either
25version 2.1 of the License, or (at your option) any later version.
26
27This library is distributed in the hope that it will be useful,
28but WITHOUT ANY WARRANTY; without even the implied warranty of
29MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
30Lesser General Public License for more details.
31
32You should have received a copy of the GNU Lesser General Public
33License along with this library; if not, write to the Free Software
34Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
35
36For the specifics of this license, see file 'COPYING', included in this
37distribution.
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.WIN32 b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.WIN32
new file mode 100755
index 0000000000..411116fea2
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.WIN32
@@ -0,0 +1,43 @@
1This file contains information on how to build and use the BeeCrypt DLL on
2Win32 platforms.
3
4The platform of preference is currently MicroSoft Visual C++ 6.0, but
5Metrowerks CodeWarrior is also still supported.
6
7To be able to use the assembler files with Visual C++, you need to have the
8Visual C++ 6.0 Processor Pack installed. It can be found at:
9
10http://msdn.microsoft.com/vstudio/downloads/ppack/default.asp
11
12To be able to use the assembler files with Metrowerks CodeWarrior, you will
13need to install an unsupported (but working for the included files) assembler
14plug-in, which can be found on the CodeWarrior download page.
15
16To build the java glue into the DLL, you should also have Sun's JDK 1.3,
17including the JNI headers, installed.
18
19Make sure all Visual C++ tools can be found on the path, i.e.:
20
21cl.exe (the compiler)
22ml.exe (the assembler)
23link.exe (the linker)
24nmake.exe (the make utility)
25
26For convenience, copy file 'Makefile.mak' to 'Makefile' and adjust paths as
27required. The Makefile assumes you will be building in support for java.
28If this is not the case, you will have to adjust the Makefile, which shouldn't
29be too difficult.
30
31Next, run 'nmake' and the library and the test program will be built.
32
33Once running, you can use any of three entropy source available on this
34platform, in order of preference:
35
36wavein (uses noise on the soundcard microphone port)
37console (uses keyboard clicks with a high resolution timer)
38wincrypt (uses random data generated by the Windows CryptAPI)
39
40To enable a specific entropy device, set variable BEECRYPT_ENTROPY to any of
41these three values; if not specified, the library will use 'wavein' as default.
42
43In the future, additional sources of entropy on this platform will be made available.
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/api.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/api.h
new file mode 100755
index 0000000000..f5ef7ff04a
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/api.h
@@ -0,0 +1,89 @@
1/*
2 * Copyright (c) 2001, 2002, 2004 Beeyond Software Holding BV
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file api.h
21 * \brief BeeCrypt API, portability headers.
22 * \author Bob Deblier <bob.deblier@pandora.be>
23 */
24
25#ifndef _BEECRYPT_API_H
26#define _BEECRYPT_API_H
27
28#if defined(_WIN32) && !defined(WIN32)
29# define WIN32 1
30#endif
31
32#if WIN32
33# if !__CYGWIN32__
34# include "beecrypt/win.h"
35# else
36# include "beecrypt/gnu.h"
37# endif
38# ifdef BEECRYPT_DLL_EXPORT
39# define BEECRYPTAPI //__declspec(dllexport)
40# else
41# define BEECRYPTAPI //__declspec(dllimport)
42# endif
43# ifdef BEECRYPT_CXX_DLL_EXPORT
44# define BEECRYPTCXXAPI //__declspec(dllexport)
45# define BEECRYPTCXXTEMPLATE
46# else
47# define BEECRYPTCXXAPI //__declspec(dllimport)
48# define BEECRYPTCXXTEMPLATE extern
49# endif
50#else
51# include "beecrypt/gnu.h"
52# define BEECRYPTAPI
53# define BEECRYPTCXXAPI
54#endif
55
56#ifndef ROTL32
57# define ROTL32(x, s) (((x) << (s)) | ((x) >> (32 - (s))))
58#endif
59#ifndef ROTR32
60# define ROTR32(x, s) (((x) >> (s)) | ((x) << (32 - (s))))
61#endif
62#ifndef ROTR64
63# define ROTR64(x, s) (((x) >> (s)) | ((x) << (64 - (s))))
64#endif
65
66typedef uint8_t byte;
67
68typedef int8_t javabyte;
69typedef int16_t javashort;
70typedef int32_t javaint;
71typedef int64_t javalong;
72
73typedef uint16_t javachar;
74
75#if (MP_WBITS == 64)
76typedef uint64_t mpw;
77typedef uint32_t mphw;
78#elif (MP_WBITS == 32)
79# if HAVE_UINT64_T
80# define HAVE_MPDW 1
81typedef uint64_t mpdw;
82# endif
83typedef uint32_t mpw;
84typedef uint16_t mphw;
85#else
86# error
87#endif
88
89#endif
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/beecrypt.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/beecrypt.h
new file mode 100755
index 0000000000..a4c8780d03
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/beecrypt.h
@@ -0,0 +1,799 @@
1/*
2 * Copyright (c) 1999, 2000, 2001, 2002 Virtual Unlimited B.V.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file beecrypt.h
21 * \brief BeeCrypt API, headers.
22 *
23 * These API functions provide an abstract way for using most of
24 * the various algorithms implemented by the library.
25 *
26 * \author Bob Deblier <bob.deblier@pandora.be>
27 * \ingroup ES_m PRNG_m HASH_m HMAC_m BC_m
28 */
29
30#ifndef _BEECRYPT_H
31#define _BEECRYPT_H
32
33#include "beecrypt/api.h"
34
35#include "beecrypt/memchunk.h"
36#include "beecrypt/mpnumber.h"
37
38/*
39 * Entropy Sources
40 */
41
42/*!\typedef entropyNext
43 * \brief Prototype definition for an entropy-generating function.
44 * \ingroup ES_m
45 */
46typedef int (*entropyNext)(byte*, size_t);
47
48/*!\brief This struct holds information and pointers to code specific to each
49 * source of entropy.
50 * \ingroup ES_m
51 */
52#ifdef __cplusplus
53struct BEECRYPTAPI entropySource
54#else
55struct _entropySource
56#endif
57{
58 /*!\var name
59 * \brief The entropy source's name.
60 */
61 const char* name;
62 /*!\var next
63 * \brief Points to the function which produces the entropy.
64 */
65 const entropyNext next;
66};
67
68#ifndef __cplusplus
69typedef struct _entropySource entropySource;
70#endif
71
72#ifdef __cplusplus
73extern "C" {
74#endif
75
76/*!\fn int entropySourceCount()
77 * \brief This function returns the number of entropy sources implemented by
78 * the library.
79 * \return The number of implemented entropy sources.
80 */
81BEECRYPTAPI
82int entropySourceCount(void);
83
84/*!\fn const entropySource* entropySourceGet(int n)
85 * \brief This function returns the \a n -th entropy source implemented by
86 * the library.
87 * \param n Index of the requested entropy source; legal values are 0
88 * through entropySourceCount() - 1.
89 * \return A pointer to an entropy source or null, if the index was out of
90 * range.
91 */
92BEECRYPTAPI
93const entropySource* entropySourceGet(int n);
94
95/*!\fn const entropySource* entropySourceFind(const char* name)
96 * \brief This function returns the entropy source specified by the given name.
97 * \param name Name of the requested entropy source.
98 * \return A pointer to an entropy source or null, if the name wasn't found.
99 */
100BEECRYPTAPI
101const entropySource* entropySourceFind(const char* name);
102
103/*!\fn const entropySource* entropySourceDefault()
104 * \brief This functions returns the default entropy source; the default value
105 * can be specified by setting environment variable BEECRYPT_ENTROPY.
106 * \return A pointer to an entropy source or null, in case an error occured.
107 */
108BEECRYPTAPI
109const entropySource* entropySourceDefault(void);
110
111/*!\fn int entropyGatherNext(byte* data, size_t size)
112 * \brief This function gathers \a size bytes of entropy into \a data.
113 *
114 * Unless environment variable BEECRYPT_ENTROPY is set, this function will
115 * try each successive entropy source to gather up the requested amount.
116 *
117 * \param data Points to where the entropy should be stored.
118 * \param size Indicates how many bytes of entropy should be gathered.
119 * \retval 0 On success.
120 * \retval -1 On failure.
121 */
122BEECRYPTAPI
123int entropyGatherNext(byte*, size_t);
124
125#ifdef __cplusplus
126}
127#endif
128
129/*
130 * Pseudo-random Number Generators
131 */
132
133typedef void randomGeneratorParam;
134
135typedef int (*randomGeneratorSetup )(randomGeneratorParam*);
136typedef int (*randomGeneratorSeed )(randomGeneratorParam*, const byte*, size_t);
137typedef int (*randomGeneratorNext )(randomGeneratorParam*, byte*, size_t);
138typedef int (*randomGeneratorCleanup)(randomGeneratorParam*);
139
140/*
141 * The struct 'randomGenerator' holds information and pointers to code specific
142 * to each random generator. Each specific random generator MUST be written to
143 * be multithread safe.
144 *
145 * WARNING: each randomGenerator, when used in cryptographic applications, MUST
146 * be guaranteed to be of suitable quality and strength (i.e. don't use the
147 * random() function found in most UN*X-es).
148 *
149 * Multiple instances of each randomGenerator can be used (even concurrently),
150 * provided they each use their own randomGeneratorParam parameters, a chunk
151 * of memory which must be at least as large as indicated by the paramsize
152 * field.
153 *
154 */
155
156/*!\brief This struct holds information and pointers to code specific to each
157 * pseudo-random number generator.
158 * \ingroup PRNG_m
159 */
160#ifdef __cplusplus
161struct BEECRYPTAPI randomGenerator
162#else
163struct _randomGenerator
164#endif
165{
166 /*!\var name
167 * \brief The random generator's name.
168 */
169 const char* name;
170 /*!\var paramsize
171 * \brief The size of the random generator's parameters.
172 * \note The implementor should set this by using sizeof(<struct holding
173 * random generator's parameters>).
174 */
175 const size_t paramsize;
176 /*!\var setup
177 * \brief Points to the setup function.
178 */
179 const randomGeneratorSetup setup;
180 /*!\var seed
181 * \brief Points to the seeding function.
182 */
183 const randomGeneratorSeed seed;
184 /*!\var seed
185 * \brief Points to the function which generates the random data.
186 */
187 const randomGeneratorNext next;
188 /*!\var seed
189 * \brief Points to the cleanup function.
190 */
191 const randomGeneratorCleanup cleanup;
192};
193
194#ifndef __cplusplus
195typedef struct _randomGenerator randomGenerator;
196#endif
197
198/*
199 * You can use the following functions to find random generators implemented by
200 * the library:
201 *
202 * randomGeneratorCount returns the number of generators available.
203 *
204 * randomGeneratorGet returns the random generator with a given index (starting
205 * at zero, up to randomGeneratorCount() - 1), or NULL if the index was out of
206 * bounds.
207 *
208 * randomGeneratorFind returns the random generator with the given name, or
209 * NULL if no random generator exists with that name.
210 */
211
212#ifdef __cplusplus
213extern "C" {
214#endif
215
216BEECRYPTAPI
217int randomGeneratorCount(void);
218BEECRYPTAPI
219const randomGenerator* randomGeneratorGet(int);
220BEECRYPTAPI
221const randomGenerator* randomGeneratorFind(const char*);
222BEECRYPTAPI
223const randomGenerator* randomGeneratorDefault(void);
224
225#ifdef __cplusplus
226}
227#endif
228
229/*
230 * The struct 'randomGeneratorContext' is used to contain both the functional
231 * part (the randomGenerator), and its parameters.
232 */
233
234#ifdef __cplusplus
235struct BEECRYPTAPI randomGeneratorContext
236#else
237struct _randomGeneratorContext
238#endif
239{
240 const randomGenerator* rng;
241 randomGeneratorParam* param;
242
243 #ifdef __cplusplus
244 randomGeneratorContext();
245 randomGeneratorContext(const randomGenerator*);
246 ~randomGeneratorContext();
247 #endif
248};
249
250#ifndef __cplusplus
251typedef struct _randomGeneratorContext randomGeneratorContext;
252#endif
253
254/*
255 * The following functions can be used to initialize and free a
256 * randomGeneratorContext. Initializing will allocate a buffer of the size
257 * required by the randomGenerator, freeing will deallocate that buffer.
258 */
259
260#ifdef __cplusplus
261extern "C" {
262#endif
263
264BEECRYPTAPI
265int randomGeneratorContextInit(randomGeneratorContext*, const randomGenerator*);
266BEECRYPTAPI
267int randomGeneratorContextFree(randomGeneratorContext*);
268BEECRYPTAPI
269int randomGeneratorContextNext(randomGeneratorContext*, byte*, size_t);
270BEECRYPTAPI
271int randomGeneratorContextSeed(randomGeneratorContext*, const byte*, size_t);
272
273#ifdef __cplusplus
274}
275#endif
276
277/*
278 * Hash Functions
279 */
280
281/*!typedef void hashFunctionParam
282 * \ingroup HASH_m
283 */
284typedef void hashFunctionParam;
285
286typedef int (*hashFunctionReset )(hashFunctionParam*);
287typedef int (*hashFunctionUpdate)(hashFunctionParam*, const byte*, size_t);
288typedef int (*hashFunctionDigest)(hashFunctionParam*, byte*);
289
290/*
291 * The struct 'hashFunction' holds information and pointers to code specific
292 * to each hash function. Specific hash functions MAY be written to be
293 * multithread-safe.
294 *
295 * NOTE: data MUST have a size (in bytes) of at least 'digestsize' as described
296 * in the hashFunction struct.
297 * NOTE: for safety reasons, after calling digest, each specific implementation
298 * MUST reset itself so that previous values in the parameters are erased.
299 */
300#ifdef __cplusplus
301struct BEECRYPTAPI hashFunction
302#else
303struct _hashFunction
304#endif
305{
306 const char* name;
307 const size_t paramsize; /* in bytes */
308 const size_t blocksize; /* in bytes */
309 const size_t digestsize; /* in bytes */
310 const hashFunctionReset reset;
311 const hashFunctionUpdate update;
312 const hashFunctionDigest digest;
313};
314
315#ifndef __cplusplus
316typedef struct _hashFunction hashFunction;
317#endif
318
319/*
320 * You can use the following functions to find hash functions implemented by
321 * the library:
322 *
323 * hashFunctionCount returns the number of hash functions available.
324 *
325 * hashFunctionGet returns the hash function with a given index (starting
326 * at zero, up to hashFunctionCount() - 1), or NULL if the index was out of
327 * bounds.
328 *
329 * hashFunctionFind returns the hash function with the given name, or
330 * NULL if no hash function exists with that name.
331 */
332
333#ifdef __cplusplus
334extern "C" {
335#endif
336
337BEECRYPTAPI
338int hashFunctionCount(void);
339BEECRYPTAPI
340const hashFunction* hashFunctionGet(int);
341BEECRYPTAPI
342const hashFunction* hashFunctionFind(const char*);
343BEECRYPTAPI
344const hashFunction* hashFunctionDefault(void);
345
346#ifdef __cplusplus
347}
348#endif
349
350/*
351 * The struct 'hashFunctionContext' is used to contain both the functional
352 * part (the hashFunction), and its parameters.
353 */
354#ifdef __cplusplus
355struct BEECRYPTAPI hashFunctionContext
356#else
357struct _hashFunctionContext
358#endif
359{
360 const hashFunction* algo;
361 hashFunctionParam* param;
362
363 #ifdef __cplusplus
364 hashFunctionContext();
365 hashFunctionContext(const hashFunction*);
366 ~hashFunctionContext();
367 #endif
368};
369
370#ifndef __cplusplus
371typedef struct _hashFunctionContext hashFunctionContext;
372#endif
373
374/*
375 * The following functions can be used to initialize and free a
376 * hashFunctionContext. Initializing will allocate a buffer of the size
377 * required by the hashFunction, freeing will deallocate that buffer.
378 */
379
380#ifdef __cplusplus
381extern "C" {
382#endif
383
384BEECRYPTAPI
385int hashFunctionContextInit(hashFunctionContext*, const hashFunction*);
386BEECRYPTAPI
387int hashFunctionContextFree(hashFunctionContext*);
388BEECRYPTAPI
389int hashFunctionContextReset(hashFunctionContext*);
390BEECRYPTAPI
391int hashFunctionContextUpdate(hashFunctionContext*, const byte*, size_t);
392BEECRYPTAPI
393int hashFunctionContextUpdateMC(hashFunctionContext*, const memchunk*);
394BEECRYPTAPI
395int hashFunctionContextUpdateMP(hashFunctionContext*, const mpnumber*);
396BEECRYPTAPI
397int hashFunctionContextDigest(hashFunctionContext*, byte*);
398BEECRYPTAPI
399int hashFunctionContextDigestMP(hashFunctionContext*, mpnumber*);
400BEECRYPTAPI
401int hashFunctionContextDigestMatch(hashFunctionContext*, const mpnumber*);
402
403#ifdef __cplusplus
404}
405#endif
406
407/*
408 * Keyed Hash Functions, a.k.a. Message Authentication Codes
409 */
410
411/*!\typedef void keyedHashFunctionParam
412 * \ingroup HMAC_m
413 */
414typedef void keyedHashFunctionParam;
415
416typedef int (*keyedHashFunctionSetup )(keyedHashFunctionParam*, const byte*, size_t);
417typedef int (*keyedHashFunctionReset )(keyedHashFunctionParam*);
418typedef int (*keyedHashFunctionUpdate )(keyedHashFunctionParam*, const byte*, size_t);
419typedef int (*keyedHashFunctionDigest )(keyedHashFunctionParam*, byte*);
420
421/*
422 * The struct 'keyedHashFunction' holds information and pointers to code
423 * specific to each keyed hash function. Specific keyed hash functions MAY be
424 * written to be multithread-safe.
425 *
426 * The struct field 'keybitsmin' contains the minimum number of bits a key
427 * must contains, 'keybitsmax' the maximum number of bits a key may contain,
428 * 'keybitsinc', the increment in bits that may be used between min and max.
429 *
430 * NOTE: data must be at least have a bytesize of 'digestsize' as described
431 * in the keyedHashFunction struct.
432 * NOTE: for safety reasons, after calling digest, each specific implementation
433 * MUST reset itself so that previous values in the parameters are erased.
434 */
435#ifdef __cplusplus
436struct BEECRYPTAPI keyedHashFunction
437#else
438struct _keyedHashFunction
439#endif
440{
441 const char* name;
442 const size_t paramsize; /* in bytes */
443 const size_t blocksize; /* in bytes */
444 const size_t digestsize; /* in bytes */
445 const size_t keybitsmin; /* in bits */
446 const size_t keybitsmax; /* in bits */
447 const size_t keybitsinc; /* in bits */
448 const keyedHashFunctionSetup setup;
449 const keyedHashFunctionReset reset;
450 const keyedHashFunctionUpdate update;
451 const keyedHashFunctionDigest digest;
452};
453
454#ifndef __cplusplus
455typedef struct _keyedHashFunction keyedHashFunction;
456#endif
457
458/*
459 * You can use the following functions to find keyed hash functions implemented
460 * by the library:
461 *
462 * keyedHashFunctionCount returns the number of keyed hash functions available.
463 *
464 * keyedHashFunctionGet returns the keyed hash function with a given index
465 * (starting at zero, up to keyedHashFunctionCount() - 1), or NULL if the index
466 * was out of bounds.
467 *
468 * keyedHashFunctionFind returns the keyed hash function with the given name,
469 * or NULL if no keyed hash function exists with that name.
470 */
471
472#ifdef __cplusplus
473extern "C" {
474#endif
475
476BEECRYPTAPI
477int keyedHashFunctionCount(void);
478BEECRYPTAPI
479const keyedHashFunction* keyedHashFunctionGet(int);
480BEECRYPTAPI
481const keyedHashFunction* keyedHashFunctionFind(const char*);
482BEECRYPTAPI
483const keyedHashFunction* keyedHashFunctionDefault(void);
484
485#ifdef __cplusplus
486}
487#endif
488
489/*
490 * The struct 'keyedHashFunctionContext' is used to contain both the functional
491 * part (the keyedHashFunction), and its parameters.
492 */
493#ifdef __cplusplus
494struct BEECRYPTAPI keyedHashFunctionContext
495#else
496struct _keyedHashFunctionContext
497#endif
498{
499 const keyedHashFunction* algo;
500 keyedHashFunctionParam* param;
501
502 #ifdef __cplusplus
503 keyedHashFunctionContext();
504 keyedHashFunctionContext(const keyedHashFunction*);
505 ~keyedHashFunctionContext();
506 #endif
507};
508
509#ifndef __cplusplus
510typedef struct _keyedHashFunctionContext keyedHashFunctionContext;
511#endif
512
513/*
514 * The following functions can be used to initialize and free a
515 * keyedHashFunctionContext. Initializing will allocate a buffer of the size
516 * required by the keyedHashFunction, freeing will deallocate that buffer.
517 */
518
519#ifdef __cplusplus
520extern "C" {
521#endif
522
523BEECRYPTAPI
524int keyedHashFunctionContextInit(keyedHashFunctionContext*, const keyedHashFunction*);
525BEECRYPTAPI
526int keyedHashFunctionContextFree(keyedHashFunctionContext*);
527BEECRYPTAPI
528int keyedHashFunctionContextSetup(keyedHashFunctionContext*, const byte*, size_t);
529BEECRYPTAPI
530int keyedHashFunctionContextReset(keyedHashFunctionContext*);
531BEECRYPTAPI
532int keyedHashFunctionContextUpdate(keyedHashFunctionContext*, const byte*, size_t);
533BEECRYPTAPI
534int keyedHashFunctionContextUpdateMC(keyedHashFunctionContext*, const memchunk*);
535BEECRYPTAPI
536int keyedHashFunctionContextUpdateMP(keyedHashFunctionContext*, const mpnumber*);
537BEECRYPTAPI
538int keyedHashFunctionContextDigest(keyedHashFunctionContext*, byte*);
539BEECRYPTAPI
540int keyedHashFunctionContextDigestMP(keyedHashFunctionContext*, mpnumber*);
541BEECRYPTAPI
542int keyedHashFunctionContextDigestMatch(keyedHashFunctionContext*, const mpnumber*);
543
544#ifdef __cplusplus
545}
546#endif
547
548/*
549 * Block ciphers
550 */
551
552/*!\enum cipherOperation
553 * \brief Specifies whether to perform encryption or decryption.
554 * \ingroup BC_m
555 */
556typedef enum
557{
558 NOCRYPT,
559 ENCRYPT,
560 DECRYPT
561} cipherOperation;
562
563/*!\typedef void blockCipherParam
564 * \brief Placeholder type definition for blockcipher parameters.
565 * \sa aesParam, blowfishParam.
566 * \ingroup BC_m
567 */
568typedef void blockCipherParam;
569
570/*!\brief Prototype definition for a setup function.
571 * \ingroup BC_m
572 */
573typedef int (*blockCipherSetup )(blockCipherParam*, const byte*, size_t, cipherOperation);
574
575/*!\typedef int (*blockCipherSetIV)(blockCipherParam* bp, const byte* iv)
576 * \brief Prototype definition for an initialization vector setup function.
577 * \param bp The blockcipher's parameters.
578 * \param iv The blockciphers' IV value.
579 * \note iv length must be equal to the cipher's block size.
580 * \retval 0 on success.
581 * \retval -1 on failure.
582 * \ingroup BC_m
583 */
584typedef int (*blockCipherSetIV )(blockCipherParam*, const byte*);
585
586/*!\typedef int (*blockCipherRawcrypt)(blockCipherParam* bp, uint32_t* dst, const uint32_t* src)
587 * \brief Prototype for a \e raw encryption or decryption function.
588 * \param bp The blockcipher's parameters.
589 * \param dst The ciphertext address; must be aligned on 32-bit boundary.
590 * \param src The cleartext address; must be aligned on 32-bit boundary.
591 * \retval 0 on success.
592 * \retval -1 on failure.
593 * \ingroup BC_m
594 */
595typedef int (*blockCipherRawcrypt)(blockCipherParam*, uint32_t*, const uint32_t*);
596
597/*!\typedef int (*blockCipherModcrypt)(blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks)
598 * \brief Prototype for a \e encryption or decryption function which operates
599 * on multiple blocks in a certain mode.
600 * \param bp The blockcipher's parameters.
601 * \param dst The ciphertext address; must be aligned on 32-bit boundary.
602 * \param src The cleartext address; must be aligned on 32-bit boundary.
603 * \param nblocks The number of blocks to process.
604 * \retval 0 on success.
605 * \retval -1 on failure.
606 * \ingroup BC_m
607 */
608typedef int (*blockCipherModcrypt)(blockCipherParam*, uint32_t*, const uint32_t*, unsigned int);
609
610typedef uint32_t* (*blockCipherFeedback)(blockCipherParam*);
611
612typedef struct
613{
614 const blockCipherRawcrypt encrypt;
615 const blockCipherRawcrypt decrypt;
616} blockCipherRaw;
617
618typedef struct
619{
620 const blockCipherModcrypt encrypt;
621 const blockCipherModcrypt decrypt;
622} blockCipherMode;
623
624/*!\brief Holds information and pointers to code specific to each cipher.
625 *
626 * Specific block ciphers \e may be written to be multithread-safe.
627 *
628 * \ingroup BC_m
629 */
630#ifdef __cplusplus
631struct BEECRYPTAPI blockCipher
632#else
633struct _blockCipher
634#endif
635{
636 /*!\var name
637 * \brief The blockcipher's name.
638 */
639 const char* name;
640 /*!\var paramsize
641 * \brief The size of the parameters required by this cipher, in bytes.
642 */
643 const size_t paramsize;
644 /*!\var blocksize
645 * \brief The size of one block of data, in bytes.
646 */
647 const size_t blocksize;
648 /*!\var keybitsmin
649 * \brief The minimum number of key bits.
650 */
651 const size_t keybitsmin;
652 /*!\var keybitsmax
653 * \brief The maximum number of key bits.
654 */
655 const size_t keybitsmax;
656 /*!\var keybitsinc
657 * \brief The allowed increment in key bits between min and max.
658 * \see keybitsmin and keybitsmax.
659 */
660 const size_t keybitsinc;
661 /*!\var setup
662 * \brief Pointer to the cipher's setup function.
663 */
664 const blockCipherSetup setup;
665 /*!\var setiv
666 * \brief Pointer to the cipher's initialization vector setup function.
667 */
668 const blockCipherSetIV setiv;
669 /*!\var raw
670 * \brief The cipher's raw functions.
671 */
672 const blockCipherRaw raw;
673 /*!\var ecb
674 * \brief The cipher's ECB functions.
675 */
676 const blockCipherMode ecb;
677 const blockCipherMode cbc;
678 /*!\var getfb
679 * \brief Pointer to the cipher's feedback-returning function.
680 */
681 const blockCipherFeedback getfb;
682};
683
684#ifndef __cplusplus
685typedef struct _blockCipher blockCipher;
686#endif
687
688#ifdef __cplusplus
689extern "C" {
690#endif
691
692/*!\fn int blockCipherCount()
693 * \brief This function returns the number of blockciphers implemented
694 * by the library.
695 * \return The number of implemented blockciphers.
696 */
697BEECRYPTAPI
698int blockCipherCount(void);
699
700/*!\fn const blockCipher* blockCipherGet(int n)
701 * \brief This function returns the \a n -th blockcipher implemented by
702 * the library.
703 * \param n Index of the requested blockcipher; legal values are 0
704 * through blockCipherCount() - 1.
705 * \return A pointer to a blockcipher or null, if the index was out of
706 * range.
707 */
708BEECRYPTAPI
709const blockCipher* blockCipherGet(int);
710
711/*!\fn const blockCipher* blockCipherFind(const char* name)
712 * \brief This function returns the blockcipher specified by the given name.
713 * \param name Name of the requested blockcipher.
714 * \return A pointer to a blockcipher or null, if the name wasn't found.
715 */
716BEECRYPTAPI
717const blockCipher* blockCipherFind(const char*);
718
719/*!\fn const blockCipher* blockCipherDefault()
720 * \brief This functions returns the default blockcipher; the default value
721 * can be specified by setting environment variable BEECRYPT_CIPHER.
722 * \return A pointer to a blockcipher or null, in case an error occured.
723 */
724BEECRYPTAPI
725const blockCipher* blockCipherDefault(void);
726
727#ifdef __cplusplus
728}
729#endif
730
731/*!\brief Holds a pointer to a blockcipher as well as its parameters.
732 * \warning A context can be used by only one thread at the same time.
733 * \ingroup BC_m
734 */
735#ifdef __cplusplus
736struct BEECRYPTAPI blockCipherContext
737#else
738struct _blockCipherContext
739#endif
740{
741 /*!\var algo
742 * \brief Pointer to a blockCipher.
743 */
744 const blockCipher* algo;
745 /*!\var param
746 * \brief Pointer to the parameters used by algo.
747 */
748 blockCipherParam* param;
749 /*!\var op
750 */
751 cipherOperation op;
752
753 #ifdef __cplusplus
754 blockCipherContext();
755 blockCipherContext(const blockCipher*);
756 ~blockCipherContext();
757 #endif
758};
759
760#ifndef __cplusplus
761typedef struct _blockCipherContext blockCipherContext;
762#endif
763
764/*
765 * The following functions can be used to initialize and free a
766 * blockCipherContext. Initializing will allocate a buffer of the size
767 * required by the blockCipher, freeing will deallocate that buffer.
768 */
769
770#ifdef __cplusplus
771extern "C" {
772#endif
773
774BEECRYPTAPI
775int blockCipherContextInit(blockCipherContext*, const blockCipher*);
776
777BEECRYPTAPI
778int blockCipherContextSetup(blockCipherContext*, const byte*, size_t, cipherOperation);
779
780BEECRYPTAPI
781int blockCipherContextSetIV(blockCipherContext*, const byte*);
782
783BEECRYPTAPI
784int blockCipherContextFree(blockCipherContext*);
785
786BEECRYPTAPI
787int blockCipherContextECB(blockCipherContext*, uint32_t*, const uint32_t*, int);
788
789BEECRYPTAPI
790int blockCipherContextCBC(blockCipherContext*, uint32_t*, const uint32_t*, int);
791
792BEECRYPTAPI
793int blockCipherContextValidKeylen(blockCipherContext*, size_t);
794
795#ifdef __cplusplus
796}
797#endif
798
799#endif
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.c
new file mode 100755
index 0000000000..cfccd43337
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.c
@@ -0,0 +1,137 @@
1/*
2 * Copyright (c) 2000, 2002 Virtual Unlimited B.V.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file blockmode.c
21 * \brief Blockcipher operation modes.
22 * \author Bob Deblier <bob.deblier@pandora.be>
23 * \ingroup BC_m
24 */
25
26#define BEECRYPT_DLL_EXPORT
27
28#if HAVE_CONFIG_H
29# include "config.h"
30#endif
31
32#include "beecrypt/blockmode.h"
33
34int blockEncryptECB(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks)
35{
36 register const unsigned int blockwords = bc->blocksize >> 2;
37
38 while (nblocks > 0)
39 {
40 bc->raw.encrypt(bp, dst, src);
41
42 dst += blockwords;
43 src += blockwords;
44
45 nblocks--;
46 }
47
48 return 0;
49}
50
51int blockDecryptECB(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks)
52{
53 register const unsigned int blockwords = bc->blocksize >> 2;
54
55 while (nblocks > 0)
56 {
57 bc->raw.decrypt(bp, dst, src);
58
59 dst += blockwords;
60 src += blockwords;
61
62 nblocks--;
63 }
64
65 return 0;
66}
67
68int blockEncryptCBC(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks)
69{
70 register const unsigned int blockwords = bc->blocksize >> 2;
71 register uint32_t* fdback = bc->getfb(bp);
72
73 if (nblocks > 0)
74 {
75 register unsigned int i;
76
77 for (i = 0; i < blockwords; i++)
78 dst[i] = src[i] ^ fdback[i];
79
80 bc->raw.encrypt(bp, dst, dst);
81
82 nblocks--;
83
84 while (nblocks > 0)
85 {
86 for (i = 0; i < blockwords; i++)
87 dst[i+blockwords] = src[i+blockwords] ^ dst[i];
88
89 dst += blockwords;
90
91 bc->raw.encrypt(bp, dst, dst);
92
93 src += blockwords;
94
95 nblocks--;
96 }
97
98 for (i = 0; i < blockwords; i++)
99 fdback[i] = dst[i];
100 }
101
102 return 0;
103}
104
105int blockDecryptCBC(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks)
106{
107 register const unsigned int blockwords = bc->blocksize >> 2;
108 register uint32_t* fdback = bc->getfb(bp);
109 register uint32_t* buf = (uint32_t*) malloc(blockwords * sizeof(uint32_t));
110
111 if (buf)
112 {
113 while (nblocks > 0)
114 {
115 register uint32_t tmp;
116 register unsigned int i;
117
118 bc->raw.decrypt(bp, buf, src);
119
120 for (i = 0; i < blockwords; i++)
121 {
122 tmp = src[i];
123 dst[i] = buf[i] ^ fdback[i];
124 fdback[i] = tmp;
125 }
126
127 dst += blockwords;
128 src += blockwords;
129
130 nblocks--;
131 }
132 free(buf);
133 return 0;
134 }
135
136 return -1;
137}
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.h
new file mode 100755
index 0000000000..4f21b81f65
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.h
@@ -0,0 +1,92 @@
1/*
2 * Copyright (c) 2000, 2002 Virtual Unlimited B.V.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file blockmode.h
21 * \brief Blockcipher operation modes.
22 * \todo Additional modes, such as CFB and OFB.
23 * \author Bob Deblier <bob.deblier@pandora.be>
24 * \ingroup BC_m
25 */
26
27#ifndef _BLOCKMODE_H
28#define _BLOCKMODE_H
29
30#include "beecrypt/beecrypt.h"
31
32#ifdef __cplusplus
33extern "C" {
34#endif
35
36/*!\fn int blockEncryptECB(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks)
37 * \brief This function encrypts a number of data blocks in Electronic Code
38 * Book mode.
39 * \param bc The blockcipher.
40 * \param bp The cipher's parameter block.
41 * \param dst The ciphertext data; should be aligned on a 32-bit boundary.
42 * \param src The cleartext data; should be aligned on a 32-bit boundary.
43 * \param nblocks The number of blocks to be encrypted.
44 * \retval 0 on success.
45 */
46BEECRYPTAPI
47int blockEncryptECB(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks);
48
49/*!\fn int blockDecryptECB(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks)
50 * \brief This function decrypts a number of data blocks in Electronic Code
51 * Book mode.
52 * \param bc The blockcipher.
53 * \param bp The cipher's parameter block.
54 * \param dst The cleartext data; should be aligned on a 32-bit boundary.
55 * \param src The ciphertext data; should be aligned on a 32-bit boundary.
56 * \param nblocks The number of blocks to be decrypted.
57 * \retval 0 on success.
58 */
59BEECRYPTAPI
60int blockDecryptECB(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks);
61
62/*!\fn int blockEncryptCBC(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks)
63 * \brief This function encrypts a number of data blocks in Cipher Block
64 * Chaining mode.
65 * \param bc The blockcipher.
66 * \param bp The cipher's parameter block.
67 * \param dst The ciphertext data; should be aligned on a 32-bit boundary.
68 * \param src The cleartext data; should be aligned on a 32-bit boundary.
69 * \param nblocks The number of blocks to be encrypted.
70 * \retval 0 on success.
71 */
72BEECRYPTAPI
73int blockEncryptCBC(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks);
74
75/*!\fn int blockDecryptCBC(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks)
76 * \brief This function decrypts a number of data blocks in Cipher Block
77 * Chaining mode.
78 * \param bc The blockcipher.
79 * \param bp The cipher's parameter block.
80 * \param dst The cleartext data; should be aligned on a 32-bit boundary.
81 * \param src The ciphertext data; should be aligned on a 32-bit boundary.
82 * \param nblocks The number of blocks to be decrypted.
83 * \retval 0 on success.
84 */
85BEECRYPTAPI
86int blockDecryptCBC(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks);
87
88#ifdef __cplusplus
89}
90#endif
91
92#endif
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.c
new file mode 100755
index 0000000000..a8b801e6ec
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.c
@@ -0,0 +1,509 @@
1/*
2 * Copyright (c) 1999, 2000, 2002 Virtual Unlimited B.V.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file blowfish.c
21 * \brief Blowfish block cipher.
22 * \author Bob Deblier <bob.deblier@pandora.be>
23 * \ingroup BC_m BC_blowfish_m
24 */
25
26#define BEECRYPT_DLL_EXPORT
27
28#if HAVE_CONFIG_H
29# include "config.h"
30#endif
31
32#include "beecrypt/blowfish.h"
33
34#if HAVE_ENDIAN_H && HAVE_ASM_BYTEORDER_H
35# include <endian.h>
36#endif
37
38#include "beecrypt/endianness.h"
39
40#ifdef ASM_BLOWFISHENCRYPTECB
41extern int blowfishEncryptECB(blowfishparam*, uint32_t*, const uint32_t*, unsigned int);
42#endif
43
44#ifdef ASM_BLOWFISHDECRYPTECB
45extern int blowfishDecryptECB(blowfishparam*, uint32_t*, const uint32_t*, unsigned int);
46#endif
47
48static uint32_t _bf_p[BLOWFISHPSIZE] = {
49 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
50 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
51 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
52 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
53 0x9216d5d9, 0x8979fb1b
54};
55
56static uint32_t _bf_s[1024] = {
57 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
58 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
59 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
60 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
61 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
62 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
63 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
64 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
65 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
66 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
67 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
68 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
69 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
70 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
71 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
72 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
73 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
74 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
75 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
76 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
77 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
78 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
79 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
80 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
81 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
82 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
83 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
84 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
85 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
86 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
87 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
88 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
89 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
90 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
91 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
92 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
93 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
94 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
95 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
96 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
97 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
98 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
99 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
100 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
101 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
102 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
103 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
104 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
105 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
106 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
107 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
108 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
109 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
110 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
111 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
112 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
113 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
114 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
115 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
116 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
117 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
118 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
119 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
120 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
121 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
122 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
123 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
124 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
125 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
126 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
127 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
128 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
129 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
130 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
131 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
132 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
133 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
134 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
135 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
136 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
137 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
138 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
139 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
140 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
141 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
142 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
143 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
144 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
145 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
146 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
147 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
148 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
149 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
150 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
151 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
152 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
153 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
154 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
155 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
156 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
157 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
158 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
159 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
160 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
161 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
162 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
163 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
164 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
165 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
166 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
167 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
168 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
169 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
170 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
171 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
172 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
173 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
174 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
175 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
176 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
177 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
178 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
179 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
180 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
181 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
182 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
183 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
184 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
185 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
186 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
187 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
188 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
189 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
190 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
191 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
192 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
193 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
194 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
195 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
196 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
197 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
198 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
199 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
200 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
201 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
202 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
203 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
204 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
205 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
206 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
207 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
208 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
209 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
210 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
211 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
212 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
213 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
214 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
215 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
216 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
217 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
218 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
219 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
220 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
221 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
222 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
223 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
224 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
225 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
226 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
227 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
228 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
229 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
230 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
231 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
232 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
233 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
234 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
235 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
236 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
237 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
238 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
239 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
240 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
241 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
242 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
243 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
244 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
245 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
246 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
247 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
248 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
249 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
250 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
251 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
252 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
253 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
254 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
255 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
256 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
257 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
258 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
259 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
260 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
261 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
262 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
263 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
264 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
265 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
266 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
267 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
268 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
269 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
270 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
271 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
272 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
273 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
274 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
275 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
276 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
277 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
278 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
279 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
280 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
281 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
282 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
283 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
284 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
285 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
286 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
287 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
288 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
289 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
290 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
291 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
292 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
293 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
294 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
295 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
296 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
297 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
298 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
299 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
300 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
301 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
302 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
303 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
304 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
305 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
306 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
307 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
308 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
309 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
310 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
311 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
312 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
313};
314
315#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]
316#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]
317
318const blockCipher blowfish = {
319 "Blowfish",
320 sizeof(blowfishParam),
321 8,
322 64,
323 448,
324 32,
325 (blockCipherSetup) blowfishSetup,
326 (blockCipherSetIV) blowfishSetIV,
327 /* raw */
328 {
329 (blockCipherRawcrypt) blowfishEncrypt,
330 (blockCipherRawcrypt) blowfishDecrypt
331 },
332 /* ecb */
333 {
334 #ifdef AES_BLOWFISHENCRYPTECB
335 (blockCipherModcrypt) blowfishEncryptECB,
336 #else
337 (blockCipherModcrypt) 0,
338 #endif
339 #ifdef AES_BLOWFISHENCRYPTECB
340 (blockCipherModcrypt) blowfishDecryptECB,
341 #else
342 (blockCipherModcrypt) 0
343 #endif
344 },
345 /* cbc */
346 {
347 (blockCipherModcrypt) 0,
348 (blockCipherModcrypt) 0
349 },
350 (blockCipherFeedback) blowfishFeedback
351};
352
353int blowfishSetup(blowfishParam* bp, const byte* key, size_t keybits, cipherOperation op)
354{
355 if ((op != ENCRYPT) && (op != DECRYPT))
356 return -1;
357
358 if (((keybits & 7) == 0) && (keybits >= 32) && (keybits <= 448))
359 {
360 register uint32_t* p = bp->p;
361 register uint32_t* s = bp->s;
362 register unsigned int i, j, k;
363
364 uint32_t tmp, work[2];
365
366 memcpy(s, _bf_s, 1024 * sizeof(uint32_t));
367
368 for (i = 0, k = 0; i < BLOWFISHPSIZE; i++)
369 {
370 tmp = 0;
371 for (j = 0; j < 4; j++)
372 {
373 tmp <<= 8;
374 tmp |= key[k++];
375 if (k >= (keybits >> 3))
376 k = 0;
377 }
378 p[i] = _bf_p[i] ^ tmp;
379 }
380
381 work[0] = work[1] = 0;
382
383 for (i = 0; i < BLOWFISHPSIZE; i += 2, p += 2)
384 {
385 blowfishEncrypt(bp, work, work);
386 #if WORDS_BIGENDIAN
387 p[0] = work[0];
388 p[1] = work[1];
389 #else
390 p[0] = swapu32(work[0]);
391 p[1] = swapu32(work[1]);
392 #endif
393 }
394
395 for (i = 0; i < 1024; i += 2, s += 2)
396 {
397 blowfishEncrypt(bp, work, work);
398 #if WORDS_BIGENDIAN
399 s[0] = work[0];
400 s[1] = work[1];
401 #else
402 s[0] = swapu32(work[0]);
403 s[1] = swapu32(work[1]);
404 #endif
405 }
406
407 /* clear fdback/iv */
408 bp->fdback[0] = 0;
409 bp->fdback[1] = 0;
410
411 return 0;
412 }
413 return -1;
414}
415
416#ifndef ASM_BLOWFISHSETIV
417int blowfishSetIV(blowfishParam* bp, const byte* iv)
418{
419 if (iv)
420 memcpy(bp->fdback, iv, 8);
421 else
422 memset(bp->fdback, 0, 8);
423
424 return 0;
425}
426#endif
427
428int blowfishBlowit(blowfishParam* bp, uint32_t* dst, const uint32_t* src)
429{
430 register uint32_t xl = src[0], xr = src[1];
431 register uint32_t* p = bp->p;
432 register uint32_t* s = bp->s;
433
434 EROUND(xl, xr); EROUND(xr, xl);
435
436 dst[1] = xr;
437 dst[0] = xl;
438
439 return 0;
440}
441
442#ifndef ASM_BLOWFISHENCRYPT
443int blowfishEncrypt(blowfishParam* bp, uint32_t* dst, const uint32_t* src)
444{
445 #if WORDS_BIGENDIAN
446 register uint32_t xl = src[0], xr = src[1];
447 #else
448 register uint32_t xl = swapu32(src[0]), xr = swapu32(src[1]);
449 #endif
450 register uint32_t* p = bp->p;
451 register uint32_t* s = bp->s;
452
453 EROUND(xl, xr); EROUND(xr, xl);
454 EROUND(xl, xr); EROUND(xr, xl);
455 EROUND(xl, xr); EROUND(xr, xl);
456 EROUND(xl, xr); EROUND(xr, xl);
457 EROUND(xl, xr); EROUND(xr, xl);
458 EROUND(xl, xr); EROUND(xr, xl);
459 EROUND(xl, xr); EROUND(xr, xl);
460 EROUND(xl, xr); EROUND(xr, xl);
461
462 #if WORDS_BIGENDIAN
463 dst[1] = xl ^ *(p++);
464 dst[0] = xr ^ *(p++);
465 #else
466 dst[1] = swapu32(xl ^ *(p++));
467 dst[0] = swapu32(xr ^ *(p++));
468 #endif
469
470 return 0;
471}
472#endif
473
474#ifndef ASM_BLOWFISHDECRYPT
475int blowfishDecrypt(blowfishParam* bp, uint32_t* dst, const uint32_t* src)
476{
477 #if WORDS_BIGENDIAN
478 register uint32_t xl = src[0], xr = src[1];
479 #else
480 register uint32_t xl = swapu32(src[0]), xr = swapu32(src[1]);
481 #endif
482 register uint32_t* p = bp->p+BLOWFISHPSIZE-1;
483 register uint32_t* s = bp->s;
484
485 DROUND(xl, xr); DROUND(xr, xl);
486 DROUND(xl, xr); DROUND(xr, xl);
487 DROUND(xl, xr); DROUND(xr, xl);
488 DROUND(xl, xr); DROUND(xr, xl);
489 DROUND(xl, xr); DROUND(xr, xl);
490 DROUND(xl, xr); DROUND(xr, xl);
491 DROUND(xl, xr); DROUND(xr, xl);
492 DROUND(xl, xr); DROUND(xr, xl);
493
494 #if WORDS_BIGENDIAN
495 dst[1] = xl ^ *(p--);
496 dst[0] = xr ^ *(p--);
497 #else
498 dst[1] = swapu32(xl ^ *(p--));
499 dst[0] = swapu32(xr ^ *(p--));
500 #endif
501
502 return 0;
503}
504#endif
505
506uint32_t* blowfishFeedback(blowfishParam* bp)
507{
508 return bp->fdback;
509}
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.h
new file mode 100755
index 0000000000..1d95ddb4f2
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.h
@@ -0,0 +1,132 @@
1/*
2 * Copyright (c) 1999, 2000, 2002 Virtual Unlimited B.V.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file blowfish.h
21 * \brief Blowfish block cipher.
22 *
23 * For more information on this blockcipher, see:
24 * "Applied Cryptography", second edition
25 * Bruce Schneier
26 * Wiley & Sons
27 *
28 * Also see http://www.counterpane.com/blowfish.html
29 *
30 * \author Bob Deblier <bob.deblier@pandora.be>
31 * \ingroup BC_m BC_blowfish_m
32 */
33
34#ifndef _BLOWFISH_H
35#define _BLOWFISH_H
36
37#include "beecrypt/beecrypt.h"
38#include "beecrypt/blowfishopt.h"
39
40#define BLOWFISHROUNDS 16
41#define BLOWFISHPSIZE (BLOWFISHROUNDS+2)
42
43/*!\brief Holds all the parameters necessary for the Blowfish cipher.
44 * \ingroup BC_blowfish_m
45 */
46#ifdef __cplusplus
47struct BEECRYPTAPI blowfishParam
48#else
49struct _blowfishParam
50#endif
51{
52 /*!\var p
53 * \brief Holds the key expansion.
54 */
55 uint32_t p[BLOWFISHPSIZE];
56 /*!\var s
57 * \brief Holds the s-boxes.
58 */
59 uint32_t s[1024];
60 /*!\var fdback
61 * \brief Buffer to be used by block chaining or feedback modes.
62 */
63 uint32_t fdback[2];
64};
65
66#ifndef __cplusplus
67typedef struct _blowfishParam blowfishParam;
68#endif
69
70#ifdef __cplusplus
71extern "C" {
72#endif
73
74/*!\var blowfish
75 * \brief Holds the full API description of the Blowfish algorithm.
76 */
77extern const BEECRYPTAPI blockCipher blowfish;
78
79/*!\fn int blowfishSetup(blowfishParam* bp, const byte* key, size_t keybits, cipherOperation
80 op)
81 * \brief The function performs the cipher's key expansion.
82 * \param bp The cipher's parameter block.
83 * \param key The key value.
84 * \param keybits The number of bits in the key; legal values are: 32 to 448,
85 * in multiples of 8.
86 * \param op ENCRYPT or DECRYPT.
87 * \retval 0 on success.
88 * \retval -1 on failure.
89 */
90BEECRYPTAPI
91int blowfishSetup (blowfishParam*, const byte*, size_t, cipherOperation);
92
93/*!\fn int blowfishSetIV(blowfishParam* bp, const byte* iv)
94 * \brief This function sets the Initialization Vector.
95 * \note This function is only useful in block chaining or feedback modes.
96 * \param bp The cipher's parameter block.
97 * \param iv The initialization vector; may be null.
98 * \retval 0 on success.
99 */
100BEECRYPTAPI
101int blowfishSetIV (blowfishParam*, const byte*);
102
103/*!\fn blowfishEncrypt(blowfishParam* bp, uint32_t* dst, const uint32_t* src)
104 * \brief This function performs the Blowfish encryption; it encrypts one block
105 * of 64 bits.
106 * \param bp The cipher's parameter block.
107 * \param dst The ciphertext; should be aligned on 32-bit boundary.
108 * \param src The cleartext; should be aligned on 32-bit boundary.
109 * \retval 0 on success.
110 */
111BEECRYPTAPI
112int blowfishEncrypt (blowfishParam*, uint32_t*, const uint32_t*);
113
114/*!\fn blowfishDecrypt(blowfishParam* bp, uint32_t* dst, const uint32_t* src)
115 * \brief This function performs the Blowfish decryption; it Rderypts one block
116 * of 64 bits.
117 * \param bp The cipher's parameter block.
118 * \param dst The cleartext; should be aligned on 32-bit boundary.
119 * \param src The ciphertext; should be aligned on 32-bit boundary.
120 * \retval 0 on success.
121 */
122BEECRYPTAPI
123int blowfishDecrypt (blowfishParam*, uint32_t*, const uint32_t*);
124
125BEECRYPTAPI
126uint32_t* blowfishFeedback(blowfishParam*);
127
128#ifdef __cplusplus
129}
130#endif
131
132#endif
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfishopt.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfishopt.h
new file mode 100755
index 0000000000..f38db94b52
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfishopt.h
@@ -0,0 +1,82 @@
1/*
2 * Copyright (c) 2000, 2002, 2003 Virtual Unlimited B.V.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file blowfishopt.h
21 * \brief Blowfish block cipher, assembler-optimized routines, headers.
22 * \author Bob Deblier <bob.deblier@pandora.be>
23 * \ingroup BC_blowfish_m
24 */
25
26#ifndef _BLOWFISHOPT_H
27#define _BLOWFISHOPT_H
28
29#include "beecrypt/beecrypt.h"
30#include "beecrypt/blowfish.h"
31
32#ifdef __cplusplus
33extern "C" {
34#endif
35
36#if WIN32
37# if defined(_MSC_VER) && defined(_M_IX86)
38# define ASM_BLOWFISHENCRYPT
39# define ASM_BLOWFISHDECRYPT
40# elif __INTEL__ && __MWERKS__
41# define ASM_BLOWFISHENCRYPT
42# define ASM_BLOWFISHDECRYPT
43# endif
44#endif
45
46#if defined(__GNUC__)
47# if defined(OPTIMIZE_I586) || defined(OPTIMIZE_I686)
48# define ASM_BLOWFISHENCRYPT
49# define ASM_BLOWFISHDECRYPT
50# endif
51# if defined(OPTIMIZE_POWERPC)
52# define ASM_BLOWFISHENCRYPT
53# define ASM_BLOWFISHDECRYPT
54# endif
55#endif
56
57#if defined(__IBMC__)
58# if defined(OPTIMIZE_POWERPC)
59# define ASM_BLOWFISHENCRYPT
60# define ASM_BLOWFISHDECRYPT
61# endif
62#endif
63
64#if defined(__INTEL_COMPILER)
65# if defined(OPTIMIZE_I586) || defined(OPTIMIZE_I686)
66# define ASM_BLOWFISHENCRYPT
67# define ASM_BLOWFISHDECRYPT
68# endif
69#endif
70
71#if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
72/* nothing here yet */
73#endif
74
75#undef ASM_BLOWFISHENCRYPT
76#undef ASM_BLOWFISHDECRYPT
77
78#ifdef __cplusplus
79}
80#endif
81
82#endif
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.c
new file mode 100755
index 0000000000..8a0999b63e
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.c
@@ -0,0 +1,94 @@
1/*
2 * Copyright (c) 1998, 1999, 2000, 2001 Virtual Unlimited B.V.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file endianness.c
21 * \brief Endian-dependant encoding/decoding.
22 * \author Bob Deblier <bob.deblier@pandora.be>
23 */
24
25#define BEECRYPT_DLL_EXPORT
26
27#if HAVE_CONFIG_H
28# include "config.h"
29#endif
30
31#if HAVE_ENDIAN_H && HAVE_ASM_BYTEORDER_H
32# include <endian.h>
33#endif
34
35#include "beecrypt/endianness.h"
36
37#undef swap16
38#undef swapu16
39#undef swap32
40#undef swapu32
41#undef swap64
42#undef swapu64
43
44int16_t swap16(int16_t n)
45{
46 return ( ((n & 0xff) << 8) |
47 ((n & 0xff00) >> 8) );
48}
49
50uint16_t swapu16(uint16_t n)
51{
52 return ( ((n & 0xffU) << 8) |
53 ((n & 0xff00U) >> 8) );
54}
55
56int32_t swap32(int32_t n)
57{
58 return ( ((n & 0xff) << 24) |
59 ((n & 0xff00) << 8) |
60 ((n & 0xff0000) >> 8) |
61 ((n & 0xff000000) >> 24) );
62}
63
64uint32_t swapu32(uint32_t n)
65{
66 return ( ((n & 0xffU) << 24) |
67 ((n & 0xff00U) << 8) |
68 ((n & 0xff0000U) >> 8) |
69 ((n & 0xff000000U) >> 24) );
70}
71
72int64_t swap64(int64_t n)
73{
74 return ( ((n & (((int64_t) 0xff) )) << 56) |
75 ((n & (((int64_t) 0xff) << 8)) << 40) |
76 ((n & (((int64_t) 0xff) << 16)) << 24) |
77 ((n & (((int64_t) 0xff) << 24)) << 8) |
78 ((n & (((int64_t) 0xff) << 32)) >> 8) |
79 ((n & (((int64_t) 0xff) << 40)) >> 24) |
80 ((n & (((int64_t) 0xff) << 48)) >> 40) |
81 ((n & (((int64_t) 0xff) << 56)) >> 56) );
82}
83
84uint64_t swapu64(uint64_t n)
85{
86 return ( ((n & (((uint64_t) 0xff) )) << 56) |
87 ((n & (((uint64_t) 0xff) << 8)) << 40) |
88 ((n & (((uint64_t) 0xff) << 16)) << 24) |
89 ((n & (((uint64_t) 0xff) << 24)) << 8) |
90 ((n & (((uint64_t) 0xff) << 32)) >> 8) |
91 ((n & (((uint64_t) 0xff) << 40)) >> 24) |
92 ((n & (((uint64_t) 0xff) << 48)) >> 40) |
93 ((n & (((uint64_t) 0xff) << 56)) >> 56) );
94}
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.h
new file mode 100755
index 0000000000..e136aa59f9
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.h
@@ -0,0 +1,128 @@
1/*
2 * endianness.h
3 *
4 * Endian-dependant encoding/decoding, header
5 *
6 * Copyright (c) 1998, 1999, 2000, 2001, 2004 Beeyond Software Holding
7 *
8 * Author: Bob Deblier <bob.deblier@telenet.be>
9 *
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
14 *
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 *
24 */
25
26#ifndef _ENDIANNESS_H
27#define _ENDIANNESS_H
28
29#include "beecrypt/beecrypt.h"
30
31#if defined(__cplusplus) || HAVE_INLINE
32
33static inline int16_t _swap16(int16_t n)
34{
35 return ( ((n & 0xff) << 8) |
36 ((n & 0xff00) >> 8) );
37}
38# define swap16(n) _swap16(n)
39
40static inline uint16_t _swapu16(uint16_t n)
41{
42 return ( ((n & 0xffU) << 8) |
43 ((n & 0xff00U) >> 8) );
44}
45# define swapu16(n) _swap16(n)
46
47# ifdef __arch__swab32
48# define swap32(n) __arch__swab32(n)
49# define swapu32(n) __arch__swab32(n)
50# else
51
52static inline int32_t _swap32(int32_t n)
53{
54 return ( ((n & 0xff) << 24) |
55 ((n & 0xff00) << 8) |
56 ((n & 0xff0000) >> 8) |
57 ((n & 0xff000000) >> 24) );
58}
59# define swap32(n) _swap32(n)
60
61static inline uint32_t _swapu32(uint32_t n)
62{
63 return ( ((n & 0xffU) << 24) |
64 ((n & 0xff00U) << 8) |
65 ((n & 0xff0000U) >> 8) |
66 ((n & 0xff000000U) >> 24) );
67}
68# define swapu32(n) _swapu32(n)
69
70# endif
71
72# ifdef __arch__swab64
73# define swap64(n) __arch__swab64(n)
74# define swapu64(n) __arch__swab64(n)
75# else
76
77static inline int64_t _swap64(int64_t n)
78{
79 return ( ((n & ((int64_t) 0xff) ) << 56) |
80 ((n & ((int64_t) 0xff) << 8) << 40) |
81 ((n & ((int64_t) 0xff) << 16) << 24) |
82 ((n & ((int64_t) 0xff) << 24) << 8) |
83 ((n & ((int64_t) 0xff) << 32) >> 8) |
84 ((n & ((int64_t) 0xff) << 40) >> 24) |
85 ((n & ((int64_t) 0xff) << 48) >> 40) |
86 ((n & ((int64_t) 0xff) << 56) >> 56) );
87}
88# define swap64(n) _swap64(n)
89
90static inline uint64_t _swapu64(uint64_t n)
91{
92 return ( ((n & ((uint64_t) 0xff) ) << 56) |
93 ((n & ((uint64_t) 0xff) << 8) << 40) |
94 ((n & ((uint64_t) 0xff) << 16) << 24) |
95 ((n & ((uint64_t) 0xff) << 24) << 8) |
96 ((n & ((uint64_t) 0xff) << 32) >> 8) |
97 ((n & ((uint64_t) 0xff) << 40) >> 24) |
98 ((n & ((uint64_t) 0xff) << 48) >> 40) |
99 ((n & ((uint64_t) 0xff) << 56) >> 56) );
100}
101# define swapu64(n) _swapu64(n)
102
103# endif
104
105#else
106BEECRYPTAPI
107 int16_t swap16 (int16_t);
108BEECRYPTAPI
109uint16_t swapu16(uint16_t);
110BEECRYPTAPI
111 int32_t swap32 (int32_t);
112BEECRYPTAPI
113uint32_t swapu32(uint32_t);
114BEECRYPTAPI
115 int64_t swap64 (int64_t);
116BEECRYPTAPI
117uint64_t swapu64(uint64_t);
118#endif
119
120#ifdef __cplusplus
121extern "C" {
122#endif
123
124#ifdef __cplusplus
125}
126#endif
127
128#endif
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/gnu.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/gnu.h
new file mode 100755
index 0000000000..18386ef997
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/gnu.h
@@ -0,0 +1,67 @@
1/*
2 * Copyright (c) 2003 Bob Deblier
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20#ifndef _BEECRYPT_GNU_H
21#define _BEECRYPT_GNU_H
22
23#include <inttypes.h>
24#include <stdint.h>
25
26
27#include <pthread.h>
28#include <stdio.h>
29#include <stdlib.h>
30
31#include <string.h>
32#include <unistd.h>
33#include <dlfcn.h>
34
35typedef pthread_cond_t bc_cond_t;
36typedef pthread_mutex_t bc_mutex_t;
37typedef pthread_t bc_thread_t;
38
39
40
41
42
43
44
45
46
47
48
49
50
51#if defined(__GNUC__)
52# if !defined(__GNUC_PREREQ__)
53# define __GNUC_PREREQ__(maj, min) (__GNUC__ > (maj) || __GNUC__ == (maj) && __GNUC_MINOR__ >= (min))
54# endif
55#else
56# define __GNUC__ 0
57# define __GNUC_PREREQ__(maj, min) 0
58#endif
59
60/* WARNING: overriding this value is dangerous; some assembler routines
61 * make assumptions about the size set by the configure script
62 */
63#if !defined(MP_WBITS)
64# define MP_WBITS 64U
65#endif
66
67#endif
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.c
new file mode 100755
index 0000000000..c28770a05b
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.c
@@ -0,0 +1,123 @@
1/*
2 * Copyright (c) 1999, 2000, 2002 Virtual Unlimited B.V.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file hmac.c
21 * \brief HMAC algorithm.
22 *
23 * \see RFC2104 HMAC: Keyed-Hashing for Message Authentication.
24 * H. Krawczyk, M. Bellare, R. Canetti.
25 *
26 * \author Bob Deblier <bob.deblier@pandore.be>
27 * \ingroup HMAC_m
28 */
29
30#define BEECRYPT_DLL_EXPORT
31
32#if HAVE_CONFIG_H
33# include "config.h"
34#endif
35
36#include "beecrypt/hmac.h"
37#include "beecrypt/endianness.h"
38
39/*!\addtogroup HMAC_m
40 * \{
41 */
42
43#define HMAC_IPAD 0x36
44#define HMAC_OPAD 0x5c
45
46int hmacSetup(byte* kxi, byte* kxo, const hashFunction* hash, hashFunctionParam* param, const byte* key, size_t keybits)
47{
48 register unsigned int i;
49
50 size_t keybytes = keybits >> 3;
51
52 /* if the key is too large, hash it first */
53 if (keybytes > hash->blocksize)
54 {
55 /* if the hash digest is too large, this doesn't help; this is really a sanity check */
56 if (hash->digestsize > hash->blocksize)
57 return -1;
58
59 if (hash->reset(param))
60 return -1;
61
62 if (hash->update(param, key, keybytes))
63 return -1;
64
65 if (hash->digest(param, kxi))
66 return -1;
67
68 memcpy(kxo, kxi, keybytes = hash->digestsize);
69 }
70 else if (keybytes > 0)
71 {
72 memcpy(kxi, key, keybytes);
73 memcpy(kxo, key, keybytes);
74 }
75 else
76 return -1;
77
78 for (i = 0; i < keybytes; i++)
79 {
80 kxi[i] ^= HMAC_IPAD;
81 kxo[i] ^= HMAC_OPAD;
82 }
83
84 for (i = keybytes; i < hash->blocksize; i++)
85 {
86 kxi[i] = HMAC_IPAD;
87 kxo[i] = HMAC_OPAD;
88 }
89
90 return hmacReset(kxi, hash, param);
91}
92
93int hmacReset(const byte* kxi, const hashFunction* hash, hashFunctionParam* param)
94{
95 if (hash->reset(param))
96 return -1;
97 if (hash->update(param, kxi, hash->blocksize))
98 return -1;
99
100 return 0;
101}
102
103int hmacUpdate(const hashFunction* hash, hashFunctionParam* param, const byte* data, size_t size)
104{
105 return hash->update(param, data, size);
106}
107
108int hmacDigest(const byte* kxo, const hashFunction* hash, hashFunctionParam* param, byte* data)
109{
110 if (hash->digest(param, data))
111 return -1;
112 if (hash->update(param, kxo, hash->blocksize))
113 return -1;
114 if (hash->update(param, data, hash->digestsize))
115 return -1;
116 if (hash->digest(param, data))
117 return -1;
118
119 return 0;
120}
121
122/*!\}
123 */
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.h
new file mode 100755
index 0000000000..709bb079f0
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.h
@@ -0,0 +1,53 @@
1/*
2 * Copyright (c) 1999, 2000, 2002 Virtual Unlimited B.V.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file hmac.h
21 * \brief HMAC algorithm, headers.
22 * \author Bob Deblier <bob.deblier@pandora.be>
23 * \ingroup HMAC_m
24 */
25
26#ifndef _HMAC_H
27#define _HMAC_H
28
29#include "beecrypt/beecrypt.h"
30
31/*!\ingroup HMAC_m
32 */
33
34#ifdef __cplusplus
35extern "C" {
36#endif
37
38/* not used directly as keyed hash function, but instead used as generic methods */
39
40BEECRYPTAPI
41int hmacSetup ( byte*, byte*, const hashFunction*, hashFunctionParam*, const byte*, size_t);
42BEECRYPTAPI
43int hmacReset (const byte*, const hashFunction*, hashFunctionParam*);
44BEECRYPTAPI
45int hmacUpdate( const hashFunction*, hashFunctionParam*, const byte*, size_t);
46BEECRYPTAPI
47int hmacDigest( const byte*, const hashFunction*, hashFunctionParam*, byte*);
48
49#ifdef __cplusplus
50}
51#endif
52
53#endif
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.c
new file mode 100755
index 0000000000..f201a45f0f
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.c
@@ -0,0 +1,77 @@
1/*
2 * Copyright (c) 1999, 2000, 2001, 2002 Virtual Unlimited B.V.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file hmacsha1.c
21 * \brief HMAC-SHA-1 message authentication code.
22 *
23 * \see RFC2202 - Test Cases for HMAC-MD5 and HMAC-SHA-1.
24 * P. Cheng, R. Glenn.
25 *
26 * \author Bob Deblier <bob.deblier@pandora.be>
27 * \ingroup HMAC_m HMAC_sha1_m
28 */
29
30#define BEECRYPT_DLL_EXPORT
31
32#if HAVE_CONFIG_H
33# include "config.h"
34#endif
35
36#include "beecrypt/hmacsha1.h"
37
38/*!\addtogroup HMAC_sha1_m
39 * \{
40 */
41
42const keyedHashFunction hmacsha1 = {
43 "HMAC-SHA-1",
44 sizeof(hmacsha1Param),
45 64,
46 20,
47 64,
48 512,
49 32,
50 (keyedHashFunctionSetup) hmacsha1Setup,
51 (keyedHashFunctionReset) hmacsha1Reset,
52 (keyedHashFunctionUpdate) hmacsha1Update,
53 (keyedHashFunctionDigest) hmacsha1Digest
54};
55
56int hmacsha1Setup (hmacsha1Param* sp, const byte* key, size_t keybits)
57{
58 return hmacSetup(sp->kxi, sp->kxo, &sha1, &sp->sparam, key, keybits);
59}
60
61int hmacsha1Reset (hmacsha1Param* sp)
62{
63 return hmacReset(sp->kxi, &sha1, &sp->sparam);
64}
65
66int hmacsha1Update(hmacsha1Param* sp, const byte* data, size_t size)
67{
68 return hmacUpdate(&sha1, &sp->sparam, data, size);
69}
70
71int hmacsha1Digest(hmacsha1Param* sp, byte* data)
72{
73 return hmacDigest(sp->kxo, &sha1, &sp->sparam, data);
74}
75
76/*!\}
77 */
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.h
new file mode 100755
index 0000000000..207f5df37f
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.h
@@ -0,0 +1,60 @@
1/*
2 * Copyright (c) 1999, 2000, 2001, 2002 Virtual Unlimited B.V.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file hmacsha1.h
21 * \brief HMAC-SHA-1 message authentication code, headers.
22 * \author Bob Deblier <bob.deblier@pandora.be>
23 * \ingroup HMAC_m HMAC_sha1_m
24 */
25
26#ifndef _HMACSHA1_H
27#define _HMACSHA1_H
28
29#include "beecrypt/hmac.h"
30#include "beecrypt/sha1.h"
31
32/*!\ingroup HMAC_sha1_m
33 */
34typedef struct
35{
36 sha1Param sparam;
37 byte kxi[64];
38 byte kxo[64];
39} hmacsha1Param;
40
41#ifdef __cplusplus
42extern "C" {
43#endif
44
45extern BEECRYPTAPI const keyedHashFunction hmacsha1;
46
47BEECRYPTAPI
48int hmacsha1Setup (hmacsha1Param*, const byte*, size_t);
49BEECRYPTAPI
50int hmacsha1Reset (hmacsha1Param*);
51BEECRYPTAPI
52int hmacsha1Update(hmacsha1Param*, const byte*, size_t);
53BEECRYPTAPI
54int hmacsha1Digest(hmacsha1Param*, byte*);
55
56#ifdef __cplusplus
57}
58#endif
59
60#endif
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/memchunk.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/memchunk.h
new file mode 100755
index 0000000000..4778b7ca89
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/memchunk.h
@@ -0,0 +1,53 @@
1/*
2 * Copyright (c) 2001 Virtual Unlimited B.V.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19/*!\file memchunk.h
20 * \author Bob Deblier <bob.deblier@pandora.be>
21 */
22
23#ifndef _MEMCHUNK_H
24#define _MEMCHUNK_H
25
26#include "beecrypt/api.h"
27
28typedef struct
29{
30 size_t size;
31 byte* data;
32} memchunk;
33
34#ifdef __cplusplus
35extern "C" {
36#endif
37
38BEECRYPTAPI
39memchunk* memchunkAlloc(size_t);
40BEECRYPTAPI
41void memchunkWipe(memchunk*);
42BEECRYPTAPI
43void memchunkFree(memchunk*);
44BEECRYPTAPI
45memchunk* memchunkResize(memchunk*, size_t);
46BEECRYPTAPI
47memchunk* memchunkClone(const memchunk*);
48
49#ifdef __cplusplus
50}
51#endif
52
53#endif
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.c
new file mode 100755
index 0000000000..82d272c17a
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.c
@@ -0,0 +1,1537 @@
1/*
2 * Copyright (c) 2002, 2003 Bob Deblier
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file mp.c
21 * \brief Multi-precision integer routines.
22 * \author Bob Deblier <bob.deblier@pandora.be>
23 * \ingroup MP_m
24 */
25
26#define BEECRYPT_DLL_EXPORT
27
28#if HAVE_CONFIG_H
29# include "config.h"
30#endif
31
32#include "beecrypt/mp.h"
33#include "beecrypt/mpopt.h"
34
35#ifndef ASM_MPZERO
36void mpzero(size_t size, mpw* data)
37{
38 while (size--)
39 *(data++) = 0;
40}
41#endif
42
43#ifndef ASM_MPFILL
44void mpfill(size_t size, mpw* data, mpw fill)
45{
46 while (size--)
47 *(data++) = fill;
48}
49#endif
50
51#ifndef ASM_MPODD
52int mpodd(size_t size, const mpw* data)
53{
54 return (int)(data[size-1] & 0x1);
55}
56#endif
57
58#ifndef ASM_MPEVEN
59int mpeven(size_t size, const mpw* data)
60{
61 return !(int)(data[size-1] & 0x1);
62}
63#endif
64
65#ifndef ASM_MPZ
66int mpz(size_t size, const mpw* data)
67{
68 while (size--)
69 if (*(data++))
70 return 0;
71 return 1;
72}
73#endif
74
75#ifndef ASM_MPNZ
76int mpnz(size_t size, const mpw* data)
77{
78 while (size--)
79 if (*(data++))
80 return 1;
81 return 0;
82}
83#endif
84
85#ifndef ASM_MPEQ
86int mpeq(size_t size, const mpw* xdata, const mpw* ydata)
87{
88 while (size--)
89 {
90 if (*xdata == *ydata)
91 {
92 xdata++;
93 ydata++;
94 }
95 else
96 return 0;
97 }
98 return 1;
99}
100#endif
101
102#ifndef ASM_MPEQX
103int mpeqx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
104{
105 if (xsize > ysize)
106 {
107 register size_t diff = xsize - ysize;
108 return mpeq(ysize, xdata+diff, ydata) && mpz(diff, xdata);
109 }
110 else if (xsize < ysize)
111 {
112 register size_t diff = ysize - xsize;
113 return mpeq(xsize, ydata+diff, xdata) && mpz(diff, ydata);
114 }
115 else
116 return mpeq(xsize, xdata, ydata);
117}
118#endif
119
120#ifndef ASM_MPNE
121int mpne(size_t size, const mpw* xdata, const mpw* ydata)
122{
123 while (size--)
124 {
125 if (*xdata == *ydata)
126 {
127 xdata++;
128 ydata++;
129 }
130 else
131 return 1;
132 }
133 return 0;
134}
135#endif
136
137#ifndef ASM_MPNEX
138int mpnex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
139{
140 if (xsize > ysize)
141 {
142 register size_t diff = xsize - ysize;
143 return mpnz(diff, xdata) || mpne(ysize, xdata+diff, ydata);
144 }
145 else if (xsize < ysize)
146 {
147 register size_t diff = ysize - xsize;
148 return mpnz(diff, ydata) || mpne(xsize, ydata+diff, xdata);
149 }
150 else
151 return mpne(xsize, xdata, ydata);
152}
153#endif
154
155#ifndef ASM_MPGT
156int mpgt(size_t size, const mpw* xdata, const mpw* ydata)
157{
158 while (size--)
159 {
160 if (*xdata < *ydata)
161 return 0;
162 if (*xdata > *ydata)
163 return 1;
164 xdata++; ydata++;
165 }
166 return 0;
167}
168#endif
169
170#ifndef ASM_MPGTX
171int mpgtx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
172{
173 if (xsize > ysize)
174 {
175 register size_t diff = xsize - ysize;
176 return mpnz(diff, xdata) || mpgt(ysize, xdata + diff, ydata);
177 }
178 else if (xsize < ysize)
179 {
180 register size_t diff = ysize - xsize;
181 return mpz(diff, ydata) && mpgt(xsize, xdata, ydata + diff);
182 }
183 else
184 return mpgt(xsize, xdata, ydata);
185}
186#endif
187
188#ifndef ASM_MPLT
189int mplt(size_t size, const mpw* xdata, const mpw* ydata)
190{
191 while (size--)
192 {
193 if (*xdata > *ydata)
194 return 0;
195 if (*xdata < *ydata)
196 return 1;
197 xdata++; ydata++;
198 }
199 return 0;
200}
201#endif
202
203#ifndef ASM_MPLTX
204int mpltx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
205{
206 if (xsize > ysize)
207 {
208 register size_t diff = xsize - ysize;
209 return mpz(diff, xdata) && mplt(ysize, xdata+diff, ydata);
210 }
211 else if (xsize < ysize)
212 {
213 register size_t diff = ysize - xsize;
214 return mpnz(diff, ydata) || mplt(xsize, xdata, ydata+diff);
215 }
216 else
217 return mplt(xsize, xdata, ydata);
218}
219#endif
220
221#ifndef ASM_MPGE
222int mpge(size_t size, const mpw* xdata, const mpw* ydata)
223{
224 while (size--)
225 {
226 if (*xdata < *ydata)
227 return 0;
228 if (*xdata > *ydata)
229 return 1;
230 xdata++; ydata++;
231 }
232 return 1;
233}
234#endif
235
236#ifndef ASM_MPGEX
237int mpgex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
238{
239 if (xsize > ysize)
240 {
241 register size_t diff = xsize - ysize;
242 return mpnz(diff, xdata) || mpge(ysize, xdata+diff, ydata);
243 }
244 else if (xsize < ysize)
245 {
246 register size_t diff = ysize - xsize;
247 return mpz(diff, ydata) && mpge(xsize, xdata, ydata+diff);
248 }
249 else
250 return mpge(xsize, xdata, ydata);
251}
252#endif
253
254#ifndef ASM_MPLE
255int mple(size_t size, const mpw* xdata, const mpw* ydata)
256{
257 while (size--)
258 {
259 if (*xdata < *ydata)
260 return 1;
261 if (*xdata > *ydata)
262 return 0;
263 xdata++; ydata++;
264 }
265 return 1;
266}
267#endif
268
269#ifndef ASM_MPLEX
270int mplex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
271{
272 if (xsize > ysize)
273 {
274 register size_t diff = xsize - ysize;
275 return mpz(diff, xdata) && mple(ysize, xdata+ diff, ydata);
276 }
277 else if (xsize < ysize)
278 {
279 register size_t diff = ysize - xsize;
280 return mpnz(diff, ydata) || mple(xsize, xdata, ydata+diff);
281 }
282 else
283 return mple(xsize, xdata, ydata);
284}
285#endif
286
287#ifndef ASM_MPISONE
288int mpisone(size_t size, const mpw* data)
289{
290 data += size;
291 if (*(--data) == 1)
292 {
293 while (--size)
294 if (*(--data))
295 return 0;
296 return 1;
297 }
298 return 0;
299}
300#endif
301
302#ifndef ASM_MPISTWO
303int mpistwo(size_t size, const mpw* data)
304{
305 data += size;
306 if (*(--data) == 2)
307 {
308 while (--size)
309 if (*(--data))
310 return 0;
311 return 1;
312 }
313 return 0;
314}
315#endif
316
317#ifndef ASM_MPEQMONE
318int mpeqmone(size_t size, const mpw* xdata, const mpw* ydata)
319{
320 xdata += size;
321 ydata += size;
322
323 if (*(--xdata)+1 == *(--ydata))
324 {
325 while (--size)
326 if (*(--xdata) != *(--ydata))
327 return 0;
328 return 1;
329 }
330 return 0;
331}
332#endif
333
334#ifndef ASM_MPLEONE
335int mpleone(size_t size, const mpw* data)
336{
337 data += size;
338 if (*(--data) > 1)
339 return 0;
340 else
341 {
342 while (--size)
343 if (*(--data))
344 return 0;
345 return 1;
346 }
347}
348#endif
349
350#ifndef ASM_MPMSBSET
351int mpmsbset(size_t size, const mpw* data)
352{
353 return (int)((*data) >> (MP_WBITS-1));
354}
355#endif
356
357#ifndef ASM_MPLSBSET
358int mplsbset(size_t size, const mpw* data)
359{
360 return (int)(data[size-1] & 0x1);
361}
362#endif
363
364#ifndef ASM_MPSETMSB
365void mpsetmsb(size_t size, mpw* data)
366{
367 *data |= MP_MSBMASK;
368}
369#endif
370
371#ifndef ASM_MPSETLSB
372void mpsetlsb(size_t size, mpw* data)
373{
374 data[size-1] |= MP_LSBMASK;
375}
376#endif
377
378#ifndef ASM_MPCLRMSB
379void mpclrmsb(size_t size, mpw* data)
380{
381 *data &= ~ MP_MSBMASK;
382}
383#endif
384
385#ifndef ASM_MPCLRLSB
386void mpclrlsb(size_t size, mpw* data)
387{
388 data[size-1] &= ~ MP_LSBMASK;
389}
390#endif
391
392#ifndef ASM_MPAND
393void mpand(size_t size, mpw* xdata, const mpw* ydata)
394{
395 while (size--)
396 xdata[size] &= ydata[size];
397}
398#endif
399
400#ifndef ASM_MPOR
401void mpor(size_t size, mpw* xdata, const mpw* ydata)
402{
403 while (size--)
404 xdata[size] |= ydata[size];
405}
406#endif
407
408#ifndef ASM_MPXOR
409void mpxor(size_t size, mpw* xdata, const mpw* ydata)
410{
411 while (size--)
412 xdata[size] ^= ydata[size];
413}
414#endif
415
416#ifndef ASM_MPNOT
417void mpnot(size_t size, mpw* data)
418{
419 while (size--)
420 data[size] = ~data[size];
421}
422#endif
423
424#ifndef ASM_MPSETW
425void mpsetw(size_t size, mpw* xdata, mpw y)
426{
427 while (--size)
428 *(xdata++) = 0;
429 *(xdata++) = y;
430}
431#endif
432
433#ifndef ASM_MPSETX
434void mpsetx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata)
435{
436 while (xsize > ysize)
437 {
438 xsize--;
439 *(xdata++) = 0;
440 }
441 while (ysize > xsize)
442 {
443 ysize--;
444 ydata++;
445 }
446 while (xsize--)
447 *(xdata++) = *(ydata++);
448}
449#endif
450
451#ifndef ASM_MPADDW
452int mpaddw(size_t size, mpw* xdata, mpw y)
453{
454 register mpw load, temp;
455 register int carry = 0;
456
457 xdata += size-1;
458
459 load = *xdata;
460 temp = load + y;
461 *(xdata--) = temp;
462 carry = (load > temp);
463
464 while (--size && carry)
465 {
466 load = *xdata;
467 temp = load + 1;
468 *(xdata--) = temp;
469 carry = (load > temp);
470 }
471 return carry;
472}
473#endif
474
475#ifndef ASM_MPADD
476int mpadd(size_t size, mpw* xdata, const mpw* ydata)
477{
478 register mpw load, temp;
479 register int carry = 0;
480
481 xdata += size-1;
482 ydata += size-1;
483
484 while (size--)
485 {
486 temp = *(ydata--);
487 load = *xdata;
488 temp = carry ? (load + temp + 1) : (load + temp);
489 *(xdata--) = temp;
490 carry = carry ? (load >= temp) : (load > temp);
491 }
492 return carry;
493}
494#endif
495
496#ifndef ASM_MPADDX
497int mpaddx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata)
498{
499 if (xsize > ysize)
500 {
501 register size_t diff = xsize - ysize;
502 return mpaddw(diff, xdata, (mpw) mpadd(ysize, xdata+diff, ydata));
503 }
504 else
505 {
506 register size_t diff = ysize - xsize;
507 return mpadd(xsize, xdata, ydata+diff);
508 }
509}
510#endif
511
512#ifndef ASM_MPSUBW
513int mpsubw(size_t size, mpw* xdata, mpw y)
514{
515 register mpw load, temp;
516 register int carry = 0;
517
518 xdata += size-1;
519
520 load = *xdata;
521 temp = load - y;
522 *(xdata--) = temp;
523 carry = (load < temp);
524
525 while (--size && carry)
526 {
527 load = *xdata;
528 temp = load - 1;
529 *(xdata--) = temp;
530 carry = (load < temp);
531 }
532 return carry;
533}
534#endif
535
536#ifndef ASM_MPSUB
537int mpsub(size_t size, mpw* xdata, const mpw* ydata)
538{
539 register mpw load, temp;
540 register int carry = 0;
541
542 xdata += size-1;
543 ydata += size-1;
544
545 while (size--)
546 {
547 temp = *(ydata--);
548 load = *xdata;
549 temp = carry ? (load - temp - 1) : (load - temp);
550 *(xdata--) = temp;
551 carry = carry ? (load <= temp) : (load < temp);
552 }
553 return carry;
554}
555#endif
556
557#ifndef ASM_MPSUBX
558int mpsubx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata)
559{
560 if (xsize > ysize)
561 {
562 register size_t diff = xsize - ysize;
563 return mpsubw(diff, xdata, (mpw) mpsub(ysize, xdata+diff, ydata));
564 }
565 else
566 {
567 register size_t diff = ysize - xsize;
568 return mpsub(xsize, xdata, ydata+diff);
569 }
570}
571#endif
572
573#ifndef ASM_MPNEG
574void mpneg(size_t size, mpw* data)
575{
576 mpnot(size, data);
577 mpaddw(size, data, 1);
578}
579#endif
580
581#ifndef ASM_MPSETMUL
582mpw mpsetmul(size_t size, mpw* result, const mpw* data, mpw y)
583{
584 #if HAVE_MPDW
585 register mpdw temp;
586 register mpw carry = 0;
587
588 data += size;
589 result += size;
590
591 while (size--)
592 {
593 temp = *(--data);
594 temp *= y;
595 temp += carry;
596 *(--result) = (mpw) temp;
597 carry = (mpw)(temp >> MP_WBITS);
598 }
599 #else
600 register mpw temp, load, carry = 0;
601 register mphw ylo, yhi;
602
603 ylo = (mphw) y;
604 yhi = (mphw) (y >> MP_HWBITS);
605
606 data += size;
607 result += size;
608
609 while (size--)
610 {
611 register mphw xlo, xhi;
612 register mpw rlo, rhi;
613
614 xlo = (mphw) (temp = *(--data));
615 xhi = (mphw) (temp >> MP_HWBITS);
616
617 rlo = (mpw) xlo * ylo;
618 rhi = (mpw) xhi * yhi;
619 load = rlo;
620 temp = (mpw) xhi * ylo;
621 rlo += (temp << MP_HWBITS);
622 rhi += (temp >> MP_HWBITS) + (load > rlo);
623 load = rlo;
624 temp = (mpw) xlo * yhi;
625 rlo += (temp << MP_HWBITS);
626 rhi += (temp >> MP_HWBITS) + (load > rlo);
627 load = rlo;
628 temp = rlo + carry;
629 carry = rhi + (load > temp);
630 *(--result) = temp;
631 }
632 #endif
633 return carry;
634}
635#endif
636
637#ifndef ASM_MPADDMUL
638mpw mpaddmul(size_t size, mpw* result, const mpw* data, mpw y)
639{
640 #if HAVE_MPDW
641 register mpdw temp;
642 register mpw carry = 0;
643
644 data += size;
645 result += size;
646
647 while (size--)
648 {
649 temp = *(--data);
650 temp *= y;
651 temp += carry;
652 temp += *(--result);
653 *result = (mpw) temp;
654 carry = (mpw)(temp >> MP_WBITS);
655 }
656 #else
657 register mpw temp, load, carry = 0;
658 register mphw ylo, yhi;
659
660 ylo = (mphw) y;
661 yhi = (mphw) (y >> MP_HWBITS);
662
663 data += size;
664 result += size;
665
666 while (size--)
667 {
668 register mphw xlo, xhi;
669 register mpw rlo, rhi;
670
671 xlo = (mphw) (temp = *(--data));
672 xhi = (mphw) (temp >> MP_HWBITS);
673
674 rlo = (mpw) xlo * ylo;
675 rhi = (mpw) xhi * yhi;
676 load = rlo;
677 temp = (mpw) xhi * ylo;
678 rlo += (temp << MP_HWBITS);
679 rhi += (temp >> MP_HWBITS) + (load > rlo);
680 load = rlo;
681 temp = (mpw) xlo * yhi;
682 rlo += (temp << MP_HWBITS);
683 rhi += (temp >> MP_HWBITS) + (load > rlo);
684 load = rlo;
685 rlo += carry;
686 temp = (load > rlo);
687 load = rhi;
688 rhi += temp;
689 carry = (load > rhi);
690 load = rlo;
691 rlo += *(--result);
692 *result = rlo;
693 carry += rhi + (load > rlo);
694 }
695 #endif
696 return carry;
697}
698#endif
699
700#ifndef ASM_MPMUL
701void mpmul(mpw* result, size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
702{
703 /* preferred passing of parameters is x the larger of the two numbers */
704 if (xsize >= ysize)
705 {
706 register mpw rc;
707
708 result += ysize;
709 ydata += ysize;
710
711 rc = mpsetmul(xsize, result, xdata, *(--ydata));
712 *(--result) = rc;
713
714 while (--ysize)
715 {
716 rc = mpaddmul(xsize, result, xdata, *(--ydata));
717 *(--result) = rc;
718 }
719 }
720 else
721 {
722 register mpw rc;
723
724 result += xsize;
725 xdata += xsize;
726
727 rc = mpsetmul(ysize, result, ydata, *(--xdata));
728 *(--result) = rc;
729
730 while (--xsize)
731 {
732 rc = mpaddmul(ysize, result, ydata, *(--xdata));
733 *(--result) = rc;
734 }
735 }
736}
737#endif
738
739#ifndef ASM_MPADDSQRTRC
740void mpaddsqrtrc(size_t size, mpw* result, const mpw* data)
741{
742 #if HAVE_MPDW
743 register mpdw temp;
744 register mpw load, carry = 0;
745
746 result += (size << 1);
747
748 while (size--)
749 {
750 temp = load = data[size];
751 temp *= load;
752 temp += carry;
753 temp += *(--result);
754 *result = (mpw) temp;
755 temp >>= MP_WBITS;
756 temp += *(--result);
757 *result = (mpw) temp;
758 carry = (mpw)(temp >> MP_WBITS);
759 }
760 #else
761 register mpw temp, load, carry = 0;
762
763 result += (size << 1);
764
765 while (size--)
766 {
767 register mphw xlo, xhi;
768 register mpw rlo, rhi;
769
770 xlo = (mphw) (temp = data[size]);
771 xhi = (mphw) (temp >> MP_HWBITS);
772
773 rlo = (mpw) xlo * xlo;
774 rhi = (mpw) xhi * xhi;
775 temp = (mpw) xhi * xlo;
776 load = rlo;
777 rlo += (temp << MP_HWBITS);
778 rhi += (temp >> MP_HWBITS) + (load > rlo);
779 load = rlo;
780 rlo += (temp << MP_HWBITS);
781 rhi += (temp >> MP_HWBITS) + (load > rlo);
782 load = rlo;
783 rlo += carry;
784 rhi += (load > rlo);
785 load = rlo;
786 rlo += *(--result);
787 *result = rlo;
788 temp = (load > rlo);
789 load = rhi;
790 rhi += temp;
791 carry = (load > rhi);
792 load = rhi;
793 rhi += *(--result);
794 *result = rhi;
795 carry += (load > rhi);
796 }
797 #endif
798}
799#endif
800
801#ifndef ASM_MPSQR
802void mpsqr(mpw* result, size_t size, const mpw* data)
803{
804 register mpw rc;
805 register size_t n = size-1;
806
807 result += size;
808 result[n] = 0;
809
810 if (n)
811 {
812 rc = mpsetmul(n, result, data, data[n]);
813 *(--result) = rc;
814 while (--n)
815 {
816 rc = mpaddmul(n, result, data, data[n]);
817 *(--result) = rc;
818 }
819 }
820
821 *(--result) = 0;
822
823 mpmultwo(size << 1, result);
824
825 mpaddsqrtrc(size, result, data);
826}
827#endif
828
829#ifndef ASM_MPSIZE
830size_t mpsize(size_t size, const mpw* data)
831{
832 while (size)
833 {
834 if (*data)
835 return size;
836 data++;
837 size--;
838 }
839 return 0;
840}
841#endif
842
843#ifndef ASM_MPBITS
844size_t mpbits(size_t size, const mpw* data)
845{
846 return MP_WORDS_TO_BITS(size) - mpmszcnt(size, data);
847}
848#endif
849
850#ifndef ASM_MPNORM
851size_t mpnorm(size_t size, mpw* data)
852{
853 register size_t shift = mpmszcnt(size, data);
854 mplshift(size, data, shift);
855 return shift;
856}
857#endif
858
859#ifndef ASM_MPDIVTWO
860void mpdivtwo(size_t size, mpw* data)
861{
862 register mpw temp, carry = 0;
863
864 while (size--)
865 {
866 temp = *data;
867 *(data++) = (temp >> 1) | carry;
868 carry = (temp << (MP_WBITS-1));
869 }
870}
871#endif
872
873#ifndef ASM_MPSDIVTWO
874void mpsdivtwo(size_t size, mpw* data)
875{
876 int carry = mpmsbset(size, data);
877 mpdivtwo(size, data);
878 if (carry)
879 mpsetmsb(size, data);
880}
881#endif
882
883#ifndef ASM_MPMULTWO
884int mpmultwo(size_t size, mpw* data)
885{
886 register mpw temp, carry = 0;
887
888 data += size;
889 while (size--)
890 {
891 temp = *(--data);
892 *data = (temp << 1) | carry;
893 carry = (temp >> (MP_WBITS-1));
894 }
895 return (int) carry;
896}
897#endif
898
899#ifndef ASM_MPMSZCNT
900size_t mpmszcnt(size_t size, const mpw* data)
901{
902 register size_t zbits = 0;
903 register size_t i = 0;
904
905 while (i < size)
906 {
907 register mpw temp = data[i++];
908 if (temp)
909 {
910 while (!(temp & MP_MSBMASK))
911 {
912 zbits++;
913 temp <<= 1;
914 }
915 break;
916 }
917 else
918 zbits += MP_WBITS;
919 }
920 return zbits;
921}
922#endif
923
924#ifndef ASM_MPLSZCNT
925size_t mplszcnt(size_t size, const mpw* data)
926{
927 register size_t zbits = 0;
928
929 while (size--)
930 {
931 register mpw temp = data[size];
932 if (temp)
933 {
934 while (!(temp & MP_LSBMASK))
935 {
936 zbits++;
937 temp >>= 1;
938 }
939 break;
940 }
941 else
942 zbits += MP_WBITS;
943 }
944 return zbits;
945}
946#endif
947
948#ifndef ASM_MPLSHIFT
949void mplshift(size_t size, mpw* data, size_t count)
950{
951 register size_t words = MP_BITS_TO_WORDS(count);
952
953 if (words < size)
954 {
955 register short lbits = (short) (count & (MP_WBITS-1));
956
957 /* first do the shifting, then do the moving */
958 if (lbits)
959 {
960 register mpw temp, carry = 0;
961 register short rbits = MP_WBITS - lbits;
962 register size_t i = size;
963
964 while (i > words)
965 {
966 temp = data[--i];
967 data[i] = (temp << lbits) | carry;
968 carry = (temp >> rbits);
969 }
970 }
971 if (words)
972 {
973 mpmove(size-words, data, data+words);
974 mpzero(words, data+size-words);
975 }
976 }
977 else
978 mpzero(size, data);
979}
980#endif
981
982#ifndef ASM_MPRSHIFT
983void mprshift(size_t size, mpw* data, size_t count)
984{
985 register size_t words = MP_BITS_TO_WORDS(count);
986
987 if (words < size)
988 {
989 register short rbits = (short) (count & (MP_WBITS-1));
990
991 /* first do the shifting, then do the moving */
992 if (rbits)
993 {
994 register mpw temp, carry = 0;
995 register short lbits = MP_WBITS - rbits;
996 register size_t i = 0;
997
998 while (i < size-words)
999 {
1000 temp = data[i];
1001 data[i++] = (temp >> rbits) | carry;
1002 carry = (temp << lbits);
1003 }
1004 }
1005 if (words)
1006 {
1007 mpmove(size-words, data+words, data);
1008 mpzero(words, data);
1009 }
1010 }
1011 else
1012 mpzero(size, data);
1013}
1014#endif
1015
1016#ifndef ASM_MPRSHIFTLSZ
1017size_t mprshiftlsz(size_t size, mpw* data)
1018{
1019 register mpw* slide = data+size-1;
1020 register size_t zwords = 0; /* counter for 'all zero bit' words */
1021 register short lbits, rbits = 0; /* counter for 'least significant zero' bits */
1022 register mpw temp, carry = 0;
1023
1024 data = slide;
1025
1026 /* count 'all zero' words and move src pointer */
1027 while (size--)
1028 {
1029 /* test if we have a non-zero word */
1030 if ((carry = *(slide--)))
1031 {
1032 /* count 'least signification zero bits and set zbits counter */
1033 while (!(carry & MP_LSBMASK))
1034 {
1035 carry >>= 1;
1036 rbits++;
1037 }
1038 break;
1039 }
1040 zwords++;
1041 }
1042
1043 if ((rbits == 0) && (zwords == 0))
1044 return 0;
1045
1046 /* prepare right-shifting of data */
1047 lbits = MP_WBITS - rbits;
1048
1049 /* shift data */
1050 while (size--)
1051 {
1052 temp = *(slide--);
1053 *(data--) = (temp << lbits) | carry;
1054 carry = (temp >> rbits);
1055 }
1056
1057 /* store the final carry */
1058 *(data--) = carry;
1059
1060 /* store the return value in size */
1061 size = MP_WORDS_TO_BITS(zwords) + rbits;
1062
1063 /* zero the (zwords) most significant words */
1064 while (zwords--)
1065 *(data--) = 0;
1066
1067 return size;
1068}
1069#endif
1070
1071/* try an alternate version here, with descending sizes */
1072/* also integrate lszcnt and rshift properly into one function */
1073#ifndef ASM_MPGCD_W
1074/*
1075 * mpgcd_w
1076 * need workspace of (size) words
1077 */
1078void mpgcd_w(size_t size, const mpw* xdata, const mpw* ydata, mpw* result, mpw* wksp)
1079{
1080 register size_t shift, temp;
1081
1082 if (mpge(size, xdata, ydata))
1083 {
1084 mpcopy(size, wksp, xdata);
1085 mpcopy(size, result, ydata);
1086 }
1087 else
1088 {
1089 mpcopy(size, wksp, ydata);
1090 mpcopy(size, result, xdata);
1091 }
1092
1093 /* get the smallest returned values, and set shift to that */
1094
1095 shift = mprshiftlsz(size, wksp);
1096 temp = mprshiftlsz(size, result);
1097
1098 if (shift > temp)
1099 shift = temp;
1100
1101 while (mpnz(size, wksp))
1102 {
1103 mprshiftlsz(size, wksp);
1104 mprshiftlsz(size, result);
1105
1106 if (mpge(size, wksp, result))
1107 mpsub(size, wksp, result);
1108 else
1109 mpsub(size, result, wksp);
1110
1111 /* slide past zero words in both operands by increasing pointers and decreasing size */
1112 if ((*wksp == 0) && (*result == 0))
1113 {
1114 size--;
1115 wksp++;
1116 result++;
1117 }
1118 }
1119
1120 /* figure out if we need to slide the result pointer back */
1121 if ((temp = MP_BITS_TO_WORDS(shift)))
1122 {
1123 size += temp;
1124 result -= temp;
1125 }
1126
1127 mplshift(size, result, shift);
1128}
1129#endif
1130
1131#ifndef ASM_MPEXTGCD_W
1132/* needs workspace of (6*size+6) words */
1133/* used to compute the modular inverse */
1134int mpextgcd_w(size_t size, const mpw* xdata, const mpw* ydata, mpw* result, mpw* wksp)
1135{
1136 /*
1137 * For computing a modular inverse, pass the modulus as xdata and the number
1138 * to be inverted as ydata.
1139 *
1140 * Fact: if a element of Zn, then a is invertible if and only if gcd(a,n) = 1
1141 * Hence: if n is even, then a must be odd, otherwise the gcd(a,n) >= 2
1142 *
1143 * The calling routine must guarantee this condition.
1144 */
1145
1146 register size_t sizep = size+1;
1147 register int full;
1148
1149 mpw* udata = wksp;
1150 mpw* vdata = udata+sizep;
1151 mpw* adata = vdata+sizep;
1152 mpw* bdata = adata+sizep;
1153 mpw* cdata = bdata+sizep;
1154 mpw* ddata = cdata+sizep;
1155
1156 mpsetx(sizep, udata, size, xdata);
1157 mpsetx(sizep, vdata, size, ydata);
1158 mpzero(sizep, bdata);
1159 mpsetw(sizep, ddata, 1);
1160
1161 if ((full = mpeven(sizep, udata)))
1162 {
1163 mpsetw(sizep, adata, 1);
1164 mpzero(sizep, cdata);
1165 }
1166
1167 while (1)
1168 {
1169 while (mpeven(sizep, udata))
1170 {
1171 mpdivtwo(sizep, udata);
1172
1173 if (mpodd(sizep, bdata) || (full && mpodd(sizep, adata)))
1174 {
1175 if (full) mpaddx(sizep, adata, size, ydata);
1176 mpsubx(sizep, bdata, size, xdata);
1177 }
1178
1179 if (full) mpsdivtwo(sizep, adata);
1180 mpsdivtwo(sizep, bdata);
1181 }
1182 while (mpeven(sizep, vdata))
1183 {
1184 mpdivtwo(sizep, vdata);
1185
1186 if (mpodd(sizep, ddata) || (full && mpodd(sizep, cdata)))
1187 {
1188 if (full) mpaddx(sizep, cdata, size, ydata);
1189 mpsubx(sizep, ddata, size, xdata);
1190 }
1191
1192 if (full) mpsdivtwo(sizep, cdata);
1193 mpsdivtwo(sizep, ddata);
1194 }
1195 if (mpge(sizep, udata, vdata))
1196 {
1197 mpsub(sizep, udata, vdata);
1198 if (full) mpsub(sizep, adata, cdata);
1199 mpsub(sizep, bdata, ddata);
1200 }
1201 else
1202 {
1203 mpsub(sizep, vdata, udata);
1204 if (full) mpsub(sizep, cdata, adata);
1205 mpsub(sizep, ddata, bdata);
1206 }
1207 if (mpz(sizep, udata))
1208 {
1209 if (mpisone(sizep, vdata))
1210 {
1211 if (result)
1212 {
1213 if (*ddata & MP_MSBMASK)
1214 {
1215 /* keep adding the modulus until we get a carry */
1216 while (!mpaddx(sizep, ddata, size, xdata));
1217 }
1218 else
1219 {
1220 /* in some computations, d ends up > x, hence:
1221 * keep subtracting n from d until d < x
1222 */
1223 while (mpgtx(sizep, ddata, size, xdata))
1224 mpsubx(sizep, ddata, size, xdata);
1225 }
1226 mpsetx(size, result, sizep, ddata);
1227 }
1228 return 1;
1229 }
1230 return 0;
1231 }
1232 }
1233}
1234#endif
1235
1236#ifndef ASM_MPPNDIV
1237mpw mppndiv(mpw xhi, mpw xlo, mpw y)
1238{
1239 register mpw result = 0;
1240 register short count = MP_WBITS;
1241 register int carry = 0;
1242
1243 while (count--)
1244 {
1245 if (carry | (xhi >= y))
1246 {
1247 xhi -= y;
1248 result++;
1249 }
1250 carry = (xhi >> (MP_WBITS-1));
1251 xhi <<= 1;
1252 xhi |= (xlo >> (MP_WBITS-1));
1253 xlo <<= 1;
1254 result <<= 1;
1255 }
1256 if (carry | (xhi >= y))
1257 {
1258 xhi -= y;
1259 result++;
1260 }
1261 return result;
1262}
1263#endif
1264
1265#ifndef ASM_MPMOD
1266void mpmod(mpw* result, size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata, mpw* workspace)
1267{
1268 /* result size xsize, workspace size 2*ysize+1 */
1269 mpw q, msw;
1270 mpw* rdata = result;
1271 mpw* ynorm = workspace+ysize+1;
1272 size_t shift, qsize = xsize-ysize;
1273
1274 mpcopy(ysize, ynorm, ydata);
1275 shift = mpnorm(ysize, ynorm);
1276 msw = *ynorm;
1277 mpcopy(xsize, rdata, xdata);
1278 if (mpge(ysize, rdata, ynorm))
1279 mpsub(ysize, rdata, ynorm);
1280
1281 while (qsize--)
1282 {
1283 q = mppndiv(rdata[0], rdata[1], msw);
1284
1285 *workspace = mpsetmul(ysize, workspace+1, ynorm, q);
1286
1287 while (mplt(ysize+1, rdata, workspace))
1288 {
1289 mpsubx(ysize+1, workspace, ysize, ynorm);
1290 q--;
1291 }
1292 mpsub(ysize+1, rdata, workspace);
1293 rdata++;
1294 }
1295 /* de-normalization steps */
1296 while (shift--)
1297 {
1298 mpdivtwo(ysize, ynorm);
1299 if (mpge(ysize, rdata, ynorm))
1300 mpsub(ysize, rdata, ynorm);
1301 }
1302}
1303#endif
1304
1305#ifndef ASM_MPNDIVMOD
1306void mpndivmod(mpw* result, size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata, register mpw* workspace)
1307{
1308 /* result must be xsize+1 in length */
1309 /* workspace must be ysize+1 in length */
1310 /* expect ydata to be normalized */
1311 mpw q;
1312 mpw msw = *ydata;
1313 size_t qsize = xsize-ysize;
1314
1315 *result = (mpge(ysize, xdata, ydata) ? 1 : 0);
1316 mpcopy(xsize, result+1, xdata);
1317
1318 if (*result)
1319 (void) mpsub(ysize, result+1, ydata);
1320
1321 result++;
1322
1323 while (qsize--)
1324 {
1325 q = mppndiv(result[0], result[1], msw);
1326
1327 *workspace = mpsetmul(ysize, workspace+1, ydata, q);
1328
1329 while (mplt(ysize+1, result, workspace))
1330 {
1331 mpsubx(ysize+1, workspace, ysize, ydata);
1332 q--;
1333 }
1334 mpsub(ysize+1, result, workspace);
1335 *(result++) = q;
1336 }
1337}
1338#endif
1339
1340void mpprint(size_t size, const mpw* data)
1341{
1342 mpfprint(stdout, size, data);
1343}
1344
1345void mpprintln(size_t size, const mpw* data)
1346{
1347 mpfprintln(stdout, size, data);
1348}
1349
1350void mpfprint(FILE* f, size_t size, const mpw* data)
1351{
1352 if (data == (mpw*) 0)
1353 return;
1354
1355 if (f == (FILE*) 0)
1356 return;
1357
1358 while (size--)
1359 {
1360 #if (MP_WBITS == 32)
1361 fprintf(f, "%08x", (unsigned) *(data++));
1362 #elif (MP_WBITS == 64)
1363 # if WIN32
1364 fprintf(f, "%016I64x", *(data++));
1365 # elif SIZEOF_UNSIGNED_LONG == 8
1366 fprintf(f, "%016lx", *(data++));
1367 # else
1368 fprintf(f, "%016llx", *(data++));
1369 # endif
1370 #else
1371 # error
1372 #endif
1373 }
1374 fflush(f);
1375}
1376
1377void mpfprintln(FILE* f, size_t size, const mpw* data)
1378{
1379 if (data == (mpw*) 0)
1380 return;
1381
1382 if (f == (FILE*) 0)
1383 return;
1384
1385 while (size--)
1386 {
1387 #if (MP_WBITS == 32)
1388 fprintf(f, "%08x", *(data++));
1389 #elif (MP_WBITS == 64)
1390 # if WIN32
1391 fprintf(f, "%016I64x", *(data++));
1392 # elif SIZEOF_UNSIGNED_LONG == 8
1393 fprintf(f, "%016lx", *(data++));
1394 # else
1395 fprintf(f, "%016llx", *(data++));
1396 # endif
1397 #else
1398 # error
1399 #endif
1400 }
1401 fprintf(f, "\n");
1402 fflush(f);
1403}
1404
1405int i2osp(byte *osdata, size_t ossize, const mpw* idata, size_t isize)
1406{
1407 #if WORDS_BIGENDIAN
1408 size_t max_bytes = MP_WORDS_TO_BYTES(isize);
1409 #endif
1410 size_t significant_bytes = (mpbits(isize, idata) + 7) >> 3;
1411
1412 /* verify that ossize is large enough to contain the significant bytes */
1413 if (ossize >= significant_bytes)
1414 {
1415 /* looking good; check if we have more space than significant bytes */
1416 if (ossize > significant_bytes)
1417 { /* fill most significant bytes with zero */
1418 memset(osdata, 0, ossize - significant_bytes);
1419 osdata += ossize - significant_bytes;
1420 }
1421 if (significant_bytes)
1422 { /* fill remaining bytes with endian-adjusted data */
1423 #if !WORDS_BIGENDIAN
1424 mpw w = idata[--isize];
1425 byte shift = 0;
1426
1427 /* fill right-to-left; much easier than left-to-right */
1428 do
1429 {
1430 osdata[--significant_bytes] = (byte)(w >> shift);
1431 shift += 8;
1432 if (shift == MP_WBITS)
1433 {
1434 shift = 0;
1435 w = idata[--isize];
1436 }
1437 } while (significant_bytes);
1438 #else
1439 /* just copy data past zero bytes */
1440 memcpy(osdata, ((byte*) idata) + (max_bytes - significant_bytes), significant_bytes);
1441 #endif
1442 }
1443 return 0;
1444 }
1445 return -1;
1446}
1447
1448int os2ip(mpw* idata, size_t isize, const byte* osdata, size_t ossize)
1449{
1450 size_t required;
1451
1452 /* skip non-significant leading zero bytes */
1453 while (!(*osdata) && ossize)
1454 {
1455 osdata++;
1456 ossize--;
1457 }
1458
1459 required = MP_BYTES_TO_WORDS(ossize + MP_WBYTES - 1);
1460
1461 if (isize >= required)
1462 {
1463 /* yes, we have enough space and can proceed */
1464 mpw w = 0;
1465 /* adjust counter so that the loop will start by skipping the proper
1466 * amount of leading bytes in the first significant word
1467 */
1468 byte b = (ossize % MP_WBYTES);
1469
1470 if (isize > required)
1471 { /* fill initials words with zero */
1472 mpzero(isize-required, idata);
1473 idata += isize-required;
1474 }
1475
1476 if (b == 0)
1477 b = MP_WBYTES;
1478
1479 while (ossize--)
1480 {
1481 w <<= 8;
1482 w |= *(osdata++);
1483 b--;
1484
1485 if (b == 0)
1486 {
1487 *(idata++) = w;
1488 w = 0;
1489 b = MP_WBYTES;
1490 }
1491 }
1492
1493 return 0;
1494 }
1495 return -1;
1496}
1497
1498int hs2ip(mpw* idata, size_t isize, const char* hsdata, size_t hssize)
1499{
1500 size_t required = MP_NIBBLES_TO_WORDS(hssize + MP_WNIBBLES - 1);
1501
1502 if (isize >= required)
1503 {
1504 register size_t i;
1505
1506
1507 if (isize > required)
1508 { /* fill initial words with zero */
1509 for (i = required; i < isize; i++)
1510 *(idata++) = 0;
1511 }
1512 while (hssize)
1513 {
1514 register mpw w = 0;
1515 register size_t chunk = hssize & (MP_WNIBBLES - 1);
1516 register char ch;
1517
1518 if (chunk == 0) chunk = MP_WNIBBLES;
1519
1520 for (i = 0; i < chunk; i++)
1521 {
1522 ch = *(hsdata++);
1523 w <<= 4;
1524 if (ch >= '0' && ch <= '9')
1525 w += (ch - '0');
1526 else if (ch >= 'A' && ch <= 'F')
1527 w += (ch - 'A') + 10;
1528 else if (ch >= 'a' && ch <= 'f')
1529 w += (ch - 'a') + 10;
1530 }
1531 *(idata++) = w;
1532 hssize -= chunk;
1533 }
1534 return 0;
1535 }
1536 return -1;
1537}
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.h
new file mode 100755
index 0000000000..57a3e6c502
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.h
@@ -0,0 +1,691 @@
1/*
2 * Copyright (c) 2002, 2003 Bob Deblier
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file mp.h
21 * \brief Multi-precision integer routines.
22 *
23 * The routines declared here are all low-level operations, most of them
24 * suitable to be implemented in assembler. Prime candidates are in order
25 * of importance (according to gprof):
26 * <ul>
27 * <li>mpaddmul
28 * <li>mpsetmul
29 * <li>mpaddsqrtrc
30 * <li>mpsub
31 * <li>mpadd
32 * </ul>
33 *
34 * With some smart use of available assembler instructions, it's possible
35 * to speed these routines up by a factor of 2 to 4.
36 *
37 * \author Bob Deblier <bob.deblier@pandora.be>
38 * \ingroup MP_m
39 */
40
41#ifndef _MP_H
42#define _MP_H
43
44#include "beecrypt/api.h"
45#include "beecrypt/mpopt.h"
46
47#define MP_HWBITS (MP_WBITS >> 1)
48#define MP_WBYTES (MP_WBITS >> 3)
49#define MP_WNIBBLES (MP_WBITS >> 2)
50
51#if (MP_WBITS == 64)
52# define MP_WORDS_TO_BITS(x) ((x) << 6)
53# define MP_WORDS_TO_NIBBLES(x) ((x) << 4)
54# define MP_WORDS_TO_BYTES(x) ((x) << 3)
55# define MP_BITS_TO_WORDS(x) ((x) >> 6)
56# define MP_NIBBLES_TO_WORDS(x) ((x) >> 4)
57# define MP_BYTES_TO_WORDS(x) ((x) >> 3)
58#elif (MP_WBITS == 32)
59# define MP_WORDS_TO_BITS(x) ((x) << 5)
60# define MP_WORDS_TO_NIBBLES(x) ((x) << 3)
61# define MP_WORDS_TO_BYTES(x) ((x) << 2)
62# define MP_BITS_TO_WORDS(x) ((x) >> 5)
63# define MP_NIBBLES_TO_WORDS(x) ((x) >> 3)
64# define MP_BYTES_TO_WORDS(x) ((x) >> 2)
65#else
66# error
67#endif
68
69#define MP_MSBMASK (((mpw) 0x1) << (MP_WBITS-1))
70#define MP_LSBMASK ((mpw) 0x1)
71#define MP_ALLMASK ~((mpw) 0x0)
72
73#ifdef __cplusplus
74extern "C" {
75#endif
76
77#ifndef ASM_MPCOPY
78# define mpcopy(size, dst, src) memcpy(dst, src, MP_WORDS_TO_BYTES(size))
79#else
80BEECRYPTAPI
81void mpcopy(size_t size, mpw* dest, const mpw* src);
82#endif
83
84#ifndef ASM_MPMOVE
85# define mpmove(size, dst, src) memmove(dst, src, MP_WORDS_TO_BYTES(size))
86#else
87BEECRYPTAPI
88void mpmove(size_t size, mpw* dest, const mpw* src);
89#endif
90
91/*!\fn void mpzero(size_t size, mpw* data)
92 * \brief This function zeroes a multi-precision integer of a given size.
93 * \param size The size of the multi-precision integer.
94 * \param data The multi-precision integer data.
95 */
96BEECRYPTAPI
97void mpzero(size_t size, mpw* data);
98
99/*!\fn void mpfill(size_t size, mpw* data, mpw fill)
100 * \brief This function fills each word of a multi-precision integer with a
101 * given value.
102 * \param size The size of the multi-precision integer.
103 * \param data The multi-precision integer data.
104 * \param fill The value fill the data with.
105 */
106BEECRYPTAPI
107void mpfill(size_t size, mpw* data, mpw fill);
108
109/*!\fn int mpodd(size_t size, const mpw* data)
110 * \brief This functions tests if a multi-precision integer is odd.
111 * \param size The size of the multi-precision integer.
112 * \param data The multi-precision integer data.
113 * \retval 1 if odd
114 * \retval 0 if even
115 */
116BEECRYPTAPI
117int mpodd (size_t size, const mpw* data);
118
119/*!\fn int mpeven(size_t size, const mpw* data)
120 * \brief This function tests if a multi-precision integer is even.
121 * \param size The size of the multi-precision integer.
122 * \param data The multi-precision integer data.
123 * \retval 1 if even
124 * \retval 0 if odd
125 */
126BEECRYPTAPI
127int mpeven(size_t size, const mpw* data);
128
129/*!\fn int mpz(size_t size, const mpw* data)
130 * \brief This function tests if a multi-precision integer is zero.
131 * \param size The size of the multi-precision integer.
132 * \param data The multi-precision integer data.
133 * \retval 1 if zero
134 * \retval 0 if not zero
135 */
136BEECRYPTAPI
137int mpz (size_t size, const mpw* data);
138
139/*!\fn int mpnz(size_t size, const mpw* data)
140 * \brief This function tests if a multi-precision integer is not zero.
141 * \param size The size of the multi-precision integer.
142 * \param data The multi-precision integer data.
143 * \retval 1 if not zero
144 * \retval 0 if zero
145 */
146BEECRYPTAPI
147int mpnz (size_t size, const mpw* data);
148
149/*!\fn int mpeq(size_t size, const mpw* xdata, const mpw* ydata)
150 * \brief This function tests if two multi-precision integers of the same size
151 * are equal.
152 * \param size The size of the multi-precision integers.
153 * \param xdata The first multi-precision integer.
154 * \param ydata The second multi-precision integer.
155 * \retval 1 if equal
156 * \retval 0 if not equal
157 */
158BEECRYPTAPI
159int mpeq (size_t size, const mpw* xdata, const mpw* ydata);
160
161/*!\fn int mpne(size_t size, const mpw* xdata, const mpw* ydata)
162 * \brief This function tests if two multi-precision integers of the same size
163 * differ.
164 * \param size The size of the multi-precision integers.
165 * \param xdata The first multi-precision integer.
166 * \param ydata The second multi-precision integer.
167 * \retval 1 if not equal
168 * \retval 0 if equal
169 */
170BEECRYPTAPI
171int mpne (size_t size, const mpw* xdata, const mpw* ydata);
172
173/*!\fn int mpgt(size_t size, const mpw* xdata, const mpw* ydata)
174 * \brief This function tests if the first of two multi-precision integers
175 * of the same size is greater than the second.
176 * \note The comparison treats the arguments as unsigned.
177 * \param size The size of the multi-precision integers.
178 * \param xdata The first multi-precision integer.
179 * \param ydata The second multi-precision integer.
180 * \retval 1 if greater
181 * \retval 0 if less or equal
182 */
183BEECRYPTAPI
184int mpgt (size_t size, const mpw* xdata, const mpw* ydata);
185
186/*!\fn int mplt(size_t size, const mpw* xdata, const mpw* ydata)
187 * \brief This function tests if the first of two multi-precision integers
188 * of the same size is less than the second.
189 * \note The comparison treats the arguments as unsigned.
190 * \param size The size of the multi-precision integers.
191 * \param xdata The first multi-precision integer.
192 * \param ydata The second multi-precision integer.
193 * \retval 1 if less
194 * \retval 0 if greater or equal
195 */
196BEECRYPTAPI
197int mplt (size_t size, const mpw* xdata, const mpw* ydata);
198
199/*!\fn int mpge(size_t size, const mpw* xdata, const mpw* ydata)
200 * \brief This function tests if the first of two multi-precision integers
201 * of the same size is greater than or equal to the second.
202 * \note The comparison treats the arguments as unsigned.
203 * \param size The size of the multi-precision integers.
204 * \param xdata The first multi-precision integer.
205 * \param ydata The second multi-precision integer.
206 * \retval 1 if greater or equal
207 * \retval 0 if less
208 */
209BEECRYPTAPI
210int mpge (size_t size, const mpw* xdata, const mpw* ydata);
211
212/*!\fn int mple(size_t size, const mpw* xdata, const mpw* ydata)
213 * \brief This function tests if the first of two multi-precision integers
214 * of the same size is less than or equal to the second.
215 * \note The comparison treats the arguments as unsigned.
216 * \param size The size of the multi-precision integers.
217 * \param xdata The first multi-precision integer.
218 * \param ydata The second multi-precision integer.
219 * \retval 1 if less or equal
220 * \retval 0 if greater
221 */
222BEECRYPTAPI
223int mple (size_t size, const mpw* xdata, const mpw* ydata);
224
225/*!\fn int mpeqx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
226 * \brief This function tests if two multi-precision integers of different
227 * size are equal.
228 * \param xsize The size of the first multi-precision integer.
229 * \param xdata The first multi-precision integer.
230 * \param ysize The size of the first multi-precision integer.
231 * \param ydata The second multi-precision integer.
232 * \retval 1 if equal
233 * \retval 0 if not equal
234 */
235BEECRYPTAPI
236int mpeqx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata);
237
238/*!\fn int mpnex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
239 * \brief This function tests if two multi-precision integers of different
240 * size are equal.
241 * \param xsize The size of the first multi-precision integer.
242 * \param xdata The first multi-precision integer.
243 * \param ysize The size of the first multi-precision integer.
244 * \param ydata The second multi-precision integer.
245 * \retval 1 if equal
246 * \retval 0 if not equal
247*/
248BEECRYPTAPI
249int mpnex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata);
250
251/*!\fn int mpgtx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
252 * \brief This function tests if the first of two multi-precision integers
253 * of different size is greater than the second.
254 * \note The comparison treats the arguments as unsigned.
255 * \param xsize The size of the first multi-precision integer.
256 * \param xdata The first multi-precision integer.
257 * \param ysize The size of the second multi-precision integer.
258 * \param ydata The second multi-precision integer.
259 * \retval 1 if greater
260 * \retval 0 if less or equal
261 */
262BEECRYPTAPI
263int mpgtx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata);
264
265/*!\fn int mpltx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
266 * \brief This function tests if the first of two multi-precision integers
267 * of different size is less than the second.
268 * \note The comparison treats the arguments as unsigned.
269 * \param xsize The size of the first multi-precision integer.
270 * \param xdata The first multi-precision integer.
271 * \param ysize The size of the second multi-precision integer.
272 * \param ydata The second multi-precision integer.
273 * \retval 1 if less
274 * \retval 0 if greater or equal
275 */
276BEECRYPTAPI
277int mpltx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata);
278
279/*!\fn int mpgex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
280 * \brief This function tests if the first of two multi-precision integers
281 * of different size is greater than or equal to the second.
282 * \note The comparison treats the arguments as unsigned.
283 * \param xsize The size of the first multi-precision integer.
284 * \param xdata The first multi-precision integer.
285 * \param ysize The size of the second multi-precision integer.
286 * \param ydata The second multi-precision integer.
287 * \retval 1 if greater or equal
288 * \retval 0 if less
289 */
290BEECRYPTAPI
291int mpgex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata);
292
293/*!\fn int mplex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
294 * \brief This function tests if the first of two multi-precision integers
295 * of different size is less than or equal to the second.
296 * \note The comparison treats the arguments as unsigned.
297 * \param xsize The size of the first multi-precision integer.
298 * \param xdata The first multi-precision integer.
299 * \param ysize The size of the second multi-precision integer.
300 * \param ydata The second multi-precision integer.
301 * \retval 1 if less or equal
302 * \retval 0 if greater
303 */
304BEECRYPTAPI
305int mplex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata);
306
307/*!\fn int mpisone(size_t size, const mpw* data)
308 * \brief This functions tests if the value of a multi-precision integer is
309 * equal to one.
310 * \param size The size of the multi-precision integer.
311 * \param data The multi-precision integer data.
312 * \retval 1 if one
313 * \retval 0 if not one
314 */
315BEECRYPTAPI
316int mpisone(size_t size, const mpw* data);
317
318/*!\fn int mpistwo(size_t size, const mpw* data)
319 * \brief This function tests if the value of a multi-precision integer is
320 * equal to two.
321 * \param size The size of the multi-precision integer.
322 * \param data The multi-precision integer data.
323 * \retval 1 if two
324 * \retval 0 if not two
325 */
326BEECRYPTAPI
327int mpistwo(size_t size, const mpw* data);
328
329/*!\fn int mpleone(size_t size, const mpw* data);
330 * \brief This function tests if the value of a multi-precision integer is
331 * less than or equal to one.
332 * \param size The size of the multi-precision integer.
333 * \param data The multi-precision integer data.
334 * \retval 1 if less than or equal to one.
335 * \retval 0 if greater than one.
336 */
337BEECRYPTAPI
338int mpleone(size_t size, const mpw* data);
339
340/*!\fn int mpeqmone(size_t size, const mpw* xdata, const mpw* ydata);
341 * \brief This function tests if multi-precision integer x is equal to y
342 * minus one.
343 * \param size The size of the multi-precision integers.
344 * \param xdata The first multi-precision integer.
345 * \param ydata The second multi-precision integer.
346 * \retval 1 if less than or equal to one.
347 * \retval 0 if greater than one.
348 */
349BEECRYPTAPI
350int mpeqmone(size_t size, const mpw* xdata, const mpw* ydata);
351
352/*!\fn int mpmsbset(size_t size, const mpw* data)
353 * \brief This function tests if the most significant bit of a multi-precision
354 * integer is set.
355 * \param size The size of the multi-precision integer.
356 * \param data The multi-precision integer data.
357 * \retval 1 if set
358 * \retval 0 if not set
359 */
360BEECRYPTAPI
361int mpmsbset(size_t size, const mpw* data);
362
363/*!\fn int mplsbset(size_t size, const mpw* data)
364 * \brief This function tests if the leiast significant bit of a multi-precision
365 * integer is set.
366 * \param size The size of the multi-precision integer.
367 * \param data The multi-precision integer data.
368 * \retval 1 if set
369 * \retval 0 if not set
370 */
371BEECRYPTAPI
372int mplsbset(size_t size, const mpw* data);
373
374/*!\fn void mpsetmsb(size_t size, mpw* data)
375 * \brief This function sets the most significant bit of a multi-precision
376 * integer.
377 * \param size The size of the multi-precision integer.
378 * \param data The multi-precision integer data.
379 */
380BEECRYPTAPI
381void mpsetmsb(size_t size, mpw* data);
382
383/*!\fn void mpsetlsb(size_t size, mpw* data)
384 * \brief This function sets the least significant bit of a multi-precision
385 * integer.
386 * \param size The size of the multi-precision integer.
387 * \param data The multi-precision integer data.
388 */
389BEECRYPTAPI
390void mpsetlsb(size_t size, mpw* data);
391
392/*!\fn void mpclrmsb(size_t size, mpw* data)
393 * \brief This function clears the most significant bit of a multi-precision
394 * integer.
395 * \param size The size of the multi-precision integer.
396 * \param data The multi-precision integer data.
397 */
398BEECRYPTAPI
399void mpclrmsb(size_t size, mpw* data);
400
401/*!\fn void mpclrlsb(size_t size, mpw* data)
402 * \brief This function clears the least significant bit of a multi-precision
403 * integer.
404 * \param size The size of the multi-precision integer.
405 * \param data The multi-precision integer data.
406 */
407BEECRYPTAPI
408void mpclrlsb(size_t size, mpw* data);
409
410/*!\fn mpand(size_t size, mpw* xdata, const mpw* ydata)
411 * \brief This function computes the bit-wise AND of two multi-precision
412 * integers. Modifies xdata.
413 * \param size The size of the multi-precision integers.
414 * \param xdata The multi-precision integer data.
415 * \param ydata The multi-precision integer data.
416 */
417BEECRYPTAPI
418void mpand(size_t size, mpw* xdata, const mpw* ydata);
419
420/*!\fn void mpor(size_t size, mpw* xdata, const mpw* ydata)
421 * \brief This function computes the bit-wise OR of two multi-precision
422 * integers. Modifies xdata.
423 * \param size The size of the multi-precision integer.
424 * \param xdata The multi-precision integer data.
425 * \param ydata The multi-precision integer data.
426 */
427BEECRYPTAPI
428void mpor(size_t size, mpw* xdata, const mpw* ydata);
429
430/*!\fn void mpxor(size_t size, mpw* xdata, const mpw* ydata)
431 * \brief This function computes the bit-wise XOR of two multi-precision
432 * integers. Modifies xdata.
433 * \param size The size of the multi-precision integer.
434 * \param xdata The multi-precision integer data.
435 * \param ydata The multi-precision integer data.
436 */
437BEECRYPTAPI
438void mpxor(size_t size, mpw* xdata, const mpw* ydata);
439
440/*!\fn mpnot(size_t size, mpw* data)
441 * \brief This function flips all bits of a multi-precision integer.
442 * \param size The size of the multi-precision integer.
443 * \param data The multi-precision integer data.
444 */
445BEECRYPTAPI
446void mpnot(size_t size, mpw* data);
447
448/*!\fn void mpsetw(size_t size, mpw* xdata, mpw y)
449 * \brief This function sets the value of a multi-precision integer to the
450 * given word. The given value is copied into the least significant word,
451 * while the most significant words are zeroed.
452 * \param size The size of the multi-precision integer.
453 * \param xdata The first multi-precision integer.
454 * \param y The multi-precision word.
455 */
456BEECRYPTAPI
457void mpsetw(size_t size, mpw* xdata, mpw y);
458
459/*!\fn void mpsetx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata)
460 * \brief This function set the value of the first multi-precision integer
461 * to the second, truncating the most significant words if ysize > xsize, or
462 * zeroing the most significant words if ysize < xsize.
463 * \param xsize The size of the first multi-precision integer.
464 * \param xdata The first multi-precision integer.
465 * \param ysize The size of the second multi-precision integer.
466 * \param ydata The second multi-precision integer.
467 */
468void mpsetx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata);
469
470/*!\fn int mpaddw(size_t size, mpw* xdata, mpw y)
471 * \brief This function adds one word to a multi-precision integer.
472 * The performed operation is in pseudocode: x += y.
473 * \param size The size of the multi-precision integer.
474 * \param xdata The first multi-precision integer.
475 * \param y The multi-precision word.
476 * \return The carry-over value of the operation; this value is either 0 or 1.
477 */
478BEECRYPTAPI
479int mpaddw(size_t size, mpw* xdata, mpw y);
480
481/*!\fn int mpadd(size_t size, mpw* xdata, const mpw* ydata)
482 * \brief This function adds two multi-precision integers of equal size.
483 * The performed operation is in pseudocode: x += y.
484 * \param size The size of the multi-precision integers.
485 * \param xdata The first multi-precision integer.
486 * \param ydata The second multi-precision integer.
487 * \return The carry-over value of the operation; this value is either 0 or 1.
488 */
489BEECRYPTAPI
490int mpadd (size_t size, mpw* xdata, const mpw* ydata);
491
492/*!\fn int mpaddx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata)
493 * \brief This function adds two multi-precision integers of different size.
494 * The performed operation in pseudocode: x += y.
495 * \param xsize The size of the first multi-precision integer.
496 * \param xdata The first multi-precision integer.
497 * \param ysize The size of the second multi-precision integer.
498 * \param ydata The second multi-precision integer.
499 * \return The carry-over value of the operation; this value is either 0 or 1.
500 */
501BEECRYPTAPI
502int mpaddx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata);
503
504/*!\fn int mpsubw(size_t size, mpw* xdata, mpw y)
505 * \brief This function subtracts one word to a multi-precision integer.
506 * The performed operation in pseudocode: x -= y
507 * \param size The size of the multi-precision integers.
508 * \param xdata The first multi-precision integer.
509 * \param y The multi-precision word.
510 * \return The carry-over value of the operation; this value is either 0 or 1.
511 */
512BEECRYPTAPI
513int mpsubw(size_t size, mpw* xdata, mpw y);
514
515/*!\fn int mpsub(size_t size, mpw* xdata, const mpw* ydata)
516 * \brief This function subtracts two multi-precision integers of equal size.
517 * The performed operation in pseudocode: x -= y
518 * \param size The size of the multi-precision integers.
519 * \param xdata The first multi-precision integer.
520 * \param ydata The second multi-precision integer.
521 * \return The carry-over value of the operation; this value is either 0 or 1.
522 */
523BEECRYPTAPI
524int mpsub (size_t size, mpw* xdata, const mpw* ydata);
525
526/*!\fn int mpsubx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata)
527 * \brief This function subtracts two multi-precision integers of different
528 * size. The performed operation in pseudocode: x -= y.
529 * \param xsize The size of the first multi-precision integer.
530 * \param xdata The first multi-precision integer.
531 * \param ysize The size of the second multi-precision integer.
532 * \param ydata The second multi-precision integer.
533 * \return The carry-over value of the operation; this value is either 0 or 1.
534 */
535BEECRYPTAPI
536int mpsubx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata);
537
538BEECRYPTAPI
539int mpmultwo(size_t size, mpw* data);
540
541/*!\fn void mpneg(size_t size, mpw* data)
542 * \brief This function negates a multi-precision integer.
543 * \param size The size of the multi-precision integer.
544 * \param data The multi-precision integer data.
545 */
546BEECRYPTAPI
547void mpneg(size_t size, mpw* data);
548
549/*!\fn size_t mpsize(size_t size, const mpw* data)
550 * \brief This function returns the true size of a multi-precision
551 * integer, after stripping leading zero words.
552 * \param size The size of the multi-precision integer.
553 * \param data The multi-precision integer data.
554 */
555BEECRYPTAPI
556size_t mpsize(size_t size, const mpw* data);
557
558/*!\fn size_t mpbits(size_t size, const mpw* data)
559 * \brief This function returns the number of significant bits
560 * in a multi-precision integer.
561 * \param size The size of the multi-precision integer.
562 * \param data The multi-precision integer data.
563 */
564BEECRYPTAPI
565size_t mpbits(size_t size, const mpw* data);
566
567BEECRYPTAPI
568size_t mpmszcnt(size_t size, const mpw* data);
569
570BEECRYPTAPI
571size_t mplszcnt(size_t size, const mpw* data);
572
573BEECRYPTAPI
574void mplshift(size_t size, mpw* data, size_t count);
575
576BEECRYPTAPI
577void mprshift(size_t size, mpw* data, size_t count);
578
579BEECRYPTAPI
580size_t mprshiftlsz(size_t size, mpw* data);
581
582BEECRYPTAPI
583size_t mpnorm(size_t size, mpw* data);
584
585BEECRYPTAPI
586void mpdivtwo (size_t size, mpw* data);
587
588BEECRYPTAPI
589void mpsdivtwo(size_t size, mpw* data);
590
591/*!\fn mpw mpsetmul(size_t size, mpw* result, const mpw* data, mpw y)
592 * \brief This function performs a multi-precision multiply-setup.
593 *
594 * This function is used in the computation of a full multi-precision
595 * multiplication. By using it we can shave off a few cycles; otherwise we'd
596 * have to zero the least significant half of the result first and use
597 * another call to the slightly slower mpaddmul function.
598 *
599 * \param size The size of multi-precision integer multiplier.
600 * \param result The place where result will be accumulated.
601 * \param data The multi-precision integer multiplier.
602 * \param y The multiplicand.
603 * \return The carry-over multi-precision word.
604 */
605BEECRYPTAPI
606mpw mpsetmul (size_t size, mpw* result, const mpw* data, mpw y);
607
608/*!\fn mpw mpaddmul(size_t size, mpw* result, const mpw* data, mpw y)
609 * \brief This function performs a mult-precision multiply-accumulate.
610 *
611 * This function is used in the computation of a full multi-precision
612 * multiplication. It computes the product-by-one-word and accumulates it with
613 * the previous result.
614 *
615 * \param size The size of multi-precision integer multiplier.
616 * \param result The place where result will be accumulated.
617 * \param data The multi-precision integer multiplier.
618 * \param y The multiplicand.
619 * \retval The carry-over multi-precision word.
620 */
621BEECRYPTAPI
622mpw mpaddmul (size_t size, mpw* result, const mpw* data, mpw y);
623
624/*!\fn void mpaddsqrtrc(size_t size, mpw* result, const mpw* data)
625 * \brief This function is used in the calculation of a multi-precision
626 * squaring.
627 */
628BEECRYPTAPI
629void mpaddsqrtrc(size_t size, mpw* result, const mpw* data);
630
631/*!\fn void mpmul(mpw* result, size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata)
632 * \brief This function computes a full multi-precision product.
633 */
634BEECRYPTAPI
635void mpmul(mpw* result, size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata);
636
637/*!\fn void mpsqr(mpw* result, size_t size, const mpw* data)
638 * \brief This function computes a full multi-precision square.
639 */
640BEECRYPTAPI
641void mpsqr(mpw* result, size_t size, const mpw* data);
642
643BEECRYPTAPI
644void mpgcd_w(size_t size, const mpw* xdata, const mpw* ydata, mpw* result, mpw* wksp);
645
646BEECRYPTAPI
647int mpextgcd_w(size_t size, const mpw* xdata, const mpw* ydata, mpw* result, mpw* wksp);
648
649BEECRYPTAPI
650mpw mppndiv(mpw xhi, mpw xlo, mpw y);
651
652BEECRYPTAPI
653void mpmod (mpw* result, size_t xsize, const mpw* xdata, size_t ysize, const mpw*ydata, mpw* wksp);
654
655BEECRYPTAPI
656void mpndivmod(mpw* result, size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata, mpw* wksp);
657
658/*
659 * Output Routines
660 */
661
662BEECRYPTAPI
663void mpprint(size_t size, const mpw* data);
664
665BEECRYPTAPI
666void mpprintln(size_t size, const mpw* data);
667
668BEECRYPTAPI
669void mpfprint(FILE* f, size_t size, const mpw* data);
670
671BEECRYPTAPI
672void mpfprintln(FILE* f, size_t size, const mpw* data);
673
674/*
675 * Conversion Routines
676 */
677
678BEECRYPTAPI
679int os2ip(mpw* idata, size_t isize, const byte* osdata, size_t ossize);
680
681BEECRYPTAPI
682int i2osp(byte* osdata, size_t ossize, const mpw* idata, size_t isize);
683
684BEECRYPTAPI
685int hs2ip(mpw* idata, size_t isize, const char* hsdata, size_t hssize);
686
687#ifdef __cplusplus
688}
689#endif
690
691#endif
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpnumber.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpnumber.h
new file mode 100755
index 0000000000..f42e82a80f
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpnumber.h
@@ -0,0 +1,115 @@
1/*
2 * Copyright (c) 2003 Bob Deblier
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file mpnumber.h
21 * \brief Multi-precision numbers, headers.
22 * \author Bob Deblier <bob.deblier@pandora.be>
23 * \ingroup MP_m
24 */
25
26#ifndef _MPNUMBER_H
27#define _MPNUMBER_H
28
29#include "beecrypt/mp.h"
30
31#ifdef __cplusplus
32# include <iostream>
33#endif
34
35#ifdef __cplusplus
36struct BEECRYPTAPI mpnumber
37#else
38struct _mpnumber
39#endif
40{
41 size_t size;
42 mpw* data;
43
44#ifdef __cplusplus
45 static const mpnumber ZERO;
46 static const mpnumber ONE;
47
48 mpnumber();
49 mpnumber(unsigned int);
50 mpnumber(const mpnumber&);
51 ~mpnumber();
52
53 const mpnumber& operator=(const mpnumber&);
54 bool operator==(const mpnumber&) const throw ();
55 bool operator!=(const mpnumber&) const throw ();
56
57 void wipe();
58
59 size_t bitlength() const throw ();
60#endif
61};
62
63#ifndef __cplusplus
64typedef struct _mpnumber mpnumber;
65#else
66BEECRYPTAPI
67std::ostream& operator<<(std::ostream&, const mpnumber&);
68/*
69BEECRYPTAPI
70std::istream& operator>>(std::istream&, mpnumber&);
71*/
72#endif
73
74#ifdef __cplusplus
75extern "C" {
76#endif
77
78BEECRYPTAPI
79void mpnzero(mpnumber*);
80BEECRYPTAPI
81void mpnsize(mpnumber*, size_t);
82BEECRYPTAPI
83void mpninit(mpnumber*, size_t, const mpw*);
84BEECRYPTAPI
85void mpnfree(mpnumber*);
86BEECRYPTAPI
87void mpncopy(mpnumber*, const mpnumber*);
88BEECRYPTAPI
89void mpnwipe(mpnumber*);
90
91BEECRYPTAPI
92void mpnset (mpnumber*, size_t, const mpw*);
93BEECRYPTAPI
94void mpnsetw (mpnumber*, mpw);
95
96BEECRYPTAPI
97int mpnsetbin(mpnumber*, const byte*, size_t);
98BEECRYPTAPI
99int mpnsethex(mpnumber*, const char*);
100
101BEECRYPTAPI
102int mpninv(mpnumber*, const mpnumber*, const mpnumber*);
103
104/*!\brief Truncate the mpnumber to the specified number of (least significant) bits.
105 */
106BEECRYPTAPI
107size_t mpntrbits(mpnumber*, size_t);
108BEECRYPTAPI
109size_t mpnbits(const mpnumber*);
110
111#ifdef __cplusplus
112}
113#endif
114
115#endif
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpopt.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpopt.h
new file mode 100755
index 0000000000..7ba66bb5f9
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpopt.h
@@ -0,0 +1,205 @@
1/*
2 * Copyright (c) 2003 Bob Deblier
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file mpopt.h
21 * \brief Multi-precision integer optimization definitions.
22 * \author Bob Deblier <bob.deblier@pandora.be>
23 * \ingroup MP_m
24 */
25
26#ifndef _MPOPT_H
27#define _MPOPT_H
28
29#if WIN32
30# if __MWERKS__ && __INTEL__
31# elif defined(_MSC_VER) && defined(_M_IX86)
32# define ASM_MPZERO
33# define ASM_MPFILL
34# define ASM_MPEVEN
35# define ASM_MPODD
36# define ASM_MPADDW
37# define ASM_MPSUBW
38# define ASM_MPADD
39# define ASM_MPSUB
40# define ASM_MPMULTWO
41# define ASM_MPDIVTWO
42# define ASM_MPSETMUL
43# define ASM_MPADDMUL
44# define ASM_MPADDSQRTRC
45# endif
46#endif
47
48#if defined(__DECC)
49# if defined(OPTIMIZE_ALPHA)
50# define ASM_MPADD
51# define ASM_MPSUB
52# define ASM_MPSETMUL
53# define ASM_MPADDMUL
54# define ASM_MPADDSQRTRC
55# endif
56#endif
57
58#if defined(__GNUC__)
59# if defined(OPTIMIZE_ALPHA)
60# define ASM_MPADD
61# define ASM_MPSUB
62# define ASM_MPSETMUL
63# define ASM_MPADDMUL
64# define ASM_MPADDSQRTRC
65# elif defined(OPTIMIZE_ARM)
66# define ASM_MPSETMUL
67# define ASM_MPADDMUL
68# define ASM_MPADDSQRTRC
69# elif defined(OPTIMIZE_I386) || defined(OPTIMIZE_I486) || defined(OPTIMIZE_I586) || defined(OPTIMIZE_I686)
70# define ASM_MPZERO
71# define ASM_MPFILL
72# define ASM_MPEVEN
73# define ASM_MPODD
74# define ASM_MPADD
75# define ASM_MPADDW
76# define ASM_MPSUB
77# define ASM_MPSUBW
78# define ASM_MPMULTWO
79# define ASM_MPDIVTWO
80# define ASM_MPSETMUL
81# define ASM_MPADDMUL
82# define ASM_MPADDSQRTRC
83# define ASM_MPPNDIV
84# elif defined(OPTIMIZE_IA64)
85# define ASM_MPZERO
86# define ASM_MPCOPY
87# define ASM_MPADD
88# define ASM_MPSUB
89# define ASM_MPMULTWO
90# define ASM_MPSETMUL
91# define ASM_MPADDMUL
92# elif defined(OPTIMIZE_M68K)
93# define ASM_MPADD
94# define ASM_MPSUB
95# define ASM_MPSETMUL
96# define ASM_MPADDMUL
97# define ASM_MPADDSQRTRC
98# elif defined(OPTIMIZE_POWERPC) || defined(OPTIMIZE_POWERPC64)
99# define ASM_MPSETMUL
100# define ASM_MPADD
101# define ASM_MPADDW
102# define ASM_MPSUB
103# define ASM_MPSUBW
104# define ASM_MPMULTWO
105# define ASM_MPADDMUL
106# define ASM_MPADDSQRTRC
107# elif defined(OPTIMIZE_S390X)
108# define ASM_MPSETMUL
109# define ASM_MPADDMUL
110# define ASM_MPADDSQRTRC
111# elif defined(OPTIMIZE_SPARCV8)
112# define ASM_MPSETMUL
113# define ASM_MPADDMUL
114# define ASM_MPADDSQRTRC
115# elif defined(OPTIMIZE_SPARCV8PLUS)
116# define ASM_MPADDW
117# define ASM_MPSUBW
118# define ASM_MPADD
119# define ASM_MPSUB
120# define ASM_MPMULTWO
121# define ASM_MPSETMUL
122# define ASM_MPADDMUL
123# define ASM_MPADDSQRTRC
124# elif defined(OPTIMIZE_X86_64)
125# define ASM_MPZERO
126# define ASM_MPFILL
127# define ASM_MPEVEN
128# define ASM_MPODD
129# define ASM_MPADD
130# define ASM_MPADDW
131# define ASM_MPSUB
132# define ASM_MPSUBW
133# define ASM_MPDIVTWO
134# define ASM_MPMULTWO
135# define ASM_MPSETMUL
136# define ASM_MPADDMUL
137# define ASM_MPADDSQRTRC
138# endif
139#endif
140
141#if defined(__IBMC__)
142# if defined(OPTIMIZE_POWERPC) || defined(OPTIMIZE_POWERPC64)
143# define ASM_MPSETMUL
144# define ASM_MPADDW
145# define ASM_MPSUBW
146# define ASM_MPADD
147# define ASM_MPSUB
148# define ASM_MPMULTWO
149# define ASM_MPADDMUL
150# define ASM_MPADDSQRTRC
151# endif
152#endif
153
154#if defined(__INTEL_COMPILER)
155# if defined(OPTIMIZE_I386) || defined(OPTIMIZE_I486) || defined(OPTIMIZE_I586) || defined(OPTIMIZE_I686)
156# define ASM_MPZERO
157# define ASM_MPFILL
158# define ASM_MPEVEN
159# define ASM_MPODD
160# define ASM_MPADDW
161# define ASM_MPSUBW
162# define ASM_MPADD
163# define ASM_MPSUB
164# define ASM_MPMULTWO
165# define ASM_MPDIVTWO
166# define ASM_MPSETMUL
167# define ASM_MPADDMUL
168# define ASM_MPADDSQRTRC
169# define ASM_MPPNDIV
170# endif
171#endif
172
173#if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
174# if defined(OPTIMIZE_SPARCV8)
175# define ASM_MPSETMUL
176# define ASM_MPADDMUL
177# define ASM_MPADDSQRTRC
178# elif defined(OPTIMIZE_SPARCV8PLUS)
179# define ASM_MPADDW
180# define ASM_MPSUBW
181# define ASM_MPADD
182# define ASM_MPSUB
183# define ASM_MPMULTWO
184# define ASM_MPSETMUL
185# define ASM_MPADDMUL
186# define ASM_MPADDSQRTRC
187# endif
188#endif
189
190#undef ASM_MPZERO
191#undef ASM_MPFILL
192#undef ASM_MPEVEN
193#undef ASM_MPODD
194#undef ASM_MPADD
195#undef ASM_MPADDW
196#undef ASM_MPSUB
197#undef ASM_MPSUBW
198#undef ASM_MPMULTWO
199#undef ASM_MPDIVTWO
200#undef ASM_MPSETMUL
201#undef ASM_MPADDMUL
202#undef ASM_MPADDSQRTRC
203#undef ASM_MPPNDIV
204
205#endif
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/rsa.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/rsa.h
new file mode 100755
index 0000000000..dbb0e45412
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/rsa.h
@@ -0,0 +1,121 @@
1/*
2 * Copyright (c) 2000, 2002 Virtual Unlimited B.V.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file rsa.h
21 * \brief RSA algorithm.
22 * \author Bob Deblier <bob.deblier@pandora.be>
23 * \ingroup IF_m IF_rsa_m
24 */
25
26#ifndef _RSA_H
27#define _RSA_H
28
29#include "beecrypt/rsakp.h"
30
31#ifdef __cplusplus
32extern "C" {
33#endif
34
35/*!\fn int rsapub(const mpbarrett* n, const mpnumber* e, const mpnumber* m, mpnumber* c)
36 * \brief This function performs a raw RSA public key operation.
37 *
38 * This function can be used for encryption and verifying.
39 *
40 * It performs the following operation:
41 * \li \f$c=m^{e}\ \textrm{mod}\ n\f$
42 *
43 * \param n The RSA modulus.
44 * \param e The RSA public exponent.
45 * \param m The message.
46 * \param c The ciphertext.
47 * \retval 0 on success.
48 * \retval -1 on failure.
49 */
50BEECRYPTAPI
51int rsapub(const mpbarrett* n, const mpnumber* e,
52 const mpnumber* m, mpnumber* c);
53
54/*!\fn int rsapri(const mpbarrett* n, const mpnumber* d, const mpnumber* c, mpnumber* m)
55 * \brief This function performs a raw RSA private key operation.
56 *
57 * This function can be used for decryption and signing.
58 *
59 * It performs the operation:
60 * \li \f$m=c^{d}\ \textrm{mod}\ n\f$
61 *
62 * \param n The RSA modulus.
63 * \param d The RSA private exponent.
64 * \param c The ciphertext.
65 * \param m The message.
66 * \retval 0 on success.
67 * \retval -1 on failure.
68 */
69BEECRYPTAPI
70int rsapri(const mpbarrett* n, const mpnumber* d,
71 const mpnumber* c, mpnumber* m);
72
73/*!\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)
74 *
75 * \brief This function performs a raw RSA private key operation, with
76 * application of the Chinese Remainder Theorem.
77 *
78 * It performs the operation:
79 * \li \f$j_1=c^{dp}\ \textrm{mod}\ p\f$
80 * \li \f$j_2=c^{dq}\ \textrm{mod}\ q\f$
81 * \li \f$h=qi \cdot (j_1-j_2)\ \textrm{mod}\ p\f$
82 * \li \f$m=j_2+hq\f$
83 *
84 * \param n The RSA modulus.
85 * \param p The first RSA prime factor.
86 * \param q The second RSA prime factor.
87 * \param dp
88 * \param dq
89 * \param qi
90 * \param c The ciphertext.
91 * \param m The message.
92 * \retval 0 on success.
93 * \retval -1 on failure.
94 */
95BEECRYPTAPI
96int rsapricrt(const mpbarrett* n, const mpbarrett* p, const mpbarrett* q,
97 const mpnumber* dp, const mpnumber* dq, const mpnumber* qi,
98 const mpnumber* c, mpnumber* m);
99
100/*!\fn int rsavrfy(const mpbarrett* n, const mpnumber* e, const mpnumber* m, const mpnumber* c)
101 * \brief This function performs a raw RSA verification.
102 *
103 * It verifies if ciphertext \a c was encrypted from cleartext \a m
104 * with the private key matching the given public key \a (n, e).
105 *
106 * \param n The RSA modulus.
107 * \param e The RSA public exponent.
108 * \param m The cleartext message.
109 * \param c The ciphertext message.
110 * \retval 1 on success.
111 * \retval 0 on failure.
112 */
113BEECRYPTAPI
114int rsavrfy(const mpbarrett* n, const mpnumber* e,
115 const mpnumber* m, const mpnumber* c);
116
117#ifdef __cplusplus
118}
119#endif
120
121#endif
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.c
new file mode 100755
index 0000000000..fe7c2cd8b4
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.c
@@ -0,0 +1,329 @@
1/*
2 * Copyright (c) 1997, 1998, 1999, 2000, 2001 Virtual Unlimited B.V.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file sha1.c
21 * \brief SHA-1 hash function, as specified by NIST FIPS 180-1.
22 * \author Bob Deblier <bob.deblier@pandora.be>
23 * \ingroup HASH_m HASH_sha1_m
24 */
25
26#define BEECRYPT_DLL_EXPORT
27
28#if HAVE_CONFIG_H
29# include "config.h"
30#endif
31
32#include "beecrypt/sha1.h"
33
34#if HAVE_ENDIAN_H && HAVE_ASM_BYTEORDER_H
35# include <endian.h>
36#endif
37
38#include "beecrypt/endianness.h"
39
40/*!\addtogroup HASH_sha1_m
41 * \{
42 */
43
44static const uint32_t k[4] = { 0x5a827999U, 0x6ed9eba1U, 0x8f1bbcdcU, 0xca62c1d6U };
45
46static const uint32_t hinit[5] = { 0x67452301U, 0xefcdab89U, 0x98badcfeU, 0x10325476U, 0xc3d2e1f0U };
47
48const hashFunction sha1 = {
49 "SHA-1",
50 sizeof(sha1Param),
51 64,
52 20,
53 (hashFunctionReset) sha1Reset,
54 (hashFunctionUpdate) sha1Update,
55 (hashFunctionDigest) sha1Digest
56};
57
58int sha1Reset(register sha1Param* p)
59{
60 memcpy(p->h, hinit, 5 * sizeof(uint32_t));
61 memset(p->data, 0, 80 * sizeof(uint32_t));
62 #if (MP_WBITS == 64)
63 mpzero(1, p->length);
64 #elif (MP_WBITS == 32)
65 mpzero(2, p->length);
66 #else
67 # error
68 #endif
69 p->offset = 0;
70 return 0;
71}
72
73#define SUBROUND1(a, b, c, d, e, w, k) \
74 e = ROTL32(a, 5) + ((b&(c^d))^d) + e + w + k; \
75 b = ROTR32(b, 2)
76#define SUBROUND2(a, b, c, d, e, w, k) \
77 e = ROTL32(a, 5) + (b^c^d) + e + w + k; \
78 b = ROTR32(b, 2)
79#define SUBROUND3(a, b, c, d, e, w, k) \
80 e = ROTL32(a, 5) + (((b|c)&d)|(b&c)) + e + w + k; \
81 b = ROTR32(b, 2)
82#define SUBROUND4(a, b, c, d, e, w, k) \
83 e = ROTL32(a, 5) + (b^c^d) + e + w + k; \
84 b = ROTR32(b, 2)
85
86#ifndef ASM_SHA1PROCESS
87void sha1Process(sha1Param* sp)
88{
89 register uint32_t a, b, c, d, e;
90 register uint32_t *w;
91 register byte t;
92
93 #if WORDS_BIGENDIAN
94 w = sp->data + 16;
95 #else
96 w = sp->data;
97 t = 16;
98 while (t--)
99 {
100 register uint32_t temp = swapu32(*w);
101 *(w++) = temp;
102 }
103 #endif
104
105 t = 64;
106 while (t--)
107 {
108 register uint32_t temp = w[-3] ^ w[-8] ^ w[-14] ^ w[-16];
109 *(w++) = ROTL32(temp, 1);
110 }
111
112 w = sp->data;
113
114 a = sp->h[0]; b = sp->h[1]; c = sp->h[2]; d = sp->h[3]; e = sp->h[4];
115
116 SUBROUND1(a,b,c,d,e,w[ 0],k[0]);
117 SUBROUND1(e,a,b,c,d,w[ 1],k[0]);
118 SUBROUND1(d,e,a,b,c,w[ 2],k[0]);
119 SUBROUND1(c,d,e,a,b,w[ 3],k[0]);
120 SUBROUND1(b,c,d,e,a,w[ 4],k[0]);
121 SUBROUND1(a,b,c,d,e,w[ 5],k[0]);
122 SUBROUND1(e,a,b,c,d,w[ 6],k[0]);
123 SUBROUND1(d,e,a,b,c,w[ 7],k[0]);
124 SUBROUND1(c,d,e,a,b,w[ 8],k[0]);
125 SUBROUND1(b,c,d,e,a,w[ 9],k[0]);
126 SUBROUND1(a,b,c,d,e,w[10],k[0]);
127 SUBROUND1(e,a,b,c,d,w[11],k[0]);
128 SUBROUND1(d,e,a,b,c,w[12],k[0]);
129 SUBROUND1(c,d,e,a,b,w[13],k[0]);
130 SUBROUND1(b,c,d,e,a,w[14],k[0]);
131 SUBROUND1(a,b,c,d,e,w[15],k[0]);
132 SUBROUND1(e,a,b,c,d,w[16],k[0]);
133 SUBROUND1(d,e,a,b,c,w[17],k[0]);
134 SUBROUND1(c,d,e,a,b,w[18],k[0]);
135 SUBROUND1(b,c,d,e,a,w[19],k[0]);
136
137 SUBROUND2(a,b,c,d,e,w[20],k[1]);
138 SUBROUND2(e,a,b,c,d,w[21],k[1]);
139 SUBROUND2(d,e,a,b,c,w[22],k[1]);
140 SUBROUND2(c,d,e,a,b,w[23],k[1]);
141 SUBROUND2(b,c,d,e,a,w[24],k[1]);
142 SUBROUND2(a,b,c,d,e,w[25],k[1]);
143 SUBROUND2(e,a,b,c,d,w[26],k[1]);
144 SUBROUND2(d,e,a,b,c,w[27],k[1]);
145 SUBROUND2(c,d,e,a,b,w[28],k[1]);
146 SUBROUND2(b,c,d,e,a,w[29],k[1]);
147 SUBROUND2(a,b,c,d,e,w[30],k[1]);
148 SUBROUND2(e,a,b,c,d,w[31],k[1]);
149 SUBROUND2(d,e,a,b,c,w[32],k[1]);
150 SUBROUND2(c,d,e,a,b,w[33],k[1]);
151 SUBROUND2(b,c,d,e,a,w[34],k[1]);
152 SUBROUND2(a,b,c,d,e,w[35],k[1]);
153 SUBROUND2(e,a,b,c,d,w[36],k[1]);
154 SUBROUND2(d,e,a,b,c,w[37],k[1]);
155 SUBROUND2(c,d,e,a,b,w[38],k[1]);
156 SUBROUND2(b,c,d,e,a,w[39],k[1]);
157
158 SUBROUND3(a,b,c,d,e,w[40],k[2]);
159 SUBROUND3(e,a,b,c,d,w[41],k[2]);
160 SUBROUND3(d,e,a,b,c,w[42],k[2]);
161 SUBROUND3(c,d,e,a,b,w[43],k[2]);
162 SUBROUND3(b,c,d,e,a,w[44],k[2]);
163 SUBROUND3(a,b,c,d,e,w[45],k[2]);
164 SUBROUND3(e,a,b,c,d,w[46],k[2]);
165 SUBROUND3(d,e,a,b,c,w[47],k[2]);
166 SUBROUND3(c,d,e,a,b,w[48],k[2]);
167 SUBROUND3(b,c,d,e,a,w[49],k[2]);
168 SUBROUND3(a,b,c,d,e,w[50],k[2]);
169 SUBROUND3(e,a,b,c,d,w[51],k[2]);
170 SUBROUND3(d,e,a,b,c,w[52],k[2]);
171 SUBROUND3(c,d,e,a,b,w[53],k[2]);
172 SUBROUND3(b,c,d,e,a,w[54],k[2]);
173 SUBROUND3(a,b,c,d,e,w[55],k[2]);
174 SUBROUND3(e,a,b,c,d,w[56],k[2]);
175 SUBROUND3(d,e,a,b,c,w[57],k[2]);
176 SUBROUND3(c,d,e,a,b,w[58],k[2]);
177 SUBROUND3(b,c,d,e,a,w[59],k[2]);
178
179 SUBROUND4(a,b,c,d,e,w[60],k[3]);
180 SUBROUND4(e,a,b,c,d,w[61],k[3]);
181 SUBROUND4(d,e,a,b,c,w[62],k[3]);
182 SUBROUND4(c,d,e,a,b,w[63],k[3]);
183 SUBROUND4(b,c,d,e,a,w[64],k[3]);
184 SUBROUND4(a,b,c,d,e,w[65],k[3]);
185 SUBROUND4(e,a,b,c,d,w[66],k[3]);
186 SUBROUND4(d,e,a,b,c,w[67],k[3]);
187 SUBROUND4(c,d,e,a,b,w[68],k[3]);
188 SUBROUND4(b,c,d,e,a,w[69],k[3]);
189 SUBROUND4(a,b,c,d,e,w[70],k[3]);
190 SUBROUND4(e,a,b,c,d,w[71],k[3]);
191 SUBROUND4(d,e,a,b,c,w[72],k[3]);
192 SUBROUND4(c,d,e,a,b,w[73],k[3]);
193 SUBROUND4(b,c,d,e,a,w[74],k[3]);
194 SUBROUND4(a,b,c,d,e,w[75],k[3]);
195 SUBROUND4(e,a,b,c,d,w[76],k[3]);
196 SUBROUND4(d,e,a,b,c,w[77],k[3]);
197 SUBROUND4(c,d,e,a,b,w[78],k[3]);
198 SUBROUND4(b,c,d,e,a,w[79],k[3]);
199
200 sp->h[0] += a;
201 sp->h[1] += b;
202 sp->h[2] += c;
203 sp->h[3] += d;
204 sp->h[4] += e;
205}
206#endif
207
208int sha1Update(sha1Param* sp, const byte* data, size_t size)
209{
210 register uint32_t proclength;
211
212 #if (MP_WBITS == 64)
213 mpw add[1];
214 mpsetw(1, add, size);
215 mplshift(1, add, 3);
216 mpadd(1, sp->length, add);
217 #elif (MP_WBITS == 32)
218 mpw add[2];
219 mpsetw(2, add, size);
220 mplshift(2, add, 3);
221 mpadd(2, sp->length, add);
222 #else
223 # error
224 #endif
225
226 while (size > 0)
227 {
228 proclength = ((sp->offset + size) > 64U) ? (64U - sp->offset) : size;
229 memcpy(((byte *) sp->data) + sp->offset, data, proclength);
230 size -= proclength;
231 data += proclength;
232 sp->offset += proclength;
233
234 if (sp->offset == 64)
235 {
236 sha1Process(sp);
237 sp->offset = 0;
238 }
239 }
240 return 0;
241}
242
243static void sha1Finish(sha1Param* sp)
244{
245 register byte *ptr = ((byte *) sp->data) + sp->offset++;
246
247 *(ptr++) = 0x80;
248
249 if (sp->offset > 56)
250 {
251 while (sp->offset++ < 64)
252 *(ptr++) = 0;
253
254 sha1Process(sp);
255 sp->offset = 0;
256 }
257
258 ptr = ((byte*) sp->data) + sp->offset;
259 while (sp->offset++ < 56)
260 *(ptr++) = 0;
261
262 #if WORDS_BIGENDIAN
263 memcpy(ptr, sp->length, 8);
264 #else
265 # if (MP_WBITS == 64)
266 ptr[0] = (byte)(sp->length[0] >> 56);
267 ptr[1] = (byte)(sp->length[0] >> 48);
268 ptr[2] = (byte)(sp->length[0] >> 40);
269 ptr[3] = (byte)(sp->length[0] >> 32);
270 ptr[4] = (byte)(sp->length[0] >> 24);
271 ptr[5] = (byte)(sp->length[0] >> 16);
272 ptr[6] = (byte)(sp->length[0] >> 8);
273 ptr[7] = (byte)(sp->length[0] );
274 #elif (MP_WBITS == 32)
275 ptr[0] = (byte)(sp->length[0] >> 24);
276 ptr[1] = (byte)(sp->length[0] >> 16);
277 ptr[2] = (byte)(sp->length[0] >> 8);
278 ptr[3] = (byte)(sp->length[0] );
279 ptr[4] = (byte)(sp->length[1] >> 24);
280 ptr[5] = (byte)(sp->length[1] >> 16);
281 ptr[6] = (byte)(sp->length[1] >> 8);
282 ptr[7] = (byte)(sp->length[1] );
283 # else
284 # error
285 # endif
286 #endif
287
288 sha1Process(sp);
289
290 sp->offset = 0;
291}
292
293int sha1Digest(sha1Param* sp, byte* data)
294{
295 sha1Finish(sp);
296
297 #if WORDS_BIGENDIAN
298 memcpy(data, sp->h, 20);
299 #else
300 /* encode 5 integers big-endian style */
301 data[ 0] = (byte)(sp->h[0] >> 24);
302 data[ 1] = (byte)(sp->h[0] >> 16);
303 data[ 2] = (byte)(sp->h[0] >> 8);
304 data[ 3] = (byte)(sp->h[0] >> 0);
305 data[ 4] = (byte)(sp->h[1] >> 24);
306 data[ 5] = (byte)(sp->h[1] >> 16);
307 data[ 6] = (byte)(sp->h[1] >> 8);
308 data[ 7] = (byte)(sp->h[1] >> 0);
309 data[ 8] = (byte)(sp->h[2] >> 24);
310 data[ 9] = (byte)(sp->h[2] >> 16);
311 data[10] = (byte)(sp->h[2] >> 8);
312 data[11] = (byte)(sp->h[2] >> 0);
313 data[12] = (byte)(sp->h[3] >> 24);
314 data[13] = (byte)(sp->h[3] >> 16);
315 data[14] = (byte)(sp->h[3] >> 8);
316 data[15] = (byte)(sp->h[3] >> 0);
317 data[16] = (byte)(sp->h[4] >> 24);
318 data[17] = (byte)(sp->h[4] >> 16);
319 data[18] = (byte)(sp->h[4] >> 8);
320 data[19] = (byte)(sp->h[4] >> 0);
321 #endif
322
323 sha1Reset(sp);
324
325 return 0;
326}
327
328/*!\}
329 */
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.h
new file mode 100755
index 0000000000..a35c917fdd
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.h
@@ -0,0 +1,120 @@
1/*
2 * Copyright (c) 1997, 1998, 1999, 2000, 2002 Virtual Unlimited B.V.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file sha1.h
21 * \brief SHA-1 hash function, headers.
22 * \author Bob Deblier <bob.deblier@pandora.be>
23 * \ingroup HASH_m HASH_sha1_m
24 */
25
26#ifndef _SHA1_H
27#define _SHA1_H
28
29#include "beecrypt/beecrypt.h"
30#include "beecrypt/sha1opt.h"
31
32/*!\brief Holds all the parameters necessary for the SHA-1 algorithm.
33 * \ingroup HASH_sha1_m
34 */
35#ifdef __cplusplus
36struct BEECRYPTAPI sha1Param
37#else
38struct _sha1Param
39#endif
40{
41 /*!\var h
42 */
43 uint32_t h[5];
44 /*!\var data
45 */
46 uint32_t data[80];
47 /*!\var length
48 * \brief Multi-precision integer counter for the bits that have been
49 * processed so far.
50 */
51 #if (MP_WBITS == 64)
52 mpw length[1];
53 #elif (MP_WBITS == 32)
54 mpw length[2];
55 #else
56 # error
57 #endif
58 /*!\var offset
59 * \brief Offset into \a data; points to the place where new data will be
60 * copied before it is processed.
61 */
62 uint32_t offset;
63};
64
65#ifndef __cplusplus
66typedef struct _sha1Param sha1Param;
67#endif
68
69#ifdef __cplusplus
70extern "C" {
71#endif
72
73/*!\var sha1
74 * \brief Holds the full API description of the SHA-1 algorithm.
75 */
76extern BEECRYPTAPI const hashFunction sha1;
77
78/*!\fn void sha1Process(sha1Param* sp)
79 * \brief This function performs the core of the SHA-1 hash algorithm; it
80 * processes a block of 64 bytes.
81 * \param sp The hash function's parameter block.
82 */
83BEECRYPTAPI
84void sha1Process(sha1Param* sp);
85
86/*!\fn int sha1Reset(sha1Param* sp)
87 * \brief This function resets the parameter block so that it's ready for a
88 * new hash.
89 * \param sp The hash function's parameter block.
90 * \retval 0 on success.
91 */
92BEECRYPTAPI
93int sha1Reset (sha1Param* sp);
94
95/*!\fn int sha1Update(sha1Param* sp, const byte* data, size_t size)
96 * \brief This function should be used to pass successive blocks of data
97 * to be hashed.
98 * \param sp The hash function's parameter block.
99 * \param data
100 * \param size
101 * \retval 0 on success.
102 */
103BEECRYPTAPI
104int sha1Update (sha1Param* sp, const byte* data, size_t size);
105
106/*!\fn int sha1Digest(sha1Param* sp, byte* digest)
107 * \brief This function finishes the current hash computation and copies
108 * the digest value into \a digest.
109 * \param sp The hash function's parameter block.
110 * \param digest The place to store the 20-byte digest.
111 * \retval 0 on success.
112 */
113BEECRYPTAPI
114int sha1Digest (sha1Param* sp, byte* digest);
115
116#ifdef __cplusplus
117}
118#endif
119
120#endif
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1opt.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1opt.h
new file mode 100755
index 0000000000..62ea87718f
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1opt.h
@@ -0,0 +1,65 @@
1/*
2 * sha1opt.h
3 *
4 * SHA-1 assembler-optimized routines, header
5 *
6 * Copyright (c) 2000, 2003 Virtual Unlimited B.V.
7 *
8 * Author: Bob Deblier <bob.deblier@pandora.be>
9 *
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
14 *
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 *
24 */
25
26#ifndef _SHA1OPT_H
27#define _SHA1OPT_H
28
29#include "beecrypt/beecrypt.h"
30#include "beecrypt/sha1.h"
31
32#ifdef __cplusplus
33extern "C" {
34#endif
35
36#if WIN32
37# if defined(_MSC_VER) && defined(_M_IX86)
38# define ASM_SHA1PROCESS
39# elif __INTEL__ && __MWERKS__
40# define ASM_SHA1PROCESS
41# endif
42#endif
43
44#if defined(__GNUC__)
45# if defined(OPTIMIZE_I386) || defined(OPTIMIZE_I486) || defined(OPTIMIZE_I586) || defined(OPTIMIZE_I686)
46# define ASM_SHA1PROCESS
47# endif
48#endif
49
50#if defined(__INTEL_COMPILER)
51# if defined(OPTIMIZE_I386) || defined(OPTIMIZE_I486) || defined(OPTIMIZE_I586) || defined(OPTIMIZE_I686)
52# define ASM_SHA1PROCESS
53# endif
54#endif
55
56#if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
57#endif
58
59#undef ASM_SHA1PROCESS
60
61#ifdef __cplusplus
62}
63#endif
64
65#endif
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/win.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/win.h
new file mode 100755
index 0000000000..d578085c29
--- /dev/null
+++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/win.h
@@ -0,0 +1,139 @@
1/*
2 * Copyright (c) 2000, 2001, 2002 Virtual Unlimited B.V.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20/*!\file win.h
21 * \brief BeeCrypt API, windows headers.
22 * \author Bob Deblier <bob.deblier@pandora.be>
23 */
24
25#ifndef _BEECRYPT_WIN_H
26#define _BEECRYPT_WIN_H
27
28#define _REENTRANT
29
30#if !defined(_WIN32_WINNT)
31#define _WIN32_WINNT 0x0400
32#endif
33
34#include <windows.h>
35
36#if __MWERKS__
37# if __INTEL__
38# define WORDS_BIGENDIAN 0
39# else
40# error Unknown CPU type in MetroWerks CodeWarrior
41# endif
42#elif defined(_MSC_VER)
43# if defined(_M_IX86)
44# define WORDS_BIGENDIAN 0
45# define ROTL32(x, s) _rotl(x, s)
46# define ROTR32(x, s) _rotr(x, s)
47# else
48# error Unknown CPU type in Microsoft Visual C
49# endif
50#else
51# error Unknown compiler for WIN32
52#endif
53
54#if defined(_MSC_VER) || __MWERKS__
55#include <stdio.h>
56#include <stdlib.h>
57#include <string.h>
58
59#define HAVE_ERRNO_H 1
60#define HAVE_CTYPE_H 1
61#define HAVE_FCNTL_H 1
62#define HAVE_TIME_H 1
63
64#define HAVE_SYS_TYPES_H 0
65#define HAVE_SYS_TIME_H 0
66
67#define HAVE_THREAD_H 0
68#define HAVE_SYNCH_H 0
69#define HAVE_PTHREAD_H 0
70#define HAVE_SEMAPHORE_H 0
71
72#define HAVE_TERMIO_H 0
73#define HAVE_SYS_AUDIOIO_H 0
74#define HAVE_SYS_IOCTL_H 0
75#define HAVE_SYS_SOUNDCARD_H 0
76
77#define HAVE_GETTIMEOFDAY 0
78#define HAVE_GETHRTIME 0
79
80#define HAVE_DEV_TTY 0
81#define HAVE_DEV_AUDIO 0
82#define HAVE_DEV_DSP 0
83#define HAVE_DEV_RANDOM 0
84#define HAVE_DEV_URANDOM 0
85#define HAVE_DEV_TTY 0
86
87#else
88#error Not set up for this compiler
89#endif
90
91#if __MWERKS__
92#define HAVE_SYS_STAT_H 0
93
94#define HAVE_LONG_LONG 1
95#define HAVE_UNSIGNED_LONG_LONG 1
96
97#define HAVE_64_BIT_INT 1
98#define HAVE_64_BIT_UINT 1
99
100typedef char int8_t;
101typedef short int16_t;
102typedef long int32_t;
103typedef long long int64_t;
104
105typedef unsigned char uint8_t;
106typedef unsigned short uint16_t;
107typedef unsigned long uint32_t;
108typedef unsigned long long uint64_t;
109
110#elif defined(_MSC_VER)
111#define HAVE_SYS_STAT_H 1
112
113#define HAVE_LONG_LONG 0
114#define HAVE_UNSIGNED_LONG_LONG 0
115
116#define HAVE_64_BIT_INT 1
117#define HAVE_64_BIT_UINT 1
118
119typedef signed char int8_t;
120typedef signed short int16_t;
121typedef signed int int32_t;
122typedef signed __int64 int64_t;
123
124typedef unsigned char uint8_t;
125typedef unsigned short uint16_t;
126typedef unsigned int uint32_t;
127typedef unsigned __int64 uint64_t;
128
129typedef long off_t;
130
131#endif
132
133#define MP_WBITS 32U
134
135typedef HANDLE bc_cond_t;
136typedef HANDLE bc_mutex_t;
137typedef HANDLE bc_thread_t;
138
139#endif
diff --git a/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/GetPot b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/GetPot
new file mode 100755
index 0000000000..0663880990
--- /dev/null
+++ b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/GetPot
@@ -0,0 +1,2433 @@
1// -*- c++ -*-
2// GetPot Version $$Version$$ $$Date$$
3//
4// WEBSITE: http://getpot.sourceforge.net
5//
6// NOTE: The LPGL License for this library is only valid in case that
7// it is not used for the production or development of applications
8// dedicated to military industry. This is what the author calls
9// the 'unofficial peace version of the LPGL'.
10//
11// This library is free software; you can redistribute it and/or modify
12// it under the terms of the GNU Lesser General Public License as
13// published by the Free Software Foundation; either version 2.1 of the
14// License, or (at your option) any later version.
15//
16// This library is distributed in the hope that it will be useful, but
17// WITHOUT ANY WARRANTY; without even the implied warranty of
18// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19// Lesser General Public License for more details.
20//
21// You should have received a copy of the GNU Lesser General Public
22// License along with this library; if not, write to the Free Software
23// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
24// USA
25//
26// (C) 2001-2005 Frank R. Schaefer <fschaef@users.sf.net>
27//==========================================================================
28
29#ifndef __include_guard_GETPOT_H__
30#define __include_guard_GETPOT_H__
31
32#if defined(WIN32) || defined(SOLARIS_RAW) || (__GNUC__ == 2) || defined(__HP_aCC)
33#define strtok_r(a, b, c) strtok(a, b)
34#endif // WINDOWS or SOLARIS or gcc 2.* or HP aCC
35
36extern "C" {
37// leave the 'extern C' to make it 100% sure to work -
38// expecially with older distributions of header files.
39#ifndef WIN32
40// this is necessary (depending on OS)
41#include <ctype.h>
42#endif
43#include <stdio.h>
44#include <stdarg.h>
45#include <assert.h>
46}
47#include <cmath>
48#include <string>
49#include <vector>
50#include <algorithm>
51
52#include <fstream>
53#include <iostream> // not every compiler distribution includes <iostream>
54// // with <fstream>
55
56typedef std::vector<std::string> STRING_VECTOR;
57
58#define victorate(TYPE, VARIABLE, ITERATOR) \
59 std::vector<TYPE>::const_iterator ITERATOR = (VARIABLE).begin(); \
60 for(; (ITERATOR) != (VARIABLE).end(); (ITERATOR)++)
61
62
63class GetPot {
64 //--------
65 inline void __basic_initialization();
66public:
67 // (*) constructors, destructor, assignment operator -----------------------
68 inline GetPot();
69 inline GetPot(const GetPot&);
70 inline GetPot(const int argc_, char** argv_,
71 const char* FieldSeparator=0x0);
72 inline GetPot(const char* FileName,
73 const char* CommentStart=0x0, const char* CommentEnd=0x0,
74 const char* FieldSeparator=0x0);
75 inline ~GetPot();
76 inline GetPot& operator=(const GetPot&);
77
78
79 // (*) absorbing contents of another GetPot object
80 inline void absorb(const GetPot& That);
81 // -- for ufo detection: recording requested arguments, options etc.
82 inline void clear_requests();
83 inline void disable_request_recording() { __request_recording_f = false; }
84 inline void enable_request_recording() { __request_recording_f = true; }
85
86 // (*) direct access to command line arguments -----------------------------
87 inline const std::string operator[](unsigned Idx) const;
88 inline int get(unsigned Idx, int Default) const;
89 inline double get(unsigned Idx, const double& Default) const;
90 inline const std::string get(unsigned Idx, const char* Default) const;
91 inline unsigned size() const;
92
93 // (*) flags ---------------------------------------------------------------
94 inline bool options_contain(const char* FlagList) const;
95 inline bool argument_contains(unsigned Idx, const char* FlagList) const;
96
97 // (*) variables -----------------------------------------------------------
98 // -- scalar values
99 inline int operator()(const char* VarName, int Default) const;
100 inline double operator()(const char* VarName, const double& Default) const;
101 inline const std::string operator()(const char* VarName, const char* Default) const;
102 // -- vectors
103 inline int operator()(const char* VarName, int Default, unsigned Idx) const;
104 inline double operator()(const char* VarName, const double& Default, unsigned Idx) const;
105 inline const std::string operator()(const char* VarName, const char* Default, unsigned Idx) const;
106
107 // -- setting variables
108 // i) from outside of GetPot (considering prefix etc.)
109 // ii) from inside, use '__set_variable()' below
110 inline void set(const char* VarName, const char* Value, const bool Requested = true);
111 inline void set(const char* VarName, const double& Value, const bool Requested = true);
112 inline void set(const char* VarName, const int Value, const bool Requested = true);
113
114 inline unsigned vector_variable_size(const char* VarName) const;
115 inline STRING_VECTOR get_variable_names() const;
116 inline STRING_VECTOR get_section_names() const;
117
118
119 // (*) cursor oriented functions -------------------------------------------
120 inline void set_prefix(const char* Prefix) { prefix = std::string(Prefix); }
121 inline bool search_failed() const { return search_failed_f; }
122
123 // -- enable/disable search for an option in loop
124 inline void disable_loop() { search_loop_f = false; }
125 inline void enable_loop() { search_loop_f = true; }
126
127 // -- reset cursor to position '1'
128 inline void reset_cursor();
129 inline void init_multiple_occurrence();
130
131 // -- search for a certain option and set cursor to position
132 inline bool search(const char* option);
133 inline bool search(unsigned No, const char* P, ...);
134 // -- get argument at cursor++
135 inline int next(int Default);
136 inline double next(const double& Default);
137 inline const std::string next(const char* Default);
138 // -- search for option and get argument at cursor++
139 inline int follow(int Default, const char* Option);
140 inline double follow(const double& Default, const char* Option);
141 inline const std::string follow(const char* Default, const char* Option);
142 // -- search for one of the given options and get argument that follows it
143 inline int follow(int Default, unsigned No, const char* Option, ...);
144 inline double follow(const double& Default, unsigned No, const char* Option, ...);
145 inline const std::string follow(const char* Default, unsigned No, const char* Option, ...);
146 // -- lists of nominuses following an option
147 inline std::vector<std::string> nominus_followers(const char* Option);
148 inline std::vector<std::string> nominus_followers(unsigned No, ...);
149
150 // -- directly followed arguments
151 inline int direct_follow(int Default, const char* Option);
152 inline double direct_follow(const double& Default, const char* Option);
153 inline const std::string direct_follow(const char* Default, const char* Option);
154
155 inline std::vector<std::string> string_tails(const char* StartString);
156 inline std::vector<int> int_tails(const char* StartString, const int Default = 1);
157 inline std::vector<double> double_tails(const char* StartString, const double Default = 1.0);
158
159 // (*) nominus arguments ---------------------------------------------------
160 inline STRING_VECTOR nominus_vector() const;
161 inline unsigned nominus_size() const { return static_cast<unsigned int>(idx_nominus.size()); }
162 inline std::string next_nominus();
163
164 // (*) unidentified flying objects -----------------------------------------
165 inline STRING_VECTOR unidentified_arguments(unsigned Number, const char* Known, ...) const;
166 inline STRING_VECTOR unidentified_arguments(const STRING_VECTOR& Knowns) const;
167 inline STRING_VECTOR unidentified_arguments() const;
168
169 inline STRING_VECTOR unidentified_options(unsigned Number, const char* Known, ...) const;
170 inline STRING_VECTOR unidentified_options(const STRING_VECTOR& Knowns) const;
171 inline STRING_VECTOR unidentified_options() const;
172
173 inline std::string unidentified_flags(const char* Known,
174 int ArgumentNumber /* =-1 */) const;
175
176 inline STRING_VECTOR unidentified_variables(unsigned Number, const char* Known, ...) const;
177 inline STRING_VECTOR unidentified_variables(const STRING_VECTOR& Knowns) const;
178 inline STRING_VECTOR unidentified_variables() const;
179
180 inline STRING_VECTOR unidentified_sections(unsigned Number, const char* Known, ...) const;
181 inline STRING_VECTOR unidentified_sections(const STRING_VECTOR& Knowns) const;
182 inline STRING_VECTOR unidentified_sections() const;
183
184 inline STRING_VECTOR unidentified_nominuses(unsigned Number, const char* Known, ...) const;
185 inline STRING_VECTOR unidentified_nominuses(const STRING_VECTOR& Knowns) const;
186 inline STRING_VECTOR unidentified_nominuses() const;
187
188 // (*) output --------------------------------------------------------------
189 inline int print() const;
190
191private:
192 // (*) Type Declaration ----------------------------------------------------
193 struct variable {
194 //-----------
195 // Variable to be specified on the command line or in input files.
196 // (i.e. of the form var='12 312 341')
197
198 // -- constructors, destructors, assignment operator
199 variable();
200 variable(const variable&);
201 variable(const char* Name, const char* Value, const char* FieldSeparator);
202 ~variable();
203 variable& operator=(const variable& That);
204
205 void take(const char* Value, const char* FieldSeparator);
206
207 // -- get a specific element in the string vector
208 // (return 0 if not present)
209 const std::string* get_element(unsigned Idx) const;
210
211 // -- data memebers
212 std::string name; // identifier of variable
213 STRING_VECTOR value; // value of variable stored in vector
214 std::string original; // value of variable as given on command line
215 };
216
217 // (*) member variables --------------------------------------------------------------
218 std::string prefix; // prefix automatically added in queries
219 std::string section; // (for dollar bracket parsing)
220 STRING_VECTOR section_list; // list of all parsed sections
221 // -- argument vector
222 STRING_VECTOR argv; // vector of command line arguments stored as strings
223 unsigned cursor; // cursor for argv
224 bool search_loop_f; // shall search start at beginning after
225 // // reaching end of arg array ?
226 bool search_failed_f; // flag indicating a failed search() operation
227 // // (e.g. next() functions react with 'missed')
228
229 // -- nominus vector
230 int nominus_cursor; // cursor for nominus_pointers
231 std::vector<unsigned> idx_nominus; // indecies of 'no minus' arguments
232
233 // -- variables
234 // (arguments of the form "variable=value")
235 std::vector<variable> variables;
236
237 // -- comment delimiters
238 std::string _comment_start;
239 std::string _comment_end;
240
241 // -- field separator (separating elements of a vector)
242 std::string _field_separator;
243
244 // -- some functions return a char pointer to a temporarily existing string
245 // this container makes them 'available' until the getpot object is destroyed.
246 std::vector<char*> __internal_string_container;
247
248 // -- keeping track about arguments that are requested, so that the UFO detection
249 // can be simplified
250 STRING_VECTOR _requested_arguments;
251 STRING_VECTOR _requested_variables;
252 STRING_VECTOR _requested_sections;
253
254 bool __request_recording_f; // speed: request recording can be turned off
255
256 // -- if an argument is requested record it and the 'tag' the section branch to which
257 // it belongs. Caution: both functions mark the sections as 'tagged'.
258 void __record_argument_request(const std::string& Arg);
259 void __record_variable_request(const std::string& Arg);
260
261 // (*) helper functions ----------------------------------------------------
262 // set variable from inside GetPot (no prefix considered)
263 inline void __set_variable(const char* VarName, const char* Value);
264
265 // -- produce three basic data vectors:
266 // - argument vector
267 // - nominus vector
268 // - variable dictionary
269 inline void __parse_argument_vector(const STRING_VECTOR& ARGV);
270
271 // -- helpers for argument list processing
272 // * search for a variable in 'variables' array
273 inline const variable* __find_variable(const char*) const;
274 // * support finding directly followed arguments
275 inline const char* __match_starting_string(const char* StartString);
276 // * support search for flags in a specific argument
277 inline bool __check_flags(const std::string& Str, const char* FlagList) const;
278 // * type conversion if possible
279 inline int __convert_to_type(const std::string& String, int Default) const;
280 inline double __convert_to_type(const std::string& String, double Default) const;
281 // * prefix extraction
282 const std::string __get_remaining_string(const std::string& String,
283 const std::string& Start) const;
284 // * search for a specific string
285 inline bool __search_string_vector(const STRING_VECTOR& Vec,
286 const std::string& Str) const;
287
288 // -- helpers to parse input file
289 // create an argument vector based on data found in an input file, i.e.:
290 // 1) delete comments (in between '_comment_start' '_comment_end')
291 // 2) contract assignment expressions, such as
292 // my-variable = '007 J. B.'
293 // into
294 // my-variable='007 J. B.'
295 // 3) interprete sections like '[../my-section]' etc.
296 inline void __skip_whitespace(std::istream& istr);
297 inline const std::string __get_next_token(std::istream& istr);
298 inline const std::string __get_string(std::istream& istr);
299 inline const std::string __get_until_closing_bracket(std::istream& istr);
300
301 inline STRING_VECTOR __read_in_stream(std::istream& istr);
302 inline STRING_VECTOR __read_in_file(const char* FileName);
303 inline std::string __process_section_label(const std::string& Section,
304 STRING_VECTOR& section_stack);
305
306 // -- dollar bracket expressions
307 std::string __DBE_expand_string(const std::string str);
308 std::string __DBE_expand(const std::string str);
309 const GetPot::variable* __DBE_get_variable(const std::string str);
310 STRING_VECTOR __DBE_get_expr_list(const std::string str, const unsigned ExpectedNumber);
311
312 std::string __double2string(const double& Value) const {
313 // -- converts a double integer into a string
314 char* tmp = new char[128];
315#ifndef WIN32
316 snprintf(tmp, (int)sizeof(char)*128, "%e", Value);
317#else
318 _snprintf(tmp, sizeof(char)*128, "%e", Value);
319#endif
320 std::string result(tmp);
321 delete [] tmp;
322 return result;
323 }
324
325 std::string __int2string(const int& Value) const {
326 // -- converts an integer into a string
327 char* tmp = new char[128];
328#ifndef WIN32
329 snprintf(tmp, (int)sizeof(char)*128, "%i", Value);
330#else
331 _snprintf(tmp, sizeof(char)*128, "%i", Value);
332#endif
333 std::string result(tmp);
334 delete [] tmp;
335 return result;
336 }
337
338 STRING_VECTOR __get_section_tree(const std::string& FullPath) {
339 // -- cuts a variable name into a tree of sub-sections. this is requested for recording
340 // requested sections when dealing with 'ufo' detection.
341 STRING_VECTOR result;
342 const char* Start = FullPath.c_str();
343
344 for(char *p = (char*)Start; *p ; p++) {
345 if( *p == '/' ) {
346 *p = '\0'; // set terminating zero for convinience
347 const std::string Section = Start;
348 *p = '/'; // reset slash at place
349 result.push_back(Section);
350 }
351 }
352
353 return result;
354 }
355};
356
357
358///////////////////////////////////////////////////////////////////////////////
359// (*) constructors, destructor, assignment operator
360//.............................................................................
361//
362inline void
363GetPot::__basic_initialization()
364{
365 cursor = 0; nominus_cursor = -1;
366 search_failed_f = true; search_loop_f = true;
367 prefix = ""; section = "";
368
369 // automatic request recording for later ufo detection
370 __request_recording_f = true;
371
372 // comment start and end strings
373 _comment_start = std::string("#");
374 _comment_end = std::string("\n");
375
376 // default: separate vector elements by whitespaces
377 _field_separator = " \t\n";
378}
379
380inline
381GetPot::GetPot()
382{
383 __basic_initialization();
384
385 STRING_VECTOR _apriori_argv;
386 _apriori_argv.push_back(std::string("Empty"));
387 __parse_argument_vector(_apriori_argv);
388}
389
390inline
391GetPot::GetPot(const int argc_, char ** argv_,
392 const char* FieldSeparator /* =0x0 */)
393 // leave 'char**' non-const to honor less capable compilers ...
394{
395 // TODO: Ponder over the problem when the argument list is of size = 0.
396 // This is 'sabotage', but it can still occur if the user specifies
397 // it himself.
398 assert(argc_ >= 1);
399 __basic_initialization();
400
401 // if specified -> overwrite default string
402 if( FieldSeparator ) _field_separator = std::string(FieldSeparator);
403
404 // -- make an internal copy of the argument list:
405 STRING_VECTOR _apriori_argv;
406 // -- for the sake of clarity: we do want to include the first argument in the argument vector !
407 // it will not be a nominus argument, though. This gives us a minimun vector size of one
408 // which facilitates error checking in many functions. Also the user will be able to
409 // retrieve the name of his application by "get[0]"
410 _apriori_argv.push_back(std::string(argv_[0]));
411 int i=1;
412 for(; i<argc_; ++i) {
413 std::string tmp(argv_[i]); // recall the problem with temporaries,
414 _apriori_argv.push_back(tmp); // reference counting in arguement lists ...
415 }
416 __parse_argument_vector(_apriori_argv);
417}
418
419
420inline
421GetPot::GetPot(const char* FileName,
422 const char* CommentStart /* = 0x0 */, const char* CommentEnd /* = 0x0 */,
423 const char* FieldSeparator/* = 0x0 */)
424{
425 __basic_initialization();
426
427 // if specified -> overwrite default strings
428 if( CommentStart ) _comment_start = std::string(CommentStart);
429 if( CommentEnd ) _comment_end = std::string(CommentEnd);
430 if( FieldSeparator ) _field_separator = FieldSeparator;
431
432 STRING_VECTOR _apriori_argv;
433 // -- file name is element of argument vector, however, it is not parsed for
434 // variable assignments or nominuses.
435 _apriori_argv.push_back(std::string(FileName));
436
437 STRING_VECTOR args = __read_in_file(FileName);
438 _apriori_argv.insert(_apriori_argv.begin()+1, args.begin(), args.end());
439 __parse_argument_vector(_apriori_argv);
440}
441
442inline
443GetPot::GetPot(const GetPot& That)
444{ GetPot::operator=(That); }
445
446inline
447GetPot::~GetPot()
448{
449 // may be some return strings had to be created, delete now !
450 victorate(char*, __internal_string_container, it)
451 delete [] *it;
452}
453
454inline GetPot&
455GetPot::operator=(const GetPot& That)
456{
457 if (&That == this) return *this;
458
459 _comment_start = That._comment_start;
460 _comment_end = That._comment_end;
461 argv = That.argv;
462 variables = That.variables;
463 prefix = That.prefix;
464
465 cursor = That.cursor;
466 nominus_cursor = That.nominus_cursor;
467 search_failed_f = That.search_failed_f;
468
469 idx_nominus = That.idx_nominus;
470 search_loop_f = That.search_loop_f;
471
472 return *this;
473}
474
475
476inline void
477GetPot::absorb(const GetPot& That)
478{
479 if (&That == this) return;
480
481 STRING_VECTOR __tmp(That.argv);
482
483 __tmp.erase(__tmp.begin());
484
485 __parse_argument_vector(__tmp);
486}
487
488inline void
489GetPot::clear_requests()
490{
491 _requested_arguments.erase(_requested_arguments.begin(), _requested_arguments.end());
492 _requested_variables.erase(_requested_variables.begin(), _requested_variables.end());
493 _requested_sections.erase(_requested_sections.begin(), _requested_sections.end());
494}
495
496inline void
497GetPot::__parse_argument_vector(const STRING_VECTOR& ARGV)
498{
499 if( ARGV.size() == 0 ) return;
500
501 // build internal databases:
502 // 1) array with no-minus arguments (usually used as filenames)
503 // 2) variable assignments:
504 // 'variable name' '=' number | string
505 STRING_VECTOR section_stack;
506 STRING_VECTOR::const_iterator it = ARGV.begin();
507
508
509 section = "";
510
511 // -- do not parse the first argument, so that it is not interpreted a s a nominus or so.
512 argv.push_back(*it);
513 ++it;
514
515 // -- loop over remaining arguments
516 unsigned i=1;
517 for(; it != ARGV.end(); ++it, ++i) {
518 std::string arg = *it;
519
520 if( arg.length() == 0 ) continue;
521
522 // -- [section] labels
523 if( arg.length() > 1 && arg[0] == '[' && arg[arg.length()-1] == ']' ) {
524
525 // (*) sections are considered 'requested arguments'
526 if( __request_recording_f ) _requested_arguments.push_back(arg);
527
528 const std::string Name = __DBE_expand_string(arg.substr(1, arg.length()-2));
529 section = __process_section_label(Name, section_stack);
530 // new section --> append to list of sections
531 if( find(section_list.begin(), section_list.end(), section) == section_list.end() )
532 if( section.length() != 0 ) section_list.push_back(section);
533 argv.push_back(arg);
534 }
535 else {
536 arg = section + __DBE_expand_string(arg);
537 argv.push_back(arg);
538 }
539
540 // -- separate array for nominus arguments
541 if( arg[0] != '-' ) idx_nominus.push_back(unsigned(i));
542
543 // -- variables: does arg contain a '=' operator ?
544 const char* p = arg.c_str();
545 for(; *p ; p++) {
546 if( *p == '=' ) {
547 // (*) record for later ufo detection
548 // arguments carriying variables are always treated as 'requested' arguments.
549 // as a whole! That is 'x=4712' is considered a requested argument.
550 //
551 // unrequested variables have to be detected with the ufo-variable
552 // detection routine.
553 if( __request_recording_f ) _requested_arguments.push_back(arg);
554
555 // set terminating 'zero' to treat first part as single string
556 // => arg (from start to 'p') = Name of variable
557 // p+1 (until terminating zero) = value of variable
558 char* o = (char*)p++;
559 *o = '\0'; // set temporary terminating zero
560 // __set_variable(...)
561 // calls __find_variable(...) which registers the search
562 // temporarily disable this
563 const bool tmp = __request_recording_f;
564 __request_recording_f = false;
565 __set_variable(arg.c_str(), p); // v-name = c_str() bis 'p', value = rest
566 __request_recording_f = tmp;
567 *o = '='; // reset the original '='
568 break;
569 }
570 }
571 }
572}
573
574
575inline STRING_VECTOR
576GetPot::__read_in_file(const char* FileName)
577{
578 std::ifstream i(FileName);
579 if( ! i ) return STRING_VECTOR();
580 // argv[0] == the filename of the file that was read in
581 return __read_in_stream(i);
582}
583
584inline STRING_VECTOR
585GetPot::__read_in_stream(std::istream& istr)
586{
587 STRING_VECTOR brute_tokens;
588 while(istr) {
589 __skip_whitespace(istr);
590 const std::string Token = __get_next_token(istr);
591 if( Token.length() == 0 || Token[0] == EOF) break;
592 brute_tokens.push_back(Token);
593 }
594
595 // -- reduce expressions of token1'='token2 to a single
596 // string 'token1=token2'
597 // -- copy everything into 'argv'
598 // -- arguments preceded by something like '[' name ']' (section)
599 // produce a second copy of each argument with a prefix '[name]argument'
600 unsigned i1 = 0;
601 unsigned i2 = 1;
602 unsigned i3 = 2;
603
604 STRING_VECTOR arglist;
605 while( i1 < brute_tokens.size() ) {
606 const std::string& SRef = brute_tokens[i1];
607 // 1) concatinate 'abcdef' '=' 'efgasdef' to 'abcdef=efgasdef'
608 // note: java.lang.String: substring(a,b) = from a to b-1
609 // C++ string: substr(a,b) = from a to a + b
610 if( i2 < brute_tokens.size() && brute_tokens[i2] == "=" ) {
611 if( i3 >= brute_tokens.size() )
612 arglist.push_back(brute_tokens[i1] + brute_tokens[i2]);
613 else
614 arglist.push_back(brute_tokens[i1] + brute_tokens[i2] + brute_tokens[i3]);
615 i1 = i3+1; i2 = i3+2; i3 = i3+3;
616 continue;
617 }
618 else {
619 arglist.push_back(SRef);
620 i1=i2; i2=i3; i3++;
621 }
622 }
623 return arglist;
624}
625
626inline void
627GetPot::__skip_whitespace(std::istream& istr)
628 // find next non-whitespace while deleting comments
629{
630 int tmp = istr.get();
631 do {
632 // -- search a non whitespace
633 while( isspace(tmp) ) {
634 tmp = istr.get();
635 if( ! istr ) return;
636 }
637
638 // -- look if characters match the comment starter string
639 const std::istream::pos_type Pos = istr.tellg();
640 unsigned i=0;
641 for(; i<_comment_start.length() ; ++i) {
642 if( tmp != _comment_start[i] ) {
643 istr.seekg(Pos);
644 // -- one step more backwards, since 'tmp' already at non-whitespace
645 istr.unget();
646 return;
647 }
648 tmp = istr.get();
649 if( ! istr ) { istr.unget(); return; }
650 }
651 // 'tmp' contains last character of _comment_starter
652
653 // -- comment starter found -> search for comment ender
654 unsigned match_no=0;
655 while(1+1 == 2) {
656 tmp = istr.get();
657 if( ! istr ) { istr.unget(); return; }
658
659 if( tmp == _comment_end[match_no] ) {
660 match_no++;
661 if( match_no == _comment_end.length() ) {
662 istr.unget();
663 break; // shuffle more whitespace, end of comment found
664 }
665 }
666 else
667 match_no = 0;
668 }
669
670 tmp = istr.get();
671
672 } while( istr );
673 istr.unget();
674}
675
676inline const std::string
677GetPot::__get_next_token(std::istream& istr)
678 // get next concatinates string token. consider quotes that embrace
679 // whitespaces
680{
681 std::string token;
682 int tmp = 0;
683 int last_letter = 0;
684 while(1+1 == 2) {
685 last_letter = tmp; tmp = istr.get();
686 if( tmp == EOF
687 || ((tmp == ' ' || tmp == '\t' || tmp == '\n') && last_letter != '\\') ) {
688 return token;
689 }
690 else if( tmp == '\'' && last_letter != '\\' ) {
691 // QUOTES: un-backslashed quotes => it's a string
692 token += __get_string(istr);
693 continue;
694 }
695 else if( tmp == '{' && last_letter == '$') {
696 token += '{' + __get_until_closing_bracket(istr);
697 continue;
698 }
699 else if( tmp == '$' && last_letter == '\\') {
700 token += tmp; tmp = 0; // so that last_letter will become = 0, not '$';
701 continue;
702 }
703 else if( tmp == '\\' && last_letter != '\\')
704 continue; // don't append un-backslashed backslashes
705 token += tmp;
706 }
707}
708
709inline const std::string
710GetPot::__get_string(std::istream& istr)
711 // parse input until next matching '
712{
713 std::string str;
714 int tmp = 0;
715 int last_letter = 0;
716 while(1 + 1 == 2) {
717 last_letter = tmp; tmp = istr.get();
718 if( tmp == EOF) return str;
719 // un-backslashed quotes => it's the end of the string
720 else if( tmp == '\'' && last_letter != '\\') return str;
721 else if( tmp == '\\' && last_letter != '\\') continue; // don't append
722
723 str += tmp;
724 }
725}
726
727inline const std::string
728GetPot::__get_until_closing_bracket(std::istream& istr)
729 // parse input until next matching }
730{
731 std::string str = "";
732 int tmp = 0;
733 int last_letter = 0;
734 int brackets = 1;
735 while(1 + 1 == 2) {
736 last_letter = tmp; tmp = istr.get();
737 if( tmp == EOF) return str;
738 else if( tmp == '{' && last_letter == '$') brackets += 1;
739 else if( tmp == '}') {
740 brackets -= 1;
741 // un-backslashed brackets => it's the end of the string
742 if( brackets == 0) return str + '}';
743 else if( tmp == '\\' && last_letter != '\\')
744 continue; // do not append an unbackslashed backslash
745 }
746 str += tmp;
747 }
748}
749
750inline std::string
751GetPot::__process_section_label(const std::string& Section,
752 STRING_VECTOR& section_stack)
753{
754 std::string sname = Section;
755 // 1) subsection of actual section ('./' prefix)
756 if( sname.length() >= 2 && sname.substr(0, 2) == "./" ) {
757 sname = sname.substr(2);
758 }
759 // 2) subsection of parent section ('../' prefix)
760 else if( sname.length() >= 3 && sname.substr(0, 3) == "../" ) {
761 do {
762 if( section_stack.end() != section_stack.begin() )
763 section_stack.pop_back();
764 sname = sname.substr(3);
765 } while( sname.substr(0, 3) == "../" );
766 }
767 // 3) subsection of the root-section
768 else {
769 section_stack.erase(section_stack.begin(), section_stack.end());
770 // [] => back to root section
771 }
772
773 if( sname != "" ) {
774 // parse section name for 'slashes'
775 unsigned i=0;
776 while( i < sname.length() ) {
777 if( sname[i] == '/' ) {
778 section_stack.push_back(sname.substr(0,i));
779 if( i+1 < sname.length()-1 )
780 sname = sname.substr(i+1);
781 i = 0;
782 }
783 else
784 ++i;
785 }
786 section_stack.push_back(sname);
787 }
788 std::string section = "";
789 if( section_stack.size() != 0 ) {
790 victorate(std::string, section_stack, it)
791 section += *it + "/";
792 }
793 return section;
794}
795
796
797// convert string to DOUBLE, if not possible return Default
798inline double
799GetPot::__convert_to_type(const std::string& String, double Default) const
800{
801 double tmp;
802 if( sscanf(String.c_str(),"%lf", &tmp) != 1 ) return Default;
803 return tmp;
804}
805
806// convert string to INT, if not possible return Default
807inline int
808GetPot::__convert_to_type(const std::string& String, int Default) const
809{
810 // NOTE: intermediate results may be floating points, so that the string
811 // may look like 2.0e1 (i.e. float format) => use float conversion
812 // in any case.
813 return (int)__convert_to_type(String, (double)Default);
814}
815
816//////////////////////////////////////////////////////////////////////////////
817// (*) cursor oriented functions
818//.............................................................................
819inline const std::string
820GetPot::__get_remaining_string(const std::string& String, const std::string& Start) const
821 // Checks if 'String' begins with 'Start' and returns the remaining String.
822 // Returns None if String does not begin with Start.
823{
824 if( Start == "" ) return String;
825 // note: java.lang.String: substring(a,b) = from a to b-1
826 // C++ string: substr(a,b) = from a to a + b
827 if( String.find(Start) == 0 ) return String.substr(Start.length());
828 else return "";
829}
830
831// -- search for a certain argument and set cursor to position
832inline bool
833GetPot::search(const char* Option)
834{
835 unsigned OldCursor = cursor;
836 const std::string SearchTerm = prefix + Option;
837
838 // (*) record requested arguments for later ufo detection
839 __record_argument_request(SearchTerm);
840
841 if( OldCursor >= argv.size() ) OldCursor = static_cast<unsigned int>(argv.size()) - 1;
842 search_failed_f = true;
843
844 // (*) first loop from cursor position until end
845 unsigned c = cursor;
846 for(; c < argv.size(); c++) {
847 if( argv[c] == SearchTerm )
848 { cursor = c; search_failed_f = false; return true; }
849 }
850 if( ! search_loop_f ) return false;
851
852 // (*) second loop from 0 to old cursor position
853 for(c = 1; c < OldCursor; c++) {
854 if( argv[c] == SearchTerm )
855 { cursor = c; search_failed_f = false; return true; }
856 }
857 // in case nothing is found the cursor stays where it was
858 return false;
859}
860
861
862inline bool
863GetPot::search(unsigned No, const char* P, ...)
864{
865 // (*) recording the requested arguments happens in subroutine 'search'
866 if( No == 0 ) return false;
867
868 // search for the first argument
869 if( search(P) == true ) return true;
870
871 // start interpreting variable argument list
872 va_list ap;
873 va_start(ap, P);
874 unsigned i = 1;
875 for(; i < No; ++i) {
876 char* Opt = va_arg(ap, char *);
877 if( search(Opt) == true ) break;
878 }
879
880 if( i < No ) {
881 ++i;
882 // loop was left before end of array --> hit but
883 // make sure that the rest of the search terms is marked
884 // as requested.
885 for(; i < No; ++i) {
886 char* Opt = va_arg(ap, char *);
887 // (*) record requested arguments for later ufo detection
888 __record_argument_request(Opt);
889 }
890 va_end(ap);
891 return true;
892 }
893
894 va_end(ap);
895 // loop was left normally --> no hit
896 return false;
897}
898
899inline void
900GetPot::reset_cursor()
901{ search_failed_f = false; cursor = 0; }
902
903inline void
904GetPot::init_multiple_occurrence()
905{ disable_loop(); reset_cursor(); }
906///////////////////////////////////////////////////////////////////////////////
907// (*) direct access to command line arguments
908//.............................................................................
909//
910inline const std::string
911GetPot::operator[](unsigned idx) const
912{ return idx < argv.size() ? argv[idx] : ""; }
913
914inline int
915GetPot::get(unsigned Idx, int Default) const
916{
917 if( Idx >= argv.size() ) return Default;
918 return __convert_to_type(argv[Idx], Default);
919}
920
921inline double
922GetPot::get(unsigned Idx, const double& Default) const
923{
924 if( Idx >= argv.size() ) return Default;
925 return __convert_to_type(argv[Idx], Default);
926}
927
928inline const std::string
929GetPot::get(unsigned Idx, const char* Default) const
930{
931 if( Idx >= argv.size() ) return Default;
932 else return argv[Idx];
933}
934
935inline unsigned
936GetPot::size() const
937{ return static_cast<unsigned int>(argv.size()); }
938
939
940// -- next() function group
941inline int
942GetPot::next(int Default)
943{
944 if( search_failed_f ) return Default;
945 cursor++;
946 if( cursor >= argv.size() )
947 { cursor = static_cast<unsigned int>(argv.size()); return Default; }
948
949 // (*) record requested argument for later ufo detection
950 __record_argument_request(argv[cursor]);
951
952 const std::string Remain = __get_remaining_string(argv[cursor], prefix);
953
954 return Remain != "" ? __convert_to_type(Remain, Default) : Default;
955}
956
957inline double
958GetPot::next(const double& Default)
959{
960 if( search_failed_f ) return Default;
961 cursor++;
962
963 if( cursor >= argv.size() )
964 { cursor = static_cast<unsigned int>(argv.size()); return Default; }
965
966 // (*) record requested argument for later ufo detection
967 __record_argument_request(argv[cursor]);
968
969 std::string Remain = __get_remaining_string(argv[cursor], prefix);
970
971 return Remain != "" ? __convert_to_type(Remain, Default) : Default;
972}
973
974inline const std::string
975GetPot::next(const char* Default)
976{
977 if( search_failed_f ) return Default;
978 cursor++;
979
980 if( cursor >= argv.size() )
981 { cursor = static_cast<unsigned int>(argv.size()); return Default; }
982
983 // (*) record requested argument for later ufo detection
984 __record_argument_request(argv[cursor]);
985
986 const std::string Remain = __get_remaining_string(argv[cursor], prefix);
987
988 if( Remain == "" ) return Default;
989
990
991 // (*) function returns a pointer to a char array (inside Remain)
992 // this array will be deleted, though after this function call.
993 // To ensure propper functioning, create a copy inside *this
994 // object and only delete it, when *this is deleted.
995 char* result = new char[Remain.length()+1];
996 strncpy(result, Remain.c_str(), Remain.length()+1);
997
998 // store the created string internally, delete if when object deleted
999 __internal_string_container.push_back(result);
1000
1001 return result;
1002}
1003
1004// -- follow() function group
1005// distinct option to be searched for
1006inline int
1007GetPot::follow(int Default, const char* Option)
1008{
1009 // (*) record requested of argument is entirely handled in 'search()' and 'next()'
1010 if( search(Option) == false ) return Default;
1011 return next(Default);
1012}
1013
1014inline double
1015GetPot::follow(const double& Default, const char* Option)
1016{
1017 // (*) record requested of argument is entirely handled in 'search()' and 'next()'
1018 if( search(Option) == false ) return Default;
1019 return next(Default);
1020}
1021
1022inline const std::string
1023GetPot::follow(const char* Default, const char* Option)
1024{
1025 // (*) record requested of argument is entirely handled in 'search()' and 'next()'
1026 if( search(Option) == false ) return Default;
1027 return next(Default);
1028}
1029
1030// -- second follow() function group
1031// multiple option to be searched for
1032inline int
1033GetPot::follow(int Default, unsigned No, const char* P, ...)
1034{
1035 // (*) record requested of argument is entirely handled in 'search()' and 'next()'
1036 if( No == 0 ) return Default;
1037 if( search(P) == true ) return next(Default);
1038
1039 va_list ap;
1040 va_start(ap, P);
1041 unsigned i=1;
1042 for(; i<No; ++i) {
1043 char* Opt = va_arg(ap, char *);
1044 if( search(Opt) == true ) {
1045 va_end(ap);
1046 return next(Default);
1047 }
1048 }
1049 va_end(ap);
1050 return Default;
1051}
1052
1053inline double
1054GetPot::follow(const double& Default, unsigned No, const char* P, ...)
1055{
1056 // (*) record requested of argument is entirely handled in 'search()' and 'next()'
1057 if( No == 0 ) return Default;
1058 if( search(P) == true ) return next(Default);
1059
1060 va_list ap;
1061 va_start(ap, P);
1062 for(unsigned i=1; i<No; ++i) {
1063 char* Opt = va_arg(ap, char *);
1064 if( search(Opt) == true ) {
1065 va_end(ap);
1066 return next(Default);
1067 }
1068 }
1069 va_end(ap);
1070 return Default;
1071}
1072
1073inline const std::string
1074GetPot::follow(const char* Default, unsigned No, const char* P, ...)
1075{
1076 // (*) record requested of argument is entirely handled in 'search()' and 'next()'
1077 if( No == 0 ) return Default;
1078 if( search(P) == true ) return next(Default);
1079
1080 va_list ap;
1081 va_start(ap, P);
1082 unsigned i=1;
1083 for(; i<No; ++i) {
1084 char* Opt = va_arg(ap, char *);
1085 if( search(Opt) == true ) {
1086 va_end(ap);
1087 return next(Default);
1088 }
1089 }
1090 va_end(ap);
1091 return Default;
1092}
1093
1094
1095///////////////////////////////////////////////////////////////////////////////
1096// (*) lists of nominus following an option
1097//.............................................................................
1098//
1099inline std::vector<std::string>
1100GetPot::nominus_followers(const char* Option)
1101{
1102 std::vector<std::string> result_list;
1103 if( search(Option) == false ) return result_list;
1104 while( 1 + 1 == 2 ) {
1105 ++cursor;
1106 if( cursor >= argv.size() ) {
1107 cursor = argv.size() - 1;
1108 return result_list;
1109 }
1110 if( argv[cursor].length() >= 1 ) {
1111 if( argv[cursor][0] == '-' ) {
1112 return result_list;
1113 }
1114 // -- record for later ufo-detection
1115 __record_argument_request(argv[cursor]);
1116 // -- append to the result list
1117 result_list.push_back(argv[cursor]);
1118 }
1119 }
1120}
1121
1122inline std::vector<std::string>
1123GetPot::nominus_followers(unsigned No, ...)
1124{
1125 std::vector<std::string> result_list;
1126 // (*) record requested of argument is entirely handled in 'search()'
1127 // and 'nominus_followers()'
1128 if( No == 0 ) return result_list;
1129
1130 va_list ap;
1131 va_start(ap, No);
1132 for(unsigned i=0; i<No; ++i) {
1133 char* Option = va_arg(ap, char *);
1134 std::vector<std::string> tmp = nominus_followers(Option);
1135 result_list.insert(result_list.end(), tmp.begin(), tmp.end());
1136
1137 // std::cerr << "option = '" << Option << "'" << std::endl;
1138 // std::cerr << "length = " << tmp.size() << std::endl;
1139 // std::cerr << "new result list = <";
1140 // for(std::vector<std::string>::const_iterator it = result_list.begin();
1141 // it != result_list.end(); ++it)
1142 // std::cerr << *it << ", ";
1143 // std::cerr << ">\n";
1144 }
1145 va_end(ap);
1146 return result_list;
1147}
1148
1149
1150///////////////////////////////////////////////////////////////////////////////
1151// (*) directly connected options
1152//.............................................................................
1153//
1154inline int
1155GetPot::direct_follow(int Default, const char* Option)
1156{
1157 const char* FollowStr = __match_starting_string(Option);
1158 if( FollowStr == 0x0 ) return Default;
1159
1160 // (*) record requested of argument for later ufo-detection
1161 __record_argument_request(std::string(Option) + FollowStr);
1162
1163 if( ++cursor >= static_cast<unsigned int>(argv.size()) ) cursor = static_cast<unsigned int>(argv.size());
1164 return __convert_to_type(FollowStr, Default);
1165}
1166
1167inline double
1168GetPot::direct_follow(const double& Default, const char* Option)
1169{
1170 const char* FollowStr = __match_starting_string(Option);
1171 if( FollowStr == 0 ) return Default;
1172
1173 // (*) record requested of argument for later ufo-detection
1174 __record_argument_request(std::string(Option) + FollowStr);
1175
1176 if( ++cursor >= static_cast<unsigned int>(argv.size()) ) cursor = static_cast<unsigned int>(argv.size());
1177 return __convert_to_type(FollowStr, Default);
1178}
1179
1180inline const std::string
1181GetPot::direct_follow(const char* Default, const char* Option)
1182{
1183 if( search_failed_f ) return Default;
1184 const char* FollowStr = __match_starting_string(Option);
1185 if( FollowStr == 0 ) return Default;
1186
1187 // (*) record requested of argument for later ufo-detection
1188 if( FollowStr ) __record_argument_request(std::string(Option) + FollowStr);
1189
1190 if( ++cursor >= static_cast<unsigned int>(argv.size()) ) cursor = static_cast<unsigned int>(argv.size());
1191 return std::string(FollowStr);
1192}
1193
1194inline std::vector<std::string>
1195GetPot::string_tails(const char* StartString)
1196{
1197 std::vector<std::string> result;
1198 const unsigned N = static_cast<unsigned int>(strlen(StartString));
1199
1200 std::vector<std::string>::iterator it = argv.begin();
1201
1202 unsigned idx = 0;
1203 while( it != argv.end() ) {
1204 // (*) does start string match the given option?
1205 // NO -> goto next option
1206 if( strncmp(StartString, (*it).c_str(), N) != 0) { ++it; ++idx; continue; }
1207
1208 // append the found tail to the result vector
1209 result.push_back((*it).substr(N));
1210
1211 // adapt the nominus vector
1212 std::vector<unsigned>::iterator nit = idx_nominus.begin();
1213 for(; nit != idx_nominus.end(); ++nit) {
1214 if( *nit == idx ) {
1215 idx_nominus.erase(nit);
1216 for(; nit != idx_nominus.end(); ++nit) *nit -= 1;
1217 break;
1218 }
1219 }
1220
1221 // erase the found option
1222 argv.erase(it);
1223
1224 // 100% safe solution: set iterator back to the beginning.
1225 // (normally, 'it--' would be enough, but who knows how the
1226 // iterator is implemented and .erase() definitely invalidates
1227 // the current iterator position.
1228 if( argv.empty() ) break;
1229 it = argv.begin();
1230 }
1231 cursor = 0;
1232 nominus_cursor = -1;
1233 return result;
1234}
1235
1236inline std::vector<int>
1237GetPot::int_tails(const char* StartString, const int Default /* = -1 */)
1238{
1239 std::vector<int> result;
1240 const unsigned N = static_cast<unsigned int>(strlen(StartString));
1241
1242 std::vector<std::string>::iterator it = argv.begin();
1243
1244 unsigned idx = 0;
1245 while( it != argv.end() ) {
1246 // (*) does start string match the given option?
1247 // NO -> goto next option
1248 if( strncmp(StartString, (*it).c_str(), N) != 0) { ++it; ++idx; continue; }
1249
1250 // append the found tail to the result vector
1251 result.push_back(__convert_to_type((*it).substr(N), Default));
1252
1253 // adapt the nominus vector
1254 std::vector<unsigned>::iterator nit = idx_nominus.begin();
1255 for(; nit != idx_nominus.end(); ++nit) {
1256 if( *nit == idx ) {
1257 idx_nominus.erase(nit);
1258 for(; nit != idx_nominus.end(); ++nit) *nit -= 1;
1259 break;
1260 }
1261 }
1262
1263 // erase the found option
1264 argv.erase(it);
1265
1266 // 100% safe solution: set iterator back to the beginning.
1267 // (normally, 'it--' would be enough, but who knows how the
1268 // iterator is implemented and .erase() definitely invalidates
1269 // the current iterator position.
1270 if( argv.empty() ) break;
1271 it = argv.begin();
1272 }
1273 cursor = 0;
1274 nominus_cursor = -1;
1275 return result;
1276}
1277
1278inline std::vector<double>
1279GetPot::double_tails(const char* StartString,
1280 const double Default /* = -1.0 */)
1281{
1282 std::vector<double> result;
1283 const unsigned N = static_cast<unsigned int>(strlen(StartString));
1284
1285 std::vector<std::string>::iterator it = argv.begin();
1286 unsigned idx = 0;
1287 while( it != argv.end() ) {
1288 // (*) does start string match the given option?
1289 // NO -> goto next option
1290 if( strncmp(StartString, (*it).c_str(), N) != 0) { ++it; ++idx; continue; }
1291
1292 // append the found tail to the result vector
1293 result.push_back(__convert_to_type((*it).substr(N), Default));
1294
1295 // adapt the nominus vector
1296 std::vector<unsigned>::iterator nit = idx_nominus.begin();
1297 for(; nit != idx_nominus.end(); ++nit) {
1298 if( *nit == idx ) {
1299 idx_nominus.erase(nit);
1300 for(; nit != idx_nominus.end(); ++nit) *nit -= 1;
1301 break;
1302 }
1303 }
1304
1305 // erase the found option
1306 argv.erase(it);
1307
1308 // 100% safe solution: set iterator back to the beginning.
1309 // (normally, 'it--' would be enough, but who knows how the
1310 // iterator is implemented and .erase() definitely invalidates
1311 // the current iterator position.
1312 if( argv.empty() ) break;
1313 it = argv.begin();
1314 }
1315 cursor = 0;
1316 nominus_cursor = -1;
1317 return result;
1318}
1319
1320
1321
1322
1323
1324inline const char*
1325GetPot::__match_starting_string(const char* StartString)
1326 // pointer to the place where the string after
1327 // the match inside the found argument starts.
1328 // 0 no argument matches the starting string.
1329{
1330 const unsigned N = static_cast<unsigned int>(strlen(StartString));
1331 unsigned OldCursor = cursor;
1332
1333 if( OldCursor >= static_cast<unsigned int>(argv.size()) ) OldCursor = static_cast<unsigned int>(argv.size()) - 1;
1334 search_failed_f = true;
1335
1336 // (*) first loop from cursor position until end
1337 unsigned c = cursor;
1338 for(; c < argv.size(); c++) {
1339 if( strncmp(StartString, argv[c].c_str(), N) == 0)
1340 { cursor = c; search_failed_f = false; return &(argv[c].c_str()[N]); }
1341 }
1342
1343 if( ! search_loop_f ) return false;
1344
1345 // (*) second loop from 0 to old cursor position
1346 for(c = 1; c < OldCursor; c++) {
1347 if( strncmp(StartString, argv[c].c_str(), N) == 0)
1348 { cursor = c; search_failed_f = false; return &(argv[c].c_str()[N]); }
1349 }
1350 return 0;
1351}
1352
1353///////////////////////////////////////////////////////////////////////////////
1354// (*) search for flags
1355//.............................................................................
1356//
1357inline bool
1358GetPot::options_contain(const char* FlagList) const
1359{
1360 // go through all arguments that start with a '-' (but not '--')
1361 std::string str;
1362 STRING_VECTOR::const_iterator it = argv.begin();
1363 for(; it != argv.end(); ++it) {
1364 str = __get_remaining_string(*it, prefix);
1365
1366 if( str.length() >= 2 && str[0] == '-' && str[1] != '-' )
1367 if( __check_flags(str, FlagList) ) return true;
1368 }
1369 return false;
1370}
1371
1372inline bool
1373GetPot::argument_contains(unsigned Idx, const char* FlagList) const
1374{
1375 if( Idx >= argv.size() ) return false;
1376
1377 // (*) record requested of argument for later ufo-detection
1378 // an argument that is checked for flags is considered to be 'requested'
1379 ((GetPot*)this)->__record_argument_request(argv[Idx]);
1380
1381 if( prefix == "" )
1382 // search argument for any flag in flag list
1383 return __check_flags(argv[Idx], FlagList);
1384
1385 // if a prefix is set, then the argument index is the index
1386 // inside the 'namespace'
1387 // => only check list of arguments that start with prefix
1388 unsigned no_matches = 0;
1389 unsigned i=0;
1390 for(; i<argv.size(); ++i) {
1391 const std::string Remain = __get_remaining_string(argv[i], prefix);
1392 if( Remain != "") {
1393 no_matches += 1;
1394 if( no_matches == Idx)
1395 return __check_flags(Remain, FlagList);
1396 }
1397 }
1398 // no argument in this namespace
1399 return false;
1400}
1401
1402inline bool
1403GetPot::__check_flags(const std::string& Str, const char* FlagList) const
1404{
1405 const char* p=FlagList;
1406 for(; *p != '\0' ; p++)
1407 if( Str.find(*p) != std::string::npos ) return true; // found something
1408 return false;
1409}
1410
1411///////////////////////////////////////////////////////////////////////////////
1412// (*) nominus arguments
1413inline STRING_VECTOR
1414GetPot::nominus_vector() const
1415 // return vector of nominus arguments
1416{
1417 STRING_VECTOR nv;
1418 std::vector<unsigned>::const_iterator it = idx_nominus.begin();
1419 for(; it != idx_nominus.end(); ++it) {
1420 nv.push_back(argv[*it]);
1421
1422 // (*) record for later ufo-detection
1423 // when a nominus vector is requested, the entire set of nominus arguments are
1424 // tagged as 'requested'
1425 ((GetPot*)this)->__record_argument_request(argv[*it]);
1426 }
1427 return nv;
1428}
1429
1430inline std::string
1431GetPot::next_nominus()
1432{
1433 if( nominus_cursor < int(idx_nominus.size()) - 1 ) {
1434 const std::string Tmp = argv[idx_nominus[++nominus_cursor]];
1435
1436 // (*) record for later ufo-detection
1437 __record_argument_request(Tmp);
1438
1439 // -- cannot use the Tmp variable, since it is temporary and c_str() will return a pointer
1440 // to something that does no longer exist.
1441 return Tmp;
1442 }
1443 return std::string("");
1444}
1445
1446///////////////////////////////////////////////////////////////////////////////
1447// (*) variables
1448//.............................................................................
1449//
1450inline int
1451GetPot::operator()(const char* VarName, int Default) const
1452{
1453 // (*) recording of requested variables happens in '__find_variable()'
1454 const variable* sv = __find_variable(VarName);
1455 if( sv == 0 ) return Default;
1456 return __convert_to_type(sv->original, Default);
1457}
1458
1459inline double
1460GetPot::operator()(const char* VarName, const double& Default) const
1461{
1462 // (*) recording of requested variables happens in '__find_variable()'
1463 const variable* sv = __find_variable(VarName);
1464 if( sv == 0 ) return Default;
1465 return __convert_to_type(sv->original, Default);
1466}
1467
1468inline const std::string
1469GetPot::operator()(const char* VarName, const char* Default) const
1470{
1471 // (*) recording of requested variables happens in '__find_variable()'
1472 const variable* sv = __find_variable(VarName);
1473 if( sv == 0 ) return Default;
1474 // -- returning a c_str() pointer is OK here, since the variable remains existant,
1475 // while 'sv' of course is delete at the end of the function.
1476 return sv->original;
1477}
1478
1479inline int
1480GetPot::operator()(const char* VarName, int Default, unsigned Idx) const
1481{
1482 // (*) recording of requested variables happens in '__find_variable()'
1483 const variable* sv = __find_variable(VarName);
1484 if( sv == 0 ) return Default;
1485 const std::string* element = sv->get_element(Idx);
1486 if( element == 0 ) return Default;
1487 return __convert_to_type(*element, Default);
1488}
1489
1490inline double
1491GetPot::operator()(const char* VarName, const double& Default, unsigned Idx) const
1492{
1493 // (*) recording of requested variables happens in '__find_variable()'
1494 const variable* sv = __find_variable(VarName);
1495 if( sv == 0 ) return Default;
1496 const std::string* element = sv->get_element(Idx);
1497 if( element == 0 ) return Default;
1498 return __convert_to_type(*element, Default);
1499}
1500
1501inline const std::string
1502GetPot::operator()(const char* VarName, const char* Default, unsigned Idx) const
1503{
1504 // (*) recording of requested variables happens in '__find_variable()'
1505 const variable* sv = __find_variable(VarName);
1506 if( sv == 0 ) return Default;
1507 const std::string* element = sv->get_element(Idx);
1508 if( element == 0 ) return Default;
1509 return *element;
1510}
1511
1512inline void
1513GetPot::__record_argument_request(const std::string& Name)
1514{
1515 if( ! __request_recording_f ) return;
1516
1517 // (*) record requested variable for later ufo detection
1518 _requested_arguments.push_back(Name);
1519
1520 // (*) record considered section for ufo detection
1521 STRING_VECTOR STree = __get_section_tree(Name);
1522 victorate(std::string, STree, it)
1523 if( find(_requested_sections.begin(), _requested_sections.end(), *it) == _requested_sections.end() )
1524 if( section.length() != 0 ) _requested_sections.push_back(*it);
1525}
1526
1527inline void
1528GetPot::__record_variable_request(const std::string& Name)
1529{
1530 if( ! __request_recording_f ) return;
1531
1532 // (*) record requested variable for later ufo detection
1533 _requested_variables.push_back(Name);
1534
1535 // (*) record considered section for ufo detection
1536 STRING_VECTOR STree = __get_section_tree(Name);
1537 victorate(std::string, STree, it)
1538 if( find(_requested_sections.begin(), _requested_sections.end(), *it) == _requested_sections.end() )
1539 if( section.length() != 0 ) _requested_sections.push_back(*it);
1540}
1541
1542// (*) following functions are to be used from 'outside', after getpot has parsed its
1543// arguments => append an argument in the argument vector that reflects the addition
1544inline void
1545GetPot::__set_variable(const char* VarName, const char* Value)
1546{
1547 const GetPot::variable* Var = __find_variable(VarName);
1548 if( Var == 0 ) variables.push_back(variable(VarName, Value, _field_separator.c_str()));
1549 else ((GetPot::variable*)Var)->take(Value, _field_separator.c_str());
1550}
1551
1552inline void
1553GetPot::set(const char* VarName, const char* Value, const bool Requested /* = yes */)
1554{
1555 const std::string Arg = prefix + std::string(VarName) + std::string("=") + std::string(Value);
1556 argv.push_back(Arg);
1557 __set_variable(VarName, Value);
1558
1559 // if user does not specify the variable as 'not being requested' it will be
1560 // considered amongst the requested variables
1561 if( Requested ) __record_variable_request(Arg);
1562}
1563
1564inline void
1565GetPot::set(const char* VarName, const double& Value, const bool Requested /* = yes */)
1566{ __set_variable(VarName, __double2string(Value).c_str()); }
1567
1568inline void
1569GetPot::set(const char* VarName, const int Value, const bool Requested /* = yes */)
1570{ __set_variable(VarName, __int2string(Value).c_str()); }
1571
1572
1573inline unsigned
1574GetPot::vector_variable_size(const char* VarName) const
1575{
1576 const variable* sv = __find_variable(VarName);
1577 if( sv == 0 ) return 0;
1578 return static_cast<unsigned int>(sv->value.size());
1579}
1580
1581inline STRING_VECTOR
1582GetPot::get_variable_names() const
1583{
1584 STRING_VECTOR result;
1585 std::vector<GetPot::variable>::const_iterator it = variables.begin();
1586 for(; it != variables.end(); ++it) {
1587 const std::string Tmp = __get_remaining_string((*it).name, prefix);
1588 if( Tmp != "" ) result.push_back(Tmp);
1589 }
1590 return result;
1591}
1592
1593inline STRING_VECTOR
1594GetPot::get_section_names() const
1595{ return section_list; }
1596
1597inline const GetPot::variable*
1598GetPot::__find_variable(const char* VarName) const
1599{
1600 const std::string Name = prefix + VarName;
1601
1602 // (*) record requested variable for later ufo detection
1603 ((GetPot*)this)->__record_variable_request(Name);
1604
1605 std::vector<variable>::const_iterator it = variables.begin();
1606 for(; it != variables.end(); ++it) {
1607 if( (*it).name == Name ) return &(*it);
1608 }
1609 return 0;
1610}
1611
1612///////////////////////////////////////////////////////////////////////////////
1613// (*) ouput (basically for debugging reasons
1614//.............................................................................
1615//
1616inline int
1617GetPot::print() const
1618{
1619 std::cout << "argc = " << static_cast<unsigned int>(argv.size()) << std::endl;
1620 STRING_VECTOR::const_iterator it = argv.begin();
1621 for(; it != argv.end(); ++it)
1622 std::cout << *it << std::endl;
1623 std::cout << std::endl;
1624 return 1;
1625}
1626
1627// (*) dollar bracket expressions (DBEs) ------------------------------------
1628//
1629// 1) Entry Function: __DBE_expand_string()
1630// Takes a string such as
1631//
1632// "${+ ${x} ${y}} Subject-${& ${section} ${subsection}}: ${title}"
1633//
1634// calls __DBE_expand() for each of the expressions
1635//
1636// ${+ ${x} ${y}}
1637// ${& ${section} ${subsection}}
1638// ${Title}
1639//
1640// and returns the string
1641//
1642// "4711 Subject-1.01: Mit den Clowns kamen die Schwaene"
1643//
1644// assuming that
1645// x = "4699"
1646// y = "12"
1647// section = "1."
1648// subsection = "01"
1649// title = "Mit den Clowns kamen die Schwaene"
1650//
1651// 2) __DBE_expand():
1652//
1653// checks for the command, i.e. the 'sign' that follows '${'
1654// divides the argument list into sub-expressions using
1655// __DBE_get_expr_list()
1656//
1657// ${+ ${x} ${y}} -> "${x}" "${y}"
1658// ${& ${section} ${subsection}} -> "${section}" "${subsection}"
1659// ${Title} -> Nothing, variable expansion
1660//
1661// 3) __DBE_expression_list():
1662//
1663// builds a vector of unbracketed whitespace separated strings, i.e.
1664//
1665// " ${Number}.a ${: Das Marmorbild} AB-${& Author= ${Eichendorf}-1870}"
1666//
1667// is split into a vector
1668//
1669// [0] ${Number}.a
1670// [1] ${: Das Marmorbild}
1671// [2] AB-${& Author= ${Eichendorf}}-1870
1672//
1673// Each sub-expression is expanded using expand().
1674//---------------------------------------------------------------------------
1675inline std::string
1676GetPot::__DBE_expand_string(const std::string str)
1677{
1678 // Parses for closing operators '${ }' and expands them letting
1679 // white spaces and other letters as they are.
1680 std::string new_string = "";
1681 unsigned open_brackets = 0;
1682 unsigned first = 0;
1683 unsigned i = 0;
1684 for(; i<str.size(); ++i) {
1685 if( i < str.size() - 2 && str.substr(i, 2) == "${" ) {
1686 if( open_brackets == 0 ) first = i+2;
1687 open_brackets++;
1688 }
1689 else if( str[i] == '}' && open_brackets > 0) {
1690 open_brackets -= 1;
1691 if( open_brackets == 0 ) {
1692 const std::string Replacement = __DBE_expand(str.substr(first, i - first));
1693 new_string += Replacement;
1694 }
1695 }
1696 else if( open_brackets == 0 )
1697 new_string += str[i];
1698 }
1699 return new_string;
1700}
1701
1702inline STRING_VECTOR
1703GetPot::__DBE_get_expr_list(const std::string str_, const unsigned ExpectedNumber)
1704 // ensures that the resulting vector has the expected number
1705 // of arguments, but they may contain an error message
1706{
1707 std::string str = str_;
1708 // Separates expressions by non-bracketed whitespaces, expands them
1709 // and puts them into a list.
1710
1711 unsigned i=0;
1712 // (1) eat initial whitespaces
1713 for(; i < str.size(); ++i)
1714 if( ! isspace(str[i]) ) break;
1715
1716 STRING_VECTOR expr_list;
1717 unsigned open_brackets = 0;
1718 std::vector<unsigned> start_idx;
1719 unsigned start_new_string = i;
1720 unsigned l = static_cast<unsigned int>(str.size());
1721
1722 // (2) search for ${ } expressions ...
1723 while( i < l ) {
1724 const char letter = str[i];
1725 // whitespace -> end of expression
1726 if( isspace(letter) && open_brackets == 0) {
1727 expr_list.push_back(str.substr(start_new_string, i - start_new_string));
1728 bool no_breakout_f = true;
1729 for(++i; i < l ; ++i) {
1730 if( ! isspace(str[i]) )
1731 { no_breakout_f = false; start_new_string = i; break; }
1732 }
1733 if( no_breakout_f ) {
1734 // end of expression list
1735 if( expr_list.size() < ExpectedNumber ) {
1736 const std::string pre_tmp("<< ${ }: missing arguments>>");
1737 STRING_VECTOR tmp(ExpectedNumber - expr_list.size(), pre_tmp);
1738 expr_list.insert(expr_list.end(), tmp.begin(), tmp.end());
1739 }
1740 return expr_list;
1741 }
1742 }
1743
1744 // dollar-bracket expression
1745 if( str.length() >= i+2 && str.substr(i, 2) == "${" ) {
1746 open_brackets++;
1747 start_idx.push_back(i+2);
1748 }
1749 else if( letter == '}' && open_brackets > 0) {
1750 int start = start_idx[start_idx.size()-1];
1751 start_idx.pop_back();
1752 const std::string Replacement = __DBE_expand(str.substr(start, i-start));
1753 if( start - 3 < (int)0)
1754 str = Replacement + str.substr(i+1);
1755 else
1756 str = str.substr(0, start-2) + Replacement + str.substr(i+1);
1757 l = static_cast<unsigned int>(str.size());
1758 i = start + static_cast<unsigned int>(Replacement.size()) - 3;
1759 open_brackets--;
1760 }
1761 ++i;
1762 }
1763
1764 // end of expression list
1765 expr_list.push_back(str.substr(start_new_string, i-start_new_string));
1766
1767 if( expr_list.size() < ExpectedNumber ) {
1768 const std::string pre_tmp("<< ${ }: missing arguments>>");
1769 STRING_VECTOR tmp(ExpectedNumber - expr_list.size(), pre_tmp);
1770 expr_list.insert(expr_list.end(), tmp.begin(), tmp.end());
1771 }
1772
1773 return expr_list;
1774}
1775
1776inline const GetPot::variable*
1777GetPot::__DBE_get_variable(std::string VarName)
1778{
1779 static GetPot::variable ev;
1780 std::string secure_Prefix = prefix;
1781
1782 prefix = section;
1783 // (1) first search in currently active section
1784 const GetPot::variable* var = __find_variable(VarName.c_str());
1785 if( var != 0 ) { prefix = secure_Prefix; return var; }
1786
1787 // (2) search in root name space
1788 prefix = "";
1789 var = __find_variable(VarName.c_str());
1790 if( var != 0 ) { prefix = secure_Prefix; return var; }
1791
1792 prefix = secure_Prefix;
1793
1794 // error occured => variable name == ""
1795 char* tmp = new char[VarName.length() + 25];
1796#ifndef WIN32
1797 snprintf(tmp, (int)sizeof(char)*(VarName.length() + 25),
1798#else
1799 _snprintf(tmp, sizeof(char)*(VarName.length() + 25),
1800#endif
1801 "<<${ } variable '%s' undefined>>", VarName.c_str());
1802 ev.name = "";
1803 ev.original = std::string(tmp);
1804 delete [] tmp;
1805 return &ev;
1806}
1807
1808inline std::string
1809GetPot::__DBE_expand(const std::string expr)
1810{
1811 // ${: } pure text
1812 if( expr[0] == ':' )
1813 return expr.substr(1);
1814
1815 // ${& expr expr ... } text concatination
1816 else if( expr[0] == '&' ) {
1817 const STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 1);
1818
1819 STRING_VECTOR::const_iterator it = A.begin();
1820 std::string result = *it++;
1821 for(; it != A.end(); ++it) result += *it;
1822
1823 return result;
1824 }
1825
1826 // ${<-> expr expr expr} text replacement
1827 else if( expr.length() >= 3 && expr.substr(0, 3) == "<->" ) {
1828 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(3), 3);
1829 std::string::size_type tmp = 0;
1830 const std::string::size_type L = A[1].length();
1831 while( (tmp = A[0].find(A[1])) != std::string::npos ) {
1832 A[0].replace(tmp, L, A[2]);
1833 }
1834 return A[0];
1835 }
1836 // ${+ ...}, ${- ...}, ${* ...}, ${/ ...} expressions
1837 else if( expr[0] == '+' ) {
1838 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
1839 STRING_VECTOR::const_iterator it = A.begin();
1840 double result = __convert_to_type(*it++, 0.0);
1841 for(; it != A.end(); ++it)
1842 result += __convert_to_type(*it, 0.0);
1843
1844 return __double2string(result);
1845 }
1846 else if( expr[0] == '-' ) {
1847 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
1848 STRING_VECTOR::const_iterator it = A.begin();
1849 double result = __convert_to_type(*it++, 0.0);
1850 for(; it != A.end(); ++it)
1851 result -= __convert_to_type(*it, 0.0);
1852
1853 return __double2string(result);
1854 }
1855 else if( expr[0] == '*' ) {
1856 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
1857 STRING_VECTOR::const_iterator it = A.begin();
1858 double result = __convert_to_type(*it++, 0.0);
1859 for(; it != A.end(); ++it)
1860 result *= __convert_to_type(*it, 0.0);
1861
1862 return __double2string(result);
1863 }
1864 else if( expr[0] == '/' ) {
1865
1866 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
1867 STRING_VECTOR::const_iterator it = A.begin();
1868 double result = __convert_to_type(*it++, 0.0);
1869 if( result == 0 ) return "0.0";
1870 for(; it != A.end(); ++it) {
1871 const double Q = __convert_to_type(*it, 0.0);
1872 if( Q == 0.0 ) return "0.0";
1873 result /= Q;
1874 }
1875 return __double2string(result);
1876 }
1877
1878 // ${^ ... } power expressions
1879 else if( expr[0] == '^' ) {
1880 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
1881 STRING_VECTOR::const_iterator it = A.begin();
1882 double result = __convert_to_type(*it++, 0.0);
1883 for(; it != A.end(); ++it)
1884 result = pow(result, __convert_to_type(*it, 0.0));
1885 return __double2string(result);
1886 }
1887
1888 // ${== } ${<= } ${>= } comparisons (return the number of the first 'match'
1889 else if( expr.length() >= 2 &&
1890 ( expr.substr(0,2) == "==" || expr.substr(0,2) == ">=" ||
1891 expr.substr(0,2) == "<=" || expr[0] == '>' || expr[0] == '<')) {
1892 // differentiate between two and one sign operators
1893 unsigned op = 0;
1894 enum { EQ, GEQ, LEQ, GT, LT };
1895 if ( expr.substr(0, 2) == "==" ) op = EQ;
1896 else if ( expr.substr(0, 2) == ">=" ) op = GEQ;
1897 else if ( expr.substr(0, 2) == "<=" ) op = LEQ;
1898 else if ( expr[0] == '>' ) op = GT;
1899 else /* "<" */ op = LT;
1900
1901 STRING_VECTOR a;
1902 if ( op == GT || op == LT ) a = __DBE_get_expr_list(expr.substr(1), 2);
1903 else a = __DBE_get_expr_list(expr.substr(2), 2);
1904
1905 std::string x_orig = a[0];
1906 double x = __convert_to_type(x_orig, 1e37);
1907 unsigned i = 1;
1908
1909 STRING_VECTOR::const_iterator y_orig = a.begin();
1910 for(y_orig++; y_orig != a.end(); y_orig++) {
1911 double y = __convert_to_type(*y_orig, 1e37);
1912
1913 // set the strings as reference if one wasn't a number
1914 if ( x == 1e37 || y == 1e37 ) {
1915 // it's a string comparison
1916 if( (op == EQ && x_orig == *y_orig) || (op == GEQ && x_orig >= *y_orig) ||
1917 (op == LEQ && x_orig <= *y_orig) || (op == GT && x_orig > *y_orig) ||
1918 (op == LT && x_orig < *y_orig) )
1919 return __int2string(i);
1920 }
1921 else {
1922 // it's a number comparison
1923 if( (op == EQ && x == y) || (op == GEQ && x >= y) ||
1924 (op == LEQ && x <= y) || (op == GT && x > y) ||
1925 (op == LT && x < y) )
1926 return __int2string(i);
1927 }
1928 ++i;
1929 }
1930
1931 // nothing fulfills the condition => return 0
1932 return "0";
1933 }
1934 // ${?? expr expr} select
1935 else if( expr.length() >= 2 && expr.substr(0, 2) == "??" ) {
1936 STRING_VECTOR a = __DBE_get_expr_list(expr.substr(2), 2);
1937 double x = __convert_to_type(a[0], 1e37);
1938 // last element is always the default argument
1939 if( x == 1e37 || x < 0 || x >= a.size() - 1 ) return a[a.size()-1];
1940
1941 // round x to closest integer
1942 return a[int(x+0.5)];
1943 }
1944 // ${? expr expr expr} if then else conditions
1945 else if( expr[0] == '?' ) {
1946 STRING_VECTOR a = __DBE_get_expr_list(expr.substr(1), 2);
1947 if( __convert_to_type(a[0], 0.0) == 1.0 ) return a[1];
1948 else if( a.size() > 2 ) return a[2];
1949 }
1950 // ${! expr} maxro expansion
1951 else if( expr[0] == '!' ) {
1952 const GetPot::variable* Var = __DBE_get_variable(expr.substr(1));
1953 // error
1954 if( Var->name == "" ) return std::string(Var->original);
1955
1956 const STRING_VECTOR A = __DBE_get_expr_list(Var->original, 2);
1957 return A[0];
1958 }
1959 // ${@: } - string subscription
1960 else if( expr.length() >= 2 && expr.substr(0,2) == "@:" ) {
1961 const STRING_VECTOR A = __DBE_get_expr_list(expr.substr(2), 2);
1962 double x = __convert_to_type(A[1], 1e37);
1963
1964 // last element is always the default argument
1965 if( x == 1e37 || x < 0 || x >= A[0].size() - 1)
1966 return "<<1st index out of range>>";
1967
1968 if( A.size() > 2 ) {
1969 double y = __convert_to_type(A[2], 1e37);
1970 if ( y != 1e37 && y > 0 && y <= A[0].size() - 1 && y > x )
1971 return A[0].substr(int(x+0.5), int(y+1.5) - int(x+0.5));
1972 else if( y == -1 )
1973 return A[0].substr(int(x+0.5));
1974 return "<<2nd index out of range>>";
1975 }
1976 else {
1977 char* tmp = new char[2];
1978 tmp[0] = A[0][int(x+0.5)]; tmp[1] = '\0';
1979 std::string result(tmp);
1980 delete [] tmp;
1981 return result;
1982 }
1983 }
1984 // ${@ } - vector subscription
1985 else if( expr[0] == '@' ) {
1986 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
1987 const GetPot::variable* Var = __DBE_get_variable(A[0]);
1988 // error
1989 if( Var->name == "" ) {
1990 // make a copy of the string if an error occured
1991 // (since the error variable is a static variable inside get_variable())
1992 return std::string(Var->original);
1993 }
1994
1995 double x = __convert_to_type(A[1], 1e37);
1996
1997 // last element is always the default argument
1998 if (x == 1e37 || x < 0 || x >= Var->value.size() )
1999 return "<<1st index out of range>>";
2000
2001 if ( A.size() > 2) {
2002 double y = __convert_to_type(A[2], 1e37);
2003 int begin = int(x+0.5);
2004 int end = 0;
2005 if ( y != 1e37 && y > 0 && y <= Var->value.size() && y > x)
2006 end = int(y+1.5);
2007 else if( y == -1 )
2008 end = static_cast<unsigned int>(Var->value.size());
2009 else
2010 return "<<2nd index out of range>>";
2011
2012 std::string result = *(Var->get_element(begin));
2013 int i = begin+1;
2014 for(; i < end; ++i)
2015 result += std::string(" ") + *(Var->get_element(i));
2016 return result;
2017 }
2018 else
2019 return *(Var->get_element(int(x+0.5)));
2020 }
2021
2022 const STRING_VECTOR A = __DBE_get_expr_list(expr, 1);
2023 const GetPot::variable* B = __DBE_get_variable(A[0]);
2024
2025 // make a copy of the string if an error occured
2026 // (since the error variable is a static variable inside get_variable())
2027 if( B->name == "" ) return std::string(B->original);
2028 // (psuggs@pobox.com mentioned to me the warning MSVC++6.0 produces
2029 // with: else return B->original (thanks))
2030 return B->original;
2031}
2032
2033
2034///////////////////////////////////////////////////////////////////////////////
2035// (*) unidentified flying objects
2036//.............................................................................
2037//
2038inline bool
2039GetPot::__search_string_vector(const STRING_VECTOR& VecStr, const std::string& Str) const
2040{
2041 victorate(std::string, VecStr, itk) {
2042 if( *itk == Str ) return true;
2043 }
2044 return false;
2045}
2046
2047inline STRING_VECTOR
2048GetPot::unidentified_arguments(unsigned Number,
2049 const char* KnownArgument1, ...) const
2050{
2051 STRING_VECTOR known_arguments;
2052
2053 // (1) create a vector of known arguments
2054 if( Number == 0 ) return STRING_VECTOR();
2055
2056 va_list ap;
2057 va_start(ap, KnownArgument1);
2058 known_arguments.push_back(std::string(KnownArgument1));
2059 unsigned i=1;
2060 for(; i<Number; ++i)
2061 known_arguments.push_back(std::string(va_arg(ap, char *)));
2062 va_end(ap);
2063
2064 return unidentified_arguments(known_arguments);
2065}
2066
2067inline STRING_VECTOR
2068GetPot::unidentified_arguments() const
2069{ return unidentified_arguments(_requested_arguments); }
2070
2071inline STRING_VECTOR
2072GetPot::unidentified_arguments(const STRING_VECTOR& Knowns) const
2073{
2074 STRING_VECTOR ufos;
2075 STRING_VECTOR::const_iterator it = argv.begin();
2076 ++it; // forget about argv[0] (application or filename)
2077 for(; it != argv.end(); ++it) {
2078 // -- argument belongs to prefixed section ?
2079 const std::string arg = __get_remaining_string(*it, prefix);
2080 if( arg == "" ) continue;
2081
2082 // -- check if in list
2083 if( __search_string_vector(Knowns, arg) == false)
2084 ufos.push_back(*it);
2085 }
2086 return ufos;
2087}
2088
2089inline STRING_VECTOR
2090GetPot::unidentified_options(unsigned Number,
2091 const char* KnownOption1, ...) const
2092{
2093 STRING_VECTOR known_options;
2094
2095 // (1) create a vector of known arguments
2096 if( Number == 0 ) return STRING_VECTOR();
2097
2098 va_list ap;
2099 va_start(ap, KnownOption1);
2100 known_options.push_back(std::string(KnownOption1));
2101 unsigned i=1;
2102 for(; i<Number; ++i)
2103 known_options.push_back(std::string(va_arg(ap, char *)));
2104 va_end(ap);
2105
2106 return unidentified_options(known_options);
2107}
2108
2109inline STRING_VECTOR
2110GetPot::unidentified_options() const
2111{
2112 // -- every option is an argument.
2113 // -- the set of requested arguments contains the set of requested options.
2114 // -- IF the set of requested arguments contains unrequested options,
2115 // THEN they were requested as 'follow' and 'next' arguments and not as real options.
2116 //
2117 // => it is not necessary to separate requested options from the list
2118 STRING_VECTOR option_list;
2119 victorate(std::string, _requested_arguments, it) {
2120 const std::string arg = *it;
2121 if( arg.length() == 0 ) continue;
2122 if( arg[0] == '-' ) option_list.push_back(arg);
2123 }
2124 return unidentified_options(option_list);
2125}
2126
2127inline STRING_VECTOR
2128GetPot::unidentified_options(const STRING_VECTOR& Knowns) const
2129{
2130 STRING_VECTOR ufos;
2131 STRING_VECTOR::const_iterator it = argv.begin();
2132 ++it; // forget about argv[0] (application or filename)
2133 for(; it != argv.end(); ++it) {
2134 // -- argument belongs to prefixed section ?
2135 const std::string arg = __get_remaining_string(*it, prefix);
2136 if( arg == "" ) continue;
2137
2138 // is argument really an option (starting with '-') ?
2139 if( arg.length() < 1 || arg[0] != '-' ) continue;
2140
2141 if( __search_string_vector(Knowns, arg) == false)
2142 ufos.push_back(*it);
2143 }
2144
2145 return ufos;
2146}
2147
2148inline std::string
2149GetPot::unidentified_flags(const char* KnownFlagList, int ArgumentNumber=-1) const
2150 // Two modes:
2151 // ArgumentNumber >= 0 check specific argument
2152 // ArgumentNumber == -1 check all options starting with one '-'
2153 // for flags
2154{
2155 std::string ufos;
2156 STRING_VECTOR known_arguments;
2157 std::string KFL(KnownFlagList);
2158
2159 // (2) iteration over '-' arguments (options)
2160 if( ArgumentNumber == -1 ) {
2161 STRING_VECTOR::const_iterator it = argv.begin();
2162 ++it; // forget about argv[0] (application or filename)
2163 for(; it != argv.end(); ++it) {
2164 // -- argument belongs to prefixed section ?
2165 const std::string arg = __get_remaining_string(*it, prefix);
2166 if( arg == "" ) continue;
2167
2168 // -- does arguments start with '-' (but not '--')
2169 if ( arg.length() < 2 ) continue;
2170 else if( arg[0] != '-' ) continue;
2171 else if( arg[1] == '-' ) continue;
2172
2173 // -- check out if flags inside option are contained in KnownFlagList
2174 const char* p=arg.c_str();
2175 p++; // skip starting minus
2176 for(; *p != '\0' ; p++)
2177 if( KFL.find(*p) == std::string::npos ) ufos += *p;
2178 }
2179 }
2180 // (1) check specific argument
2181 else {
2182 // -- only check arguments that start with prefix
2183 int no_matches = 0;
2184 unsigned i=1;
2185 for(; i<argv.size(); ++i) {
2186 const std::string Remain = __get_remaining_string(argv[i], prefix);
2187 if( Remain != "") {
2188 no_matches++;
2189 if( no_matches == ArgumentNumber) {
2190 // -- the right argument number inside the section is found
2191 // => check it for flags
2192 const char* p = Remain.c_str();
2193 p++; // skip starting minus
2194 for(; *p != '\0' ; p++)
2195 if( KFL.find(*p) == std::string::npos ) ufos += *p;
2196 return ufos;
2197 }
2198 }
2199 }
2200 }
2201 return ufos;
2202}
2203
2204inline STRING_VECTOR
2205GetPot::unidentified_variables(unsigned Number,
2206 const char* KnownVariable1, ...) const
2207{
2208 STRING_VECTOR known_variables;
2209
2210 // create vector of known arguments
2211 if( Number == 0 ) return STRING_VECTOR();
2212
2213 va_list ap;
2214 va_start(ap, KnownVariable1);
2215 known_variables.push_back(std::string(KnownVariable1));
2216 unsigned i=1;
2217 for(; i<Number; ++i)
2218 known_variables.push_back(std::string(va_arg(ap, char *)));
2219 va_end(ap);
2220
2221 return unidentified_variables(known_variables);
2222}
2223
2224inline STRING_VECTOR
2225GetPot::unidentified_variables(const STRING_VECTOR& Knowns) const
2226{
2227 STRING_VECTOR ufos;
2228
2229 victorate(GetPot::variable, variables, it) {
2230 // -- check if variable has specific prefix
2231 const std::string var_name = __get_remaining_string((*it).name, prefix);
2232 if( var_name == "" ) continue;
2233
2234 // -- check if variable is known
2235 if( __search_string_vector(Knowns, var_name) == false)
2236 ufos.push_back((*it).name);
2237 }
2238 return ufos;
2239}
2240
2241inline STRING_VECTOR
2242GetPot::unidentified_variables() const
2243{ return unidentified_variables(_requested_variables); }
2244
2245
2246inline STRING_VECTOR
2247GetPot::unidentified_sections(unsigned Number,
2248 const char* KnownSection1, ...) const
2249{
2250 STRING_VECTOR known_sections;
2251
2252 // (1) create a vector of known arguments
2253 if( Number == 0 ) return STRING_VECTOR();
2254
2255 va_list ap;
2256 va_start(ap, KnownSection1);
2257 known_sections.push_back(std::string(KnownSection1));
2258 unsigned i=1;
2259 for(; i<Number; ++i) {
2260 std::string tmp = std::string(va_arg(ap, char *));
2261 if( tmp.length() == 0 ) continue;
2262 if( tmp[tmp.length()-1] != '/' ) tmp += '/';
2263 known_sections.push_back(tmp);
2264 }
2265 va_end(ap);
2266
2267 return unidentified_sections(known_sections);
2268}
2269
2270inline STRING_VECTOR
2271GetPot::unidentified_sections() const
2272{ return unidentified_sections(_requested_sections); }
2273
2274inline STRING_VECTOR
2275GetPot::unidentified_sections(const STRING_VECTOR& Knowns) const
2276{
2277 STRING_VECTOR ufos;
2278
2279 victorate(std::string, section_list, it) {
2280 // -- check if section conform to prefix
2281 const std::string sec_name = __get_remaining_string(*it, prefix);
2282 if( sec_name == "" ) continue;
2283
2284 // -- check if section is known
2285 if( __search_string_vector(Knowns, sec_name) == false )
2286 ufos.push_back(*it);
2287 }
2288
2289 return ufos;
2290}
2291
2292
2293inline STRING_VECTOR
2294GetPot::unidentified_nominuses(unsigned Number, const char* Known, ...) const
2295{
2296 STRING_VECTOR known_nominuses;
2297
2298 // create vector of known arguments
2299 if( Number == 0 ) return STRING_VECTOR();
2300
2301 va_list ap;
2302 va_start(ap, Known);
2303 known_nominuses.push_back(std::string(Known));
2304 unsigned i=1;
2305 for(; i<Number; ++i) {
2306 std::string tmp = std::string(va_arg(ap, char *));
2307 if( tmp.length() == 0 ) continue;
2308 known_nominuses.push_back(tmp);
2309 }
2310 va_end(ap);
2311
2312 return unidentified_nominuses(known_nominuses);
2313}
2314
2315inline STRING_VECTOR
2316GetPot::unidentified_nominuses() const {
2317 // -- every nominus is an argument.
2318 // -- the set of requested arguments contains the set of requested nominuss.
2319 // -- IF the set of requested arguments contains unrequested nominuss,
2320 // THEN they were requested as 'follow' and 'next' arguments and not as real nominuses.
2321 //
2322 // => it is not necessary to separate requested nominus from the list
2323
2324 return unidentified_nominuses(_requested_arguments);
2325}
2326
2327inline STRING_VECTOR
2328GetPot::unidentified_nominuses(const STRING_VECTOR& Knowns) const
2329{
2330 STRING_VECTOR ufos;
2331
2332 // (2) iterate over all arguments
2333 STRING_VECTOR::const_iterator it = argv.begin();
2334 ++it; // forget about argv[0] (application or filename)
2335 for(; it != argv.end(); ++it) {
2336 // -- check if nominus part of prefix
2337 const std::string arg = __get_remaining_string(*it, prefix);
2338 if( arg == "" ) continue;
2339
2340 if( arg.length() < 1 ) continue;
2341 // option ? --> not a nomius
2342 if( arg[0] == '-' ) continue;
2343 // section ? --> not a real nominus
2344 if( arg[0] == '[' && arg[arg.length()-1] == ']' ) continue;
2345 // variable definition ? --> not a real nominus
2346 bool continue_f = false;
2347 unsigned i=0;
2348 for(; i<arg.length() ; ++i)
2349 if( arg[i] == '=' ) { continue_f = true; break; }
2350 if( continue_f ) continue;
2351
2352 // real nominuses are compared with the given list
2353 if( __search_string_vector(Knowns, arg) == false )
2354 ufos.push_back(*it);
2355 }
2356 return ufos;
2357}
2358
2359
2360///////////////////////////////////////////////////////////////////////////////
2361// (*) variable class
2362//.............................................................................
2363//
2364inline
2365GetPot::variable::variable()
2366{}
2367
2368inline
2369GetPot::variable::variable(const variable& That)
2370{
2371#ifdef WIN32
2372 operator=(That);
2373#else
2374 GetPot::variable::operator=(That);
2375#endif
2376}
2377
2378
2379inline
2380GetPot::variable::variable(const char* Name, const char* Value, const char* FieldSeparator)
2381 : name(Name)
2382{
2383 // make a copy of the 'Value'
2384 take(Value, FieldSeparator);
2385}
2386
2387inline const std::string*
2388GetPot::variable::get_element(unsigned Idx) const
2389{ if( Idx >= value.size() ) return 0; else return &(value[Idx]); }
2390
2391inline void
2392GetPot::variable::take(const char* Value, const char* FieldSeparator)
2393{
2394 original = std::string(Value);
2395
2396 // separate string by white space delimiters using 'strtok'
2397 // thread safe usage of strtok (no static members)
2398 char* spt = 0;
2399 // make a copy of the 'Value'
2400 char* copy = new char[strlen(Value)+1];
2401 strcpy(copy, Value);
2402 char* follow_token = strtok_r(copy, FieldSeparator, &spt);
2403 if( value.size() != 0 ) value.erase(value.begin(), value.end());
2404 while(follow_token != 0) {
2405 value.push_back(std::string(follow_token));
2406 follow_token = strtok_r(NULL, FieldSeparator, &spt);
2407 }
2408
2409 delete [] copy;
2410}
2411
2412inline
2413GetPot::variable::~variable()
2414{}
2415
2416inline GetPot::variable&
2417GetPot::variable::operator=(const GetPot::variable& That)
2418{
2419 if( &That != this) {
2420 name = That.name;
2421 value = That.value;
2422 original = That.original;
2423 }
2424 return *this;
2425}
2426
2427#undef victorate
2428
2429
2430#endif // __include_guard_GETPOT_H__
2431
2432
2433
diff --git a/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/LPGL.txt b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/LPGL.txt
new file mode 100755
index 0000000000..b1e3f5a263
--- /dev/null
+++ b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/LPGL.txt
@@ -0,0 +1,504 @@
1 GNU LESSER GENERAL PUBLIC LICENSE
2 Version 2.1, February 1999
3
4 Copyright (C) 1991, 1999 Free Software Foundation, Inc.
5 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
6 Everyone is permitted to copy and distribute verbatim copies
7 of this license document, but changing it is not allowed.
8
9[This is the first released version of the Lesser GPL. It also counts
10 as the successor of the GNU Library Public License, version 2, hence
11 the version number 2.1.]
12
13 Preamble
14
15 The licenses for most software are designed to take away your
16freedom to share and change it. By contrast, the GNU General Public
17Licenses are intended to guarantee your freedom to share and change
18free software--to make sure the software is free for all its users.
19
20 This license, the Lesser General Public License, applies to some
21specially designated software packages--typically libraries--of the
22Free Software Foundation and other authors who decide to use it. You
23can use it too, but we suggest you first think carefully about whether
24this license or the ordinary General Public License is the better
25strategy to use in any particular case, based on the explanations below.
26
27 When we speak of free software, we are referring to freedom of use,
28not price. Our General Public Licenses are designed to make sure that
29you have the freedom to distribute copies of free software (and charge
30for this service if you wish); that you receive source code or can get
31it if you want it; that you can change the software and use pieces of
32it in new free programs; and that you are informed that you can do
33these things.
34
35 To protect your rights, we need to make restrictions that forbid
36distributors to deny you these rights or to ask you to surrender these
37rights. These restrictions translate to certain responsibilities for
38you if you distribute copies of the library or if you modify it.
39
40 For example, if you distribute copies of the library, whether gratis
41or for a fee, you must give the recipients all the rights that we gave
42you. You must make sure that they, too, receive or can get the source
43code. If you link other code with the library, you must provide
44complete object files to the recipients, so that they can relink them
45with the library after making changes to the library and recompiling
46it. And you must show them these terms so they know their rights.
47
48 We protect your rights with a two-step method: (1) we copyright the
49library, and (2) we offer you this license, which gives you legal
50permission to copy, distribute and/or modify the library.
51
52 To protect each distributor, we want to make it very clear that
53there is no warranty for the free library. Also, if the library is
54modified by someone else and passed on, the recipients should know
55that what they have is not the original version, so that the original
56author's reputation will not be affected by problems that might be
57introduced by others.
58
59 Finally, software patents pose a constant threat to the existence of
60any free program. We wish to make sure that a company cannot
61effectively restrict the users of a free program by obtaining a
62restrictive license from a patent holder. Therefore, we insist that
63any patent license obtained for a version of the library must be
64consistent with the full freedom of use specified in this license.
65
66 Most GNU software, including some libraries, is covered by the
67ordinary GNU General Public License. This license, the GNU Lesser
68General Public License, applies to certain designated libraries, and
69is quite different from the ordinary General Public License. We use
70this license for certain libraries in order to permit linking those
71libraries into non-free programs.
72
73 When a program is linked with a library, whether statically or using
74a shared library, the combination of the two is legally speaking a
75combined work, a derivative of the original library. The ordinary
76General Public License therefore permits such linking only if the
77entire combination fits its criteria of freedom. The Lesser General
78Public License permits more lax criteria for linking other code with
79the library.
80
81 We call this license the "Lesser" General Public License because it
82does Less to protect the user's freedom than the ordinary General
83Public License. It also provides other free software developers Less
84of an advantage over competing non-free programs. These disadvantages
85are the reason we use the ordinary General Public License for many
86libraries. However, the Lesser license provides advantages in certain
87special circumstances.
88
89 For example, on rare occasions, there may be a special need to
90encourage the widest possible use of a certain library, so that it becomes
91a de-facto standard. To achieve this, non-free programs must be
92allowed to use the library. A more frequent case is that a free
93library does the same job as widely used non-free libraries. In this
94case, there is little to gain by limiting the free library to free
95software only, so we use the Lesser General Public License.
96
97 In other cases, permission to use a particular library in non-free
98programs enables a greater number of people to use a large body of
99free software. For example, permission to use the GNU C Library in
100non-free programs enables many more people to use the whole GNU
101operating system, as well as its variant, the GNU/Linux operating
102system.
103
104 Although the Lesser General Public License is Less protective of the
105users' freedom, it does ensure that the user of a program that is
106linked with the Library has the freedom and the wherewithal to run
107that program using a modified version of the Library.
108
109 The precise terms and conditions for copying, distribution and
110modification follow. Pay close attention to the difference between a
111"work based on the library" and a "work that uses the library". The
112former contains code derived from the library, whereas the latter must
113be combined with the library in order to run.
114
115 GNU LESSER GENERAL PUBLIC LICENSE
116 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
117
118 0. This License Agreement applies to any software library or other
119program which contains a notice placed by the copyright holder or
120other authorized party saying it may be distributed under the terms of
121this Lesser General Public License (also called "this License").
122Each licensee is addressed as "you".
123
124 A "library" means a collection of software functions and/or data
125prepared so as to be conveniently linked with application programs
126(which use some of those functions and data) to form executables.
127
128 The "Library", below, refers to any such software library or work
129which has been distributed under these terms. A "work based on the
130Library" means either the Library or any derivative work under
131copyright law: that is to say, a work containing the Library or a
132portion of it, either verbatim or with modifications and/or translated
133straightforwardly into another language. (Hereinafter, translation is
134included without limitation in the term "modification".)
135
136 "Source code" for a work means the preferred form of the work for
137making modifications to it. For a library, complete source code means
138all the source code for all modules it contains, plus any associated
139interface definition files, plus the scripts used to control compilation
140and installation of the library.
141
142 Activities other than copying, distribution and modification are not
143covered by this License; they are outside its scope. The act of
144running a program using the Library is not restricted, and output from
145such a program is covered only if its contents constitute a work based
146on the Library (independent of the use of the Library in a tool for
147writing it). Whether that is true depends on what the Library does
148and what the program that uses the Library does.
149
150 1. You may copy and distribute verbatim copies of the Library's
151complete source code as you receive it, in any medium, provided that
152you conspicuously and appropriately publish on each copy an
153appropriate copyright notice and disclaimer of warranty; keep intact
154all the notices that refer to this License and to the absence of any
155warranty; and distribute a copy of this License along with the
156Library.
157
158 You may charge a fee for the physical act of transferring a copy,
159and you may at your option offer warranty protection in exchange for a
160fee.
161
162 2. You may modify your copy or copies of the Library or any portion
163of it, thus forming a work based on the Library, and copy and
164distribute such modifications or work under the terms of Section 1
165above, provided that you also meet all of these conditions:
166
167 a) The modified work must itself be a software library.
168
169 b) You must cause the files modified to carry prominent notices
170 stating that you changed the files and the date of any change.
171
172 c) You must cause the whole of the work to be licensed at no
173 charge to all third parties under the terms of this License.
174
175 d) If a facility in the modified Library refers to a function or a
176 table of data to be supplied by an application program that uses
177 the facility, other than as an argument passed when the facility
178 is invoked, then you must make a good faith effort to ensure that,
179 in the event an application does not supply such function or
180 table, the facility still operates, and performs whatever part of
181 its purpose remains meaningful.
182
183 (For example, a function in a library to compute square roots has
184 a purpose that is entirely well-defined independent of the
185 application. Therefore, Subsection 2d requires that any
186 application-supplied function or table used by this function must
187 be optional: if the application does not supply it, the square
188 root function must still compute square roots.)
189
190These requirements apply to the modified work as a whole. If
191identifiable sections of that work are not derived from the Library,
192and can be reasonably considered independent and separate works in
193themselves, then this License, and its terms, do not apply to those
194sections when you distribute them as separate works. But when you
195distribute the same sections as part of a whole which is a work based
196on the Library, the distribution of the whole must be on the terms of
197this License, whose permissions for other licensees extend to the
198entire whole, and thus to each and every part regardless of who wrote
199it.
200
201Thus, it is not the intent of this section to claim rights or contest
202your rights to work written entirely by you; rather, the intent is to
203exercise the right to control the distribution of derivative or
204collective works based on the Library.
205
206In addition, mere aggregation of another work not based on the Library
207with the Library (or with a work based on the Library) on a volume of
208a storage or distribution medium does not bring the other work under
209the scope of this License.
210
211 3. You may opt to apply the terms of the ordinary GNU General Public
212License instead of this License to a given copy of the Library. To do
213this, you must alter all the notices that refer to this License, so
214that they refer to the ordinary GNU General Public License, version 2,
215instead of to this License. (If a newer version than version 2 of the
216ordinary GNU General Public License has appeared, then you can specify
217that version instead if you wish.) Do not make any other change in
218these notices.
219
220 Once this change is made in a given copy, it is irreversible for
221that copy, so the ordinary GNU General Public License applies to all
222subsequent copies and derivative works made from that copy.
223
224 This option is useful when you wish to copy part of the code of
225the Library into a program that is not a library.
226
227 4. You may copy and distribute the Library (or a portion or
228derivative of it, under Section 2) in object code or executable form
229under the terms of Sections 1 and 2 above provided that you accompany
230it with the complete corresponding machine-readable source code, which
231must be distributed under the terms of Sections 1 and 2 above on a
232medium customarily used for software interchange.
233
234 If distribution of object code is made by offering access to copy
235from a designated place, then offering equivalent access to copy the
236source code from the same place satisfies the requirement to
237distribute the source code, even though third parties are not
238compelled to copy the source along with the object code.
239
240 5. A program that contains no derivative of any portion of the
241Library, but is designed to work with the Library by being compiled or
242linked with it, is called a "work that uses the Library". Such a
243work, in isolation, is not a derivative work of the Library, and
244therefore falls outside the scope of this License.
245
246 However, linking a "work that uses the Library" with the Library
247creates an executable that is a derivative of the Library (because it
248contains portions of the Library), rather than a "work that uses the
249library". The executable is therefore covered by this License.
250Section 6 states terms for distribution of such executables.
251
252 When a "work that uses the Library" uses material from a header file
253that is part of the Library, the object code for the work may be a
254derivative work of the Library even though the source code is not.
255Whether this is true is especially significant if the work can be
256linked without the Library, or if the work is itself a library. The
257threshold for this to be true is not precisely defined by law.
258
259 If such an object file uses only numerical parameters, data
260structure layouts and accessors, and small macros and small inline
261functions (ten lines or less in length), then the use of the object
262file is unrestricted, regardless of whether it is legally a derivative
263work. (Executables containing this object code plus portions of the
264Library will still fall under Section 6.)
265
266 Otherwise, if the work is a derivative of the Library, you may
267distribute the object code for the work under the terms of Section 6.
268Any executables containing that work also fall under Section 6,
269whether or not they are linked directly with the Library itself.
270
271 6. As an exception to the Sections above, you may also combine or
272link a "work that uses the Library" with the Library to produce a
273work containing portions of the Library, and distribute that work
274under terms of your choice, provided that the terms permit
275modification of the work for the customer's own use and reverse
276engineering for debugging such modifications.
277
278 You must give prominent notice with each copy of the work that the
279Library is used in it and that the Library and its use are covered by
280this License. You must supply a copy of this License. If the work
281during execution displays copyright notices, you must include the
282copyright notice for the Library among them, as well as a reference
283directing the user to the copy of this License. Also, you must do one
284of these things:
285
286 a) Accompany the work with the complete corresponding
287 machine-readable source code for the Library including whatever
288 changes were used in the work (which must be distributed under
289 Sections 1 and 2 above); and, if the work is an executable linked
290 with the Library, with the complete machine-readable "work that
291 uses the Library", as object code and/or source code, so that the
292 user can modify the Library and then relink to produce a modified
293 executable containing the modified Library. (It is understood
294 that the user who changes the contents of definitions files in the
295 Library will not necessarily be able to recompile the application
296 to use the modified definitions.)
297
298 b) Use a suitable shared library mechanism for linking with the
299 Library. A suitable mechanism is one that (1) uses at run time a
300 copy of the library already present on the user's computer system,
301 rather than copying library functions into the executable, and (2)
302 will operate properly with a modified version of the library, if
303 the user installs one, as long as the modified version is
304 interface-compatible with the version that the work was made with.
305
306 c) Accompany the work with a written offer, valid for at
307 least three years, to give the same user the materials
308 specified in Subsection 6a, above, for a charge no more
309 than the cost of performing this distribution.
310
311 d) If distribution of the work is made by offering access to copy
312 from a designated place, offer equivalent access to copy the above
313 specified materials from the same place.
314
315 e) Verify that the user has already received a copy of these
316 materials or that you have already sent this user a copy.
317
318 For an executable, the required form of the "work that uses the
319Library" must include any data and utility programs needed for
320reproducing the executable from it. However, as a special exception,
321the materials to be distributed need not include anything that is
322normally distributed (in either source or binary form) with the major
323components (compiler, kernel, and so on) of the operating system on
324which the executable runs, unless that component itself accompanies
325the executable.
326
327 It may happen that this requirement contradicts the license
328restrictions of other proprietary libraries that do not normally
329accompany the operating system. Such a contradiction means you cannot
330use both them and the Library together in an executable that you
331distribute.
332
333 7. You may place library facilities that are a work based on the
334Library side-by-side in a single library together with other library
335facilities not covered by this License, and distribute such a combined
336library, provided that the separate distribution of the work based on
337the Library and of the other library facilities is otherwise
338permitted, and provided that you do these two things:
339
340 a) Accompany the combined library with a copy of the same work
341 based on the Library, uncombined with any other library
342 facilities. This must be distributed under the terms of the
343 Sections above.
344
345 b) Give prominent notice with the combined library of the fact
346 that part of it is a work based on the Library, and explaining
347 where to find the accompanying uncombined form of the same work.
348
349 8. You may not copy, modify, sublicense, link with, or distribute
350the Library except as expressly provided under this License. Any
351attempt otherwise to copy, modify, sublicense, link with, or
352distribute the Library is void, and will automatically terminate your
353rights under this License. However, parties who have received copies,
354or rights, from you under this License will not have their licenses
355terminated so long as such parties remain in full compliance.
356
357 9. You are not required to accept this License, since you have not
358signed it. However, nothing else grants you permission to modify or
359distribute the Library or its derivative works. These actions are
360prohibited by law if you do not accept this License. Therefore, by
361modifying or distributing the Library (or any work based on the
362Library), you indicate your acceptance of this License to do so, and
363all its terms and conditions for copying, distributing or modifying
364the Library or works based on it.
365
366 10. Each time you redistribute the Library (or any work based on the
367Library), the recipient automatically receives a license from the
368original licensor to copy, distribute, link with or modify the Library
369subject to these terms and conditions. You may not impose any further
370restrictions on the recipients' exercise of the rights granted herein.
371You are not responsible for enforcing compliance by third parties with
372this License.
373
374 11. If, as a consequence of a court judgment or allegation of patent
375infringement or for any other reason (not limited to patent issues),
376conditions are imposed on you (whether by court order, agreement or
377otherwise) that contradict the conditions of this License, they do not
378excuse you from the conditions of this License. If you cannot
379distribute so as to satisfy simultaneously your obligations under this
380License and any other pertinent obligations, then as a consequence you
381may not distribute the Library at all. For example, if a patent
382license would not permit royalty-free redistribution of the Library by
383all those who receive copies directly or indirectly through you, then
384the only way you could satisfy both it and this License would be to
385refrain entirely from distribution of the Library.
386
387If any portion of this section is held invalid or unenforceable under any
388particular circumstance, the balance of the section is intended to apply,
389and the section as a whole is intended to apply in other circumstances.
390
391It is not the purpose of this section to induce you to infringe any
392patents or other property right claims or to contest validity of any
393such claims; this section has the sole purpose of protecting the
394integrity of the free software distribution system which is
395implemented by public license practices. Many people have made
396generous contributions to the wide range of software distributed
397through that system in reliance on consistent application of that
398system; it is up to the author/donor to decide if he or she is willing
399to distribute software through any other system and a licensee cannot
400impose that choice.
401
402This section is intended to make thoroughly clear what is believed to
403be a consequence of the rest of this License.
404
405 12. If the distribution and/or use of the Library is restricted in
406certain countries either by patents or by copyrighted interfaces, the
407original copyright holder who places the Library under this License may add
408an explicit geographical distribution limitation excluding those countries,
409so that distribution is permitted only in or among countries not thus
410excluded. In such case, this License incorporates the limitation as if
411written in the body of this License.
412
413 13. The Free Software Foundation may publish revised and/or new
414versions of the Lesser General Public License from time to time.
415Such new versions will be similar in spirit to the present version,
416but may differ in detail to address new problems or concerns.
417
418Each version is given a distinguishing version number. If the Library
419specifies a version number of this License which applies to it and
420"any later version", you have the option of following the terms and
421conditions either of that version or of any later version published by
422the Free Software Foundation. If the Library does not specify a
423license version number, you may choose any version ever published by
424the Free Software Foundation.
425
426 14. If you wish to incorporate parts of the Library into other free
427programs whose distribution conditions are incompatible with these,
428write to the author to ask for permission. For software which is
429copyrighted by the Free Software Foundation, write to the Free
430Software Foundation; we sometimes make exceptions for this. Our
431decision will be guided by the two goals of preserving the free status
432of all derivatives of our free software and of promoting the sharing
433and reuse of software generally.
434
435 NO WARRANTY
436
437 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
438WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
439EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
440OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
441KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
442IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
443PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
444LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
445THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
446
447 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
448WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
449AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
450FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
451CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
452LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
453RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
454FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
455SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
456DAMAGES.
457
458 END OF TERMS AND CONDITIONS
459
460 How to Apply These Terms to Your New Libraries
461
462 If you develop a new library, and you want it to be of the greatest
463possible use to the public, we recommend making it free software that
464everyone can redistribute and change. You can do so by permitting
465redistribution under these terms (or, alternatively, under the terms of the
466ordinary General Public License).
467
468 To apply these terms, attach the following notices to the library. It is
469safest to attach them to the start of each source file to most effectively
470convey the exclusion of warranty; and each file should have at least the
471"copyright" line and a pointer to where the full notice is found.
472
473 <one line to give the library's name and a brief idea of what it does.>
474 Copyright (C) <year> <name of author>
475
476 This library is free software; you can redistribute it and/or
477 modify it under the terms of the GNU Lesser General Public
478 License as published by the Free Software Foundation; either
479 version 2.1 of the License, or (at your option) any later version.
480
481 This library is distributed in the hope that it will be useful,
482 but WITHOUT ANY WARRANTY; without even the implied warranty of
483 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
484 Lesser General Public License for more details.
485
486 You should have received a copy of the GNU Lesser General Public
487 License along with this library; if not, write to the Free Software
488 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
489
490Also add information on how to contact you by electronic and paper mail.
491
492You should also get your employer (if you work as a programmer) or your
493school, if any, to sign a "copyright disclaimer" for the library, if
494necessary. Here is a sample; alter the names:
495
496 Yoyodyne, Inc., hereby disclaims all copyright interest in the
497 library `Frob' (a library for tweaking knobs) written by James Random Hacker.
498
499 <signature of Ty Coon>, 1 April 1990
500 Ty Coon, President of Vice
501
502That's all there is to it!
503
504
diff --git a/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/README b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/README
new file mode 100755
index 0000000000..3d55352a6b
--- /dev/null
+++ b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/README
@@ -0,0 +1,50 @@
1GetPot - C++:
2--------------
3
4Attention: This version contains a couple of beautiful
5---------- new features, that are not documented yet.
6
7 E.g.: -- automated ufo detection
8 -- arbitrary comment delimiters
9 -- arbitrary vector field separators
10 -- tails, i.e. easy access to all tails
11 of options such as '-L' or '-I'.
12
13 Please, refere to the example/ directory
14 for usage descriptions.
15
16This is the C++ version of the popular GetPot library for
17command line and input file parsing. The documentation
18can be downloaded at:
19
20 http://getpot.sourceforge.net
21
22The files in the 'examples' directory should be enough, though, to be
23able to use this library. It is fairly easy to use.
24
25Installation:
26-------------
27
28In order to install GetPot, simply copy the file 'GetPot'
29somewhere where your c++ compiler can find it.
30
31The 'file emacs-getpot-mode.el' contains some lines of
32emacs-lisp code. If you append these lines to your .emacs
33file, it will highlight your 'getpot' - input files.
34
35Bug reports, Feature requests:
36------------------------------
37
38Please, notify me in case there are any bugs or you think
39that there should be more features in the library.
40My email address is:
41
42fschaef@users.sourceforge.net
43
44Thanks for using this software.
45Enjoy !
46
47
48Juli 2005,
49Frank R. Schaefer
50
diff --git a/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/getpot.hpp b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/getpot.hpp
new file mode 100755
index 0000000000..fe820c91a2
--- /dev/null
+++ b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/getpot.hpp
@@ -0,0 +1,2435 @@
1// -*- c++ -*-
2// GetPot Version $$Version$$ $$Date$$
3//
4// WEBSITE: http://getpot.sourceforge.net
5//
6// NOTE: The LPGL License for this library is only valid in case that
7// it is not used for the production or development of applications
8// dedicated to military industry. This is what the author calls
9// the 'unofficial peace version of the LPGL'.
10//
11// This library is free software; you can redistribute it and/or modify
12// it under the terms of the GNU Lesser General Public License as
13// published by the Free Software Foundation; either version 2.1 of the
14// License, or (at your option) any later version.
15//
16// This library is distributed in the hope that it will be useful, but
17// WITHOUT ANY WARRANTY; without even the implied warranty of
18// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19// Lesser General Public License for more details.
20//
21// You should have received a copy of the GNU Lesser General Public
22// License along with this library; if not, write to the Free Software
23// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
24// USA
25//
26// (C) 2001-2005 Frank R. Schaefer <fschaef@users.sf.net>
27//==========================================================================
28
29#ifndef __include_guard_GETPOT_H__
30#define __include_guard_GETPOT_H__
31
32#if defined(WIN32) || defined(SOLARIS_RAW) || (__GNUC__ == 2) || defined(__HP_aCC)
33#define strtok_r(a, b, c) strtok(a, b)
34#endif // WINDOWS or SOLARIS or gcc 2.* or HP aCC
35
36extern "C" {
37// leave the 'extern C' to make it 100% sure to work -
38// expecially with older distributions of header files.
39#ifndef WIN32
40// this is necessary (depending on OS)
41#include <ctype.h>
42#endif
43#include <stdio.h>
44#include <stdarg.h>
45#include <assert.h>
46}
47#include <cmath>
48#include <string>
49#include <vector>
50#include <algorithm>
51
52#include <fstream>
53#include <iostream> // not every compiler distribution includes <iostream>
54// // with <fstream>
55
56typedef std::vector<std::string> STRING_VECTOR;
57
58#define victorate(TYPE, VARIABLE, ITERATOR) \
59 std::vector<TYPE>::const_iterator ITERATOR = (VARIABLE).begin(); \
60 for(; (ITERATOR) != (VARIABLE).end(); (ITERATOR)++)
61
62
63class GetPot {
64 //--------
65 inline void __basic_initialization();
66public:
67 // (*) constructors, destructor, assignment operator -----------------------
68 inline GetPot();
69 inline GetPot(const GetPot&);
70 inline GetPot(const int argc_, char** argv_,
71 const char* FieldSeparator=0x0);
72 inline GetPot(const char* FileName,
73 const char* CommentStart=0x0, const char* CommentEnd=0x0,
74 const char* FieldSeparator=0x0);
75 inline ~GetPot();
76 inline GetPot& operator=(const GetPot&);
77
78
79 // (*) absorbing contents of another GetPot object
80 inline void absorb(const GetPot& That);
81 // -- for ufo detection: recording requested arguments, options etc.
82 inline void clear_requests();
83 inline void disable_request_recording() { __request_recording_f = false; }
84 inline void enable_request_recording() { __request_recording_f = true; }
85
86 // (*) direct access to command line arguments -----------------------------
87 inline const std::string operator[](unsigned Idx) const;
88 inline int get(unsigned Idx, int Default) const;
89 inline double get(unsigned Idx, const double& Default) const;
90 inline const std::string get(unsigned Idx, const char* Default) const;
91 inline unsigned size() const;
92
93 // (*) flags ---------------------------------------------------------------
94 inline bool options_contain(const char* FlagList) const;
95 inline bool argument_contains(unsigned Idx, const char* FlagList) const;
96
97 // (*) variables -----------------------------------------------------------
98 // -- scalar values
99 inline int operator()(const char* VarName, int Default) const;
100 inline double operator()(const char* VarName, const double& Default) const;
101 inline const std::string operator()(const char* VarName, const char* Default) const;
102 // -- vectors
103 inline int operator()(const char* VarName, int Default, unsigned Idx) const;
104 inline double operator()(const char* VarName, const double& Default, unsigned Idx) const;
105 inline const std::string operator()(const char* VarName, const char* Default, unsigned Idx) const;
106
107 // -- setting variables
108 // i) from outside of GetPot (considering prefix etc.)
109 // ii) from inside, use '__set_variable()' below
110 inline void set(const char* VarName, const char* Value, const bool Requested = true);
111 inline void set(const char* VarName, const double& Value, const bool Requested = true);
112 inline void set(const char* VarName, const int Value, const bool Requested = true);
113
114 inline unsigned vector_variable_size(const char* VarName) const;
115 inline STRING_VECTOR get_variable_names() const;
116 inline STRING_VECTOR get_section_names() const;
117
118
119 // (*) cursor oriented functions -------------------------------------------
120 inline void set_prefix(const char* Prefix) { prefix = std::string(Prefix); }
121 inline bool search_failed() const { return search_failed_f; }
122
123 // -- enable/disable search for an option in loop
124 inline void disable_loop() { search_loop_f = false; }
125 inline void enable_loop() { search_loop_f = true; }
126
127 // -- reset cursor to position '1'
128 inline void reset_cursor();
129 inline void init_multiple_occurrence();
130
131 // -- search for a certain option and set cursor to position
132 inline bool search(const char* option);
133 inline bool search(unsigned No, const char* P, ...);
134 // -- get argument at cursor++
135 inline int next(int Default);
136 inline double next(const double& Default);
137 inline const std::string next(const char* Default);
138 // -- search for option and get argument at cursor++
139 inline int follow(int Default, const char* Option);
140 inline double follow(const double& Default, const char* Option);
141 inline const std::string follow(const char* Default, const char* Option);
142 // -- search for one of the given options and get argument that follows it
143 inline int follow(int Default, unsigned No, const char* Option, ...);
144 inline double follow(const double& Default, unsigned No, const char* Option, ...);
145 inline const std::string follow(const char* Default, unsigned No, const char* Option, ...);
146 // -- lists of nominuses following an option
147 inline std::vector<std::string> nominus_followers(const char* Option);
148 inline std::vector<std::string> nominus_followers(unsigned No, ...);
149
150 // -- directly followed arguments
151 inline int direct_follow(int Default, const char* Option);
152 inline double direct_follow(const double& Default, const char* Option);
153 inline const std::string direct_follow(const char* Default, const char* Option);
154
155 inline std::vector<std::string> string_tails(const char* StartString);
156 inline std::vector<int> int_tails(const char* StartString, const int Default = 1);
157 inline std::vector<double> double_tails(const char* StartString, const double Default = 1.0);
158
159 // (*) nominus arguments ---------------------------------------------------
160 inline STRING_VECTOR nominus_vector() const;
161 inline unsigned nominus_size() const { return static_cast<unsigned int>(idx_nominus.size()); }
162 inline std::string next_nominus();
163
164 // (*) unidentified flying objects -----------------------------------------
165 inline STRING_VECTOR unidentified_arguments(unsigned Number, const char* Known, ...) const;
166 inline STRING_VECTOR unidentified_arguments(const STRING_VECTOR& Knowns) const;
167 inline STRING_VECTOR unidentified_arguments() const;
168
169 inline STRING_VECTOR unidentified_options(unsigned Number, const char* Known, ...) const;
170 inline STRING_VECTOR unidentified_options(const STRING_VECTOR& Knowns) const;
171 inline STRING_VECTOR unidentified_options() const;
172
173 inline std::string unidentified_flags(const char* Known,
174 int ArgumentNumber /* =-1 */) const;
175
176 inline STRING_VECTOR unidentified_variables(unsigned Number, const char* Known, ...) const;
177 inline STRING_VECTOR unidentified_variables(const STRING_VECTOR& Knowns) const;
178 inline STRING_VECTOR unidentified_variables() const;
179
180 inline STRING_VECTOR unidentified_sections(unsigned Number, const char* Known, ...) const;
181 inline STRING_VECTOR unidentified_sections(const STRING_VECTOR& Knowns) const;
182 inline STRING_VECTOR unidentified_sections() const;
183
184 inline STRING_VECTOR unidentified_nominuses(unsigned Number, const char* Known, ...) const;
185 inline STRING_VECTOR unidentified_nominuses(const STRING_VECTOR& Knowns) const;
186 inline STRING_VECTOR unidentified_nominuses() const;
187
188 // (*) output --------------------------------------------------------------
189 inline int print() const;
190
191private:
192 // (*) Type Declaration ----------------------------------------------------
193 struct variable {
194 //-----------
195 // Variable to be specified on the command line or in input files.
196 // (i.e. of the form var='12 312 341')
197
198 // -- constructors, destructors, assignment operator
199 variable();
200 variable(const variable&);
201 variable(const char* Name, const char* Value, const char* FieldSeparator);
202 ~variable();
203 variable& operator=(const variable& That);
204
205 void take(const char* Value, const char* FieldSeparator);
206
207 // -- get a specific element in the string vector
208 // (return 0 if not present)
209 const std::string* get_element(unsigned Idx) const;
210
211 // -- data memebers
212 std::string name; // identifier of variable
213 STRING_VECTOR value; // value of variable stored in vector
214 std::string original; // value of variable as given on command line
215 };
216
217 // (*) member variables --------------------------------------------------------------
218 std::string prefix; // prefix automatically added in queries
219 std::string section; // (for dollar bracket parsing)
220 STRING_VECTOR section_list; // list of all parsed sections
221 // -- argument vector
222 STRING_VECTOR argv; // vector of command line arguments stored as strings
223 unsigned cursor; // cursor for argv
224 bool search_loop_f; // shall search start at beginning after
225 // // reaching end of arg array ?
226 bool search_failed_f; // flag indicating a failed search() operation
227 // // (e.g. next() functions react with 'missed')
228
229 // -- nominus vector
230 int nominus_cursor; // cursor for nominus_pointers
231 std::vector<unsigned> idx_nominus; // indecies of 'no minus' arguments
232
233 // -- variables
234 // (arguments of the form "variable=value")
235 std::vector<variable> variables;
236
237 // -- comment delimiters
238 std::string _comment_start;
239 std::string _comment_end;
240
241 // -- field separator (separating elements of a vector)
242 std::string _field_separator;
243
244 // -- some functions return a char pointer to a temporarily existing string
245 // this container makes them 'available' until the getpot object is destroyed.
246 std::vector<char*> __internal_string_container;
247
248 // -- keeping track about arguments that are requested, so that the UFO detection
249 // can be simplified
250 STRING_VECTOR _requested_arguments;
251 STRING_VECTOR _requested_variables;
252 STRING_VECTOR _requested_sections;
253
254 bool __request_recording_f; // speed: request recording can be turned off
255
256 // -- if an argument is requested record it and the 'tag' the section branch to which
257 // it belongs. Caution: both functions mark the sections as 'tagged'.
258 void __record_argument_request(const std::string& Arg);
259 void __record_variable_request(const std::string& Arg);
260
261 // (*) helper functions ----------------------------------------------------
262 // set variable from inside GetPot (no prefix considered)
263 inline void __set_variable(const char* VarName, const char* Value);
264
265 // -- produce three basic data vectors:
266 // - argument vector
267 // - nominus vector
268 // - variable dictionary
269 inline void __parse_argument_vector(const STRING_VECTOR& ARGV);
270
271 // -- helpers for argument list processing
272 // * search for a variable in 'variables' array
273 inline const variable* __find_variable(const char*) const;
274 // * support finding directly followed arguments
275 inline const char* __match_starting_string(const char* StartString);
276 // * support search for flags in a specific argument
277 inline bool __check_flags(const std::string& Str, const char* FlagList) const;
278 // * type conversion if possible
279 inline int __convert_to_type(const std::string& String, int Default) const;
280 inline double __convert_to_type(const std::string& String, double Default) const;
281 // * prefix extraction
282 const std::string __get_remaining_string(const std::string& String,
283 const std::string& Start) const;
284 // * search for a specific string
285 inline bool __search_string_vector(const STRING_VECTOR& Vec,
286 const std::string& Str) const;
287
288 // -- helpers to parse input file
289 // create an argument vector based on data found in an input file, i.e.:
290 // 1) delete comments (in between '_comment_start' '_comment_end')
291 // 2) contract assignment expressions, such as
292 // my-variable = '007 J. B.'
293 // into
294 // my-variable='007 J. B.'
295 // 3) interprete sections like '[../my-section]' etc.
296 inline void __skip_whitespace(std::istream& istr);
297 inline const std::string __get_next_token(std::istream& istr);
298 inline const std::string __get_string(std::istream& istr);
299 inline const std::string __get_until_closing_bracket(std::istream& istr);
300
301 inline STRING_VECTOR __read_in_stream(std::istream& istr);
302 inline STRING_VECTOR __read_in_file(const char* FileName);
303 inline std::string __process_section_label(const std::string& Section,
304 STRING_VECTOR& section_stack);
305
306 // -- dollar bracket expressions
307 std::string __DBE_expand_string(const std::string str);
308 std::string __DBE_expand(const std::string str);
309 const GetPot::variable* __DBE_get_variable(const std::string str);
310 STRING_VECTOR __DBE_get_expr_list(const std::string str, const unsigned ExpectedNumber);
311
312 std::string __double2string(const double& Value) const {
313 // -- converts a double integer into a string
314 char* tmp = new char[128];
315#ifndef WIN32
316 snprintf(tmp, (int)sizeof(char)*128, "%e", Value);
317#else
318 _snprintf(tmp, sizeof(char)*128, "%e", Value);
319#endif
320 std::string result(tmp);
321 delete [] tmp;
322 return result;
323 }
324
325 std::string __int2string(const int& Value) const {
326 // -- converts an integer into a string
327 char* tmp = new char[128];
328#ifndef WIN32
329 snprintf(tmp, (int)sizeof(char)*128, "%i", Value);
330#else
331 _snprintf(tmp, sizeof(char)*128, "%i", Value);
332#endif
333 std::string result(tmp);
334 delete [] tmp;
335 return result;
336 }
337
338 STRING_VECTOR __get_section_tree(const std::string& FullPath) {
339 // -- cuts a variable name into a tree of sub-sections. this is requested for recording
340 // requested sections when dealing with 'ufo' detection.
341 STRING_VECTOR result;
342 const char* Start = FullPath.c_str();
343
344 for(char *p = (char*)Start; *p ; p++) {
345 if( *p == '/' ) {
346 *p = '\0'; // set terminating zero for convinience
347 const std::string Section = Start;
348 *p = '/'; // reset slash at place
349 result.push_back(Section);
350 }
351 }
352
353 return result;
354 }
355};
356
357
358///////////////////////////////////////////////////////////////////////////////
359// (*) constructors, destructor, assignment operator
360//.............................................................................
361//
362inline void
363GetPot::__basic_initialization()
364{
365 cursor = 0; nominus_cursor = -1;
366 search_failed_f = true; search_loop_f = true;
367 prefix = ""; section = "";
368
369 // automatic request recording for later ufo detection
370 __request_recording_f = true;
371
372 // comment start and end strings
373 _comment_start = std::string("#");
374 _comment_end = std::string("\n");
375
376 // default: separate vector elements by whitespaces
377 _field_separator = " \t\n";
378}
379
380inline
381GetPot::GetPot()
382{
383 __basic_initialization();
384
385 STRING_VECTOR _apriori_argv;
386 _apriori_argv.push_back(std::string("Empty"));
387 __parse_argument_vector(_apriori_argv);
388}
389
390inline
391GetPot::GetPot(const int argc_, char ** argv_,
392 const char* FieldSeparator /* =0x0 */)
393 // leave 'char**' non-const to honor less capable compilers ...
394{
395 // TODO: Ponder over the problem when the argument list is of size = 0.
396 // This is 'sabotage', but it can still occur if the user specifies
397 // it himself.
398 assert(argc_ >= 1);
399 __basic_initialization();
400
401 // if specified -> overwrite default string
402 if( FieldSeparator ) _field_separator = std::string(FieldSeparator);
403
404 // -- make an internal copy of the argument list:
405 STRING_VECTOR _apriori_argv;
406 // -- for the sake of clarity: we do want to include the first argument in the argument vector !
407 // it will not be a nominus argument, though. This gives us a minimun vector size of one
408 // which facilitates error checking in many functions. Also the user will be able to
409 // retrieve the name of his application by "get[0]"
410 _apriori_argv.push_back(std::string(argv_[0]));
411 int i=1;
412 for(; i<argc_; ++i) {
413 std::string tmp(argv_[i]); // recall the problem with temporaries,
414 _apriori_argv.push_back(tmp); // reference counting in arguement lists ...
415 }
416 __parse_argument_vector(_apriori_argv);
417}
418
419
420inline
421GetPot::GetPot(const char* FileName,
422 const char* CommentStart /* = 0x0 */, const char* CommentEnd /* = 0x0 */,
423 const char* FieldSeparator/* = 0x0 */)
424{
425 __basic_initialization();
426
427 // if specified -> overwrite default strings
428 if( CommentStart ) _comment_start = std::string(CommentStart);
429 if( CommentEnd ) _comment_end = std::string(CommentEnd);
430 if( FieldSeparator ) _field_separator = FieldSeparator;
431
432 STRING_VECTOR _apriori_argv;
433 // -- file name is element of argument vector, however, it is not parsed for
434 // variable assignments or nominuses.
435 _apriori_argv.push_back(std::string(FileName));
436
437 STRING_VECTOR args = __read_in_file(FileName);
438 _apriori_argv.insert(_apriori_argv.begin()+1, args.begin(), args.end());
439 __parse_argument_vector(_apriori_argv);
440}
441
442inline
443GetPot::GetPot(const GetPot& That)
444{ GetPot::operator=(That); }
445
446inline
447GetPot::~GetPot()
448{
449 // may be some return strings had to be created, delete now !
450 victorate(char*, __internal_string_container, it)
451 delete [] *it;
452}
453
454inline GetPot&
455GetPot::operator=(const GetPot& That)
456{
457 if (&That == this) return *this;
458
459 _comment_start = That._comment_start;
460 _comment_end = That._comment_end;
461 argv = That.argv;
462 variables = That.variables;
463 prefix = That.prefix;
464
465 cursor = That.cursor;
466 nominus_cursor = That.nominus_cursor;
467 search_failed_f = That.search_failed_f;
468
469 idx_nominus = That.idx_nominus;
470 search_loop_f = That.search_loop_f;
471
472 return *this;
473}
474
475
476inline void
477GetPot::absorb(const GetPot& That)
478{
479 if (&That == this) return;
480
481 STRING_VECTOR __tmp(That.argv);
482
483 __tmp.erase(__tmp.begin());
484
485 __parse_argument_vector(__tmp);
486}
487
488inline void
489GetPot::clear_requests()
490{
491 _requested_arguments.erase(_requested_arguments.begin(), _requested_arguments.end());
492 _requested_variables.erase(_requested_variables.begin(), _requested_variables.end());
493 _requested_sections.erase(_requested_sections.begin(), _requested_sections.end());
494}
495
496inline void
497GetPot::__parse_argument_vector(const STRING_VECTOR& ARGV)
498{
499 if( ARGV.size() == 0 ) return;
500
501 // build internal databases:
502 // 1) array with no-minus arguments (usually used as filenames)
503 // 2) variable assignments:
504 // 'variable name' '=' number | string
505 STRING_VECTOR section_stack;
506 STRING_VECTOR::const_iterator it = ARGV.begin();
507
508
509 section = "";
510
511 // -- do not parse the first argument, so that it is not interpreted a s a nominus or so.
512 argv.push_back(*it);
513 ++it;
514
515 // -- loop over remaining arguments
516 unsigned i=1;
517 for(; it != ARGV.end(); ++it, ++i) {
518 std::string arg = *it;
519
520 if( arg.length() == 0 ) continue;
521
522 // -- [section] labels
523 if( arg.length() > 1 && arg[0] == '[' && arg[arg.length()-1] == ']' ) {
524
525 // (*) sections are considered 'requested arguments'
526 if( __request_recording_f ) _requested_arguments.push_back(arg);
527
528 const std::string Name = __DBE_expand_string(arg.substr(1, arg.length()-2));
529 section = __process_section_label(Name, section_stack);
530 // new section --> append to list of sections
531 if( find(section_list.begin(), section_list.end(), section) == section_list.end() )
532 if( section.length() != 0 ) section_list.push_back(section);
533 argv.push_back(arg);
534 }
535 else {
536 arg = section + __DBE_expand_string(arg);
537 argv.push_back(arg);
538 }
539
540 // -- separate array for nominus arguments
541 if( arg[0] != '-' ) idx_nominus.push_back(unsigned(i));
542
543 // -- variables: does arg contain a '=' operator ?
544 const char* p = arg.c_str();
545 for(; *p ; p++) {
546 if( *p == '=' ) {
547 // (*) record for later ufo detection
548 // arguments carriying variables are always treated as 'requested' arguments.
549 // as a whole! That is 'x=4712' is considered a requested argument.
550 //
551 // unrequested variables have to be detected with the ufo-variable
552 // detection routine.
553 if( __request_recording_f ) _requested_arguments.push_back(arg);
554
555 // set terminating 'zero' to treat first part as single string
556 // => arg (from start to 'p') = Name of variable
557 // p+1 (until terminating zero) = value of variable
558 char* o = (char*)p++;
559 *o = '\0'; // set temporary terminating zero
560 // __set_variable(...)
561 // calls __find_variable(...) which registers the search
562 // temporarily disable this
563 const bool tmp = __request_recording_f;
564 __request_recording_f = false;
565 __set_variable(arg.c_str(), p); // v-name = c_str() bis 'p', value = rest
566 __request_recording_f = tmp;
567 *o = '='; // reset the original '='
568 break;
569 }
570 }
571 }
572}
573
574
575inline STRING_VECTOR
576GetPot::__read_in_file(const char* FileName)
577{
578 std::ifstream i(FileName);
579 if( ! i ) return STRING_VECTOR();
580 // argv[0] == the filename of the file that was read in
581 return __read_in_stream(i);
582}
583
584inline STRING_VECTOR
585GetPot::__read_in_stream(std::istream& istr)
586{
587 STRING_VECTOR brute_tokens;
588 while(istr) {
589 __skip_whitespace(istr);
590
591 const std::string Token = __get_next_token(istr);
592 if( Token.length() == 0 || Token[0] == EOF) break;
593 brute_tokens.push_back(Token);
594 }
595
596 // -- reduce expressions of token1'='token2 to a single
597 // string 'token1=token2'
598 // -- copy everything into 'argv'
599 // -- arguments preceded by something like '[' name ']' (section)
600 // produce a second copy of each argument with a prefix '[name]argument'
601 unsigned i1 = 0;
602 unsigned i2 = 1;
603 unsigned i3 = 2;
604
605 STRING_VECTOR arglist;
606 while( i1 < brute_tokens.size() ) {
607 const std::string& SRef = brute_tokens[i1];
608 // 1) concatinate 'abcdef' '=' 'efgasdef' to 'abcdef=efgasdef'
609 // note: java.lang.String: substring(a,b) = from a to b-1
610 // C++ string: substr(a,b) = from a to a + b
611 if( i2 < brute_tokens.size() && brute_tokens[i2] == "=" ) {
612 if( i3 >= brute_tokens.size() )
613 arglist.push_back(brute_tokens[i1] + brute_tokens[i2]);
614 else
615 arglist.push_back(brute_tokens[i1] + brute_tokens[i2] + brute_tokens[i3]);
616 i1 = i3+1; i2 = i3+2; i3 = i3+3;
617 continue;
618 }
619 else {
620 arglist.push_back(SRef);
621 i1=i2; i2=i3; i3++;
622 }
623 }
624 return arglist;
625}
626
627inline void
628GetPot::__skip_whitespace(std::istream& istr)
629 // find next non-whitespace while deleting comments
630{
631 int tmp = istr.get();
632 do {
633 // -- search a non whitespace
634 while( isspace(tmp) ) {
635 tmp = istr.get();
636 if( ! istr ) return;
637 }
638
639 // -- look if characters match the comment starter string
640 const std::istream::pos_type Pos = istr.tellg();
641 unsigned i=0;
642 for(; i<_comment_start.length() ; ++i) {
643 if( tmp != _comment_start[i] ) {
644// HACK: The following line throws off msvc8:
645// istr.seekg(Pos);
646 // -- one step more backwards, since 'tmp' already at non-whitespace
647 istr.unget();
648 return;
649 }
650 tmp = istr.get();
651 if( ! istr ) { istr.unget(); return; }
652 }
653 // 'tmp' contains last character of _comment_starter
654
655 // -- comment starter found -> search for comment ender
656 unsigned match_no=0;
657 while(1+1 == 2) {
658 tmp = istr.get();
659 if( ! istr ) { istr.unget(); return; }
660
661 if( tmp == _comment_end[match_no] ) {
662 match_no++;
663 if( match_no == _comment_end.length() ) {
664 istr.unget();
665 break; // shuffle more whitespace, end of comment found
666 }
667 }
668 else
669 match_no = 0;
670 }
671
672 tmp = istr.get();
673
674 } while( istr );
675 istr.unget();
676}
677
678inline const std::string
679GetPot::__get_next_token(std::istream& istr)
680 // get next concatinates string token. consider quotes that embrace
681 // whitespaces
682{
683 std::string token;
684 int tmp = 0;
685 int last_letter = 0;
686 while(1+1 == 2) {
687 last_letter = tmp; tmp = istr.get();
688 if( tmp == EOF
689 || ((tmp == ' ' || tmp == '\t' || tmp == '\n') && last_letter != '\\') ) {
690 return token;
691 }
692 else if( tmp == '\'' && last_letter != '\\' ) {
693 // QUOTES: un-backslashed quotes => it's a string
694 token += __get_string(istr);
695 continue;
696 }
697 else if( tmp == '{' && last_letter == '$') {
698 token += '{' + __get_until_closing_bracket(istr);
699 continue;
700 }
701 else if( tmp == '$' && last_letter == '\\') {
702 token += tmp; tmp = 0; // so that last_letter will become = 0, not '$';
703 continue;
704 }
705 else if( tmp == '\\' && last_letter != '\\')
706 continue; // don't append un-backslashed backslashes
707 token += tmp;
708 }
709}
710
711inline const std::string
712GetPot::__get_string(std::istream& istr)
713 // parse input until next matching '
714{
715 std::string str;
716 int tmp = 0;
717 int last_letter = 0;
718 while(1 + 1 == 2) {
719 last_letter = tmp; tmp = istr.get();
720 if( tmp == EOF) return str;
721 // un-backslashed quotes => it's the end of the string
722 else if( tmp == '\'' && last_letter != '\\') return str;
723 else if( tmp == '\\' && last_letter != '\\') continue; // don't append
724
725 str += tmp;
726 }
727}
728
729inline const std::string
730GetPot::__get_until_closing_bracket(std::istream& istr)
731 // parse input until next matching }
732{
733 std::string str = "";
734 int tmp = 0;
735 int last_letter = 0;
736 int brackets = 1;
737 while(1 + 1 == 2) {
738 last_letter = tmp; tmp = istr.get();
739 if( tmp == EOF) return str;
740 else if( tmp == '{' && last_letter == '$') brackets += 1;
741 else if( tmp == '}') {
742 brackets -= 1;
743 // un-backslashed brackets => it's the end of the string
744 if( brackets == 0) return str + '}';
745 else if( tmp == '\\' && last_letter != '\\')
746 continue; // do not append an unbackslashed backslash
747 }
748 str += tmp;
749 }
750}
751
752inline std::string
753GetPot::__process_section_label(const std::string& Section,
754 STRING_VECTOR& section_stack)
755{
756 std::string sname = Section;
757 // 1) subsection of actual section ('./' prefix)
758 if( sname.length() >= 2 && sname.substr(0, 2) == "./" ) {
759 sname = sname.substr(2);
760 }
761 // 2) subsection of parent section ('../' prefix)
762 else if( sname.length() >= 3 && sname.substr(0, 3) == "../" ) {
763 do {
764 if( section_stack.end() != section_stack.begin() )
765 section_stack.pop_back();
766 sname = sname.substr(3);
767 } while( sname.substr(0, 3) == "../" );
768 }
769 // 3) subsection of the root-section
770 else {
771 section_stack.erase(section_stack.begin(), section_stack.end());
772 // [] => back to root section
773 }
774
775 if( sname != "" ) {
776 // parse section name for 'slashes'
777 unsigned i=0;
778 while( i < sname.length() ) {
779 if( sname[i] == '/' ) {
780 section_stack.push_back(sname.substr(0,i));
781 if( i+1 < sname.length()-1 )
782 sname = sname.substr(i+1);
783 i = 0;
784 }
785 else
786 ++i;
787 }
788 section_stack.push_back(sname);
789 }
790 std::string section = "";
791 if( section_stack.size() != 0 ) {
792 victorate(std::string, section_stack, it)
793 section += *it + "/";
794 }
795 return section;
796}
797
798
799// convert string to DOUBLE, if not possible return Default
800inline double
801GetPot::__convert_to_type(const std::string& String, double Default) const
802{
803 double tmp;
804 if( sscanf(String.c_str(),"%lf", &tmp) != 1 ) return Default;
805 return tmp;
806}
807
808// convert string to INT, if not possible return Default
809inline int
810GetPot::__convert_to_type(const std::string& String, int Default) const
811{
812 // NOTE: intermediate results may be floating points, so that the string
813 // may look like 2.0e1 (i.e. float format) => use float conversion
814 // in any case.
815 return (int)__convert_to_type(String, (double)Default);
816}
817
818//////////////////////////////////////////////////////////////////////////////
819// (*) cursor oriented functions
820//.............................................................................
821inline const std::string
822GetPot::__get_remaining_string(const std::string& String, const std::string& Start) const
823 // Checks if 'String' begins with 'Start' and returns the remaining String.
824 // Returns None if String does not begin with Start.
825{
826 if( Start == "" ) return String;
827 // note: java.lang.String: substring(a,b) = from a to b-1
828 // C++ string: substr(a,b) = from a to a + b
829 if( String.find(Start) == 0 ) return String.substr(Start.length());
830 else return "";
831}
832
833// -- search for a certain argument and set cursor to position
834inline bool
835GetPot::search(const char* Option)
836{
837 unsigned OldCursor = cursor;
838 const std::string SearchTerm = prefix + Option;
839
840 // (*) record requested arguments for later ufo detection
841 __record_argument_request(SearchTerm);
842
843 if( OldCursor >= argv.size() ) OldCursor = static_cast<unsigned int>(argv.size()) - 1;
844 search_failed_f = true;
845
846 // (*) first loop from cursor position until end
847 unsigned c = cursor;
848 for(; c < argv.size(); c++) {
849 if( argv[c] == SearchTerm )
850 { cursor = c; search_failed_f = false; return true; }
851 }
852 if( ! search_loop_f ) return false;
853
854 // (*) second loop from 0 to old cursor position
855 for(c = 1; c < OldCursor; c++) {
856 if( argv[c] == SearchTerm )
857 { cursor = c; search_failed_f = false; return true; }
858 }
859 // in case nothing is found the cursor stays where it was
860 return false;
861}
862
863
864inline bool
865GetPot::search(unsigned No, const char* P, ...)
866{
867 // (*) recording the requested arguments happens in subroutine 'search'
868 if( No == 0 ) return false;
869
870 // search for the first argument
871 if( search(P) == true ) return true;
872
873 // start interpreting variable argument list
874 va_list ap;
875 va_start(ap, P);
876 unsigned i = 1;
877 for(; i < No; ++i) {
878 char* Opt = va_arg(ap, char *);
879 if( search(Opt) == true ) break;
880 }
881
882 if( i < No ) {
883 ++i;
884 // loop was left before end of array --> hit but
885 // make sure that the rest of the search terms is marked
886 // as requested.
887 for(; i < No; ++i) {
888 char* Opt = va_arg(ap, char *);
889 // (*) record requested arguments for later ufo detection
890 __record_argument_request(Opt);
891 }
892 va_end(ap);
893 return true;
894 }
895
896 va_end(ap);
897 // loop was left normally --> no hit
898 return false;
899}
900
901inline void
902GetPot::reset_cursor()
903{ search_failed_f = false; cursor = 0; }
904
905inline void
906GetPot::init_multiple_occurrence()
907{ disable_loop(); reset_cursor(); }
908///////////////////////////////////////////////////////////////////////////////
909// (*) direct access to command line arguments
910//.............................................................................
911//
912inline const std::string
913GetPot::operator[](unsigned idx) const
914{ return idx < argv.size() ? argv[idx] : ""; }
915
916inline int
917GetPot::get(unsigned Idx, int Default) const
918{
919 if( Idx >= argv.size() ) return Default;
920 return __convert_to_type(argv[Idx], Default);
921}
922
923inline double
924GetPot::get(unsigned Idx, const double& Default) const
925{
926 if( Idx >= argv.size() ) return Default;
927 return __convert_to_type(argv[Idx], Default);
928}
929
930inline const std::string
931GetPot::get(unsigned Idx, const char* Default) const
932{
933 if( Idx >= argv.size() ) return Default;
934 else return argv[Idx];
935}
936
937inline unsigned
938GetPot::size() const
939{ return static_cast<unsigned int>(argv.size()); }
940
941
942// -- next() function group
943inline int
944GetPot::next(int Default)
945{
946 if( search_failed_f ) return Default;
947 cursor++;
948 if( cursor >= argv.size() )
949 { cursor = static_cast<unsigned int>(argv.size()); return Default; }
950
951 // (*) record requested argument for later ufo detection
952 __record_argument_request(argv[cursor]);
953
954 const std::string Remain = __get_remaining_string(argv[cursor], prefix);
955
956 return Remain != "" ? __convert_to_type(Remain, Default) : Default;
957}
958
959inline double
960GetPot::next(const double& Default)
961{
962 if( search_failed_f ) return Default;
963 cursor++;
964
965 if( cursor >= argv.size() )
966 { cursor = static_cast<unsigned int>(argv.size()); return Default; }
967
968 // (*) record requested argument for later ufo detection
969 __record_argument_request(argv[cursor]);
970
971 std::string Remain = __get_remaining_string(argv[cursor], prefix);
972
973 return Remain != "" ? __convert_to_type(Remain, Default) : Default;
974}
975
976inline const std::string
977GetPot::next(const char* Default)
978{
979 if( search_failed_f ) return Default;
980 cursor++;
981
982 if( cursor >= argv.size() )
983 { cursor = static_cast<unsigned int>(argv.size()); return Default; }
984
985 // (*) record requested argument for later ufo detection
986 __record_argument_request(argv[cursor]);
987
988 const std::string Remain = __get_remaining_string(argv[cursor], prefix);
989
990 if( Remain == "" ) return Default;
991
992
993 // (*) function returns a pointer to a char array (inside Remain)
994 // this array will be deleted, though after this function call.
995 // To ensure propper functioning, create a copy inside *this
996 // object and only delete it, when *this is deleted.
997 char* result = new char[Remain.length()+1];
998 strncpy(result, Remain.c_str(), Remain.length()+1);
999
1000 // store the created string internally, delete if when object deleted
1001 __internal_string_container.push_back(result);
1002
1003 return result;
1004}
1005
1006// -- follow() function group
1007// distinct option to be searched for
1008inline int
1009GetPot::follow(int Default, const char* Option)
1010{
1011 // (*) record requested of argument is entirely handled in 'search()' and 'next()'
1012 if( search(Option) == false ) return Default;
1013 return next(Default);
1014}
1015
1016inline double
1017GetPot::follow(const double& Default, const char* Option)
1018{
1019 // (*) record requested of argument is entirely handled in 'search()' and 'next()'
1020 if( search(Option) == false ) return Default;
1021 return next(Default);
1022}
1023
1024inline const std::string
1025GetPot::follow(const char* Default, const char* Option)
1026{
1027 // (*) record requested of argument is entirely handled in 'search()' and 'next()'
1028 if( search(Option) == false ) return Default;
1029 return next(Default);
1030}
1031
1032// -- second follow() function group
1033// multiple option to be searched for
1034inline int
1035GetPot::follow(int Default, unsigned No, const char* P, ...)
1036{
1037 // (*) record requested of argument is entirely handled in 'search()' and 'next()'
1038 if( No == 0 ) return Default;
1039 if( search(P) == true ) return next(Default);
1040
1041 va_list ap;
1042 va_start(ap, P);
1043 unsigned i=1;
1044 for(; i<No; ++i) {
1045 char* Opt = va_arg(ap, char *);
1046 if( search(Opt) == true ) {
1047 va_end(ap);
1048 return next(Default);
1049 }
1050 }
1051 va_end(ap);
1052 return Default;
1053}
1054
1055inline double
1056GetPot::follow(const double& Default, unsigned No, const char* P, ...)
1057{
1058 // (*) record requested of argument is entirely handled in 'search()' and 'next()'
1059 if( No == 0 ) return Default;
1060 if( search(P) == true ) return next(Default);
1061
1062 va_list ap;
1063 va_start(ap, P);
1064 for(unsigned i=1; i<No; ++i) {
1065 char* Opt = va_arg(ap, char *);
1066 if( search(Opt) == true ) {
1067 va_end(ap);
1068 return next(Default);
1069 }
1070 }
1071 va_end(ap);
1072 return Default;
1073}
1074
1075inline const std::string
1076GetPot::follow(const char* Default, unsigned No, const char* P, ...)
1077{
1078 // (*) record requested of argument is entirely handled in 'search()' and 'next()'
1079 if( No == 0 ) return Default;
1080 if( search(P) == true ) return next(Default);
1081
1082 va_list ap;
1083 va_start(ap, P);
1084 unsigned i=1;
1085 for(; i<No; ++i) {
1086 char* Opt = va_arg(ap, char *);
1087 if( search(Opt) == true ) {
1088 va_end(ap);
1089 return next(Default);
1090 }
1091 }
1092 va_end(ap);
1093 return Default;
1094}
1095
1096
1097///////////////////////////////////////////////////////////////////////////////
1098// (*) lists of nominus following an option
1099//.............................................................................
1100//
1101inline std::vector<std::string>
1102GetPot::nominus_followers(const char* Option)
1103{
1104 std::vector<std::string> result_list;
1105 if( search(Option) == false ) return result_list;
1106 while( 1 + 1 == 2 ) {
1107 ++cursor;
1108 if( cursor >= argv.size() ) {
1109 cursor = argv.size() - 1;
1110 return result_list;
1111 }
1112 if( argv[cursor].length() >= 1 ) {
1113 if( argv[cursor][0] == '-' ) {
1114 return result_list;
1115 }
1116 // -- record for later ufo-detection
1117 __record_argument_request(argv[cursor]);
1118 // -- append to the result list
1119 result_list.push_back(argv[cursor]);
1120 }
1121 }
1122}
1123
1124inline std::vector<std::string>
1125GetPot::nominus_followers(unsigned No, ...)
1126{
1127 std::vector<std::string> result_list;
1128 // (*) record requested of argument is entirely handled in 'search()'
1129 // and 'nominus_followers()'
1130 if( No == 0 ) return result_list;
1131
1132 va_list ap;
1133 va_start(ap, No);
1134 for(unsigned i=0; i<No; ++i) {
1135 char* Option = va_arg(ap, char *);
1136 std::vector<std::string> tmp = nominus_followers(Option);
1137 result_list.insert(result_list.end(), tmp.begin(), tmp.end());
1138
1139 // std::cerr << "option = '" << Option << "'" << std::endl;
1140 // std::cerr << "length = " << tmp.size() << std::endl;
1141 // std::cerr << "new result list = <";
1142 // for(std::vector<std::string>::const_iterator it = result_list.begin();
1143 // it != result_list.end(); ++it)
1144 // std::cerr << *it << ", ";
1145 // std::cerr << ">\n";
1146 }
1147 va_end(ap);
1148 return result_list;
1149}
1150
1151
1152///////////////////////////////////////////////////////////////////////////////
1153// (*) directly connected options
1154//.............................................................................
1155//
1156inline int
1157GetPot::direct_follow(int Default, const char* Option)
1158{
1159 const char* FollowStr = __match_starting_string(Option);
1160 if( FollowStr == 0x0 ) return Default;
1161
1162 // (*) record requested of argument for later ufo-detection
1163 __record_argument_request(std::string(Option) + FollowStr);
1164
1165 if( ++cursor >= static_cast<unsigned int>(argv.size()) ) cursor = static_cast<unsigned int>(argv.size());
1166 return __convert_to_type(FollowStr, Default);
1167}
1168
1169inline double
1170GetPot::direct_follow(const double& Default, const char* Option)
1171{
1172 const char* FollowStr = __match_starting_string(Option);
1173 if( FollowStr == 0 ) return Default;
1174
1175 // (*) record requested of argument for later ufo-detection
1176 __record_argument_request(std::string(Option) + FollowStr);
1177
1178 if( ++cursor >= static_cast<unsigned int>(argv.size()) ) cursor = static_cast<unsigned int>(argv.size());
1179 return __convert_to_type(FollowStr, Default);
1180}
1181
1182inline const std::string
1183GetPot::direct_follow(const char* Default, const char* Option)
1184{
1185 if( search_failed_f ) return Default;
1186 const char* FollowStr = __match_starting_string(Option);
1187 if( FollowStr == 0 ) return Default;
1188
1189 // (*) record requested of argument for later ufo-detection
1190 if( FollowStr ) __record_argument_request(std::string(Option) + FollowStr);
1191
1192 if( ++cursor >= static_cast<unsigned int>(argv.size()) ) cursor = static_cast<unsigned int>(argv.size());
1193 return std::string(FollowStr);
1194}
1195
1196inline std::vector<std::string>
1197GetPot::string_tails(const char* StartString)
1198{
1199 std::vector<std::string> result;
1200 const unsigned N = static_cast<unsigned int>(strlen(StartString));
1201
1202 std::vector<std::string>::iterator it = argv.begin();
1203
1204 unsigned idx = 0;
1205 while( it != argv.end() ) {
1206 // (*) does start string match the given option?
1207 // NO -> goto next option
1208 if( strncmp(StartString, (*it).c_str(), N) != 0) { ++it; ++idx; continue; }
1209
1210 // append the found tail to the result vector
1211 result.push_back((*it).substr(N));
1212
1213 // adapt the nominus vector
1214 std::vector<unsigned>::iterator nit = idx_nominus.begin();
1215 for(; nit != idx_nominus.end(); ++nit) {
1216 if( *nit == idx ) {
1217 idx_nominus.erase(nit);
1218 for(; nit != idx_nominus.end(); ++nit) *nit -= 1;
1219 break;
1220 }
1221 }
1222
1223 // erase the found option
1224 argv.erase(it);
1225
1226 // 100% safe solution: set iterator back to the beginning.
1227 // (normally, 'it--' would be enough, but who knows how the
1228 // iterator is implemented and .erase() definitely invalidates
1229 // the current iterator position.
1230 if( argv.empty() ) break;
1231 it = argv.begin();
1232 }
1233 cursor = 0;
1234 nominus_cursor = -1;
1235 return result;
1236}
1237
1238inline std::vector<int>
1239GetPot::int_tails(const char* StartString, const int Default /* = -1 */)
1240{
1241 std::vector<int> result;
1242 const unsigned N = static_cast<unsigned int>(strlen(StartString));
1243
1244 std::vector<std::string>::iterator it = argv.begin();
1245
1246 unsigned idx = 0;
1247 while( it != argv.end() ) {
1248 // (*) does start string match the given option?
1249 // NO -> goto next option
1250 if( strncmp(StartString, (*it).c_str(), N) != 0) { ++it; ++idx; continue; }
1251
1252 // append the found tail to the result vector
1253 result.push_back(__convert_to_type((*it).substr(N), Default));
1254
1255 // adapt the nominus vector
1256 std::vector<unsigned>::iterator nit = idx_nominus.begin();
1257 for(; nit != idx_nominus.end(); ++nit) {
1258 if( *nit == idx ) {
1259 idx_nominus.erase(nit);
1260 for(; nit != idx_nominus.end(); ++nit) *nit -= 1;
1261 break;
1262 }
1263 }
1264
1265 // erase the found option
1266 argv.erase(it);
1267
1268 // 100% safe solution: set iterator back to the beginning.
1269 // (normally, 'it--' would be enough, but who knows how the
1270 // iterator is implemented and .erase() definitely invalidates
1271 // the current iterator position.
1272 if( argv.empty() ) break;
1273 it = argv.begin();
1274 }
1275 cursor = 0;
1276 nominus_cursor = -1;
1277 return result;
1278}
1279
1280inline std::vector<double>
1281GetPot::double_tails(const char* StartString,
1282 const double Default /* = -1.0 */)
1283{
1284 std::vector<double> result;
1285 const unsigned N = static_cast<unsigned int>(strlen(StartString));
1286
1287 std::vector<std::string>::iterator it = argv.begin();
1288 unsigned idx = 0;
1289 while( it != argv.end() ) {
1290 // (*) does start string match the given option?
1291 // NO -> goto next option
1292 if( strncmp(StartString, (*it).c_str(), N) != 0) { ++it; ++idx; continue; }
1293
1294 // append the found tail to the result vector
1295 result.push_back(__convert_to_type((*it).substr(N), Default));
1296
1297 // adapt the nominus vector
1298 std::vector<unsigned>::iterator nit = idx_nominus.begin();
1299 for(; nit != idx_nominus.end(); ++nit) {
1300 if( *nit == idx ) {
1301 idx_nominus.erase(nit);
1302 for(; nit != idx_nominus.end(); ++nit) *nit -= 1;
1303 break;
1304 }
1305 }
1306
1307 // erase the found option
1308 argv.erase(it);
1309
1310 // 100% safe solution: set iterator back to the beginning.
1311 // (normally, 'it--' would be enough, but who knows how the
1312 // iterator is implemented and .erase() definitely invalidates
1313 // the current iterator position.
1314 if( argv.empty() ) break;
1315 it = argv.begin();
1316 }
1317 cursor = 0;
1318 nominus_cursor = -1;
1319 return result;
1320}
1321
1322
1323
1324
1325
1326inline const char*
1327GetPot::__match_starting_string(const char* StartString)
1328 // pointer to the place where the string after
1329 // the match inside the found argument starts.
1330 // 0 no argument matches the starting string.
1331{
1332 const unsigned N = static_cast<unsigned int>(strlen(StartString));
1333 unsigned OldCursor = cursor;
1334
1335 if( OldCursor >= static_cast<unsigned int>(argv.size()) ) OldCursor = static_cast<unsigned int>(argv.size()) - 1;
1336 search_failed_f = true;
1337
1338 // (*) first loop from cursor position until end
1339 unsigned c = cursor;
1340 for(; c < argv.size(); c++) {
1341 if( strncmp(StartString, argv[c].c_str(), N) == 0)
1342 { cursor = c; search_failed_f = false; return &(argv[c].c_str()[N]); }
1343 }
1344
1345 if( ! search_loop_f ) return false;
1346
1347 // (*) second loop from 0 to old cursor position
1348 for(c = 1; c < OldCursor; c++) {
1349 if( strncmp(StartString, argv[c].c_str(), N) == 0)
1350 { cursor = c; search_failed_f = false; return &(argv[c].c_str()[N]); }
1351 }
1352 return 0;
1353}
1354
1355///////////////////////////////////////////////////////////////////////////////
1356// (*) search for flags
1357//.............................................................................
1358//
1359inline bool
1360GetPot::options_contain(const char* FlagList) const
1361{
1362 // go through all arguments that start with a '-' (but not '--')
1363 std::string str;
1364 STRING_VECTOR::const_iterator it = argv.begin();
1365 for(; it != argv.end(); ++it) {
1366 str = __get_remaining_string(*it, prefix);
1367
1368 if( str.length() >= 2 && str[0] == '-' && str[1] != '-' )
1369 if( __check_flags(str, FlagList) ) return true;
1370 }
1371 return false;
1372}
1373
1374inline bool
1375GetPot::argument_contains(unsigned Idx, const char* FlagList) const
1376{
1377 if( Idx >= argv.size() ) return false;
1378
1379 // (*) record requested of argument for later ufo-detection
1380 // an argument that is checked for flags is considered to be 'requested'
1381 ((GetPot*)this)->__record_argument_request(argv[Idx]);
1382
1383 if( prefix == "" )
1384 // search argument for any flag in flag list
1385 return __check_flags(argv[Idx], FlagList);
1386
1387 // if a prefix is set, then the argument index is the index
1388 // inside the 'namespace'
1389 // => only check list of arguments that start with prefix
1390 unsigned no_matches = 0;
1391 unsigned i=0;
1392 for(; i<argv.size(); ++i) {
1393 const std::string Remain = __get_remaining_string(argv[i], prefix);
1394 if( Remain != "") {
1395 no_matches += 1;
1396 if( no_matches == Idx)
1397 return __check_flags(Remain, FlagList);
1398 }
1399 }
1400 // no argument in this namespace
1401 return false;
1402}
1403
1404inline bool
1405GetPot::__check_flags(const std::string& Str, const char* FlagList) const
1406{
1407 const char* p=FlagList;
1408 for(; *p != '\0' ; p++)
1409 if( Str.find(*p) != std::string::npos ) return true; // found something
1410 return false;
1411}
1412
1413///////////////////////////////////////////////////////////////////////////////
1414// (*) nominus arguments
1415inline STRING_VECTOR
1416GetPot::nominus_vector() const
1417 // return vector of nominus arguments
1418{
1419 STRING_VECTOR nv;
1420 std::vector<unsigned>::const_iterator it = idx_nominus.begin();
1421 for(; it != idx_nominus.end(); ++it) {
1422 nv.push_back(argv[*it]);
1423
1424 // (*) record for later ufo-detection
1425 // when a nominus vector is requested, the entire set of nominus arguments are
1426 // tagged as 'requested'
1427 ((GetPot*)this)->__record_argument_request(argv[*it]);
1428 }
1429 return nv;
1430}
1431
1432inline std::string
1433GetPot::next_nominus()
1434{
1435 if( nominus_cursor < int(idx_nominus.size()) - 1 ) {
1436 const std::string Tmp = argv[idx_nominus[++nominus_cursor]];
1437
1438 // (*) record for later ufo-detection
1439 __record_argument_request(Tmp);
1440
1441 // -- cannot use the Tmp variable, since it is temporary and c_str() will return a pointer
1442 // to something that does no longer exist.
1443 return Tmp;
1444 }
1445 return std::string("");
1446}
1447
1448///////////////////////////////////////////////////////////////////////////////
1449// (*) variables
1450//.............................................................................
1451//
1452inline int
1453GetPot::operator()(const char* VarName, int Default) const
1454{
1455 // (*) recording of requested variables happens in '__find_variable()'
1456 const variable* sv = __find_variable(VarName);
1457 if( sv == 0 ) return Default;
1458 return __convert_to_type(sv->original, Default);
1459}
1460
1461inline double
1462GetPot::operator()(const char* VarName, const double& Default) const
1463{
1464 // (*) recording of requested variables happens in '__find_variable()'
1465 const variable* sv = __find_variable(VarName);
1466 if( sv == 0 ) return Default;
1467 return __convert_to_type(sv->original, Default);
1468}
1469
1470inline const std::string
1471GetPot::operator()(const char* VarName, const char* Default) const
1472{
1473 // (*) recording of requested variables happens in '__find_variable()'
1474 const variable* sv = __find_variable(VarName);
1475 if( sv == 0 ) return Default;
1476 // -- returning a c_str() pointer is OK here, since the variable remains existant,
1477 // while 'sv' of course is delete at the end of the function.
1478 return sv->original;
1479}
1480
1481inline int
1482GetPot::operator()(const char* VarName, int Default, unsigned Idx) const
1483{
1484 // (*) recording of requested variables happens in '__find_variable()'
1485 const variable* sv = __find_variable(VarName);
1486 if( sv == 0 ) return Default;
1487 const std::string* element = sv->get_element(Idx);
1488 if( element == 0 ) return Default;
1489 return __convert_to_type(*element, Default);
1490}
1491
1492inline double
1493GetPot::operator()(const char* VarName, const double& Default, unsigned Idx) const
1494{
1495 // (*) recording of requested variables happens in '__find_variable()'
1496 const variable* sv = __find_variable(VarName);
1497 if( sv == 0 ) return Default;
1498 const std::string* element = sv->get_element(Idx);
1499 if( element == 0 ) return Default;
1500 return __convert_to_type(*element, Default);
1501}
1502
1503inline const std::string
1504GetPot::operator()(const char* VarName, const char* Default, unsigned Idx) const
1505{
1506 // (*) recording of requested variables happens in '__find_variable()'
1507 const variable* sv = __find_variable(VarName);
1508 if( sv == 0 ) return Default;
1509 const std::string* element = sv->get_element(Idx);
1510 if( element == 0 ) return Default;
1511 return *element;
1512}
1513
1514inline void
1515GetPot::__record_argument_request(const std::string& Name)
1516{
1517 if( ! __request_recording_f ) return;
1518
1519 // (*) record requested variable for later ufo detection
1520 _requested_arguments.push_back(Name);
1521
1522 // (*) record considered section for ufo detection
1523 STRING_VECTOR STree = __get_section_tree(Name);
1524 victorate(std::string, STree, it)
1525 if( find(_requested_sections.begin(), _requested_sections.end(), *it) == _requested_sections.end() )
1526 if( section.length() != 0 ) _requested_sections.push_back(*it);
1527}
1528
1529inline void
1530GetPot::__record_variable_request(const std::string& Name)
1531{
1532 if( ! __request_recording_f ) return;
1533
1534 // (*) record requested variable for later ufo detection
1535 _requested_variables.push_back(Name);
1536
1537 // (*) record considered section for ufo detection
1538 STRING_VECTOR STree = __get_section_tree(Name);
1539 victorate(std::string, STree, it)
1540 if( find(_requested_sections.begin(), _requested_sections.end(), *it) == _requested_sections.end() )
1541 if( section.length() != 0 ) _requested_sections.push_back(*it);
1542}
1543
1544// (*) following functions are to be used from 'outside', after getpot has parsed its
1545// arguments => append an argument in the argument vector that reflects the addition
1546inline void
1547GetPot::__set_variable(const char* VarName, const char* Value)
1548{
1549 const GetPot::variable* Var = __find_variable(VarName);
1550 if( Var == 0 ) variables.push_back(variable(VarName, Value, _field_separator.c_str()));
1551 else ((GetPot::variable*)Var)->take(Value, _field_separator.c_str());
1552}
1553
1554inline void
1555GetPot::set(const char* VarName, const char* Value, const bool Requested /* = yes */)
1556{
1557 const std::string Arg = prefix + std::string(VarName) + std::string("=") + std::string(Value);
1558 argv.push_back(Arg);
1559 __set_variable(VarName, Value);
1560
1561 // if user does not specify the variable as 'not being requested' it will be
1562 // considered amongst the requested variables
1563 if( Requested ) __record_variable_request(Arg);
1564}
1565
1566inline void
1567GetPot::set(const char* VarName, const double& Value, const bool Requested /* = yes */)
1568{ __set_variable(VarName, __double2string(Value).c_str()); }
1569
1570inline void
1571GetPot::set(const char* VarName, const int Value, const bool Requested /* = yes */)
1572{ __set_variable(VarName, __int2string(Value).c_str()); }
1573
1574
1575inline unsigned
1576GetPot::vector_variable_size(const char* VarName) const
1577{
1578 const variable* sv = __find_variable(VarName);
1579 if( sv == 0 ) return 0;
1580 return static_cast<unsigned int>(sv->value.size());
1581}
1582
1583inline STRING_VECTOR
1584GetPot::get_variable_names() const
1585{
1586 STRING_VECTOR result;
1587 std::vector<GetPot::variable>::const_iterator it = variables.begin();
1588 for(; it != variables.end(); ++it) {
1589 const std::string Tmp = __get_remaining_string((*it).name, prefix);
1590 if( Tmp != "" ) result.push_back(Tmp);
1591 }
1592 return result;
1593}
1594
1595inline STRING_VECTOR
1596GetPot::get_section_names() const
1597{ return section_list; }
1598
1599inline const GetPot::variable*
1600GetPot::__find_variable(const char* VarName) const
1601{
1602 const std::string Name = prefix + VarName;
1603
1604 // (*) record requested variable for later ufo detection
1605 ((GetPot*)this)->__record_variable_request(Name);
1606
1607 std::vector<variable>::const_iterator it = variables.begin();
1608 for(; it != variables.end(); ++it) {
1609 if( (*it).name == Name ) return &(*it);
1610 }
1611 return 0;
1612}
1613
1614///////////////////////////////////////////////////////////////////////////////
1615// (*) ouput (basically for debugging reasons
1616//.............................................................................
1617//
1618inline int
1619GetPot::print() const
1620{
1621 std::cout << "argc = " << static_cast<unsigned int>(argv.size()) << std::endl;
1622 STRING_VECTOR::const_iterator it = argv.begin();
1623 for(; it != argv.end(); ++it)
1624 std::cout << *it << std::endl;
1625 std::cout << std::endl;
1626 return 1;
1627}
1628
1629// (*) dollar bracket expressions (DBEs) ------------------------------------
1630//
1631// 1) Entry Function: __DBE_expand_string()
1632// Takes a string such as
1633//
1634// "${+ ${x} ${y}} Subject-${& ${section} ${subsection}}: ${title}"
1635//
1636// calls __DBE_expand() for each of the expressions
1637//
1638// ${+ ${x} ${y}}
1639// ${& ${section} ${subsection}}
1640// ${Title}
1641//
1642// and returns the string
1643//
1644// "4711 Subject-1.01: Mit den Clowns kamen die Schwaene"
1645//
1646// assuming that
1647// x = "4699"
1648// y = "12"
1649// section = "1."
1650// subsection = "01"
1651// title = "Mit den Clowns kamen die Schwaene"
1652//
1653// 2) __DBE_expand():
1654//
1655// checks for the command, i.e. the 'sign' that follows '${'
1656// divides the argument list into sub-expressions using
1657// __DBE_get_expr_list()
1658//
1659// ${+ ${x} ${y}} -> "${x}" "${y}"
1660// ${& ${section} ${subsection}} -> "${section}" "${subsection}"
1661// ${Title} -> Nothing, variable expansion
1662//
1663// 3) __DBE_expression_list():
1664//
1665// builds a vector of unbracketed whitespace separated strings, i.e.
1666//
1667// " ${Number}.a ${: Das Marmorbild} AB-${& Author= ${Eichendorf}-1870}"
1668//
1669// is split into a vector
1670//
1671// [0] ${Number}.a
1672// [1] ${: Das Marmorbild}
1673// [2] AB-${& Author= ${Eichendorf}}-1870
1674//
1675// Each sub-expression is expanded using expand().
1676//---------------------------------------------------------------------------
1677inline std::string
1678GetPot::__DBE_expand_string(const std::string str)
1679{
1680 // Parses for closing operators '${ }' and expands them letting
1681 // white spaces and other letters as they are.
1682 std::string new_string = "";
1683 unsigned open_brackets = 0;
1684 unsigned first = 0;
1685 unsigned i = 0;
1686 for(; i<str.size(); ++i) {
1687 if( i < str.size() - 2 && str.substr(i, 2) == "${" ) {
1688 if( open_brackets == 0 ) first = i+2;
1689 open_brackets++;
1690 }
1691 else if( str[i] == '}' && open_brackets > 0) {
1692 open_brackets -= 1;
1693 if( open_brackets == 0 ) {
1694 const std::string Replacement = __DBE_expand(str.substr(first, i - first));
1695 new_string += Replacement;
1696 }
1697 }
1698 else if( open_brackets == 0 )
1699 new_string += str[i];
1700 }
1701 return new_string;
1702}
1703
1704inline STRING_VECTOR
1705GetPot::__DBE_get_expr_list(const std::string str_, const unsigned ExpectedNumber)
1706 // ensures that the resulting vector has the expected number
1707 // of arguments, but they may contain an error message
1708{
1709 std::string str = str_;
1710 // Separates expressions by non-bracketed whitespaces, expands them
1711 // and puts them into a list.
1712
1713 unsigned i=0;
1714 // (1) eat initial whitespaces
1715 for(; i < str.size(); ++i)
1716 if( ! isspace(str[i]) ) break;
1717
1718 STRING_VECTOR expr_list;
1719 unsigned open_brackets = 0;
1720 std::vector<unsigned> start_idx;
1721 unsigned start_new_string = i;
1722 unsigned l = static_cast<unsigned int>(str.size());
1723
1724 // (2) search for ${ } expressions ...
1725 while( i < l ) {
1726 const char letter = str[i];
1727 // whitespace -> end of expression
1728 if( isspace(letter) && open_brackets == 0) {
1729 expr_list.push_back(str.substr(start_new_string, i - start_new_string));
1730 bool no_breakout_f = true;
1731 for(++i; i < l ; ++i) {
1732 if( ! isspace(str[i]) )
1733 { no_breakout_f = false; start_new_string = i; break; }
1734 }
1735 if( no_breakout_f ) {
1736 // end of expression list
1737 if( expr_list.size() < ExpectedNumber ) {
1738 const std::string pre_tmp("<< ${ }: missing arguments>>");
1739 STRING_VECTOR tmp(ExpectedNumber - expr_list.size(), pre_tmp);
1740 expr_list.insert(expr_list.end(), tmp.begin(), tmp.end());
1741 }
1742 return expr_list;
1743 }
1744 }
1745
1746 // dollar-bracket expression
1747 if( str.length() >= i+2 && str.substr(i, 2) == "${" ) {
1748 open_brackets++;
1749 start_idx.push_back(i+2);
1750 }
1751 else if( letter == '}' && open_brackets > 0) {
1752 int start = start_idx[start_idx.size()-1];
1753 start_idx.pop_back();
1754 const std::string Replacement = __DBE_expand(str.substr(start, i-start));
1755 if( start - 3 < (int)0)
1756 str = Replacement + str.substr(i+1);
1757 else
1758 str = str.substr(0, start-2) + Replacement + str.substr(i+1);
1759 l = static_cast<unsigned int>(str.size());
1760 i = start + static_cast<unsigned int>(Replacement.size()) - 3;
1761 open_brackets--;
1762 }
1763 ++i;
1764 }
1765
1766 // end of expression list
1767 expr_list.push_back(str.substr(start_new_string, i-start_new_string));
1768
1769 if( expr_list.size() < ExpectedNumber ) {
1770 const std::string pre_tmp("<< ${ }: missing arguments>>");
1771 STRING_VECTOR tmp(ExpectedNumber - expr_list.size(), pre_tmp);
1772 expr_list.insert(expr_list.end(), tmp.begin(), tmp.end());
1773 }
1774
1775 return expr_list;
1776}
1777
1778inline const GetPot::variable*
1779GetPot::__DBE_get_variable(std::string VarName)
1780{
1781 static GetPot::variable ev;
1782 std::string secure_Prefix = prefix;
1783
1784 prefix = section;
1785 // (1) first search in currently active section
1786 const GetPot::variable* var = __find_variable(VarName.c_str());
1787 if( var != 0 ) { prefix = secure_Prefix; return var; }
1788
1789 // (2) search in root name space
1790 prefix = "";
1791 var = __find_variable(VarName.c_str());
1792 if( var != 0 ) { prefix = secure_Prefix; return var; }
1793
1794 prefix = secure_Prefix;
1795
1796 // error occured => variable name == ""
1797 char* tmp = new char[VarName.length() + 25];
1798#ifndef WIN32
1799 snprintf(tmp, (int)sizeof(char)*(VarName.length() + 25),
1800#else
1801 _snprintf(tmp, sizeof(char)*(VarName.length() + 25),
1802#endif
1803 "<<${ } variable '%s' undefined>>", VarName.c_str());
1804 ev.name = "";
1805 ev.original = std::string(tmp);
1806 delete [] tmp;
1807 return &ev;
1808}
1809
1810inline std::string
1811GetPot::__DBE_expand(const std::string expr)
1812{
1813 // ${: } pure text
1814 if( expr[0] == ':' )
1815 return expr.substr(1);
1816
1817 // ${& expr expr ... } text concatination
1818 else if( expr[0] == '&' ) {
1819 const STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 1);
1820
1821 STRING_VECTOR::const_iterator it = A.begin();
1822 std::string result = *it++;
1823 for(; it != A.end(); ++it) result += *it;
1824
1825 return result;
1826 }
1827
1828 // ${<-> expr expr expr} text replacement
1829 else if( expr.length() >= 3 && expr.substr(0, 3) == "<->" ) {
1830 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(3), 3);
1831 std::string::size_type tmp = 0;
1832 const std::string::size_type L = A[1].length();
1833 while( (tmp = A[0].find(A[1])) != std::string::npos ) {
1834 A[0].replace(tmp, L, A[2]);
1835 }
1836 return A[0];
1837 }
1838 // ${+ ...}, ${- ...}, ${* ...}, ${/ ...} expressions
1839 else if( expr[0] == '+' ) {
1840 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
1841 STRING_VECTOR::const_iterator it = A.begin();
1842 double result = __convert_to_type(*it++, 0.0);
1843 for(; it != A.end(); ++it)
1844 result += __convert_to_type(*it, 0.0);
1845
1846 return __double2string(result);
1847 }
1848 else if( expr[0] == '-' ) {
1849 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
1850 STRING_VECTOR::const_iterator it = A.begin();
1851 double result = __convert_to_type(*it++, 0.0);
1852 for(; it != A.end(); ++it)
1853 result -= __convert_to_type(*it, 0.0);
1854
1855 return __double2string(result);
1856 }
1857 else if( expr[0] == '*' ) {
1858 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
1859 STRING_VECTOR::const_iterator it = A.begin();
1860 double result = __convert_to_type(*it++, 0.0);
1861 for(; it != A.end(); ++it)
1862 result *= __convert_to_type(*it, 0.0);
1863
1864 return __double2string(result);
1865 }
1866 else if( expr[0] == '/' ) {
1867
1868 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
1869 STRING_VECTOR::const_iterator it = A.begin();
1870 double result = __convert_to_type(*it++, 0.0);
1871 if( result == 0 ) return "0.0";
1872 for(; it != A.end(); ++it) {
1873 const double Q = __convert_to_type(*it, 0.0);
1874 if( Q == 0.0 ) return "0.0";
1875 result /= Q;
1876 }
1877 return __double2string(result);
1878 }
1879
1880 // ${^ ... } power expressions
1881 else if( expr[0] == '^' ) {
1882 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
1883 STRING_VECTOR::const_iterator it = A.begin();
1884 double result = __convert_to_type(*it++, 0.0);
1885 for(; it != A.end(); ++it)
1886 result = pow(result, __convert_to_type(*it, 0.0));
1887 return __double2string(result);
1888 }
1889
1890 // ${== } ${<= } ${>= } comparisons (return the number of the first 'match'
1891 else if( expr.length() >= 2 &&
1892 ( expr.substr(0,2) == "==" || expr.substr(0,2) == ">=" ||
1893 expr.substr(0,2) == "<=" || expr[0] == '>' || expr[0] == '<')) {
1894 // differentiate between two and one sign operators
1895 unsigned op = 0;
1896 enum { EQ, GEQ, LEQ, GT, LT };
1897 if ( expr.substr(0, 2) == "==" ) op = EQ;
1898 else if ( expr.substr(0, 2) == ">=" ) op = GEQ;
1899 else if ( expr.substr(0, 2) == "<=" ) op = LEQ;
1900 else if ( expr[0] == '>' ) op = GT;
1901 else /* "<" */ op = LT;
1902
1903 STRING_VECTOR a;
1904 if ( op == GT || op == LT ) a = __DBE_get_expr_list(expr.substr(1), 2);
1905 else a = __DBE_get_expr_list(expr.substr(2), 2);
1906
1907 std::string x_orig = a[0];
1908 double x = __convert_to_type(x_orig, 1e37);
1909 unsigned i = 1;
1910
1911 STRING_VECTOR::const_iterator y_orig = a.begin();
1912 for(y_orig++; y_orig != a.end(); y_orig++) {
1913 double y = __convert_to_type(*y_orig, 1e37);
1914
1915 // set the strings as reference if one wasn't a number
1916 if ( x == 1e37 || y == 1e37 ) {
1917 // it's a string comparison
1918 if( (op == EQ && x_orig == *y_orig) || (op == GEQ && x_orig >= *y_orig) ||
1919 (op == LEQ && x_orig <= *y_orig) || (op == GT && x_orig > *y_orig) ||
1920 (op == LT && x_orig < *y_orig) )
1921 return __int2string(i);
1922 }
1923 else {
1924 // it's a number comparison
1925 if( (op == EQ && x == y) || (op == GEQ && x >= y) ||
1926 (op == LEQ && x <= y) || (op == GT && x > y) ||
1927 (op == LT && x < y) )
1928 return __int2string(i);
1929 }
1930 ++i;
1931 }
1932
1933 // nothing fulfills the condition => return 0
1934 return "0";
1935 }
1936 // ${?? expr expr} select
1937 else if( expr.length() >= 2 && expr.substr(0, 2) == "??" ) {
1938 STRING_VECTOR a = __DBE_get_expr_list(expr.substr(2), 2);
1939 double x = __convert_to_type(a[0], 1e37);
1940 // last element is always the default argument
1941 if( x == 1e37 || x < 0 || x >= a.size() - 1 ) return a[a.size()-1];
1942
1943 // round x to closest integer
1944 return a[int(x+0.5)];
1945 }
1946 // ${? expr expr expr} if then else conditions
1947 else if( expr[0] == '?' ) {
1948 STRING_VECTOR a = __DBE_get_expr_list(expr.substr(1), 2);
1949 if( __convert_to_type(a[0], 0.0) == 1.0 ) return a[1];
1950 else if( a.size() > 2 ) return a[2];
1951 }
1952 // ${! expr} maxro expansion
1953 else if( expr[0] == '!' ) {
1954 const GetPot::variable* Var = __DBE_get_variable(expr.substr(1));
1955 // error
1956 if( Var->name == "" ) return std::string(Var->original);
1957
1958 const STRING_VECTOR A = __DBE_get_expr_list(Var->original, 2);
1959 return A[0];
1960 }
1961 // ${@: } - string subscription
1962 else if( expr.length() >= 2 && expr.substr(0,2) == "@:" ) {
1963 const STRING_VECTOR A = __DBE_get_expr_list(expr.substr(2), 2);
1964 double x = __convert_to_type(A[1], 1e37);
1965
1966 // last element is always the default argument
1967 if( x == 1e37 || x < 0 || x >= A[0].size() - 1)
1968 return "<<1st index out of range>>";
1969
1970 if( A.size() > 2 ) {
1971 double y = __convert_to_type(A[2], 1e37);
1972 if ( y != 1e37 && y > 0 && y <= A[0].size() - 1 && y > x )
1973 return A[0].substr(int(x+0.5), int(y+1.5) - int(x+0.5));
1974 else if( y == -1 )
1975 return A[0].substr(int(x+0.5));
1976 return "<<2nd index out of range>>";
1977 }
1978 else {
1979 char* tmp = new char[2];
1980 tmp[0] = A[0][int(x+0.5)]; tmp[1] = '\0';
1981 std::string result(tmp);
1982 delete [] tmp;
1983 return result;
1984 }
1985 }
1986 // ${@ } - vector subscription
1987 else if( expr[0] == '@' ) {
1988 STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
1989 const GetPot::variable* Var = __DBE_get_variable(A[0]);
1990 // error
1991 if( Var->name == "" ) {
1992 // make a copy of the string if an error occured
1993 // (since the error variable is a static variable inside get_variable())
1994 return std::string(Var->original);
1995 }
1996
1997 double x = __convert_to_type(A[1], 1e37);
1998
1999 // last element is always the default argument
2000 if (x == 1e37 || x < 0 || x >= Var->value.size() )
2001 return "<<1st index out of range>>";
2002
2003 if ( A.size() > 2) {
2004 double y = __convert_to_type(A[2], 1e37);
2005 int begin = int(x+0.5);
2006 int end = 0;
2007 if ( y != 1e37 && y > 0 && y <= Var->value.size() && y > x)
2008 end = int(y+1.5);
2009 else if( y == -1 )
2010 end = static_cast<unsigned int>(Var->value.size());
2011 else
2012 return "<<2nd index out of range>>";
2013
2014 std::string result = *(Var->get_element(begin));
2015 int i = begin+1;
2016 for(; i < end; ++i)
2017 result += std::string(" ") + *(Var->get_element(i));
2018 return result;
2019 }
2020 else
2021 return *(Var->get_element(int(x+0.5)));
2022 }
2023
2024 const STRING_VECTOR A = __DBE_get_expr_list(expr, 1);
2025 const GetPot::variable* B = __DBE_get_variable(A[0]);
2026
2027 // make a copy of the string if an error occured
2028 // (since the error variable is a static variable inside get_variable())
2029 if( B->name == "" ) return std::string(B->original);
2030 // (psuggs@pobox.com mentioned to me the warning MSVC++6.0 produces
2031 // with: else return B->original (thanks))
2032 return B->original;
2033}
2034
2035
2036///////////////////////////////////////////////////////////////////////////////
2037// (*) unidentified flying objects
2038//.............................................................................
2039//
2040inline bool
2041GetPot::__search_string_vector(const STRING_VECTOR& VecStr, const std::string& Str) const
2042{
2043 victorate(std::string, VecStr, itk) {
2044 if( *itk == Str ) return true;
2045 }
2046 return false;
2047}
2048
2049inline STRING_VECTOR
2050GetPot::unidentified_arguments(unsigned Number,
2051 const char* KnownArgument1, ...) const
2052{
2053 STRING_VECTOR known_arguments;
2054
2055 // (1) create a vector of known arguments
2056 if( Number == 0 ) return STRING_VECTOR();
2057
2058 va_list ap;
2059 va_start(ap, KnownArgument1);
2060 known_arguments.push_back(std::string(KnownArgument1));
2061 unsigned i=1;
2062 for(; i<Number; ++i)
2063 known_arguments.push_back(std::string(va_arg(ap, char *)));
2064 va_end(ap);
2065
2066 return unidentified_arguments(known_arguments);
2067}
2068
2069inline STRING_VECTOR
2070GetPot::unidentified_arguments() const
2071{ return unidentified_arguments(_requested_arguments); }
2072
2073inline STRING_VECTOR
2074GetPot::unidentified_arguments(const STRING_VECTOR& Knowns) const
2075{
2076 STRING_VECTOR ufos;
2077 STRING_VECTOR::const_iterator it = argv.begin();
2078 ++it; // forget about argv[0] (application or filename)
2079 for(; it != argv.end(); ++it) {
2080 // -- argument belongs to prefixed section ?
2081 const std::string arg = __get_remaining_string(*it, prefix);
2082 if( arg == "" ) continue;
2083
2084 // -- check if in list
2085 if( __search_string_vector(Knowns, arg) == false)
2086 ufos.push_back(*it);
2087 }
2088 return ufos;
2089}
2090
2091inline STRING_VECTOR
2092GetPot::unidentified_options(unsigned Number,
2093 const char* KnownOption1, ...) const
2094{
2095 STRING_VECTOR known_options;
2096
2097 // (1) create a vector of known arguments
2098 if( Number == 0 ) return STRING_VECTOR();
2099
2100 va_list ap;
2101 va_start(ap, KnownOption1);
2102 known_options.push_back(std::string(KnownOption1));
2103 unsigned i=1;
2104 for(; i<Number; ++i)
2105 known_options.push_back(std::string(va_arg(ap, char *)));
2106 va_end(ap);
2107
2108 return unidentified_options(known_options);
2109}
2110
2111inline STRING_VECTOR
2112GetPot::unidentified_options() const
2113{
2114 // -- every option is an argument.
2115 // -- the set of requested arguments contains the set of requested options.
2116 // -- IF the set of requested arguments contains unrequested options,
2117 // THEN they were requested as 'follow' and 'next' arguments and not as real options.
2118 //
2119 // => it is not necessary to separate requested options from the list
2120 STRING_VECTOR option_list;
2121 victorate(std::string, _requested_arguments, it) {
2122 const std::string arg = *it;
2123 if( arg.length() == 0 ) continue;
2124 if( arg[0] == '-' ) option_list.push_back(arg);
2125 }
2126 return unidentified_options(option_list);
2127}
2128
2129inline STRING_VECTOR
2130GetPot::unidentified_options(const STRING_VECTOR& Knowns) const
2131{
2132 STRING_VECTOR ufos;
2133 STRING_VECTOR::const_iterator it = argv.begin();
2134 ++it; // forget about argv[0] (application or filename)
2135 for(; it != argv.end(); ++it) {
2136 // -- argument belongs to prefixed section ?
2137 const std::string arg = __get_remaining_string(*it, prefix);
2138 if( arg == "" ) continue;
2139
2140 // is argument really an option (starting with '-') ?
2141 if( arg.length() < 1 || arg[0] != '-' ) continue;
2142
2143 if( __search_string_vector(Knowns, arg) == false)
2144 ufos.push_back(*it);
2145 }
2146
2147 return ufos;
2148}
2149
2150inline std::string
2151GetPot::unidentified_flags(const char* KnownFlagList, int ArgumentNumber=-1) const
2152 // Two modes:
2153 // ArgumentNumber >= 0 check specific argument
2154 // ArgumentNumber == -1 check all options starting with one '-'
2155 // for flags
2156{
2157 std::string ufos;
2158 STRING_VECTOR known_arguments;
2159 std::string KFL(KnownFlagList);
2160
2161 // (2) iteration over '-' arguments (options)
2162 if( ArgumentNumber == -1 ) {
2163 STRING_VECTOR::const_iterator it = argv.begin();
2164 ++it; // forget about argv[0] (application or filename)
2165 for(; it != argv.end(); ++it) {
2166 // -- argument belongs to prefixed section ?
2167 const std::string arg = __get_remaining_string(*it, prefix);
2168 if( arg == "" ) continue;
2169
2170 // -- does arguments start with '-' (but not '--')
2171 if ( arg.length() < 2 ) continue;
2172 else if( arg[0] != '-' ) continue;
2173 else if( arg[1] == '-' ) continue;
2174
2175 // -- check out if flags inside option are contained in KnownFlagList
2176 const char* p=arg.c_str();
2177 p++; // skip starting minus
2178 for(; *p != '\0' ; p++)
2179 if( KFL.find(*p) == std::string::npos ) ufos += *p;
2180 }
2181 }
2182 // (1) check specific argument
2183 else {
2184 // -- only check arguments that start with prefix
2185 int no_matches = 0;
2186 unsigned i=1;
2187 for(; i<argv.size(); ++i) {
2188 const std::string Remain = __get_remaining_string(argv[i], prefix);
2189 if( Remain != "") {
2190 no_matches++;
2191 if( no_matches == ArgumentNumber) {
2192 // -- the right argument number inside the section is found
2193 // => check it for flags
2194 const char* p = Remain.c_str();
2195 p++; // skip starting minus
2196 for(; *p != '\0' ; p++)
2197 if( KFL.find(*p) == std::string::npos ) ufos += *p;
2198 return ufos;
2199 }
2200 }
2201 }
2202 }
2203 return ufos;
2204}
2205
2206inline STRING_VECTOR
2207GetPot::unidentified_variables(unsigned Number,
2208 const char* KnownVariable1, ...) const
2209{
2210 STRING_VECTOR known_variables;
2211
2212 // create vector of known arguments
2213 if( Number == 0 ) return STRING_VECTOR();
2214
2215 va_list ap;
2216 va_start(ap, KnownVariable1);
2217 known_variables.push_back(std::string(KnownVariable1));
2218 unsigned i=1;
2219 for(; i<Number; ++i)
2220 known_variables.push_back(std::string(va_arg(ap, char *)));
2221 va_end(ap);
2222
2223 return unidentified_variables(known_variables);
2224}
2225
2226inline STRING_VECTOR
2227GetPot::unidentified_variables(const STRING_VECTOR& Knowns) const
2228{
2229 STRING_VECTOR ufos;
2230
2231 victorate(GetPot::variable, variables, it) {
2232 // -- check if variable has specific prefix
2233 const std::string var_name = __get_remaining_string((*it).name, prefix);
2234 if( var_name == "" ) continue;
2235
2236 // -- check if variable is known
2237 if( __search_string_vector(Knowns, var_name) == false)
2238 ufos.push_back((*it).name);
2239 }
2240 return ufos;
2241}
2242
2243inline STRING_VECTOR
2244GetPot::unidentified_variables() const
2245{ return unidentified_variables(_requested_variables); }
2246
2247
2248inline STRING_VECTOR
2249GetPot::unidentified_sections(unsigned Number,
2250 const char* KnownSection1, ...) const
2251{
2252 STRING_VECTOR known_sections;
2253
2254 // (1) create a vector of known arguments
2255 if( Number == 0 ) return STRING_VECTOR();
2256
2257 va_list ap;
2258 va_start(ap, KnownSection1);
2259 known_sections.push_back(std::string(KnownSection1));
2260 unsigned i=1;
2261 for(; i<Number; ++i) {
2262 std::string tmp = std::string(va_arg(ap, char *));
2263 if( tmp.length() == 0 ) continue;
2264 if( tmp[tmp.length()-1] != '/' ) tmp += '/';
2265 known_sections.push_back(tmp);
2266 }
2267 va_end(ap);
2268
2269 return unidentified_sections(known_sections);
2270}
2271
2272inline STRING_VECTOR
2273GetPot::unidentified_sections() const
2274{ return unidentified_sections(_requested_sections); }
2275
2276inline STRING_VECTOR
2277GetPot::unidentified_sections(const STRING_VECTOR& Knowns) const
2278{
2279 STRING_VECTOR ufos;
2280
2281 victorate(std::string, section_list, it) {
2282 // -- check if section conform to prefix
2283 const std::string sec_name = __get_remaining_string(*it, prefix);
2284 if( sec_name == "" ) continue;
2285
2286 // -- check if section is known
2287 if( __search_string_vector(Knowns, sec_name) == false )
2288 ufos.push_back(*it);
2289 }
2290
2291 return ufos;
2292}
2293
2294
2295inline STRING_VECTOR
2296GetPot::unidentified_nominuses(unsigned Number, const char* Known, ...) const
2297{
2298 STRING_VECTOR known_nominuses;
2299
2300 // create vector of known arguments
2301 if( Number == 0 ) return STRING_VECTOR();
2302
2303 va_list ap;
2304 va_start(ap, Known);
2305 known_nominuses.push_back(std::string(Known));
2306 unsigned i=1;
2307 for(; i<Number; ++i) {
2308 std::string tmp = std::string(va_arg(ap, char *));
2309 if( tmp.length() == 0 ) continue;
2310 known_nominuses.push_back(tmp);
2311 }
2312 va_end(ap);
2313
2314 return unidentified_nominuses(known_nominuses);
2315}
2316
2317inline STRING_VECTOR
2318GetPot::unidentified_nominuses() const {
2319 // -- every nominus is an argument.
2320 // -- the set of requested arguments contains the set of requested nominuss.
2321 // -- IF the set of requested arguments contains unrequested nominuss,
2322 // THEN they were requested as 'follow' and 'next' arguments and not as real nominuses.
2323 //
2324 // => it is not necessary to separate requested nominus from the list
2325
2326 return unidentified_nominuses(_requested_arguments);
2327}
2328
2329inline STRING_VECTOR
2330GetPot::unidentified_nominuses(const STRING_VECTOR& Knowns) const
2331{
2332 STRING_VECTOR ufos;
2333
2334 // (2) iterate over all arguments
2335 STRING_VECTOR::const_iterator it = argv.begin();
2336 ++it; // forget about argv[0] (application or filename)
2337 for(; it != argv.end(); ++it) {
2338 // -- check if nominus part of prefix
2339 const std::string arg = __get_remaining_string(*it, prefix);
2340 if( arg == "" ) continue;
2341
2342 if( arg.length() < 1 ) continue;
2343 // option ? --> not a nomius
2344 if( arg[0] == '-' ) continue;
2345 // section ? --> not a real nominus
2346 if( arg[0] == '[' && arg[arg.length()-1] == ']' ) continue;
2347 // variable definition ? --> not a real nominus
2348 bool continue_f = false;
2349 unsigned i=0;
2350 for(; i<arg.length() ; ++i)
2351 if( arg[i] == '=' ) { continue_f = true; break; }
2352 if( continue_f ) continue;
2353
2354 // real nominuses are compared with the given list
2355 if( __search_string_vector(Knowns, arg) == false )
2356 ufos.push_back(*it);
2357 }
2358 return ufos;
2359}
2360
2361
2362///////////////////////////////////////////////////////////////////////////////
2363// (*) variable class
2364//.............................................................................
2365//
2366inline
2367GetPot::variable::variable()
2368{}
2369
2370inline
2371GetPot::variable::variable(const variable& That)
2372{
2373#ifdef WIN32
2374 operator=(That);
2375#else
2376 GetPot::variable::operator=(That);
2377#endif
2378}
2379
2380
2381inline
2382GetPot::variable::variable(const char* Name, const char* Value, const char* FieldSeparator)
2383 : name(Name)
2384{
2385 // make a copy of the 'Value'
2386 take(Value, FieldSeparator);
2387}
2388
2389inline const std::string*
2390GetPot::variable::get_element(unsigned Idx) const
2391{ if( Idx >= value.size() ) return 0; else return &(value[Idx]); }
2392
2393inline void
2394GetPot::variable::take(const char* Value, const char* FieldSeparator)
2395{
2396 original = std::string(Value);
2397
2398 // separate string by white space delimiters using 'strtok'
2399 // thread safe usage of strtok (no static members)
2400 char* spt = 0;
2401 // make a copy of the 'Value'
2402 char* copy = new char[strlen(Value)+1];
2403 strcpy(copy, Value);
2404 char* follow_token = strtok_r(copy, FieldSeparator, &spt);
2405 if( value.size() != 0 ) value.erase(value.begin(), value.end());
2406 while(follow_token != 0) {
2407 value.push_back(std::string(follow_token));
2408 follow_token = strtok_r(NULL, FieldSeparator, &spt);
2409 }
2410
2411 delete [] copy;
2412}
2413
2414inline
2415GetPot::variable::~variable()
2416{}
2417
2418inline GetPot::variable&
2419GetPot::variable::operator=(const GetPot::variable& That)
2420{
2421 if( &That != this) {
2422 name = That.name;
2423 value = That.value;
2424 original = That.original;
2425 }
2426 return *this;
2427}
2428
2429#undef victorate
2430
2431
2432#endif // __include_guard_GETPOT_H__
2433
2434
2435
diff --git a/utils/zenutils/libraries/pelib-0.9/CMakeLists.txt b/utils/zenutils/libraries/pelib-0.9/CMakeLists.txt
new file mode 100755
index 0000000000..540fa99c8c
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/CMakeLists.txt
@@ -0,0 +1,20 @@
1PROJECT(pelib)
2
3# source files for pelib
4SET(pelib_srcs
5 pelib/BoundImportDirectory.cpp
6 pelib/ComHeaderDirectory.cpp
7 pelib/DebugDirectory.cpp
8 pelib/ExportDirectory.cpp
9 pelib/IatDirectory.cpp
10 pelib/MzHeader.cpp
11 pelib/PeFile.cpp
12 pelib/PeHeader.cpp
13 pelib/PeLibAux.cpp
14 pelib/RelocationsDirectory.cpp
15 pelib/ResourceDirectory.cpp
16 pelib/buffer/InputBuffer.cpp
17 pelib/buffer/OutputBuffer.cpp
18)
19
20ADD_LIBRARY(pelib ${pelib_srcs})
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.cpp
new file mode 100755
index 0000000000..5b84931838
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.cpp
@@ -0,0 +1,511 @@
1/*
2* BoundImportDirectory.cpp - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#include "PeLibInc.h"
14#include "BoundImportDirectory.h"
15#include <numeric>
16#include <set>
17#include <map>
18
19namespace PeLib
20{
21 /**
22 * Adds another bound import to the BoundImport directory.
23 * @param strModuleName Name of the PE file which will be imported.
24 * @param dwTds Value of the TimeDateStamp of the bound import field.
25 * @param wOmn Value of the OffsetModuleName of the bound import field.
26 * @param wWfr Value of the NumberOfModuleForwarderRefs of the bound import field.
27 **/
28 int BoundImportDirectory::addBoundImport(const std::string& strModuleName, dword dwTds, word wOmn, word wWfr)
29 {
30 for (unsigned int i=0;i<m_vIbd.size();i++)
31 {
32 if (isEqualNc(strModuleName, m_vIbd[i].strModuleName))
33 {
34 return ERROR_DUPLICATE_ENTRY;
35 }
36 }
37
38 PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR ibidCurrent;
39 ibidCurrent.TimeDateStamp = dwTds;
40 ibidCurrent.OffsetModuleName = wOmn;
41 ibidCurrent.NumberOfModuleForwarderRefs = wWfr;
42 PELIB_IMAGE_BOUND_DIRECTORY ibdCurrent;
43 ibdCurrent.ibdDescriptor = ibidCurrent;
44 ibdCurrent.strModuleName = strModuleName;
45 m_vIbd.push_back(ibdCurrent);
46
47 return NO_ERROR;
48 }
49
50 /**
51 * Searches for the first instance of a module with the given modulename.
52 * @param strModuleName The name of a module.
53 * @return The id of the module.
54 **/
55 int BoundImportDirectory::getModuleIndex(const std::string& strModuleName) const
56 {
57 std::vector<PELIB_IMAGE_BOUND_DIRECTORY>::const_iterator Iter = std::find_if(m_vIbd.begin(), m_vIbd.end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_BOUND_DIRECTORY::equal), strModuleName));
58
59 if (Iter == m_vIbd.end())
60 {
61 return ERROR_ENTRY_NOT_FOUND;
62 }
63
64 return static_cast<int>(std::distance(m_vIbd.begin(), Iter));
65 }
66
67 /**
68 * @return Number of files in the current BoundImport directory.
69 **/
70 unsigned int BoundImportDirectory::calcNumberOfModules() const
71 {
72 return static_cast<unsigned int>(m_vIbd.size());
73 }
74
75 int BoundImportDirectory::read(InputBuffer& inpBuffer, unsigned char* data, unsigned int dwSize)
76 {
77 std::vector<PELIB_IMAGE_BOUND_DIRECTORY> currentDirectory;
78
79 do
80 {
81 PELIB_IMAGE_BOUND_DIRECTORY ibdCurrent;
82
83 inpBuffer >> ibdCurrent.ibdDescriptor.TimeDateStamp;
84 inpBuffer >> ibdCurrent.ibdDescriptor.OffsetModuleName;
85 inpBuffer >> ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs;
86
87 if (ibdCurrent.ibdDescriptor.TimeDateStamp == 0 && ibdCurrent.ibdDescriptor.OffsetModuleName == 0 && ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs == 0) break;
88
89 for (int i=0;i<ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs;i++)
90 {
91 PELIB_IMAGE_BOUND_DIRECTORY currentForwarder;
92
93 inpBuffer >> currentForwarder.ibdDescriptor.TimeDateStamp;
94 inpBuffer >> currentForwarder.ibdDescriptor.OffsetModuleName;
95 inpBuffer >> currentForwarder.ibdDescriptor.NumberOfModuleForwarderRefs;
96
97 ibdCurrent.moduleForwarders.push_back(currentForwarder);
98 }
99
100 currentDirectory.push_back(ibdCurrent);
101 ibdCurrent.moduleForwarders.clear();
102 } while (true);
103
104 for (unsigned int i=0;i<currentDirectory.size();i++)
105 {
106 dword wOmn = currentDirectory[i].ibdDescriptor.OffsetModuleName;
107 if (wOmn > dwSize)
108 {
109 return ERROR_INVALID_FILE;
110 }
111
112 currentDirectory[i].strModuleName = "";
113 for (int k=0;data[wOmn + k] != 0 && k + wOmn < dwSize;k++)
114 {
115 currentDirectory[i].strModuleName += data[wOmn + k];
116 }
117
118 for (unsigned int j=0;j<currentDirectory[i].moduleForwarders.size();j++)
119 {
120 dword wOmn = currentDirectory[i].moduleForwarders[j].ibdDescriptor.OffsetModuleName;
121
122 if (wOmn > dwSize)
123 {
124 return ERROR_INVALID_FILE;
125 }
126
127// m_vIbd[i].moduleForwarders[j].strModuleName.assign((char*)(&vBimpDir[wOmn]));
128 currentDirectory[i].moduleForwarders[j].strModuleName = "";
129 for (int k=0;data[wOmn + k] != 0 && k + wOmn < dwSize;k++)
130 {
131 currentDirectory[i].moduleForwarders[j].strModuleName += data[wOmn + k];
132 }
133 }
134 }
135
136 std::swap(m_vIbd, currentDirectory);
137
138 return NO_ERROR;
139 }
140
141 /**
142 * Reads the BoundImport directory from a PE file.
143 * @param strModuleName The name of the PE file from which the BoundImport directory is read.
144 * @param dwOffset The file offset where the BoundImport directory can be found (see #PeFile::PeHeader::getIDBoundImportRVA).
145 * @param dwSize The size of the BoundImport directory (see #PeFile::PeHeader::getIDBoundImportSize).
146 **/
147 int BoundImportDirectory::read(const std::string& strModuleName, dword dwOffset, unsigned int uiSize)
148 {
149 std::ifstream ifFile(strModuleName.c_str(), std::ios::binary);
150
151 if (!ifFile)
152 {
153 return ERROR_OPENING_FILE;
154 }
155
156 if (fileSize(ifFile) < dwOffset + uiSize)
157 {
158 return ERROR_INVALID_FILE;
159 }
160
161 ifFile.seekg(dwOffset, std::ios::beg);
162
163 std::vector<unsigned char> vBimpDir(uiSize);
164 ifFile.read(reinterpret_cast<char*>(&vBimpDir[0]), uiSize);
165
166 InputBuffer inpBuffer(vBimpDir);
167
168 return read(inpBuffer, &vBimpDir[0], uiSize);
169 }
170
171 int BoundImportDirectory::read(unsigned char* pcBuffer, unsigned int uiSize)
172 {
173 std::vector<unsigned char> vBimpDir(pcBuffer, pcBuffer + uiSize);
174 InputBuffer inpBuffer(vBimpDir);
175
176 return read(inpBuffer, &vBimpDir[0], uiSize);
177 }
178
179 unsigned int BoundImportDirectory::totalModules() const
180 {
181 unsigned int modules = static_cast<unsigned int>(m_vIbd.size());
182
183 for (unsigned int i=0;i<m_vIbd.size();i++)
184 {
185 modules += static_cast<unsigned int>(m_vIbd[i].moduleForwarders.size());
186 }
187
188 return modules;
189 }
190
191 /**
192 * Rebuilds the BoundImport directory. The rebuilded BoundImport directory can then be
193 * written back to a PE file.
194 * @param vBuffer Buffer where the rebuilt BoundImport directory will be stored.
195 * @param fMakeValid If this flag is true a valid directory will be produced.
196 **/
197 void BoundImportDirectory::rebuild(std::vector<byte>& vBuffer, bool fMakeValid) const
198 {
199 std::map<std::string, word> filename_offsets;
200
201 OutputBuffer obBuffer(vBuffer);
202
203 word ulNameOffset = static_cast<word>((totalModules() + 1) * PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size());
204
205 for (unsigned int i=0;i<m_vIbd.size();i++)
206 {
207 obBuffer << m_vIbd[i].ibdDescriptor.TimeDateStamp;
208
209 // Recalculate the offsets if a valid directory is wanted.
210 if (fMakeValid)
211 {
212 if (filename_offsets.find(m_vIbd[i].strModuleName) == filename_offsets.end())
213 {
214 filename_offsets[m_vIbd[i].strModuleName] = ulNameOffset;
215 obBuffer << ulNameOffset;
216 ulNameOffset += static_cast<word>(m_vIbd[i].strModuleName.size() + 1);
217 }
218 else
219 {
220 obBuffer << filename_offsets[m_vIbd[i].strModuleName];
221 }
222 }
223 else // Otherwise just copy the old values into the buffer.
224 {
225 obBuffer << m_vIbd[i].ibdDescriptor.OffsetModuleName;
226 }
227
228 obBuffer << m_vIbd[i].ibdDescriptor.NumberOfModuleForwarderRefs;
229
230 for (int j=0;j<calcNumberOfModuleForwarderRefs(i);j++)
231 {
232 obBuffer << m_vIbd[i].moduleForwarders[j].ibdDescriptor.TimeDateStamp;
233
234 if (fMakeValid)
235 {
236 if (filename_offsets.find(m_vIbd[i].strModuleName) == filename_offsets.end())
237 {
238 filename_offsets[m_vIbd[i].moduleForwarders[j].strModuleName] = ulNameOffset;
239 obBuffer << ulNameOffset;
240 ulNameOffset += static_cast<word>(m_vIbd[i].moduleForwarders[j].strModuleName.size() + 1);
241 }
242 else
243 {
244 obBuffer << filename_offsets[m_vIbd[i].moduleForwarders[j].strModuleName];
245 }
246 }
247 else // Otherwise just copy the old values into the buffer.
248 {
249 obBuffer << m_vIbd[i].moduleForwarders[j].ibdDescriptor.OffsetModuleName;
250 }
251
252 obBuffer << m_vIbd[i].moduleForwarders[j].ibdDescriptor.NumberOfModuleForwarderRefs;
253 }
254 }
255
256 obBuffer << static_cast<dword>(0);
257 obBuffer << static_cast<word>(0);
258 obBuffer << static_cast<word>(0);
259
260 for (unsigned int i=0;i<m_vIbd.size();i++)
261 {
262 if (filename_offsets.find(m_vIbd[i].strModuleName) != filename_offsets.end())
263 {
264 obBuffer.add(getModuleName(i).c_str(), static_cast<unsigned long>(getModuleName(i).size() + 1));
265 filename_offsets.erase(m_vIbd[i].strModuleName);
266 }
267
268 for (int j=0;j<calcNumberOfModuleForwarderRefs(i);j++)
269 {
270 if (filename_offsets.find(getModuleName(i, j)) != filename_offsets.end())
271 {
272 obBuffer.add(getModuleName(i, j).c_str(), static_cast<unsigned long>(getModuleName(i, j).size() + 1));
273 filename_offsets.erase(getModuleName(i, j));
274 }
275 }
276 }
277 }
278
279 /**
280 * Removes all bound import files.
281 **/
282 void BoundImportDirectory::clear()
283 {
284 m_vIbd.clear();
285 }
286
287 /**
288 * Removes a field specified by the parameter filename from the BoundImport directory.
289 * @param strModuleName Name of the file whose field will be removed from the BoundImport directory.
290 **/
291 void BoundImportDirectory::removeBoundImport(const std::string& strModuleName)
292 {
293 m_vIbd.erase(std::remove_if(m_vIbd.begin(), m_vIbd.end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_BOUND_DIRECTORY::equal), strModuleName)), m_vIbd.end());
294 }
295
296 /**
297 * Returns the size of the rebuilt BoundImportDirectory.
298 * @return Size of the rebuilt BoundImportDirectory.
299 **/
300 unsigned int BoundImportDirectory::size() const
301 {
302 unsigned int size = PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size();
303
304 std::set<std::string> filenames;
305
306 for (unsigned int i = 0; i < m_vIbd.size(); i++)
307 {
308 filenames.insert(m_vIbd[i].strModuleName);
309
310 size += PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size();
311
312 for (unsigned int j = 0; j < m_vIbd[i].moduleForwarders.size(); j++)
313 {
314 filenames.insert(m_vIbd[i].moduleForwarders[j].strModuleName);
315
316 size += PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size();
317 }
318 }
319
320 for (std::set<std::string>::iterator iter = filenames.begin(); iter != filenames.end(); ++iter)
321 {
322 size += static_cast<unsigned int>(iter->size()) + 1;
323 }
324
325 return size;
326 }
327
328 /**
329 * @param strFilename Name of the file.
330 * @param dwOffset File offset the bound importdirectory will be written to.
331 * @param fMakeValid If this flag is true a valid directory will be produced.
332 **/
333 int BoundImportDirectory::write(const std::string& strFilename, dword dwOffset, bool fMakeValid) const
334 {
335 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
336
337 if (!ofFile)
338 {
339 ofFile.clear();
340 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
341 }
342 else
343 {
344 ofFile.close();
345 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
346 }
347
348 if (!ofFile)
349 {
350 return ERROR_OPENING_FILE;
351 }
352
353 ofFile.seekp(dwOffset, std::ios::beg);
354
355 std::vector<unsigned char> vBuffer;
356 rebuild(vBuffer, fMakeValid);
357
358 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<std::streamsize>(vBuffer.size()));
359
360 ofFile.close();
361
362 return NO_ERROR;
363 }
364
365 /**
366 * Retrieves the value of the TimeDateStamp value of a bound import field.
367 * @param dwBidnr Number of the bound import field.
368 * @return Value of the TimeDateStamp of the bound import field.
369 **/
370 dword BoundImportDirectory::getTimeDateStamp(dword dwBidnr) const
371 {
372 return m_vIbd[dwBidnr].ibdDescriptor.TimeDateStamp;
373 }
374
375 /**
376 * Retrieves the value of the OffsetModuleName value of a bound import field.
377 * @param dwBidnr Number of the bound import field.
378 * @return Value of the OffsetModuleName of the bound import field.
379 **/
380 word BoundImportDirectory::getOffsetModuleName(dword dwBidnr) const
381 {
382 return m_vIbd[dwBidnr].ibdDescriptor.OffsetModuleName;
383 }
384
385 /**
386 * Retrieves the value of the NumberOfModuleForwarderRefs value of a bound import field.
387 * @param dwBidnr Number of the bound import field.
388 * @return Value of the NumberOfModuleForwarderRefs of the bound import field.
389 **/
390 word BoundImportDirectory::getNumberOfModuleForwarderRefs(dword dwBidnr) const
391 {
392 return m_vIbd[dwBidnr].ibdDescriptor.NumberOfModuleForwarderRefs;
393 }
394
395 /**
396 * Retrieves the value of the ModuleName value of a bound import field.
397 * @param dwBidnr Number of the bound import field.
398 * @return Value of the ModuleName of the bound import field.
399 **/
400 std::string BoundImportDirectory::getModuleName(dword dwBidnr) const
401 {
402 return m_vIbd[dwBidnr].strModuleName;
403 }
404
405 /**
406 * Changes the TimeDateStamp value of an existing bound import field.
407 * @param dwBidnr Number of the bound import field which will be changed.
408 * @param dwTds New value of the TimeDateStamp of the bound import field.
409 **/
410 void BoundImportDirectory::setTimeDateStamp(dword dwBidnr, dword dwTds)
411 {
412 m_vIbd[dwBidnr].ibdDescriptor.TimeDateStamp = dwTds;
413 }
414
415 /**
416 * Changes the OffsetModuleName value of an existing bound import field.
417 * @param dwBidnr Number of the bound import field which will be changed.
418 * @param wOmn New value of the OffsetModuleName of the bound import field.
419 **/
420 void BoundImportDirectory::setOffsetModuleName(dword dwBidnr, word wOmn)
421 {
422 m_vIbd[dwBidnr].ibdDescriptor.OffsetModuleName = wOmn;
423 }
424
425 /**
426 * Changes the NumberOfModuleForwarderRefs value of an existing bound import field.
427 * @param dwBidnr Number of the bound import field which will be changed.
428 * @param wMfr New value of the NumberOfModuleForwarderRefs of the bound import field.
429 **/
430 void BoundImportDirectory::setNumberOfModuleForwarderRefs(dword dwBidnr, word wMfr)
431 {
432 m_vIbd[dwBidnr].ibdDescriptor.NumberOfModuleForwarderRefs = wMfr;
433 }
434
435 /**
436 * Changes the ModuleName value of an existing bound import field.
437 * @param dwBidnr Number of the bound import field which will be changed.
438 * @param strModuleName New value of the ModuleName of the bound import field.
439 **/
440 void BoundImportDirectory::setModuleName(dword dwBidnr, const std::string& strModuleName)
441 {
442 m_vIbd[dwBidnr].strModuleName = strModuleName;
443 }
444
445 dword BoundImportDirectory::getTimeDateStamp(dword dwBidnr, dword forwardedModule) const
446 {
447 return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.TimeDateStamp;
448 }
449
450 word BoundImportDirectory::getOffsetModuleName(dword dwBidnr, dword forwardedModule) const
451 {
452 return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.OffsetModuleName;
453 }
454
455 word BoundImportDirectory::getNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule) const
456 {
457 return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.NumberOfModuleForwarderRefs;
458 }
459
460 std::string BoundImportDirectory::getModuleName(dword dwBidnr, dword forwardedModule) const
461 {
462 return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].strModuleName;
463 }
464
465 void BoundImportDirectory::setTimeDateStamp(dword dwBidnr, dword forwardedModule, dword dwTds)
466 {
467 m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.TimeDateStamp = dwTds;
468 }
469
470 void BoundImportDirectory::setOffsetModuleName(dword dwBidnr, dword forwardedModule, word wOmn)
471 {
472 m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.OffsetModuleName = wOmn;
473 }
474
475 void BoundImportDirectory::setNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule, word wMfr)
476 {
477 m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.NumberOfModuleForwarderRefs = wMfr;
478 }
479
480 void BoundImportDirectory::setModuleName(dword dwBidnr, dword forwardedModule, const std::string& strModuleName)
481 {
482 m_vIbd[dwBidnr].moduleForwarders[forwardedModule].strModuleName = strModuleName;
483 }
484
485 word BoundImportDirectory::calcNumberOfModuleForwarderRefs(dword dwBidnr) const
486 {
487 return static_cast<word>(m_vIbd[dwBidnr].moduleForwarders.size());
488 }
489
490 void BoundImportDirectory::addForwardedModule(dword dwBidnr, const std::string& name, dword timeStamp, word offsetModuleName, word forwardedModules)
491 {
492 // XXX: Maybe test if there are already 0xFFFF forwarded modules.
493 // XXX: Check for duplicate entries. Is it also necessary to check
494 // non-forwarded entries and forwarded entries in other non-forwarded
495 // entries?
496 // XXX: Can forwarders forward recursively?
497
498 PELIB_IMAGE_BOUND_DIRECTORY ibdCurrent;
499 ibdCurrent.strModuleName = name;
500 ibdCurrent.ibdDescriptor.TimeDateStamp = timeStamp;
501 ibdCurrent.ibdDescriptor.OffsetModuleName = offsetModuleName;
502 ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs = forwardedModules;
503
504 m_vIbd[dwBidnr].moduleForwarders.push_back(ibdCurrent);
505 }
506
507 void BoundImportDirectory::removeForwardedModule(dword dwBidnr, word forwardedModule)
508 {
509 m_vIbd[dwBidnr].moduleForwarders.erase(m_vIbd[dwBidnr].moduleForwarders.begin() + forwardedModule);
510 }
511}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.h
new file mode 100755
index 0000000000..fd2bab56fd
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.h
@@ -0,0 +1,87 @@
1/*
2* BoundImportDirectory.h - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#ifndef BOUNDIMPORTDIRECTORY_H
14#define BOUNDIMPORTDIRECTORY_H
15
16#include "PeLibAux.h"
17
18namespace PeLib
19{
20 /// Class that handles the BoundImport directory.
21 /**
22 * This class can read and modify the BoundImport directory table of a PE file.
23 **/
24 class BoundImportDirectory
25 {
26 private:
27 std::vector<PELIB_IMAGE_BOUND_DIRECTORY> m_vIbd; ///< Stores the individual BoundImport fields.
28
29 int read(InputBuffer& inpBuffer, unsigned char* data, unsigned int dwSize);
30 unsigned int totalModules() const;
31 public:
32 /// Adds another bound import.
33 int addBoundImport(const std::string& strModuleName, dword dwTds, word dwOmn, word wWfr); // EXPORT
34 /// Identifies a module through it's name.
35 int getModuleIndex(const std::string& strModuleName) const; // EXPORT
36 /// Returns the number of files in the BoundImport directory.
37 unsigned int calcNumberOfModules() const; // EXPORT
38 /// Reads the BoundImport directory table from a PE file.
39 int read(const std::string& strFileName, dword dwOffset, unsigned int uiSize); // EXPORT
40 int read(unsigned char* pcBuffer, unsigned int uiSize); // EXPORT
41 /// Rebuilds the BoundImport directory.
42 void rebuild(std::vector<byte>& vBuffer, bool fMakeValid = true) const; // EXPORT
43 /// Empties the BoundImport directory.
44 void clear(); // EXPORT
45 /// Removes a bound import.
46 void removeBoundImport(const std::string& strModuleName); // EXPORT
47 /// Returns the size of the BoundImport directory.
48 unsigned int size() const; // EXPORT
49 /// Writes the current bound import directory to a file.
50 int write(const std::string& strFilename, dword dwOffset, bool fMakeValid = true) const; // EXPORT
51
52 /// Retrieves the TimeDateStamp value of a bound import.
53 dword getTimeDateStamp(dword dwBidnr) const; // EXPORT
54 /// Retrieves the OffsetModuleName value of a bound import.
55 word getOffsetModuleName(dword dwBidnr) const; // EXPORT
56 /// Retrieves the NumberOfModuleForwarderRefs value of a bound import.
57 word getNumberOfModuleForwarderRefs(dword dwBidnr) const; // EXPORT
58 /// Retrieves the ModuleName value of a bound import.
59 std::string getModuleName(dword dwBidnr) const; // EXPORT
60
61 /// Updates the TimeDateStamp value of a bound import.
62 void setTimeDateStamp(dword dwBidnr, dword dwTds); // EXPORT
63 /// Updates the OffsetModuleName value of a bound import.
64 void setOffsetModuleName(dword dwBidnr, word wOmn); // EXPORT
65 /// Updates the NumberOfModuleForwarderRefs value of a bound import.
66 void setNumberOfModuleForwarderRefs(dword dwBidnr, word wMfr); // EXPORT
67 /// Updates the ModuleName value of a bound import.
68 void setModuleName(dword dwBidnr, const std::string& strModuleName); // EXPORT
69
70 dword getTimeDateStamp(dword dwBidnr, dword forwardedModule) const; // EXPORT _module
71 word getOffsetModuleName(dword dwBidnr, dword forwardedModule) const; // EXPORT _module
72 word getNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule) const; // EXPORT _module
73 std::string getModuleName(dword dwBidnr, dword forwardedModule) const; // EXPORT _module
74
75 void setTimeDateStamp(dword dwBidnr, dword forwardedModule, dword dwTds); // EXPORT _module
76 void setOffsetModuleName(dword dwBidnr, dword forwardedModule, word wOmn); // EXPORT _module
77 void setNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule, word wMfr); // EXPORT _module
78 void setModuleName(dword dwBidnr, dword forwardedModule, const std::string& strModuleName); // EXPORT _module
79
80 word calcNumberOfModuleForwarderRefs(dword dwBidnr) const; // EXPORT
81 void addForwardedModule(dword dwBidnr, const std::string& name, dword timeStamp = 0, word offsetModuleName = 0, word forwardedModules = 0); // EXPORT
82 void removeForwardedModule(dword dwBidnr, word forwardedModule); // EXPORT
83 };
84}
85
86
87#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.cpp
new file mode 100755
index 0000000000..886348994e
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.cpp
@@ -0,0 +1,467 @@
1/*
2* ComHeaderDirectory.cpp - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#include "PeLibInc.h"
14#include "ComHeaderDirectory.h"
15
16namespace PeLib
17{
18 void ComHeaderDirectory::read(InputBuffer& inputbuffer)
19 {
20 PELIB_IMAGE_COR20_HEADER ichCurr;
21
22 inputbuffer >> ichCurr.cb;
23 inputbuffer >> ichCurr.MajorRuntimeVersion;
24 inputbuffer >> ichCurr.MinorRuntimeVersion;
25 inputbuffer >> ichCurr.MetaData.VirtualAddress;
26 inputbuffer >> ichCurr.MetaData.Size;
27 inputbuffer >> ichCurr.Flags;
28 inputbuffer >> ichCurr.EntryPointToken;
29 inputbuffer >> ichCurr.Resources.VirtualAddress;
30 inputbuffer >> ichCurr.Resources.Size;
31 inputbuffer >> ichCurr.StrongNameSignature.VirtualAddress;
32 inputbuffer >> ichCurr.StrongNameSignature.Size;
33 inputbuffer >> ichCurr.CodeManagerTable.VirtualAddress;
34 inputbuffer >> ichCurr.CodeManagerTable.Size;
35 inputbuffer >> ichCurr.VTableFixups.VirtualAddress;
36 inputbuffer >> ichCurr.VTableFixups.Size;
37 inputbuffer >> ichCurr.ExportAddressTableJumps.VirtualAddress;
38 inputbuffer >> ichCurr.ExportAddressTableJumps.Size;
39 inputbuffer >> ichCurr.ManagedNativeHeader.VirtualAddress;
40 inputbuffer >> ichCurr.ManagedNativeHeader.Size;
41
42 std::swap(ichCurr, m_ichComHeader);
43 }
44
45 int ComHeaderDirectory::read(unsigned char* buffer, unsigned int buffersize)
46 {
47 if (buffersize < PELIB_IMAGE_COR20_HEADER::size())
48 {
49 return ERROR_INVALID_FILE;
50 }
51
52 std::vector<byte> vComDescDirectory(buffer, buffer + buffersize);
53
54 InputBuffer ibBuffer(vComDescDirectory);
55 read(ibBuffer);
56 return NO_ERROR;
57 }
58
59 /**
60 * Reads a file's COM+ descriptor.
61 * @param strFilename Name of the file.
62 * @param uiOffset File offset of the COM+ descriptor.
63 * @param uiSize Size of the COM+ descriptor.
64 **/
65 int ComHeaderDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize)
66 {
67 std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
68 unsigned int ulFileSize = fileSize(ifFile);
69
70 if (!ifFile)
71 {
72 return ERROR_OPENING_FILE;
73 }
74
75 if (ulFileSize < uiOffset + uiSize)
76 {
77 return ERROR_INVALID_FILE;
78 }
79
80 ifFile.seekg(uiOffset, std::ios::beg);
81
82 std::vector<byte> vComDescDirectory(uiSize);
83 ifFile.read(reinterpret_cast<char*>(&vComDescDirectory[0]), uiSize);
84
85 InputBuffer ibBuffer(vComDescDirectory);
86 read(ibBuffer);
87 return NO_ERROR;
88 }
89
90 /**
91 * Rebuilds the current COM+ descriptor.
92 * @param vBuffer Buffer where the COM+ descriptor will be written to.
93 **/
94 void ComHeaderDirectory::rebuild(std::vector<byte>& vBuffer) const
95 {
96 OutputBuffer obBuffer(vBuffer);
97
98 obBuffer << m_ichComHeader.cb;
99 obBuffer << m_ichComHeader.MajorRuntimeVersion;
100 obBuffer << m_ichComHeader.MinorRuntimeVersion;
101 obBuffer << m_ichComHeader.MetaData.VirtualAddress;
102 obBuffer << m_ichComHeader.MetaData.Size;
103 obBuffer << m_ichComHeader.Flags;
104 obBuffer << m_ichComHeader.EntryPointToken;
105 obBuffer << m_ichComHeader.Resources.VirtualAddress;
106 obBuffer << m_ichComHeader.Resources.Size;
107 obBuffer << m_ichComHeader.StrongNameSignature.VirtualAddress;
108 obBuffer << m_ichComHeader.StrongNameSignature.Size;
109 obBuffer << m_ichComHeader.CodeManagerTable.VirtualAddress;
110 obBuffer << m_ichComHeader.CodeManagerTable.Size;
111 obBuffer << m_ichComHeader.VTableFixups.VirtualAddress;
112 obBuffer << m_ichComHeader.VTableFixups.Size;
113 obBuffer << m_ichComHeader.ExportAddressTableJumps.VirtualAddress;
114 obBuffer << m_ichComHeader.ExportAddressTableJumps.Size;
115 obBuffer << m_ichComHeader.ManagedNativeHeader.VirtualAddress;
116 obBuffer << m_ichComHeader.ManagedNativeHeader.Size;
117 }
118
119 /**
120 * @return Size in bytes.
121 **/
122 unsigned int ComHeaderDirectory::size() const
123 {
124 return PELIB_IMAGE_COR20_HEADER::size();
125 }
126
127 /**
128 * @param strFilename Name of the file.
129 * @param dwOffset File offset the COM+ descriptor will be written to.
130 **/
131 int ComHeaderDirectory::write(const std::string& strFilename, unsigned int dwOffset) const
132 {
133 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
134
135 if (!ofFile)
136 {
137 ofFile.clear();
138 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
139 }
140 else
141 {
142 ofFile.close();
143 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
144 }
145
146 if (!ofFile)
147 {
148 return ERROR_OPENING_FILE;
149 }
150
151 ofFile.seekp(dwOffset, std::ios::beg);
152
153 std::vector<unsigned char> vBuffer;
154 rebuild(vBuffer);
155
156 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
157
158 ofFile.close();
159
160 return NO_ERROR;
161 }
162
163 /**
164 * @return SizeOfHeader value of the current COM+ descriptor.
165 **/
166 dword ComHeaderDirectory::getSizeOfHeader() const
167 {
168 return m_ichComHeader.cb;
169 }
170
171 /**
172 * @return MajorRuntimeVersion value of the current COM+ descriptor.
173 **/
174 word ComHeaderDirectory::getMajorRuntimeVersion() const
175 {
176 return m_ichComHeader.MajorRuntimeVersion;
177 }
178
179 /**
180 * @return MinorRuntimeVersion value of the current COM+ descriptor.
181 **/
182 word ComHeaderDirectory::getMinorRuntimeVersion() const
183 {
184 return m_ichComHeader.MinorRuntimeVersion;
185 }
186
187 /**
188 * @return MetaData (Virtual Address) value of the current COM+ descriptor.
189 **/
190 dword ComHeaderDirectory::getMetaDataVa() const
191 {
192 return m_ichComHeader.MetaData.VirtualAddress;
193 }
194
195 /**
196 * @return MetaData (Size) value of the current COM+ descriptor.
197 **/
198 dword ComHeaderDirectory::getMetaDataSize() const
199 {
200 return m_ichComHeader.MetaData.Size;
201 }
202
203 /**
204 * @return Flags value of the current COM+ descriptor.
205 **/
206 dword ComHeaderDirectory::getFlags() const
207 {
208 return m_ichComHeader.Flags;
209 }
210
211 /**
212 * @return EntryPointToken value of the current COM+ descriptor.
213 **/
214 dword ComHeaderDirectory::getEntryPointToken() const
215 {
216 return m_ichComHeader.EntryPointToken;
217 }
218
219 /**
220 * @return Resources (Virtual Address) value of the current COM+ descriptor.
221 **/
222 dword ComHeaderDirectory::getResourcesVa() const
223 {
224 return m_ichComHeader.Resources.VirtualAddress;
225 }
226
227 /**
228 * @return Resources (Size) value of the current COM+ descriptor.
229 **/
230 dword ComHeaderDirectory::getResourcesSize()
231 {
232 return m_ichComHeader.Resources.Size;
233 }
234
235 /**
236 * @return StrongNameSignature (Virtual Address) value of the current COM+ descriptor.
237 **/
238 dword ComHeaderDirectory::getStrongNameSignatureVa() const
239 {
240 return m_ichComHeader.StrongNameSignature.VirtualAddress;
241 }
242
243 /**
244 * @return StrongNameSignature (Size) value of the current COM+ descriptor.
245 **/
246 dword ComHeaderDirectory::getStrongNameSignagureSize() const
247 {
248 return m_ichComHeader.StrongNameSignature.Size;
249 }
250
251 /**
252 * @return CodeManagerTable (Virtual Address) value of the current COM+ descriptor.
253 **/
254 dword ComHeaderDirectory::getCodeManagerTableVa() const
255 {
256 return m_ichComHeader.CodeManagerTable.VirtualAddress;
257 }
258
259 /**
260 * @return CodeManagerTable (Size) value of the current COM+ descriptor.
261 **/
262 dword ComHeaderDirectory::getCodeManagerTableSize() const
263 {
264 return m_ichComHeader.CodeManagerTable.Size;
265 }
266
267 /**
268 * @return VTableFixups (Virtual Address) value of the current COM+ descriptor.
269 **/
270 dword ComHeaderDirectory::getVTableFixupsVa() const
271 {
272 return m_ichComHeader.VTableFixups.VirtualAddress;
273 }
274
275 /**
276 * @return VTableFixups (Size) value of the current COM+ descriptor.
277 **/
278 dword ComHeaderDirectory::getVTableFixupsSize() const
279 {
280 return m_ichComHeader.VTableFixups.Size;
281 }
282
283 /**
284 * @return ExportAddressTableJumps (Virtual Address) value of the current COM+ descriptor.
285 **/
286 dword ComHeaderDirectory::getExportAddressTableJumpsVa() const
287 {
288 return m_ichComHeader.ExportAddressTableJumps.VirtualAddress;
289 }
290
291 /**
292 * @return ExportAddressTableJumps (Size) value of the current COM+ descriptor.
293 **/
294 dword ComHeaderDirectory::getExportAddressTableJumpsSize() const
295 {
296 return m_ichComHeader.ExportAddressTableJumps.Size;
297 }
298
299 /**
300 * @return ManagedNativeHeader (Virtual Address) value of the current COM+ descriptor.
301 **/
302 dword ComHeaderDirectory::getManagedNativeHeaderVa() const
303 {
304 return m_ichComHeader.ManagedNativeHeader.VirtualAddress;
305 }
306
307 /**
308 * @return ManagedNativeHeader (Size) value of the current COM+ descriptor.
309 **/
310 dword ComHeaderDirectory::getManagedNativeHeaderSize() const
311 {
312 return m_ichComHeader.ManagedNativeHeader.Size;
313 }
314
315 /**
316 * @param dwValue New value for the current SizeOfHeader (cb) value.
317 **/
318 void ComHeaderDirectory::setSizeOfHeader(dword dwValue)
319 {
320 m_ichComHeader.cb = dwValue;
321 }
322
323 /**
324 * @param wValue New value for the current MajorRuntimeVersion value.
325 **/
326 void ComHeaderDirectory::setMajorRuntimeVersion(word wValue)
327 {
328 m_ichComHeader.MajorRuntimeVersion = wValue;
329 }
330
331 /**
332 * @param wValue New value for the current MinorRuntimeVersion value.
333 **/
334 void ComHeaderDirectory::setMinorRuntimeVersion(word wValue)
335 {
336 m_ichComHeader.MinorRuntimeVersion = wValue;
337 }
338
339 /**
340 * @param dwValue New value for the current MetaData (VirtualAddress) value.
341 **/
342 void ComHeaderDirectory::setMetaDataVa(dword dwValue)
343 {
344 m_ichComHeader.MetaData.VirtualAddress = dwValue;
345 }
346
347 /**
348 * @param dwValue New value for the current MetaData (Size) value.
349 **/
350 void ComHeaderDirectory::setMetaDataSize(dword dwValue)
351 {
352 m_ichComHeader.MetaData.Size = dwValue;
353 }
354
355 /**
356 * @param dwValue New value for the current Flags value.
357 **/
358 void ComHeaderDirectory::setFlags(dword dwValue)
359 {
360 m_ichComHeader.Flags = dwValue;
361 }
362
363 /**
364 * @param dwValue New value for the current EntryPointToken value.
365 **/
366 void ComHeaderDirectory::setEntryPointToken(dword dwValue)
367 {
368 m_ichComHeader.EntryPointToken = dwValue;
369 }
370
371 /**
372 * @param dwValue New value for the current Resources (VirtualAddress) value.
373 **/
374 void ComHeaderDirectory::setResourcesVa(dword dwValue)
375 {
376 m_ichComHeader.Resources.VirtualAddress = dwValue;
377 }
378
379 /**
380 * @param dwValue New value for the current Resources (Size) value.
381 **/
382 void ComHeaderDirectory::setResourcesSize(dword dwValue)
383 {
384 m_ichComHeader.Resources.Size = dwValue;
385 }
386
387 /**
388 * @param dwValue New value for the current StrongNameSignature (VirtualAddress) value.
389 **/
390 void ComHeaderDirectory::setStrongNameSignatureVa(dword dwValue)
391 {
392 m_ichComHeader.StrongNameSignature.VirtualAddress = dwValue;
393 }
394
395 /**
396 * @param dwValue New value for the current StrongNameSignature (Size) value.
397 **/
398 void ComHeaderDirectory::setStrongNameSignagureSize(dword dwValue)
399 {
400 m_ichComHeader.StrongNameSignature.Size = dwValue;
401 }
402
403 /**
404 * @param dwValue New value for the current CodeManagerTable (VirtualAddress) value.
405 **/
406 void ComHeaderDirectory::setCodeManagerTableVa(dword dwValue)
407 {
408 m_ichComHeader.CodeManagerTable.VirtualAddress = dwValue;
409 }
410
411 /**
412 * @param dwValue New value for the current CodeManagerTable (Size) value.
413 **/
414 void ComHeaderDirectory::setCodeManagerTableSize(dword dwValue)
415 {
416 m_ichComHeader.CodeManagerTable.Size = dwValue;
417 }
418
419 /**
420 * @param dwValue New value for the current VTableFixups (VirtualAddress) value.
421 **/
422 void ComHeaderDirectory::setVTableFixupsVa(dword dwValue)
423 {
424 m_ichComHeader.VTableFixups.VirtualAddress = dwValue;
425 }
426
427 /**
428 * @param dwValue New value for the current VTableFixups (Size) value.
429 **/
430 void ComHeaderDirectory::setVTableFixupsSize(dword dwValue)
431 {
432 m_ichComHeader.VTableFixups.Size = dwValue;
433 }
434
435 /**
436 * @param dwValue New value for the current ExportAddressTableJumps (VirtualAddress) value.
437 **/
438 void ComHeaderDirectory::setExportAddressTableJumpsVa(dword dwValue)
439 {
440 m_ichComHeader.ExportAddressTableJumps.VirtualAddress = dwValue;
441 }
442
443 /**
444 * @param dwValue New value for the current ExportAddressTableJumps (Size) value.
445 **/
446 void ComHeaderDirectory::setExportAddressTableJumpsSize(dword dwValue)
447 {
448 m_ichComHeader.ExportAddressTableJumps.Size = dwValue;
449 }
450
451 /**
452 * @param dwValue New value for the current ManagedNativeHeader (VirtualAddress) value.
453 **/
454 void ComHeaderDirectory::setManagedNativeHeaderVa(dword dwValue)
455 {
456 m_ichComHeader.ManagedNativeHeader.VirtualAddress = dwValue;
457 }
458
459 /**
460 * @param dwValue New value for the current ManagedNativeHeader (Size) value.
461 **/
462 void ComHeaderDirectory::setManagedNativeHeaderSize(dword dwValue)
463 {
464 m_ichComHeader.ManagedNativeHeader.Size = dwValue;
465 }
466
467}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.h
new file mode 100755
index 0000000000..915813c1cc
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.h
@@ -0,0 +1,120 @@
1/*
2* ComHeaderDirectory.h - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#ifndef COMHEADERDIRECTORY_H
14#define COMHEADERDIRECTORY_H
15
16namespace PeLib
17{
18 /// Class that handles the COM+ descriptor directory.
19 /**
20 * This class handles the COM+ Descriptor directory which was added to PE files
21 * which work with the .NET runtime modules.
22 **/
23 class ComHeaderDirectory
24 {
25 private:
26 PELIB_IMAGE_COR20_HEADER m_ichComHeader; ///< The COM+ descriptor.
27
28 void read(InputBuffer& inputbuffer);
29
30 public:
31 /// Read a file's COM+ runtime descriptor directory.
32 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize); // EXPORT
33 int read(unsigned char* buffer, unsigned int buffersize); // EXPORT
34 /// Rebuild the COM+ descriptor.
35 void rebuild(std::vector<byte>& vBuffer) const; // EXPORT
36 /// Returns the size of the current COM+ descriptor.
37 unsigned int size() const; // EXPORT
38 /// Writes the current COM+ descriptor directory to a file.
39 int write(const std::string& strFilename, unsigned int dwOffset) const; // EXPORT
40
41 /// Get the COM+ descriptor's SizeOfHeader (cb) value.
42 dword getSizeOfHeader() const; // EXPORT
43 /// Get the COM+ descriptor's MajorRuntimeVersion value.
44 word getMajorRuntimeVersion() const; // EXPORT
45 /// Get the COM+ descriptor's MinorRuntimeVersion value.
46 word getMinorRuntimeVersion() const; // EXPORT
47 /// Get the COM+ descriptor's MetaData (Virtual Address) value.
48 dword getMetaDataVa() const; // EXPORT
49 /// Get the COM+ descriptor's MetaData (Size) value.
50 dword getMetaDataSize() const; // EXPORT
51 /// Get the COM+ descriptor's Flags value.
52 dword getFlags() const; // EXPORT
53 /// Get the COM+ descriptor's EntryPointToken value.
54 dword getEntryPointToken() const; // EXPORT
55 /// Get the COM+ descriptor's Resources (Virtual Address) value.
56 dword getResourcesVa() const; // EXPORT
57 /// Get the COM+ descriptor's Resources (Size) value.
58 dword getResourcesSize(); // EXPORT
59 /// Get the COM+ descriptor's StrongNameSignature (Virtual Address) value.
60 dword getStrongNameSignatureVa() const; // EXPORT
61 /// Get the COM+ descriptor's StrongNameSignature (Size) value.
62 dword getStrongNameSignagureSize() const; // EXPORT
63 /// Get the COM+ descriptor's CodeManagerTable (Virtual Address) value.
64 dword getCodeManagerTableVa() const; // EXPORT
65 /// Get the COM+ descriptor's CodeManagerTable (Size) value.
66 dword getCodeManagerTableSize() const; // EXPORT
67 /// Get the COM+ descriptor's VTableFixup (Virtual Address) value.
68 dword getVTableFixupsVa() const; // EXPORT
69 /// Get the COM+ descriptor's VTableFixup (Size) value.
70 dword getVTableFixupsSize() const; // EXPORT
71 /// Get the COM+ descriptor's ExportAddressTable (Virtual Address) value.
72 dword getExportAddressTableJumpsVa() const; // EXPORT
73 /// Get the COM+ descriptor's ExportAddressTable (Size) value.
74 dword getExportAddressTableJumpsSize() const; // EXPORT
75 /// Get the COM+ descriptor's ManagedNativeHeader (Virtual Address) value.
76 dword getManagedNativeHeaderVa() const; // EXPORT
77 /// Get the COM+ descriptor's ManagedNativeHeader (Size) value.
78 dword getManagedNativeHeaderSize() const; // EXPORT
79
80 /// Change the COM+ descriptor's SizeOfHeader (cb) value.
81 void setSizeOfHeader(dword dwValue); // EXPORT
82 /// Change the COM+ descriptor's MajorRuntimeVersion value.
83 void setMajorRuntimeVersion(word wValue); // EXPORT
84 /// Change the COM+ descriptor's MinorRuntimeVersion value.
85 void setMinorRuntimeVersion(word wValue); // EXPORT
86 /// Change the COM+ descriptor's MetaData (VirtualAddress) value.
87 void setMetaDataVa(dword dwValue); // EXPORT
88 /// Change the COM+ descriptor's MetaData (Size) value.
89 void setMetaDataSize(dword dwValue); // EXPORT
90 /// Change the COM+ descriptor's Flags value.
91 void setFlags(dword dwValue); // EXPORT
92 /// Change the COM+ descriptor's EntryPointToken value.
93 void setEntryPointToken(dword dwValue); // EXPORT
94 /// Change the COM+ descriptor's Resources (VirtualAddress) value.
95 void setResourcesVa(dword dwValue); // EXPORT
96 /// Change the COM+ descriptor's Resources (Size) value.
97 void setResourcesSize(dword dwValue); // EXPORT
98 /// Change the COM+ descriptor's StrongNameSignatureVa (VirtualAddress) value.
99 void setStrongNameSignatureVa(dword dwValue); // EXPORT
100 /// Change the COM+ descriptor's StrongNameSignatureVa (Size) value.
101 void setStrongNameSignagureSize(dword dwValue); // EXPORT
102 /// Change the COM+ descriptor's CodeManagerTable (VirtualAddress) value.
103 void setCodeManagerTableVa(dword dwValue); // EXPORT
104 /// Change the COM+ descriptor's CodeManagerTable (Size) value.
105 void setCodeManagerTableSize(dword dwValue); // EXPORT
106 /// Change the COM+ descriptor's VTableFixups (VirtualAddress) value.
107 void setVTableFixupsVa(dword dwValue); // EXPORT
108 /// Change the COM+ descriptor's VTableFixups (Size) value.
109 void setVTableFixupsSize(dword dwValue); // EXPORT
110 /// Change the COM+ descriptor's ExportAddressTableJumps (VirtualAddress) value.
111 void setExportAddressTableJumpsVa(dword dwValue); // EXPORT
112 /// Change the COM+ descriptor's ExportAddressTableJumps (Size) value.
113 void setExportAddressTableJumpsSize(dword dwValue); // EXPORT
114 /// Change the COM+ descriptor's ManagedNativeHeader (VirtualAddress) value.
115 void setManagedNativeHeaderVa(dword dwValue); // EXPORT
116 /// Change the COM+ descriptor's ManagedNativeHeader (Size) value.
117 void setManagedNativeHeaderSize(dword dwValue); // EXPORT
118 };
119}
120#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.cpp
new file mode 100755
index 0000000000..eb3d5c5600
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.cpp
@@ -0,0 +1,383 @@
1/*
2* DebugDirectory.cpp - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#include "PeLibInc.h"
14#include "DebugDirectory.h"
15
16namespace PeLib
17{
18 void DebugDirectory::clear()
19 {
20 m_vDebugInfo.clear();
21 }
22
23 std::vector<PELIB_IMG_DEBUG_DIRECTORY> DebugDirectory::read(InputBuffer& ibBuffer, unsigned int uiSize)
24 {
25 std::vector<PELIB_IMG_DEBUG_DIRECTORY> currDebugInfo;
26
27 PELIB_IMG_DEBUG_DIRECTORY iddCurr;
28
29 for (unsigned int i=0;i<uiSize/PELIB_IMAGE_DEBUG_DIRECTORY::size();i++)
30 {
31
32 ibBuffer >> iddCurr.idd.Characteristics;
33 ibBuffer >> iddCurr.idd.TimeDateStamp;
34 ibBuffer >> iddCurr.idd.MajorVersion;
35 ibBuffer >> iddCurr.idd.MinorVersion;
36 ibBuffer >> iddCurr.idd.Type;
37 ibBuffer >> iddCurr.idd.SizeOfData;
38 ibBuffer >> iddCurr.idd.AddressOfRawData;
39 ibBuffer >> iddCurr.idd.PointerToRawData;
40
41 currDebugInfo.push_back(iddCurr);
42 }
43
44 return currDebugInfo;
45 }
46
47 int DebugDirectory::read(unsigned char* buffer, unsigned int buffersize)
48 {
49 // XXX: Note, debug data is not read at all. This might or might not change
50 // in the future.
51
52 std::vector<byte> vDebugDirectory(buffer, buffer + buffersize);
53
54 InputBuffer ibBuffer(vDebugDirectory);
55
56 std::vector<PELIB_IMG_DEBUG_DIRECTORY> currDebugInfo = read(ibBuffer, buffersize);
57
58 std::swap(currDebugInfo, m_vDebugInfo);
59
60 return NO_ERROR;
61 }
62
63 /**
64 * @param strFilename Name of the file which will be read.
65 * @param uiOffset File offset of the Debug directory.
66 * @param uiSize Size of the Debug directory.
67 **/
68 int DebugDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize)
69 {
70 std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
71 unsigned int ulFileSize = fileSize(ifFile);
72
73 if (!ifFile)
74 {
75 return ERROR_OPENING_FILE;
76 }
77
78 if (ulFileSize < uiOffset + uiSize)
79 {
80 return ERROR_INVALID_FILE;
81 }
82
83 ifFile.seekg(uiOffset, std::ios::beg);
84
85 std::vector<byte> vDebugDirectory(uiSize);
86 ifFile.read(reinterpret_cast<char*>(&vDebugDirectory[0]), uiSize);
87
88 InputBuffer ibBuffer(vDebugDirectory);
89
90 std::vector<PELIB_IMG_DEBUG_DIRECTORY> currDebugInfo = read(ibBuffer, uiSize);
91
92 for (unsigned int i=0;i<currDebugInfo.size();i++)
93 {
94 ifFile.seekg(currDebugInfo[i].idd.PointerToRawData, std::ios::beg);
95 currDebugInfo[i].data.resize(currDebugInfo[i].idd.SizeOfData);
96 ifFile.read(reinterpret_cast<char*>(&currDebugInfo[i].data[0]), currDebugInfo[i].idd.SizeOfData);
97 if (!ifFile) return ERROR_INVALID_FILE;
98 }
99
100 std::swap(currDebugInfo, m_vDebugInfo);
101
102 return NO_ERROR;
103 }
104
105 /**
106 * Rebuilds the current debug directory.
107 * @param vBuffer Buffer where the rebuilt directory is stored.
108 **/
109 void DebugDirectory::rebuild(std::vector<byte>& vBuffer) const
110 {
111 OutputBuffer obBuffer(vBuffer);
112
113 for (unsigned int i=0;i<m_vDebugInfo.size();i++)
114 {
115 obBuffer << m_vDebugInfo[i].idd.Characteristics;
116 obBuffer << m_vDebugInfo[i].idd.TimeDateStamp;
117 obBuffer << m_vDebugInfo[i].idd.MajorVersion;
118 obBuffer << m_vDebugInfo[i].idd.MinorVersion;
119 obBuffer << m_vDebugInfo[i].idd.Type;
120 obBuffer << m_vDebugInfo[i].idd.SizeOfData;
121 obBuffer << m_vDebugInfo[i].idd.AddressOfRawData;
122 obBuffer << m_vDebugInfo[i].idd.PointerToRawData;
123 }
124 }
125
126 /**
127 * @return Size of the debug directory.
128 **/
129 unsigned int DebugDirectory::size() const
130 {
131 return static_cast<unsigned int>(m_vDebugInfo.size()) * PELIB_IMAGE_DEBUG_DIRECTORY::size();
132 }
133
134 /**
135 * @param strFilename Name of the file which will be written.
136 * @param uiOffset File offset where the debug directory will be stored.
137 **/
138 int DebugDirectory::write(const std::string& strFilename, unsigned int uiOffset) const
139 {
140 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
141
142 if (!ofFile)
143 {
144 ofFile.clear();
145 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
146 }
147 else
148 {
149 ofFile.close();
150 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
151 }
152
153 if (!ofFile)
154 {
155 return ERROR_OPENING_FILE;
156 }
157
158 ofFile.seekp(uiOffset, std::ios::beg);
159
160 std::vector<unsigned char> vBuffer;
161 rebuild(vBuffer);
162
163 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
164
165 ofFile.close();
166
167 return NO_ERROR;
168 }
169
170 /**
171 * @return Number of debug structures in the current Debug directory.
172 **/
173 unsigned int DebugDirectory::calcNumberOfEntries() const
174 {
175 return static_cast<unsigned int>(m_vDebugInfo.size());
176 }
177
178 /**
179 * Adds a new debug structure to the debug directory. The initial values of all members of the structure
180 * are undefined.
181 **/
182 void DebugDirectory::addEntry()
183 {
184 PELIB_IMG_DEBUG_DIRECTORY p;
185 m_vDebugInfo.push_back(p);
186 }
187
188 /**
189 * Removes a debug structure from the current debug directory. If an invalid structure is specified
190 * by the parameter uiIndex the result will be undefined behaviour.
191 * @param uiIndex Identifies the debug structure.
192 **/
193 void DebugDirectory::removeEntry(unsigned int uiIndex)
194 {
195 m_vDebugInfo.erase(m_vDebugInfo.begin() + uiIndex);
196 }
197
198 /**
199 * Returns the Characteristics value of a debug structure. If an invalid structure is specified
200 * by the parameter uiIndex the result will be undefined behaviour.
201 * @param uiIndex Identifies the debug structure.
202 * @return Characteristics value of the debug structure.
203 **/
204 dword DebugDirectory::getCharacteristics(unsigned int uiIndex) const
205 {
206 return m_vDebugInfo[uiIndex].idd.Characteristics;
207 }
208
209 /**
210 * Returns the TimeDateStamp value of a debug structure. If an invalid structure is specified
211 * by the parameter uiIndex the result will be undefined behaviour.
212 * @param uiIndex Identifies the debug structure.
213 * @return TimeDateStamp value of the debug structure.
214 **/
215 dword DebugDirectory::getTimeDateStamp(unsigned int uiIndex) const
216 {
217 return m_vDebugInfo[uiIndex].idd.TimeDateStamp;
218 }
219
220 /**
221 * Returns the MajorVersion value of a debug structure. If an invalid structure is specified
222 * by the parameter uiIndex the result will be undefined behaviour.
223 * @param uiIndex Identifies the debug structure.
224 * @return MajorVersion value of the debug structure.
225 **/
226 word DebugDirectory::getMajorVersion(unsigned int uiIndex) const
227 {
228 return m_vDebugInfo[uiIndex].idd.MajorVersion;
229 }
230
231 /**
232 * Returns the MinorVersion value of a debug structure. If an invalid structure is specified
233 * by the parameter uiIndex the result will be undefined behaviour.
234 * @param uiIndex Identifies the debug structure.
235 * @return MinorVersion value of the debug structure.
236 **/
237 word DebugDirectory::getMinorVersion(unsigned int uiIndex) const
238 {
239 return m_vDebugInfo[uiIndex].idd.MinorVersion;
240 }
241
242 /**
243 * Returns the Type value of a debug structure. If an invalid structure is specified
244 * by the parameter uiIndex the result will be undefined behaviour.
245 * @param uiIndex Identifies the debug structure.
246 * @return Type value of the debug structure.
247 **/
248 dword DebugDirectory::getType(unsigned int uiIndex) const
249 {
250 return m_vDebugInfo[uiIndex].idd.Type;
251 }
252
253 /**
254 * Returns the SizeOfData value of a debug structure. If an invalid structure is specified
255 * by the parameter uiIndex the result will be undefined behaviour.
256 * @param uiIndex Identifies the debug structure.
257 * @return SizeOfData value of the debug structure.
258 **/
259 dword DebugDirectory::getSizeOfData(unsigned int uiIndex) const
260 {
261 return m_vDebugInfo[uiIndex].idd.SizeOfData;
262 }
263
264 /**
265 * Returns the AddressOfRawData value of a debug structure. If an invalid structure is specified
266 * by the parameter uiIndex the result will be undefined behaviour.
267 * @param uiIndex Identifies the debug structure.
268 * @return AddressOfRawData value of the debug structure.
269 **/
270 dword DebugDirectory::getAddressOfRawData(unsigned int uiIndex) const
271 {
272 return m_vDebugInfo[uiIndex].idd.AddressOfRawData;
273 }
274
275 /**
276 * Returns the PointerToRawData value of a debug structure. If an invalid structure is specified
277 * by the parameter uiIndex the result will be undefined behaviour.
278 * @param uiIndex Identifies the debug structure.
279 * @return PointerToRawData value of the debug structure.
280 **/
281 dword DebugDirectory::getPointerToRawData(unsigned int uiIndex) const
282 {
283 return m_vDebugInfo[uiIndex].idd.PointerToRawData;
284 }
285
286 std::vector<byte> DebugDirectory::getData(unsigned int index) const
287 {
288 return m_vDebugInfo[index].data;
289 }
290
291 /**
292 * Changes the Characteristics value of a debug structure. If an invalid structure is specified
293 * by the parameter uiIndex the result will be undefined behaviour.
294 * @param uiIndex Identifies the debug structure.
295 * @param dwValue New value of the Characteristics value of the debug structure.
296 **/
297 void DebugDirectory::setCharacteristics(unsigned int uiIndex, dword dwValue)
298 {
299 m_vDebugInfo[uiIndex].idd.Characteristics = dwValue;
300 }
301
302 /**
303 * Changes the TimeDateStamp value of a debug structure. If an invalid structure is specified
304 * by the parameter uiIndex the result will be undefined behaviour.
305 * @param uiIndex Identifies the debug structure.
306 * @param dwValue New value of the TimeDateStamp value of the debug structure.
307 **/
308 void DebugDirectory::setTimeDateStamp(unsigned int uiIndex, dword dwValue)
309 {
310 m_vDebugInfo[uiIndex].idd.TimeDateStamp = dwValue;
311 }
312
313 /**
314 * Changes the MajorVersion value of a debug structure. If an invalid structure is specified
315 * by the parameter uiIndex the result will be undefined behaviour.
316 * @param uiIndex Identifies the debug structure.
317 * @param wValue New value of the MajorVersion value of the debug structure.
318 **/
319 void DebugDirectory::setMajorVersion(unsigned int uiIndex, word wValue)
320 {
321 m_vDebugInfo[uiIndex].idd.MajorVersion = wValue;
322 }
323
324 /**
325 * Changes the MinorVersion value of a debug structure. If an invalid structure is specified
326 * by the parameter uiIndex the result will be undefined behaviour.
327 * @param uiIndex Identifies the debug structure.
328 * @param wValue New value of the MinorVersion value of the debug structure.
329 **/
330 void DebugDirectory::setMinorVersion(unsigned int uiIndex, word wValue)
331 {
332 m_vDebugInfo[uiIndex].idd.MinorVersion = wValue;
333 }
334
335 /**
336 * Changes the Type value of a debug structure. If an invalid structure is specified
337 * by the parameter uiIndex the result will be undefined behaviour.
338 * @param uiIndex Identifies the debug structure.
339 * @param dwValue New value of the Type value of the debug structure.
340 **/
341 void DebugDirectory::setType(unsigned int uiIndex, dword dwValue)
342 {
343 m_vDebugInfo[uiIndex].idd.Type = dwValue;
344 }
345
346 /**
347 * Changes the SizeOfData value of a debug structure. If an invalid structure is specified
348 * by the parameter uiIndex the result will be undefined behaviour.
349 * @param uiIndex Identifies the debug structure.
350 * @param dwValue New value of the SizeOfData value of the debug structure.
351 **/
352 void DebugDirectory::setSizeOfData(unsigned int uiIndex, dword dwValue)
353 {
354 m_vDebugInfo[uiIndex].idd.SizeOfData = dwValue;
355 }
356
357 /**
358 * Changes the AddressOfRawData value of a debug structure. If an invalid structure is specified
359 * by the parameter uiIndex the result will be undefined behaviour.
360 * @param uiIndex Identifies the debug structure.
361 * @param dwValue New value of the AddressOfRawData value of the debug structure.
362 **/
363 void DebugDirectory::setAddressOfRawData(unsigned int uiIndex, dword dwValue)
364 {
365 m_vDebugInfo[uiIndex].idd.AddressOfRawData = dwValue;
366 }
367
368 /**
369 * Changes the PointerToRawData value of a debug structure. If an invalid structure is specified
370 * by the parameter uiIndex the result will be undefined behaviour.
371 * @param uiIndex Identifies the debug structure.
372 * @param dwValue New value of the PointerToRawData value of the debug structure.
373 **/
374 void DebugDirectory::setPointerToRawData(unsigned int uiIndex, dword dwValue)
375 {
376 m_vDebugInfo[uiIndex].idd.PointerToRawData = dwValue;
377 }
378
379 void DebugDirectory::setData(unsigned int index, const std::vector<byte>& data)
380 {
381 m_vDebugInfo[index].data = data;
382 }
383}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.h
new file mode 100755
index 0000000000..0ffda38815
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.h
@@ -0,0 +1,84 @@
1/*
2* DebugDirectory.h - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#ifndef DEBUGDIRECTORY_H
14#define DEBUGDIRECTORY_H
15
16namespace PeLib
17{
18 /// Class that handles the Debug directory.
19 class DebugDirectory
20 {
21 private:
22 /// Stores the various DebugDirectory structures.
23 std::vector<PELIB_IMG_DEBUG_DIRECTORY> m_vDebugInfo;
24
25 std::vector<PELIB_IMG_DEBUG_DIRECTORY> read(InputBuffer& ibBuffer, unsigned int uiSize);
26
27 public:
28 void clear(); // EXPORT
29 /// Reads the Debug directory from a file.
30 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize); // EXPORT
31 int read(unsigned char* buffer, unsigned int buffersize);
32 /// Rebuilds the current Debug directory.
33 void rebuild(std::vector<byte>& obBuffer) const; // EXPORT
34 /// Returns the size the current Debug directory needs after rebuilding.
35 unsigned int size() const;
36 /// Writes the current Debug directory back to a file.
37 int write(const std::string& strFilename, unsigned int uiOffset) const; // EXPORT
38
39 /// Returns the number of DebugDirectory image structures in the current DebugDirectory.
40 unsigned int calcNumberOfEntries() const; // EXPORT
41
42 /// Adds a new debug structure.
43 void addEntry(); // EXPORT
44 /// Removes a debug structure.
45 void removeEntry(unsigned int uiIndex); // EXPORT
46
47 /// Returns the Characteristics value of a debug structure.
48 dword getCharacteristics(unsigned int uiIndex) const; // EXPORT
49 /// Returns the TimeDateStamp value of a debug structure.
50 dword getTimeDateStamp(unsigned int uiIndex) const; // EXPORT
51 /// Returns the MajorVersion value of a debug structure.
52 word getMajorVersion(unsigned int uiIndex) const; // EXPORT
53 /// Returns the MinorVersion value of a debug structure.
54 word getMinorVersion(unsigned int uiIndex) const; // EXPORT
55 /// Returns the Type value of a debug structure.
56 dword getType(unsigned int uiIndex) const; // EXPORT
57 /// Returns the SizeOfData value of a debug structure.
58 dword getSizeOfData(unsigned int uiIndex) const; // EXPORT
59 /// Returns the AddressOfRawData value of a debug structure.
60 dword getAddressOfRawData(unsigned int uiIndex) const; // EXPORT
61 /// Returns the PointerToRawData value of a debug structure.
62 dword getPointerToRawData(unsigned int uiIndex) const; // EXPORT
63 std::vector<byte> getData(unsigned int index) const; // EXPORT
64
65 /// Sets the Characteristics value of a debug structure.
66 void setCharacteristics(unsigned int uiIndex, dword dwValue); // EXPORT
67 /// Sets the TimeDateStamp value of a debug structure.
68 void setTimeDateStamp(unsigned int uiIndex, dword dwValue); // EXPORT
69 /// Sets the MajorVersion value of a debug structure.
70 void setMajorVersion(unsigned int uiIndex, word wValue); // EXPORT
71 /// Sets the MinorVersion value of a debug structure.
72 void setMinorVersion(unsigned int uiIndex, word wValue); // EXPORT
73 /// Sets the Type value of a debug structure.
74 void setType(unsigned int uiIndex, dword dwValue); // EXPORT
75 /// Sets the SizeOfData value of a debug structure.
76 void setSizeOfData(unsigned int uiIndex, dword dwValue); // EXPORT
77 /// Sets the AddressOfRawData value of a debug structure.
78 void setAddressOfRawData(unsigned int uiIndex, dword dwValue); // EXPORT
79 /// Sets the PointerToRawData value of a debug structure.
80 void setPointerToRawData(unsigned int uiIndex, dword dwValue); // EXPORT
81 void setData(unsigned int index, const std::vector<byte>& data); // EXPORT
82 };
83}
84#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.cpp
new file mode 100755
index 0000000000..aa9c28a50f
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.cpp
@@ -0,0 +1,692 @@
1/*
2* ExportDirectory.cpp - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13//#ifdef false
14
15#include "PeLibInc.h"
16#include "ExportDirectory.h"
17
18namespace PeLib
19{
20 /**
21 * @param strFuncname Name of the function.
22 * @param dwFuncAddr RVA of the function.
23 **/
24 void ExportDirectory::addFunction(const std::string& strFuncname, dword dwFuncAddr)
25 {
26 PELIB_EXP_FUNC_INFORMATION efiCurr;
27 efiCurr.funcname = strFuncname;
28 efiCurr.addroffunc = dwFuncAddr;
29 m_ied.functions.push_back(efiCurr);
30 }
31
32 void ExportDirectory::removeFunction(unsigned int index)
33 {
34 m_ied.functions.erase(m_ied.functions.begin() + index);
35 }
36
37 void ExportDirectory::clear()
38 {
39 m_ied.functions.clear();
40 }
41
42 unsigned int ExportDirectory::calcNumberOfFunctions() const
43 {
44 return static_cast<unsigned int>(m_ied.functions.size());
45 }
46
47 /**
48 * Identifies an exported function through it's name.
49 * @param strFunctionName Name of the function
50 * @return Number which identifies the functions.
51 **/
52 int ExportDirectory::getFunctionIndex(const std::string& strFunctionName) const
53 {
54 std::vector<PELIB_EXP_FUNC_INFORMATION>::const_iterator Iter = std::find_if(m_ied.functions.begin(), m_ied.functions.end(), std::bind2nd(std::mem_fun_ref(&PELIB_EXP_FUNC_INFORMATION::equal), strFunctionName));
55
56 if (Iter == m_ied.functions.end())
57 {
58// throw Exceptions::InvalidName(ExportDirectoryId, __LINE__);
59 return -1;
60 }
61
62 return static_cast<int>(std::distance(m_ied.functions.begin(), Iter));
63 }
64
65 /**
66 * @param strFilename Name of the file.
67 * @param uiOffset File offset of the export directory.
68 * @param uiSize Size of the export directory.
69 * @param pehHeader A valid PE header which is necessary because some RVA calculations need to be done.
70 * \todo: Proper use of InputBuffer
71 **/
72 int ExportDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, const PeHeader& pehHeader)
73 {
74 std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
75
76 if (!ifFile)
77 {
78 return ERROR_OPENING_FILE;
79 }
80
81 unsigned int filesize = fileSize(ifFile);
82
83 if (filesize < uiOffset + uiSize)
84 {
85 return ERROR_INVALID_FILE;
86 }
87
88 ifFile.seekg(uiOffset, std::ios::beg);
89
90 PELIB_IMAGE_EXP_DIRECTORY iedCurr;
91
92 std::vector<unsigned char> vExportdirectory(uiSize);
93 ifFile.read(reinterpret_cast<char*>(&vExportdirectory[0]), uiSize);
94
95 InputBuffer inpBuffer(vExportdirectory);
96
97 inpBuffer >> iedCurr.ied.Characteristics;
98 inpBuffer >> iedCurr.ied.TimeDateStamp;
99 inpBuffer >> iedCurr.ied.MajorVersion;
100 inpBuffer >> iedCurr.ied.MinorVersion;
101 inpBuffer >> iedCurr.ied.Name;
102 inpBuffer >> iedCurr.ied.Base;
103 inpBuffer >> iedCurr.ied.NumberOfFunctions;
104 inpBuffer >> iedCurr.ied.NumberOfNames;
105 inpBuffer >> iedCurr.ied.AddressOfFunctions;
106 inpBuffer >> iedCurr.ied.AddressOfNames;
107 inpBuffer >> iedCurr.ied.AddressOfNameOrdinals;
108
109 if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
110 {
111 unsigned int offset = p32->rvaToOffset(iedCurr.ied.Name);
112
113 if (offset >= filesize)
114 return ERROR_INVALID_FILE;
115
116 ifFile.seekg(offset, std::ios::beg);
117 }
118 else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
119 {
120 // XXX: Files might be > 4 GB
121 unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.Name));
122
123 if (offset >= filesize)
124 return ERROR_INVALID_FILE;
125
126 ifFile.seekg(offset, std::ios::beg);
127 }
128
129 char c = 0;
130 std::string strFname = "";
131 do
132 {
133 ifFile.read(reinterpret_cast<char*>(&c), sizeof(c));
134 if (!ifFile) return ERROR_INVALID_FILE;
135 if (c) strFname += c;
136 }
137 while (c != 0);
138 iedCurr.name = strFname;
139
140 if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
141 {
142 unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfFunctions);
143
144 if (offset >= filesize)
145 return ERROR_INVALID_FILE;
146
147 ifFile.seekg(offset, std::ios::beg);
148 }
149 else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
150 {
151 // XXX: File might be > 4 GB
152 unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfFunctions));
153
154 if (offset >= filesize)
155 return ERROR_INVALID_FILE;
156
157 ifFile.seekg(offset, std::ios::beg);
158 }
159
160 PELIB_EXP_FUNC_INFORMATION efiCurr;
161 efiCurr.ordinal = 0; efiCurr.addroffunc = 0; efiCurr.addrofname = 0;
162
163 for (unsigned int i=0;i<iedCurr.ied.NumberOfFunctions;i++)
164 {
165 if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
166 {
167 unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfFunctions) + i*sizeof(efiCurr.addroffunc);
168
169 if (offset >= filesize)
170 return ERROR_INVALID_FILE;
171
172 ifFile.seekg(offset, std::ios::beg);
173 }
174 else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
175 {
176 // XXX: File might be > 4GB
177 unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfFunctions)) + i*sizeof(efiCurr.addroffunc);
178
179 if (offset >= filesize)
180 return ERROR_INVALID_FILE;
181
182 ifFile.seekg(offset, std::ios::beg);
183 }
184
185 ifFile.read(reinterpret_cast<char*>(&efiCurr.addroffunc), sizeof(efiCurr.addroffunc));
186
187 if (!ifFile)
188 return ERROR_INVALID_FILE;
189
190 efiCurr.ordinal = i;
191 iedCurr.functions.push_back(efiCurr);
192 }
193
194 for (unsigned int i=0;i<iedCurr.ied.NumberOfNames;i++)
195 {
196 if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
197 {
198 unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfNameOrdinals) + i*sizeof(efiCurr.ordinal);
199
200 if (offset >= filesize)
201 return ERROR_INVALID_FILE;
202
203 ifFile.seekg(offset, std::ios::beg);
204 }
205 else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
206 {
207 // XXX: File might be > 4 GB
208 unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfNameOrdinals)) + i*sizeof(efiCurr.ordinal);
209
210 if (offset >= filesize)
211 return ERROR_INVALID_FILE;
212
213 ifFile.seekg(offset, std::ios::beg);
214 }
215
216 word ordinal;
217 ifFile.read(reinterpret_cast<char*>(&ordinal), sizeof(ordinal));
218
219 if (!ifFile)
220 return ERROR_INVALID_FILE;
221
222 iedCurr.functions[ordinal].ordinal = ordinal;
223
224 if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
225 {
226 unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfNames) + i*sizeof(efiCurr.addrofname);
227
228 if (offset >= filesize)
229 return ERROR_INVALID_FILE;
230
231 ifFile.seekg(offset, std::ios::beg);
232 }
233 else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
234 {
235 // XXX: File might be > 4 GB.
236 unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfNames)) + i*sizeof(efiCurr.addrofname);
237
238 if (offset >= filesize)
239 return ERROR_INVALID_FILE;
240
241 ifFile.seekg(offset, std::ios::beg);
242 }
243
244 ifFile.read(reinterpret_cast<char*>(&iedCurr.functions[ordinal].addrofname), sizeof(iedCurr.functions[ordinal].addrofname));
245
246 if (!ifFile)
247 return ERROR_INVALID_FILE;
248
249 if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
250 {
251 unsigned int offset = p32->rvaToOffset(iedCurr.functions[ordinal].addrofname);
252
253 if (offset >= filesize)
254 return ERROR_INVALID_FILE;
255
256 ifFile.seekg(offset, std::ios::beg);
257 }
258 else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
259 {
260 // XXX: File might be > 4 GB.
261 unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.functions[ordinal].addrofname));
262
263 if (offset >= filesize)
264 return ERROR_INVALID_FILE;
265
266 ifFile.seekg(static_cast<unsigned int>(p64->rvaToOffset(iedCurr.functions[ordinal].addrofname)), std::ios::beg);
267 }
268
269 char c = 0;
270 std::string strFname = "";
271 do
272 {
273 ifFile.read(reinterpret_cast<char*>(&c), sizeof(c));
274
275 if (!ifFile)
276 return ERROR_INVALID_FILE;
277
278 if (c) strFname += c;
279 }
280 while (c != 0);
281
282 iedCurr.functions[ordinal].funcname = strFname;
283 }
284
285 std::swap(m_ied, iedCurr);
286
287 return NO_ERROR;
288 }
289
290 /**
291 * @param vBuffer Buffer where the rebuilt export directory is written to.
292 * @param dwRva RVA of the export directory.
293 * \todo fValid flag
294 **/
295 void ExportDirectory::rebuild(std::vector<byte>& vBuffer, dword dwRva) const
296 {
297 unsigned int uiSizeDirectory = sizeof(PELIB_IMAGE_EXPORT_DIRECTORY);
298
299 unsigned int uiSizeNames = 0;
300 unsigned int uiSizeAddrFuncs = 0;
301 unsigned int uiSizeAddrNames = 0;
302 unsigned int uiSizeOrdinals = 0;
303
304 for (unsigned int i=0;i<m_ied.functions.size();i++)
305 {
306 uiSizeNames += (m_ied.functions[i].funcname.empty()) ? 0 : static_cast<unsigned int>(m_ied.functions[i].funcname.size()) + 1;
307 uiSizeAddrFuncs += sizeof(m_ied.functions[i].addroffunc);
308 uiSizeAddrNames += (m_ied.functions[i].funcname.empty()) ? 0 : sizeof(m_ied.functions[i].addrofname);
309 uiSizeOrdinals += (m_ied.functions[i].funcname.empty()) ? 0 : sizeof(m_ied.functions[i].ordinal);
310 }
311
312 unsigned int uiFilenameSize = static_cast<unsigned int>(m_ied.name.size()) + 1;
313
314 OutputBuffer obBuffer(vBuffer);
315
316 obBuffer << m_ied.ied.Characteristics;
317 obBuffer << m_ied.ied.TimeDateStamp;
318 obBuffer << m_ied.ied.MajorVersion;
319 obBuffer << m_ied.ied.MinorVersion;
320 obBuffer << dwRva + uiSizeDirectory;
321 obBuffer << m_ied.ied.Base;
322 obBuffer << static_cast<unsigned int>(m_ied.functions.size());
323
324 // TODO: Not correct but sufficient for now. (Update: I forgot what this comment refers to, but I'll leave it in)
325 obBuffer << static_cast<unsigned int>(m_ied.functions.size());
326 obBuffer << dwRva + uiSizeDirectory + uiFilenameSize;
327 obBuffer << dwRva + uiSizeDirectory + uiFilenameSize + uiSizeAddrFuncs;
328 obBuffer << dwRva + uiSizeDirectory + uiFilenameSize + uiSizeAddrFuncs + uiSizeAddrNames;
329
330 obBuffer.add(m_ied.name.c_str(), static_cast<unsigned int>(m_ied.name.size())+1);
331
332 for (unsigned int i=0;i<m_ied.functions.size();i++)
333 {
334 obBuffer << m_ied.functions[i].addroffunc;
335 }
336
337 unsigned int ulFuncCounter = dwRva + uiSizeDirectory + uiFilenameSize + uiSizeAddrFuncs + uiSizeAddrNames + uiSizeOrdinals;
338
339 for (unsigned int i=0;i<m_ied.functions.size();i++)
340 {
341 if (!m_ied.functions[i].funcname.empty())
342 {
343 obBuffer << ulFuncCounter;
344 ulFuncCounter += static_cast<unsigned int>(m_ied.functions[i].funcname.size()) + 1;
345 }
346 }
347
348 for (unsigned int i=0;i<m_ied.functions.size();i++)
349 {
350 if (!m_ied.functions[i].funcname.empty())
351 {
352 obBuffer << m_ied.functions[i].ordinal;
353 }
354 }
355
356 for (unsigned int i=0;i<m_ied.functions.size();i++)
357 {
358 if (m_ied.functions[i].funcname.empty() && m_ied.functions[i].addroffunc)
359 {
360 obBuffer << m_ied.functions[i].ordinal;
361 }
362 }
363
364 for (unsigned int i=0;i<m_ied.functions.size();i++)
365 {
366 if (!m_ied.functions[i].funcname.empty())
367 {
368 obBuffer.add(m_ied.functions[i].funcname.c_str(), static_cast<unsigned int>(m_ied.functions[i].funcname.size()) + 1);
369 }
370 }
371 }
372
373 /**
374 * @return Size of the current export directory.
375 **/
376 unsigned int ExportDirectory::size() const
377 {
378 return m_ied.size();
379 }
380
381 /**
382 * @param strFilename Name of the file.
383 * @param uiOffset File offset the export directory will be written to.
384 * @param uiRva RVA of the export directory.
385 * \todo Check if ofFile.write succeeded.
386 **/
387 int ExportDirectory::write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva) const
388 {
389 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
390
391 if (!ofFile)
392 {
393 ofFile.clear();
394 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
395 }
396 else
397 {
398 ofFile.close();
399 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
400 }
401
402 if (!ofFile)
403 {
404 return ERROR_OPENING_FILE;
405 }
406
407 ofFile.seekp(uiOffset, std::ios::beg);
408
409 std::vector<unsigned char> vBuffer;
410 rebuild(vBuffer, uiRva);
411
412 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
413
414 ofFile.close();
415
416 return NO_ERROR;
417 }
418
419 /**
420 * Changes the filename according to the export directory.
421 * @param strFilename New filename.
422 **/
423 void ExportDirectory::setNameString(const std::string& strFilename)
424 {
425 m_ied.name = strFilename;
426 }
427
428 std::string ExportDirectory::getNameString() const
429 {
430 return m_ied.name;
431 }
432
433 /**
434 * @param dwIndex Number which identifies an exported function.
435 * @return The name of that function.
436 **/
437 std::string ExportDirectory::getFunctionName(dword dwIndex) const
438 {
439 return m_ied.functions[dwIndex].funcname;
440 }
441
442 /**
443 * @param dwIndex Number which identifies an exported function.
444 * @return The ordinal of that function.
445 **/
446 word ExportDirectory::getFunctionOrdinal(dword dwIndex) const
447 {
448 return m_ied.functions[dwIndex].ordinal;
449 }
450
451 /**
452 * @param dwIndex Number which identifies an exported function.
453 * @return The RVA of the name string of that function.
454 **/
455 dword ExportDirectory::getAddressOfName(dword dwIndex) const
456 {
457 return m_ied.functions[dwIndex].addrofname;
458 }
459
460 /**
461 * @param dwIndex Number which identifies an exported function.
462 * @return The RVA of that function.
463 **/
464 dword ExportDirectory::getAddressOfFunction(dword dwIndex) const
465 {
466 return m_ied.functions[dwIndex].addroffunc;
467 }
468
469 /**
470 * @param dwIndex Number which identifies an exported function.
471 * @param strName The name of that function.
472 **/
473 void ExportDirectory::setFunctionName(dword dwIndex, const std::string& strName)
474 {
475 m_ied.functions[dwIndex].funcname = strName;
476 }
477
478 /**
479 * @param dwIndex Number which identifies an exported function.
480 * @param wValue The ordinal of that function.
481 **/
482 void ExportDirectory::setFunctionOrdinal(dword dwIndex, word wValue)
483 {
484 m_ied.functions[dwIndex].ordinal = wValue;
485 }
486
487 /**
488 * @param dwIndex Number which identifies an exported function.
489 * @param dwValue The RVA of the name string of that function.
490 **/
491 void ExportDirectory::setAddressOfName(dword dwIndex, dword dwValue)
492 {
493 m_ied.functions[dwIndex].addrofname = dwValue;
494 }
495
496 /**
497 * @param dwIndex Number which identifies an exported function.
498 * @param dwValue The RVA of that function.
499 **/
500 void ExportDirectory::setAddressOfFunction(dword dwIndex, dword dwValue)
501 {
502 m_ied.functions[dwIndex].addroffunc = dwValue;
503 }
504
505 /**
506 * @return The ordinal base of the export directory.
507 **/
508 dword ExportDirectory::getBase() const
509 {
510 return m_ied.ied.Base;
511 }
512
513 /**
514 * @return The characteristics of the export directory.
515 **/
516 dword ExportDirectory::getCharacteristics() const
517 {
518 return m_ied.ied.Characteristics;
519 }
520
521 /**
522 * @return The time/date stamp of the export directory.
523 **/
524 dword ExportDirectory::getTimeDateStamp() const
525 {
526 return m_ied.ied.TimeDateStamp;
527 }
528
529 /**
530 * @return The MajorVersion of the export directory.
531 **/
532 word ExportDirectory::getMajorVersion() const
533 {
534 return m_ied.ied.MajorVersion;
535 }
536
537 /**
538 * @return The MinorVersion of the export directory.
539 **/
540 word ExportDirectory::getMinorVersion() const
541 {
542 return m_ied.ied.MinorVersion;
543 }
544
545 /**
546 * @return The RVA of the name of the file.
547 **/
548 dword ExportDirectory::getName() const
549 {
550 return m_ied.ied.Name;
551 }
552
553 /**
554 * @return The NumberOfFunctions of the export directory.
555 **/
556 dword ExportDirectory::getNumberOfFunctions() const
557 {
558 return m_ied.ied.NumberOfFunctions;
559 }
560
561 /**
562 * @return The NumberOfNames of the export directory.
563 **/
564 dword ExportDirectory::getNumberOfNames() const
565 {
566 return m_ied.ied.NumberOfNames;
567 }
568
569 /**
570 * @return The AddressOfFunctions of the export directory.
571 **/
572 dword ExportDirectory::getAddressOfFunctions() const
573 {
574 return m_ied.ied.AddressOfFunctions;
575 }
576
577 /**
578 * @return The AddressOfNames of the export directory.
579 **/
580 dword ExportDirectory::getAddressOfNames() const
581 {
582 return m_ied.ied.AddressOfNames;
583 }
584
585/* dword ExportDirectory::getNumberOfNameOrdinals() const
586 {
587 return static_cast<dword>(m_ied.functions.size());
588 }
589
590 dword ExportDirectory::getNumberOfAddressOfFunctionNames() const
591 {
592 return static_cast<dword>(m_ied.functions.size());
593 }
594
595 dword ExportDirectory::getNumberOfAddressOfFunctions() const
596 {
597 return static_cast<dword>(m_ied.functions.size());
598 }
599*/
600 /**
601 * @return The AddressOfNameOrdinals of the export directory.
602 **/
603 dword ExportDirectory::getAddressOfNameOrdinals() const
604 {
605 return m_ied.ied.AddressOfNameOrdinals;
606 }
607
608 /**
609 * @param dwValue The ordinal base of the export directory.
610 **/
611 void ExportDirectory::setBase(dword dwValue)
612 {
613 m_ied.ied.Base = dwValue;
614 }
615
616 /**
617 * @param dwValue The Characteristics of the export directory.
618 **/
619 void ExportDirectory::setCharacteristics(dword dwValue)
620 {
621 m_ied.ied.Characteristics = dwValue;
622 }
623
624 /**
625 * @param dwValue The TimeDateStamp of the export directory.
626 **/
627 void ExportDirectory::setTimeDateStamp(dword dwValue)
628 {
629 m_ied.ied.TimeDateStamp = dwValue;
630 }
631
632 /**
633 * @param wValue The MajorVersion of the export directory.
634 **/
635 void ExportDirectory::setMajorVersion(word wValue)
636 {
637 m_ied.ied.MajorVersion = wValue;
638 }
639
640 /**
641 * @param wValue The MinorVersion of the export directory.
642 **/
643 void ExportDirectory::setMinorVersion(word wValue)
644 {
645 m_ied.ied.MinorVersion = wValue;
646 }
647
648 /**
649 * @param dwValue The Name of the export directory.
650 **/
651 void ExportDirectory::setName(dword dwValue)
652 {
653 m_ied.ied.Name = dwValue;
654 }
655
656 /**
657 * @param dwValue The NumberOfFunctions of the export directory.
658 **/
659 void ExportDirectory::setNumberOfFunctions(dword dwValue)
660 {
661 m_ied.ied.NumberOfFunctions = dwValue;
662 }
663
664 /**
665 * @param dwValue The NumberOfNames of the export directory.
666 **/
667 void ExportDirectory::setNumberOfNames(dword dwValue)
668 {
669 m_ied.ied.NumberOfNames = dwValue;
670 }
671
672 /**
673 * @param dwValue The AddressOfFunctions of the export directory.
674 **/
675 void ExportDirectory::setAddressOfFunctions(dword dwValue)
676 {
677 m_ied.ied.AddressOfFunctions = dwValue;
678 }
679
680 /**
681 * @param dwValue The AddressOfNames of the export directory.
682 **/
683 void ExportDirectory::setAddressOfNames(dword dwValue)
684 {
685 m_ied.ied.AddressOfNames = dwValue;
686 }
687
688 void ExportDirectory::setAddressOfNameOrdinals(dword value)
689 {
690 m_ied.ied.AddressOfNameOrdinals = value;
691 }
692}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.h
new file mode 100755
index 0000000000..17a7e57020
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.h
@@ -0,0 +1,133 @@
1/*
2* ExportDirectory.h - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#ifndef EXPORTDIRECTORY_H
14#define EXPORTDIRECTORY_H
15#include "PeHeader.h"
16
17namespace PeLib
18{
19 /// Class that handles the export directory.
20 /**
21 * This class handles the export directory.
22 * \todo getNameString
23 **/
24// template<int bits>
25 class ExportDirectory
26 {
27 private:
28 /// Used to store all necessary information about a file's exported functions.
29 PELIB_IMAGE_EXP_DIRECTORY m_ied;
30
31 public:
32 /// Add another function to be exported.
33 void addFunction(const std::string& strFuncname, dword dwFuncAddr); // EXPORT
34 unsigned int calcNumberOfFunctions() const; // EXPORT
35 void clear(); // EXPORT
36 /// Identifies a function through it's name.
37 int getFunctionIndex(const std::string& strFunctionName) const; // EXPORT
38 /// Read a file's export directory.
39 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, const PeHeader& pehHeader); // EXPORT
40 /// Rebuild the current export directory.
41 void rebuild(std::vector<byte>& vBuffer, dword dwRva) const; // EXPORT
42 void removeFunction(unsigned int index); // EXPORT
43 /// Returns the size of the current export directory.
44 unsigned int size() const; // EXPORT
45 /// Writes the current export directory to a file.
46 int write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva) const; // EXPORT
47
48 /// Changes the name of the file (according to the export directory).
49 void setNameString(const std::string& strFilename); // EXPORT
50 std::string getNameString() const; // EXPORT
51
52 /// Get the name of an exported function.
53 std::string getFunctionName(unsigned int index) const; // EXPORT
54 /// Get the ordinal of an exported function.
55 word getFunctionOrdinal(unsigned int index) const; // EXPORT
56 /// Get the address of the name of an exported function.
57 dword getAddressOfName(unsigned int index) const; // EXPORT
58 /// Get the address of an exported function.
59 dword getAddressOfFunction(unsigned int index) const; // EXPORT
60
61 /// Change the name of an exported function.
62 void setFunctionName(unsigned int index, const std::string& strName); // EXPORT
63 /// Change the ordinal of an exported function.
64 void setFunctionOrdinal(unsigned int index, word wValue); // EXPORT
65 /// Change the address of the name of an exported function.
66 void setAddressOfName(unsigned int index, dword dwValue); // EXPORT
67 /// Change the address of an exported function.
68 void setAddressOfFunction(unsigned int index, dword dwValue); // EXPORT
69
70 /*
71 word getFunctionOrdinal(std::string strFuncname) const;
72 dword getAddressOfName(std::string strFuncname) const;
73 dword getAddressOfFunction(std::string strFuncname) const;
74
75 void setFunctionOrdinal(std::string strFuncname, word wValue);
76 void setAddressOfName(std::string strFuncname, dword dwValue);
77 void setAddressOfFunction(std::string strFuncname, dword dwValue);
78 */
79
80 /// Return the Base value of the export directory.
81 dword getBase() const; // EXPORT
82 /// Return the Characteristics value of the export directory.
83 dword getCharacteristics() const; // EXPORT
84 /// Return the TimeDateStamp value of the export directory.
85 dword getTimeDateStamp() const; // EXPORT
86 /// Return the MajorVersion value of the export directory.
87 word getMajorVersion() const; // EXPORT
88 /// Return the MinorVersion value of the export directory.
89 word getMinorVersion() const; // EXPORT
90 /// Return the Name value of the export directory.
91 dword getName() const; // EXPORT
92 /// Return the NumberOfFunctions value of the export directory.
93 dword getNumberOfFunctions() const; // EXPORT
94 /// Return the NumberOfNames value of the export directory.
95 dword getNumberOfNames() const; // EXPORT
96 /// Return the AddressOfFunctions value of the export directory.
97 dword getAddressOfFunctions() const; // EXPORT
98 /// Return the AddressOfNames value of the export directory.
99 dword getAddressOfNames() const; // EXPORT
100 /// Returns the AddressOfNameOrdinals value.
101 dword getAddressOfNameOrdinals() const; // EXPORT
102
103/* /// Returns the number of NameOrdinals.
104 dword getNumberOfNameOrdinals() const; // EXPORT
105 /// Returns the number of AddressOfFunctionNames values.
106 dword getNumberOfAddressOfFunctionNames() const; // EXPORT
107 /// Returns the number of AddressOfFunction values.
108 dword getNumberOfAddressOfFunctions() const; // EXPORT
109*/
110 /// Set the Base value of the export directory.
111 void setBase(dword dwValue); // EXPORT
112 /// Set the Characteristics value of the export directory.
113 void setCharacteristics(dword dwValue); // EXPORT
114 /// Set the TimeDateStamp value of the export directory.
115 void setTimeDateStamp(dword dwValue); // EXPORT
116 /// Set the MajorVersion value of the export directory.
117 void setMajorVersion(word wValue); // EXPORT
118 /// Set the MinorVersion value of the export directory.
119 void setMinorVersion(word wValue); // EXPORT
120 /// Set the Name value of the export directory.
121 void setName(dword dwValue); // EXPORT
122 /// Set the NumberOfFunctions value of the export directory.
123 void setNumberOfFunctions(dword dwValue); // EXPORT
124 /// Set the NumberOfNames value of the export directory.
125 void setNumberOfNames(dword dwValue); // EXPORT
126 /// Set the AddressOfFunctions value of the export directory.
127 void setAddressOfFunctions(dword dwValue); // EXPORT
128 /// Set the AddressOfNames value of the export directory.
129 void setAddressOfNames(dword dwValue); // EXPORT
130 void setAddressOfNameOrdinals(dword value); // EXPORT
131 };
132}
133#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.cpp
new file mode 100755
index 0000000000..36482fcbeb
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.cpp
@@ -0,0 +1,179 @@
1/*
2* IatDirectory.h - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#include "IatDirectory.h"
14
15namespace PeLib
16{
17 int IatDirectory::read(InputBuffer& inputBuffer, unsigned int size)
18 {
19 dword dwAddr;
20
21 std::vector<dword> vIat;
22
23 for (unsigned int i=0;i<size/sizeof(dword);i++)
24 {
25 inputBuffer >> dwAddr;
26 vIat.push_back(dwAddr);
27 }
28
29 std::swap(vIat, m_vIat);
30
31 return NO_ERROR;
32 }
33
34 /**
35 * Reads the Import Address table from a file.
36 * @param strFilename Name of the file.
37 * @param dwOffset File offset of the IAT (see #PeFile::PeHeader::getIDIatRVA).
38 * @param dwSize Size of the IAT (see #PeFile::PeHeader::getIDIatSize).
39 **/
40 int IatDirectory::read(const std::string& strFilename, unsigned int dwOffset, unsigned int dwSize)
41 {
42 std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
43
44 if (!ifFile)
45 {
46 return ERROR_OPENING_FILE;
47 }
48
49 if (fileSize(ifFile) < dwOffset + dwSize)
50 {
51 return ERROR_INVALID_FILE;
52 }
53
54 ifFile.seekg(dwOffset, std::ios::beg);
55
56 std::vector<byte> vBuffer(dwSize);
57 ifFile.read(reinterpret_cast<char*>(&vBuffer[0]), dwSize);
58
59 InputBuffer inpBuffer(vBuffer);
60 return read(inpBuffer, dwSize);
61 }
62
63 int IatDirectory::read(unsigned char* buffer, unsigned int buffersize)
64 {
65 std::vector<byte> vBuffer(buffer, buffer + buffersize);
66 InputBuffer inpBuffer(vBuffer);
67 return read(inpBuffer, buffersize);
68 }
69
70 /**
71 * Returns the number of fields in the IAT. This is equivalent to the number of
72 * imported functions.
73 * @return Number of fields in the IAT.
74 **/
75 unsigned int IatDirectory::calcNumberOfAddresses() const
76 {
77 return static_cast<unsigned int>(m_vIat.size());
78 }
79
80 /**
81 * Returns the dwValue of a field in the IAT.
82 * @param dwAddrnr Number identifying the field.
83 * @return dwValue of the field.
84 **/
85 dword IatDirectory::getAddress(unsigned int index) const
86 {
87 return m_vIat[index];
88 }
89
90 /**
91 * Updates the dwValue of a field in the IAT.
92 * @param dwAddrnr Number identifying the field.
93 * @param dwValue New dwValue of the field.
94 **/
95 void IatDirectory::setAddress(dword dwAddrnr, dword dwValue)
96 {
97 m_vIat[dwAddrnr] = dwValue;
98 }
99
100 /**
101 * Adds another field to the IAT.
102 * @param dwValue dwValue of the new field.
103 **/
104 void IatDirectory::addAddress(dword dwValue)
105 {
106 m_vIat.push_back(dwValue);
107 }
108
109 /**
110 * Removes an address from the IAT.
111 * @param dwAddrnr Number identifying the field.
112 **/
113 void IatDirectory::removeAddress(unsigned int index)
114 {
115 std::vector<dword>::iterator pos = m_vIat.begin() + index;
116 m_vIat.erase(pos);
117 }
118
119 /**
120 * Delete all entries from the IAT.
121 **/
122 void IatDirectory::clear()
123 {
124 m_vIat.clear();
125 }
126
127 /**
128 * Rebuilds the complete Import Address Table.
129 * @param vBuffer Buffer where the rebuilt IAT will be stored.
130 **/
131 void IatDirectory::rebuild(std::vector<byte>& vBuffer) const
132 {
133 vBuffer.reserve(size());
134 OutputBuffer obBuffer(vBuffer);
135
136 for (unsigned int i=0;i<m_vIat.size();i++)
137 {
138 obBuffer << m_vIat[i];
139 }
140 }
141
142 unsigned int IatDirectory::size() const
143 {
144 return static_cast<unsigned int>(m_vIat.size())* sizeof(dword);
145 }
146
147 /// Writes the current IAT to a file.
148 int IatDirectory::write(const std::string& strFilename, unsigned int uiOffset) const
149 {
150 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
151
152 if (!ofFile)
153 {
154 ofFile.clear();
155 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
156 }
157 else
158 {
159 ofFile.close();
160 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
161 }
162
163 if (!ofFile)
164 {
165 return ERROR_OPENING_FILE;
166 }
167
168 ofFile.seekp(uiOffset, std::ios::beg);
169
170 std::vector<unsigned char> vBuffer;
171 rebuild(vBuffer);
172
173 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
174
175 ofFile.close();
176
177 return NO_ERROR;
178 }
179}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.h
new file mode 100755
index 0000000000..81ef77ed6a
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.h
@@ -0,0 +1,58 @@
1/*
2* IatDirectory.h - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#ifndef IATDIRECTORY_H
14#define IATDIRECTORY_H
15
16#include "PeLibInc.h"
17
18namespace PeLib
19{
20 /// Class that handles the Import Address Table (IAT)
21 /**
22 * This class can read and modify the Import Address Table of a PE file.
23 **/
24 class IatDirectory
25 {
26 private:
27 std::vector<dword> m_vIat; ///< Stores the individual IAT fields.
28
29 int read(InputBuffer& inputBuffer, unsigned int size);
30
31 public:
32 /// Reads the Import Address Table from a PE file.
33 int read(const std::string& strFilename, unsigned int dwOffset, unsigned int dwSize); // EXPORT
34 int read(unsigned char* buffer, unsigned int buffersize); // EXPORT
35 /// Returns the number of fields in the IAT.
36 unsigned int calcNumberOfAddresses() const; // EXPORT
37 /// Adds another address to the IAT.
38 void addAddress(dword dwValue); // EXPORT
39 /// Removes an address from the IAT.
40 void removeAddress(unsigned int index); // EXPORT
41 /// Empties the IAT.
42 void clear(); // EXPORT
43 // Rebuilds the IAT.
44 void rebuild(std::vector<byte>& vBuffer) const; // EXPORT
45 /// Returns the size of the current IAT.
46 unsigned int size() const; // EXPORT
47 /// Writes the current IAT to a file.
48 int write(const std::string& strFilename, unsigned int uiOffset) const; // EXPORT
49
50 /// Retrieve the value of a field in the IAT.
51 dword getAddress(unsigned int index) const; // EXPORT
52 /// Change the value of a field in the IAT.
53 void setAddress(dword dwAddrnr, dword dwValue); // EXPORT
54 };
55}
56
57#endif
58
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/ImportDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/ImportDirectory.h
new file mode 100755
index 0000000000..6578f0712a
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/ImportDirectory.h
@@ -0,0 +1,1139 @@
1/*
2* ImportDirectory.h - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#ifndef IMPORTDIRECTORY_H
14#define IMPORTDIRECTORY_H
15
16#include "PeLibAux.h"
17#include "PeHeader.h"
18
19namespace PeLib
20{
21 /// Parameter for functions that can operate on the OLDDIR or new import directory.
22 enum currdir {OLDDIR = 1, NEWDIR};
23
24 class PeLibException;
25
26 /// Class that handles import directories.
27 /**
28 * This class can read import directories from existing PE files or start completely from scratch.
29 * Modifying import directories and writing them to files is also possible.
30 * It's worthy to note that many functions require an extra parameter of type currdir
31 * because the structure of import directories make it necessary that the OLDDIR import directory
32 * must be preserved. That's why some functions (like adding and removing) imported functions
33 * only exist for the new import directory, not for the one which is already written to the file.
34 * \todo Adding functions by ordinal doesn't work yet (rebuild needs to be changed).
35 * \todo Somehow store the rvas of the chunks in the file.
36 **/
37 template<int bits>
38 class ImportDirectory
39 {
40 typedef typename std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> >::iterator ImpDirFileIterator;
41 typedef typename std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> >::const_iterator ConstImpDirFileIterator;
42
43 private:
44 /// Stores information about already imported DLLs.
45 std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> > m_vOldiid;
46 /// Stores information about imported DLLs which will be added.
47 std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> > m_vNewiid;
48
49 // I can't convince Borland C++ to compile the function outside of the class declaration.
50 // That's why the function definition is here.
51 /// Tests if a certain function is imported.
52 template<typename T> bool hasFunction(std::string strFilename, T value, bool(PELIB_THUNK_DATA<bits>::* comp)(T) const) const
53 {
54 ConstImpDirFileIterator FileIter = m_vOldiid.begin();
55 ConstImpDirFileIterator EndIter = m_vOldiid.end();
56
57 for (int i=0;i<=1;i++) // Loop once for m_vOldiid and once for m_vNewiid
58 {
59 do
60 {
61 FileIter = std::find_if(FileIter, EndIter, std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_IMPORT_DIRECTORY<bits>::operator==), strFilename));
62
63 if (FileIter != EndIter)
64 {
65 typename std::vector<PELIB_THUNK_DATA<bits> >::const_iterator Iter = std::find_if(FileIter->originalfirstthunk.begin(), FileIter->originalfirstthunk.end(), std::bind2nd(std::mem_fun_ref(comp), value));
66 if (Iter != FileIter->originalfirstthunk.end())
67 {
68 return true;
69 }
70 ++FileIter;
71 }
72 }
73 while (FileIter != EndIter);
74
75 FileIter = m_vNewiid.begin();
76 EndIter = m_vNewiid.end();
77 }
78
79 return false;
80 }
81
82
83 public:
84
85 /// Add a function to the import directory.
86 int addFunction(const std::string& strFilename, word wHint); // EXPORT _byHint
87 /// Add a function to the import directory.
88 int addFunction(const std::string& strFilename, const std::string& strFuncname); // EXPORT _byName
89
90 /// Get the ID of a file through it's name.
91 unsigned int getFileIndex(const std::string& strFilename, currdir cdDir) const; // EXPORT
92 /// Get the ID of a function through it's name.
93 unsigned int getFunctionIndex(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const; // EXPORT
94
95 /// Get the name of an imported file.
96 std::string getFileName(dword dwFilenr, currdir cdDir) const; // EXPORT
97
98 void setFileName(dword filenr, currdir dir, const std::string& name); // EXPORT
99
100 /// Get the hint of an imported function.
101 word getFunctionHint(dword dwFilenr, dword dwFuncnr, currdir cdDir) const; // EXPORT
102 void setFunctionHint(dword dwFilenr, dword dwFuncnr, currdir cdDir, word value); // EXPORT
103 /// Get the name of an imported function.
104 std::string getFunctionName(dword dwFilenr, dword dwFuncnr, currdir cdDir) const; // EXPORT
105 void setFunctionName(dword dwFilenr, dword dwFuncnr, currdir cdDir, const std::string& functionName); // EXPORT
106 /// Get the number of files which are imported.
107 dword getNumberOfFiles(currdir cdDir) const; // EXPORT
108 /// Get the number of fucntions which are imported by a specific file.
109 dword getNumberOfFunctions(dword dwFilenr, currdir cdDir) const; // EXPORT
110 /// Read a file's import directory.
111 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, const PeHeaderT<bits>& pehHeader); // EXPORT
112 /// Rebuild the import directory.
113 void rebuild(std::vector<byte>& vBuffer, dword dwRva, bool fixEntries = true) const; // EXPORT
114 /// Remove a file from the import directory.
115 int removeFile(const std::string& strFilename); // EXPORT
116 /// Remove a function from the import directory.
117 int removeFunction(const std::string& strFilename, const std::string& strFuncname); // EXPORT _byName
118 /// Remove a function from the import directory.
119 int removeFunction(const std::string& strFilename, word wHint); // EXPORT _byHint
120 /// Returns the size of the current import directory.
121 unsigned int size() const; // EXPORT
122 /// Writes the import directory to a file.
123 int write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva); // EXPORT
124
125 /// Returns the FirstThunk value of a function.
126 dword getFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir) const; // EXPORT _byNumber
127 void setFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir, dword value); // EXPORT _byNumber
128 /// Returns the OriginalFirstThunk value of a function.
129 dword getOriginalFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir) const; // EXPORT _byNumber
130 void setOriginalFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir, dword value); // EXPORT
131
132// dword getFirstThunk(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const throw (PeLibException);
133// dword getOriginalFirstThunk(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const throw (PeLibException);
134
135 /// Returns the FirstThunk value of a file.
136 dword getFirstThunk(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName
137 /// Returns the OriginalFirstThunk value of a file.
138 dword getOriginalFirstThunk(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName
139 /// Returns the ForwarderChain value of a file.
140 dword getForwarderChain(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName
141 dword getRvaOfName(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName
142 /// Returns the TimeDateStamp value of a file.
143 dword getTimeDateStamp(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName
144
145 /// Returns the FirstThunk value of a file.
146 dword getFirstThunk(dword dwFilenr, currdir cdDir) const; // EXPORT
147 void setFirstThunk(dword dwFilenr, currdir cdDir, dword value); // EXPORT _byNumber_function
148 /// Returns the OriginalFirstThunk value of a file.
149 dword getOriginalFirstThunk(dword dwFilenr, currdir cdDir) const; // EXPORT
150 void setOriginalFirstThunk(dword dwFilenr, currdir cdDir, dword value); // EXPORT _byNumber_function
151 /// Returns the ForwarderChain value of a file.
152 dword getForwarderChain(dword dwFilenr, currdir cdDir) const; // EXPORT _byNumber
153 void setForwarderChain(dword dwFilenr, currdir cdDir, dword value); // EXPORT _byNumber_function
154 dword getRvaOfName(dword dwFilenr, currdir cdDir) const; // EXPORT _byNumber
155 void setRvaOfName(dword dwFilenr, currdir cdDir, dword value); // EXPORT
156 /// Returns the TimeDateStamp value of a file.
157 dword getTimeDateStamp(dword dwFilenr, currdir cdDir) const; // EXPORT
158 void setTimeDateStamp(dword dwFilenr, currdir cdDir, dword value); // EXPORT _byNumber
159
160// word getFunctionHint(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const throw (PeLibException);
161 };
162
163 /**
164 * Add another import (by Ordinal) to the current file. Note that the import table is not automatically updated.
165 * The new imported functions will be added when you recalculate the import table as it's necessary
166 * to specify the address the import table will have in the file.
167 * @param strFilename The name of a DLL.
168 * @param wHint The ordinal of the function in the DLL.
169 **/
170 template<int bits>
171 int ImportDirectory<bits>::addFunction(const std::string& strFilename, word wHint)
172 {
173 if (hasFunction(strFilename, wHint, &PELIB_THUNK_DATA<bits>::equalHint))
174 {
175 return ERROR_DUPLICATE_ENTRY;
176 }
177
178 // Find the imported file.
179 ImpDirFileIterator FileIter = std::find_if(m_vNewiid.begin(), m_vNewiid.end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_IMPORT_DIRECTORY<bits>::operator==), strFilename));
180
181 PELIB_IMAGE_IMPORT_DIRECTORY<bits> iid;
182 PELIB_THUNK_DATA<bits> td;
183 td.hint = wHint;
184 td.itd.Ordinal = wHint | PELIB_IMAGE_ORDINAL_FLAGS<bits>::IMAGE_ORDINAL_FLAG;
185 iid.name = strFilename;
186 if (FileIter == m_vNewiid.end())
187 {
188 iid.originalfirstthunk.push_back(td);
189 iid.firstthunk.push_back(td);
190 m_vNewiid.push_back(iid);
191 }
192 else
193 {
194 FileIter->originalfirstthunk.push_back(td);
195 FileIter->firstthunk.push_back(td);
196 }
197
198 return NO_ERROR;
199 }
200
201 /**
202 * Add a function to the Import Directory.
203 * @param strFilename Name of the file which will be imported
204 * @param strFuncname Name of the function which will be imported.
205 **/
206 template<int bits>
207 int ImportDirectory<bits>::addFunction(const std::string& strFilename, const std::string& strFuncname)
208 {
209 if (hasFunction(strFilename, strFuncname, &PELIB_THUNK_DATA<bits>::equalFunctionName))
210 {
211 return ERROR_DUPLICATE_ENTRY;
212 }
213
214 // Find the imported file.
215 ImpDirFileIterator FileIter = std::find_if(m_vNewiid.begin(), m_vNewiid.end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_IMPORT_DIRECTORY<bits>::operator==), strFilename));
216
217 PELIB_IMAGE_IMPORT_DIRECTORY<bits> iid;
218 PELIB_THUNK_DATA<bits> td;
219 td.fname = strFuncname;
220 iid.name = strFilename;
221 if (FileIter == m_vNewiid.end())
222 {
223 iid.originalfirstthunk.push_back(td);
224 iid.firstthunk.push_back(td);
225 m_vNewiid.push_back(iid);
226 }
227 else
228 {
229 FileIter->originalfirstthunk.push_back(td);
230 FileIter->firstthunk.push_back(td);
231 }
232
233 return NO_ERROR;
234 }
235
236 /**
237 * Searches through the import directory and returns the number of the import
238 * directory entry which belongs to the given filename.
239 * @param strFilename Name of the imported file.
240 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
241 * @return The ID of an imported file.
242 **/
243 template<int bits>
244 unsigned int ImportDirectory<bits>::getFileIndex(const std::string& strFilename, currdir cdDir) const
245 {
246 const std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> >* currDir;
247
248 if (cdDir == OLDDIR)
249 {
250 currDir = &m_vOldiid;
251 }
252 else
253 {
254 currDir = &m_vNewiid;
255 }
256
257 ConstImpDirFileIterator FileIter = std::find_if(currDir->begin(), currDir->end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_IMPORT_DIRECTORY<bits>::operator==), strFilename));
258
259 if (FileIter != currDir->end())
260 {
261 return static_cast<unsigned int>(std::distance(currDir->begin(), FileIter));
262 }
263 else
264 {
265 return -1;
266 // throw Exceptions::InvalidName(ImportDirectoryId, __LINE__);
267 }
268
269 return NO_ERROR;
270 }
271
272 /**
273 * Searches through an imported file for a specific function.
274 * @param strFilename Name of the imported file.
275 * @param strFuncname Name of the imported function.
276 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
277 * @return ID of the imported function.
278 **/
279 template<int bits>
280 unsigned int ImportDirectory<bits>::getFunctionIndex(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const
281 {
282 unsigned int uiFile = getFileIndex(strFilename, cdDir);
283
284 for (unsigned int i=0;i<getNumberOfFunctions(uiFile, cdDir);i++)
285 {
286 if (getFunctionName(uiFile, i, cdDir) == strFuncname) return i;
287 }
288
289 return -1;
290 }
291
292 /**
293 * Get the name of an imported file.
294 * @param dwFilenr Identifies which file should be checked.
295 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
296 * @return Name of an imported file.
297 **/
298 template<int bits>
299 std::string ImportDirectory<bits>::getFileName(dword dwFilenr, currdir cdDir) const
300 {
301 if (cdDir == OLDDIR) return m_vOldiid[dwFilenr].name;
302 else return m_vNewiid[dwFilenr].name;
303 }
304
305 template<int bits>
306 void ImportDirectory<bits>::setFileName(dword filenr, currdir dir, const std::string& name)
307 {
308 if (dir == OLDDIR) m_vOldiid[filenr].name = name;
309 else m_vNewiid[filenr].name = name;
310 }
311
312 /**
313 * Get the name of an imported function.
314 * @param dwFilenr Identifies which file should be checked.
315 * @param dwFuncnr Identifies which function should be checked.
316 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
317 * @return Name of an imported function.
318 * \todo Marked line is unsafe (function should be rewritten).
319 **/
320 template<int bits>
321 std::string ImportDirectory<bits>::getFunctionName(dword dwFilenr, dword dwFuncnr, currdir cdDir) const
322 {
323 if (cdDir == OLDDIR)
324 {
325 // Unsafe
326 if (m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk)
327 {
328 return m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].fname;
329 }
330 else
331 {
332 return m_vOldiid[dwFilenr].firstthunk[dwFuncnr].fname;
333 }
334 }
335 else
336 {
337 if (m_vNewiid[dwFilenr].impdesc.OriginalFirstThunk)
338 {
339 return m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].fname;
340 }
341 else
342 {
343 return m_vNewiid[dwFilenr].firstthunk[dwFuncnr].fname;
344 }
345 }
346 }
347
348 template<int bits>
349 void ImportDirectory<bits>::setFunctionName(dword dwFilenr, dword dwFuncnr, currdir cdDir, const std::string& functionName)
350 {
351 if (cdDir == OLDDIR)
352 {
353 // Unsafe
354 if (m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk)
355 {
356 m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].fname = functionName;
357 }
358 else
359 {
360 m_vOldiid[dwFilenr].firstthunk[dwFuncnr].fname = functionName;
361 }
362 }
363 else
364 {
365 if (m_vNewiid[dwFilenr].impdesc.OriginalFirstThunk)
366 {
367 m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].fname = functionName;
368 }
369 else
370 {
371 m_vNewiid[dwFilenr].firstthunk[dwFuncnr].fname = functionName;
372 }
373 }
374 }
375
376 /**
377 * Get the hint of an imported function.
378 * @param dwFilenr Identifies which file should be checked.
379 * @param dwFuncnr Identifies which function should be checked.
380 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
381 * @return Hint of an imported function.
382 **/
383 template<int bits>
384 word ImportDirectory<bits>::getFunctionHint(dword dwFilenr, dword dwFuncnr, currdir cdDir) const
385 {
386 if (cdDir == OLDDIR)
387 {
388 if (m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk)
389 {
390 return m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].hint;
391 }
392 else
393 {
394 return m_vOldiid[dwFilenr].firstthunk[dwFuncnr].hint;
395 }
396 }
397 else return m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].hint;
398 }
399
400 template<int bits>
401 void ImportDirectory<bits>::setFunctionHint(dword dwFilenr, dword dwFuncnr, currdir cdDir, word value)
402 {
403 if (cdDir == OLDDIR)
404 {
405 if (m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk)
406 {
407 m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].hint = value;
408 }
409 else
410 {
411 m_vOldiid[dwFilenr].firstthunk[dwFuncnr].hint = value;
412 }
413 }
414 else m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].hint = value;
415 }
416
417 /**
418 * Get the number of files which are currently being imported.
419 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
420 * @return Number of files which are currently being imported.
421 **/
422 template<int bits>
423 dword ImportDirectory<bits>::getNumberOfFiles(currdir cdDir) const
424 {
425 if (cdDir == OLDDIR) return static_cast<dword>(m_vOldiid.size());
426 else return static_cast<dword>(m_vNewiid.size());
427 }
428
429 /**
430 * Get the number of functions which are currently being imported from a specific file.
431 * @param dwFilenr Identifies which file should be checked.
432 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
433 * @return Number of functions which are currently being imported from a specific file.
434 **/
435 template<int bits>
436 dword ImportDirectory<bits>::getNumberOfFunctions(dword dwFilenr, currdir cdDir) const
437 {
438 if (cdDir == OLDDIR) return static_cast<unsigned int>(m_vOldiid[dwFilenr].firstthunk.size());
439 else return static_cast<unsigned int>(m_vNewiid[dwFilenr].firstthunk.size());
440 }
441
442 /**
443 * Read an import directory from a file.
444 * \todo Check if streams failed.
445 * @param strFilename Name of the file which will be read.
446 * @param uiOffset Offset of the import directory (see #PeLib::PeHeader::getIDImportRVA).
447 * @param uiSize Size of the import directory (see #PeLib::PeHeader::getIDImportSize).
448 * @param pehHeader A valid PE header.
449 **/
450 template<int bits>
451 int ImportDirectory<bits>::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, const PeHeaderT<bits>& pehHeader)
452 {
453 std::ifstream ifFile(strFilename.c_str(), std::ios_base::binary);
454
455 if (!ifFile)
456 {
457 return ERROR_OPENING_FILE;
458 }
459
460 unsigned int uiFileSize = fileSize(ifFile);
461
462 if (uiFileSize < uiOffset + uiSize)
463 {
464 return ERROR_INVALID_FILE;
465 }
466
467 ifFile.seekg(uiOffset, std::ios_base::beg);
468
469 std::vector<unsigned char> vImportdirectory(uiSize);
470 ifFile.read(reinterpret_cast<char*>(&vImportdirectory[0]), uiSize);
471
472 PELIB_IMAGE_IMPORT_DIRECTORY<bits> iidCurr;
473 unsigned int uiDesccounter = 0;
474
475 InputBuffer inpBuffer(vImportdirectory);
476
477 std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> > vOldIidCurr;
478
479 do // Read and store all descriptors
480 {
481 inpBuffer >> iidCurr.impdesc.OriginalFirstThunk;
482 inpBuffer >> iidCurr.impdesc.TimeDateStamp;
483 inpBuffer >> iidCurr.impdesc.ForwarderChain;
484 inpBuffer >> iidCurr.impdesc.Name;
485 inpBuffer >> iidCurr.impdesc.FirstThunk;
486
487 if (iidCurr.impdesc.OriginalFirstThunk != 0 || iidCurr.impdesc.TimeDateStamp != 0 || iidCurr.impdesc.ForwarderChain != 0 ||
488 iidCurr.impdesc.Name != 0 || iidCurr.impdesc.FirstThunk != 0)
489 {
490 vOldIidCurr.push_back(iidCurr);
491 }
492
493 uiDesccounter++;
494
495 if (uiSize < (uiDesccounter + 1) * PELIB_IMAGE_IMPORT_DESCRIPTOR::size()) break;
496 } while (iidCurr.impdesc.OriginalFirstThunk != 0 || iidCurr.impdesc.TimeDateStamp != 0 || iidCurr.impdesc.ForwarderChain != 0 ||
497 iidCurr.impdesc.Name != 0 || iidCurr.impdesc.FirstThunk != 0);
498
499 char namebuffer[2] = {0};
500
501 // Name
502 for (unsigned int i=0;i<vOldIidCurr.size();i++)
503 {
504 ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(vOldIidCurr[i].impdesc.Name)), std::ios_base::beg);
505
506 std::string dllname = "";
507
508 do
509 {
510 ifFile.read(namebuffer, 1);
511 if (!ifFile || !namebuffer[0]) break; // reached end of file or 0-byte
512 dllname += namebuffer;
513 } while (true);
514
515 vOldIidCurr[i].name = dllname;
516
517 }
518
519 // OriginalFirstThunk
520 for (unsigned int i=0;i<vOldIidCurr.size();i++)
521 {
522 PELIB_THUNK_DATA<bits> tdCurr;
523 dword uiVaoft = vOldIidCurr[i].impdesc.OriginalFirstThunk;
524
525 if (!uiVaoft)
526 {
527 continue;
528 }
529
530 ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(uiVaoft)), std::ios_base::beg);
531
532 do
533 {
534 if (uiFileSize < pehHeader.rvaToOffset(uiVaoft) + sizeof(tdCurr.itd.Ordinal))
535 {
536 return ERROR_INVALID_FILE;
537 }
538 uiVaoft += sizeof(tdCurr.itd.Ordinal);
539
540 ifFile.read(reinterpret_cast<char*>(&tdCurr.itd.Ordinal), sizeof(tdCurr.itd.Ordinal));
541 if (tdCurr.itd.Ordinal) vOldIidCurr[i].originalfirstthunk.push_back(tdCurr);
542 } while (tdCurr.itd.Ordinal);
543 }
544
545 // FirstThunk
546 for (unsigned int i=0;i<vOldIidCurr.size();i++)
547 {
548 dword uiVaoft = vOldIidCurr[i].impdesc.FirstThunk;
549 PELIB_THUNK_DATA<bits> tdCurr;
550
551 ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(uiVaoft)), std::ios_base::beg);
552
553 do
554 {
555 if (uiFileSize < pehHeader.rvaToOffset(uiVaoft) + sizeof(tdCurr.itd.Ordinal))
556 {
557 return ERROR_INVALID_FILE;
558 }
559
560 uiVaoft += sizeof(tdCurr.itd.Ordinal);
561
562 ifFile.read(reinterpret_cast<char*>(&tdCurr.itd.Ordinal), sizeof(tdCurr.itd.Ordinal));
563 if (tdCurr.itd.Ordinal) vOldIidCurr[i].firstthunk.push_back(tdCurr);
564 } while (tdCurr.itd.Ordinal);
565 }
566
567 // Names
568 for (unsigned int i=0;i<vOldIidCurr.size();i++)
569 {
570 if (vOldIidCurr[i].impdesc.OriginalFirstThunk)
571 {
572 for (unsigned int j=0;j<vOldIidCurr[i].originalfirstthunk.size();j++)
573 {
574 if (vOldIidCurr[i].originalfirstthunk[j].itd.Ordinal & PELIB_IMAGE_ORDINAL_FLAGS<bits>::IMAGE_ORDINAL_FLAG)
575 {
576 vOldIidCurr[i].originalfirstthunk[j].hint = 0;
577 continue;
578 }
579
580 ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(vOldIidCurr[i].originalfirstthunk[j].itd.Ordinal)), std::ios_base::beg);
581
582 ifFile.read(reinterpret_cast<char*>(&vOldIidCurr[i].originalfirstthunk[j].hint), sizeof(vOldIidCurr[i].originalfirstthunk[j].hint));
583
584 if (!ifFile)
585 return ERROR_INVALID_FILE;
586
587 std::string funcname = "";
588 do
589 {
590 ifFile.read(namebuffer, 1);
591 if (!ifFile || !namebuffer[0]) break; // reached end of file or 0-byte
592 funcname += namebuffer;
593 } while (true);
594
595 vOldIidCurr[i].originalfirstthunk[j].fname = funcname;
596 }
597 }
598 else
599 {
600 for (unsigned int j=0;j<vOldIidCurr[i].firstthunk.size();j++)
601 {
602 if (vOldIidCurr[i].firstthunk[j].itd.Ordinal & PELIB_IMAGE_ORDINAL_FLAGS<bits>::IMAGE_ORDINAL_FLAG)
603 {
604 continue;
605 }
606
607 ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(vOldIidCurr[i].firstthunk[j].itd.Ordinal)), std::ios_base::beg);
608
609 ifFile.read(reinterpret_cast<char*>(&vOldIidCurr[i].firstthunk[j].hint), sizeof(vOldIidCurr[i].firstthunk[j].hint));
610
611 if (!ifFile)
612 return ERROR_INVALID_FILE;
613
614 std::string funcname = "";
615 do
616 {
617 ifFile.read(namebuffer, 1);
618 if (!ifFile || !namebuffer[0]) break; // reached end of file or 0-byte
619 funcname += namebuffer;
620 } while (true);
621
622 vOldIidCurr[i].firstthunk[j].fname = funcname;
623 }
624 }
625 }
626 std::swap(vOldIidCurr, m_vOldiid);
627 return NO_ERROR;
628 }
629
630 /**
631 * Rebuilds the import directory.
632 * @param vBuffer Buffer the rebuilt import directory will be written to.
633 * @param dwRva The RVA of the ImportDirectory in the file.
634 * \todo uiSizeoffuncnames is not used.
635 **/
636 template<int bits>
637 void ImportDirectory<bits>::rebuild(std::vector<byte>& vBuffer, dword dwRva, bool fixEntries) const
638 {
639 unsigned int uiImprva = dwRva;
640 unsigned int uiSizeofdescriptors = (static_cast<unsigned int>(m_vNewiid.size() + m_vOldiid.size()) + 1) * PELIB_IMAGE_IMPORT_DESCRIPTOR::size();
641
642 unsigned int uiSizeofdllnames = 0, uiSizeoffuncnames = 0;
643 unsigned int uiSizeofoft = 0;
644
645 for (unsigned int i=0;i<m_vNewiid.size();i++)
646 {
647 uiSizeofdllnames += static_cast<unsigned int>(m_vNewiid[i].name.size()) + 1;
648 uiSizeofoft += (static_cast<unsigned int>(m_vNewiid[i].originalfirstthunk.size())+1) * PELIB_IMAGE_THUNK_DATA<bits>::size();
649
650 for(unsigned int j=0;j<m_vNewiid[i].originalfirstthunk.size();j++)
651 {
652 // +3 for hint (word) and 00-byte
653 uiSizeoffuncnames += (static_cast<unsigned int>(m_vNewiid[i].originalfirstthunk[j].fname.size()) + 3);
654 }
655 }
656
657// for (unsigned int i=0;i<m_vNewiid.size();i++)
658// {
659// uiSizeofoft += (static_cast<unsigned int>(m_vNewiid[i].originalfirstthunk.size())+1) * PELIB_IMAGE_THUNK_DATA<bits>::size();
660// }
661
662 OutputBuffer obBuffer(vBuffer);
663
664 // Rebuild IMAGE_IMPORT_DESCRIPTORS
665 for (unsigned int i=0;i<m_vOldiid.size();i++)
666 {
667 obBuffer << m_vOldiid[i].impdesc.OriginalFirstThunk;
668 obBuffer << m_vOldiid[i].impdesc.TimeDateStamp;
669 obBuffer << m_vOldiid[i].impdesc.ForwarderChain;
670 obBuffer << m_vOldiid[i].impdesc.Name;
671 obBuffer << m_vOldiid[i].impdesc.FirstThunk;
672 }
673
674 unsigned int dllsize = 0;
675
676 for (unsigned int i=0;i<m_vNewiid.size();i++)
677 {
678 dword dwPoft = uiSizeofdescriptors + uiImprva;
679
680 for (unsigned int j=1;j<=i;j++)
681 {
682 dwPoft += (static_cast<unsigned int>(m_vNewiid[j-1].originalfirstthunk.size()) + 1) * PELIB_IMAGE_THUNK_DATA<bits>::size();
683 }
684
685 obBuffer << (fixEntries ? dwPoft : m_vNewiid[i].impdesc.OriginalFirstThunk);
686 obBuffer << m_vNewiid[i].impdesc.TimeDateStamp;
687 obBuffer << m_vNewiid[i].impdesc.ForwarderChain;
688 dword dwPdll = uiSizeofdescriptors + uiSizeofoft + uiImprva + dllsize;
689 obBuffer << (fixEntries ? dwPdll : m_vNewiid[i].impdesc.Name);
690 obBuffer << (fixEntries ? dwPoft : m_vNewiid[i].impdesc.FirstThunk);
691
692 dllsize += static_cast<unsigned int>(m_vNewiid[i].name.size()) + 1;
693 }
694
695 obBuffer << (dword)0;
696 obBuffer << (dword)0;
697 obBuffer << (dword)0;
698 obBuffer << (dword)0;
699 obBuffer << (dword)0;
700
701 unsigned int uiPfunc = uiSizeofdescriptors + uiSizeofoft + uiSizeofdllnames + uiImprva;
702
703 // Rebuild original first thunk
704 for (unsigned int i=0;i<m_vNewiid.size();i++)
705 {
706 for (unsigned int j=0;j<m_vNewiid[i].originalfirstthunk.size();j++)
707 {
708 if (m_vNewiid[i].originalfirstthunk[j].itd.Ordinal & PELIB_IMAGE_ORDINAL_FLAGS<bits>::IMAGE_ORDINAL_FLAG
709 || fixEntries == false)
710 {
711 obBuffer << m_vNewiid[i].originalfirstthunk[j].itd.Ordinal;
712 }
713 else
714 {
715 obBuffer << uiPfunc;
716 }
717 uiPfunc += static_cast<unsigned int>(m_vNewiid[i].originalfirstthunk[j].fname.size()) + 3;
718 }
719 obBuffer << (dword)0;
720 }
721
722 // Write dllnames into import directory
723 for (unsigned int i=0;i<m_vNewiid.size();i++)
724 {
725 obBuffer.add(m_vNewiid[i].name.c_str(), static_cast<unsigned int>(m_vNewiid[i].name.size())+1);
726 }
727
728 // Write function names into directory
729 for (unsigned int i=0;i<m_vNewiid.size();i++)
730 {
731 for (unsigned int j=0;j<m_vNewiid[i].originalfirstthunk.size();j++)
732 {
733 obBuffer << m_vNewiid[i].originalfirstthunk[j].hint;
734 obBuffer.add(m_vNewiid[i].originalfirstthunk[j].fname.c_str(), static_cast<unsigned int>(m_vNewiid[i].originalfirstthunk[j].fname.size()) + 1);
735 }
736 }
737 }
738
739 /**
740 * Removes a specific file and all functions of it from the import directory.
741 * @param strFilename Name of the file which will be removed.
742 **/
743 template<int bits>
744 int ImportDirectory<bits>::removeFile(const std::string& strFilename)
745 {
746 unsigned int oldSize = static_cast<unsigned int>(m_vNewiid.size());
747
748 m_vNewiid.erase(std::remove_if(m_vNewiid.begin(), m_vNewiid.end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_IMPORT_DIRECTORY<bits>::operator==), strFilename)), m_vNewiid.end());
749
750 return oldSize == m_vNewiid.size() ? 1 : 0;
751 }
752
753 /**
754 * Removes a specific function from the import directory.
755 * @param strFilename Name of the file which exports the function.
756 * @param strFuncname Name of the imported function.
757 **/
758 template<int bits>
759 int ImportDirectory<bits>::removeFunction(const std::string& strFilename, const std::string& strFuncname)
760 {
761 ImpDirFileIterator viPos = m_vNewiid.begin();
762
763 int notFound = 1;
764
765 while (viPos != m_vNewiid.end())
766 {
767 if (isEqualNc(viPos->name, strFilename))
768 {
769 unsigned int oldSize = static_cast<unsigned int>(viPos->originalfirstthunk.size());
770 viPos->originalfirstthunk.erase(std::remove_if(viPos->originalfirstthunk.begin(), viPos->originalfirstthunk.end(), std::bind2nd(std::mem_fun_ref(&PELIB_THUNK_DATA<bits>::equalFunctionName), strFuncname)), viPos->originalfirstthunk.end());
771 //viPos->originalfirstthunk.erase(std::remove_if(viPos->originalfirstthunk.begin(), viPos->originalfirstthunk.end(), std::bind2nd(CompPolicy<PELIB_THUNK_DATA, std::string>(), strFuncname)));
772 if (viPos->originalfirstthunk.size() != oldSize) notFound = 0;
773 }
774 ++viPos;
775 }
776
777 return notFound;
778 }
779
780 /**
781 * Removes a specific function from the import directory.
782 * @param strFilename Name of the file which exports the function.
783 * @param wHint The hint of the function.
784 **/
785 template<int bits>
786 int ImportDirectory<bits>::removeFunction(const std::string& strFilename, word wHint)
787 {
788 ImpDirFileIterator viPos = m_vNewiid.begin();
789 int notFound = 1;
790
791 while (viPos != m_vNewiid.end())
792 {
793 if (isEqualNc(viPos->name, strFilename))
794 {
795 unsigned int oldSize = static_cast<unsigned int>(viPos->originalfirstthunk.size());
796 viPos->originalfirstthunk.erase(std::remove_if(viPos->originalfirstthunk.begin(), viPos->originalfirstthunk.end(), std::bind2nd(std::mem_fun_ref(&PELIB_THUNK_DATA<bits>::equalHint), wHint)), viPos->originalfirstthunk.end());
797 unsigned int newPos = static_cast<unsigned int>(viPos->originalfirstthunk.size());
798 if (viPos->originalfirstthunk.size() != oldSize) notFound = 0;
799 }
800 ++viPos;
801 }
802
803 return notFound;
804 }
805
806 /**
807 * Writes the current import directory to a file.
808 * @param strFilename Name of the file.
809 * @param uiOffset File Offset of the new import directory.
810 * @param uiRva RVA which belongs to that file offset.
811 **/
812 template<int bits>
813 int ImportDirectory<bits>::write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva)
814 {
815 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
816
817 if (!ofFile)
818 {
819 ofFile.clear();
820 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
821 }
822 else
823 {
824 ofFile.close();
825 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
826 }
827
828 if (!ofFile)
829 {
830 return ERROR_OPENING_FILE;
831 }
832
833 ofFile.seekp(uiOffset, std::ios_base::beg);
834
835 std::vector<byte> vBuffer;
836
837 rebuild(vBuffer, uiRva);
838
839 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), vBuffer.size());
840 ofFile.close();
841
842 std::copy(m_vNewiid.begin(), m_vNewiid.end(), std::back_inserter(m_vOldiid));
843 m_vNewiid.clear();
844
845 return NO_ERROR;
846 }
847
848 /**
849 * Returns the size of the import directory.
850 * @return Size of the import directory.
851 **/
852 template<int bits>
853 unsigned int ImportDirectory<bits>::size() const
854 {
855 // Only the descriptors of m_vOldiid must be rebuilt, not the data they point to.
856 return std::accumulate(m_vNewiid.begin(), m_vNewiid.end(), 0, accumulate<PELIB_IMAGE_IMPORT_DIRECTORY<bits> >)
857 + (m_vOldiid.size() + 1) * PELIB_IMAGE_IMPORT_DESCRIPTOR::size();
858 }
859
860 /**
861 * @param strFilename Name of the imported file.
862 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
863 * @return FirstThunk value of an imported file.
864 **/
865 template<int bits>
866 dword ImportDirectory<bits>::getFirstThunk(const std::string& strFilename, currdir cdDir) const
867 {
868 if (cdDir == OLDDIR)
869 {
870 return m_vOldiid[getFileIndex(strFilename, cdDir)].impdesc.FirstThunk;
871 }
872 else
873 {
874 return m_vNewiid[getFileIndex(strFilename, cdDir)].impdesc.FirstThunk;
875 }
876 }
877
878 /**
879 * @param strFilename Name of the imported file.
880 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
881 * @return OriginalFirstThunk value of an imported file.
882 **/
883 template<int bits>
884 dword ImportDirectory<bits>::getOriginalFirstThunk(const std::string& strFilename, currdir cdDir) const
885 {
886 if (cdDir == OLDDIR)
887 {
888 return m_vOldiid[getFileIndex(strFilename, cdDir)].impdesc.OriginalFirstThunk;
889 }
890 else
891 {
892 return m_vNewiid[getFileIndex(strFilename, cdDir)].impdesc.OriginalFirstThunk;
893 }
894 }
895
896 /**
897 * @param strFilename Name of the imported file.
898 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
899 * @return ForwarderChain value of an imported file.
900 **/
901 template<int bits>
902 dword ImportDirectory<bits>::getForwarderChain(const std::string& strFilename, currdir cdDir) const
903 {
904 if (cdDir == OLDDIR)
905 {
906 return m_vOldiid[getFileIndex(strFilename, cdDir)].impdesc.ForwarderChain;
907 }
908 else
909 {
910 return m_vNewiid[getFileIndex(strFilename, cdDir)].impdesc.ForwarderChain;
911 }
912 }
913
914 /**
915 * @param strFilename Name of the imported file.
916 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
917 * @return TimeDateStamp value of an imported file.
918 **/
919 template<int bits>
920 dword ImportDirectory<bits>::getTimeDateStamp(const std::string& strFilename, currdir cdDir) const
921 {
922 if (cdDir == OLDDIR)
923 {
924 return m_vOldiid[getFileIndex(strFilename, cdDir)].impdesc.TimeDateStamp;
925 }
926 else
927 {
928 return m_vNewiid[getFileIndex(strFilename, cdDir)].impdesc.TimeDateStamp;
929 }
930 }
931
932 template<int bits>
933 dword ImportDirectory<bits>::getRvaOfName(const std::string& strFilename, currdir cdDir) const
934 {
935 if (cdDir == OLDDIR)
936 {
937 return m_vOldiid[getFileIndex(strFilename, cdDir)].impdesc.Name;
938 }
939 else
940 {
941 return m_vNewiid[getFileIndex(strFilename, cdDir)].impdesc.Name;
942 }
943 }
944
945 /**
946 * @param strFilename Name of the imported file.
947 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
948 * @return FirstThunk value of an imported file.
949 **/
950 template<int bits>
951 dword ImportDirectory<bits>::getFirstThunk(dword dwFilenr, currdir cdDir) const
952 {
953 if (cdDir == OLDDIR)
954 {
955 return m_vOldiid[dwFilenr].impdesc.FirstThunk;
956 }
957 else
958 {
959 return m_vNewiid[dwFilenr].impdesc.FirstThunk;
960 }
961 }
962
963 template<int bits>
964 void ImportDirectory<bits>::setFirstThunk(dword dwFilenr, currdir cdDir, dword value)
965 {
966 if (cdDir == OLDDIR)
967 {
968 m_vOldiid[dwFilenr].impdesc.FirstThunk = value;
969 }
970 else
971 {
972 m_vNewiid[dwFilenr].impdesc.FirstThunk = value;
973 }
974 }
975
976 /**
977 * @param strFilename Name of the imported file.
978 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
979 * @return OriginalFirstThunk value of an imported file.
980 **/
981 template<int bits>
982 dword ImportDirectory<bits>::getOriginalFirstThunk(dword dwFilenr, currdir cdDir) const
983 {
984 if (cdDir == OLDDIR)
985 {
986 return m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk;
987 }
988 else
989 {
990 return m_vNewiid[dwFilenr].impdesc.OriginalFirstThunk;
991 }
992 }
993
994 template<int bits>
995 void ImportDirectory<bits>::setOriginalFirstThunk(dword dwFilenr, currdir cdDir, dword value)
996 {
997 if (cdDir == OLDDIR)
998 {
999 m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk = value;
1000 }
1001 else
1002 {
1003 m_vNewiid[dwFilenr].impdesc.OriginalFirstThunk = value;
1004 }
1005 }
1006
1007 /**
1008 * @param strFilename Name of the imported file.
1009 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
1010 * @return ForwarderChain value of an imported file.
1011 **/
1012 template<int bits>
1013 dword ImportDirectory<bits>::getForwarderChain(dword dwFilenr, currdir cdDir) const
1014 {
1015 if (cdDir == OLDDIR)
1016 {
1017 return m_vOldiid[dwFilenr].impdesc.ForwarderChain;
1018 }
1019 else
1020 {
1021 return m_vNewiid[dwFilenr].impdesc.ForwarderChain;
1022 }
1023 }
1024
1025 template<int bits>
1026 void ImportDirectory<bits>::setForwarderChain(dword dwFilenr, currdir cdDir, dword value)
1027 {
1028 if (cdDir == OLDDIR)
1029 {
1030 m_vOldiid[dwFilenr].impdesc.ForwarderChain = value;
1031 }
1032 else
1033 {
1034 m_vNewiid[dwFilenr].impdesc.ForwarderChain = value;
1035 }
1036 }
1037
1038 /**
1039 * @param strFilename Name of the imported file.
1040 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
1041 * @return TimeDateStamp value of an imported file.
1042 **/
1043 template<int bits>
1044 dword ImportDirectory<bits>::getTimeDateStamp(dword dwFilenr, currdir cdDir) const
1045 {
1046 if (cdDir == OLDDIR)
1047 {
1048 return m_vOldiid[dwFilenr].impdesc.TimeDateStamp;
1049 }
1050 else
1051 {
1052 return m_vNewiid[dwFilenr].impdesc.TimeDateStamp;
1053 }
1054 }
1055
1056 template<int bits>
1057 void ImportDirectory<bits>::setTimeDateStamp(dword dwFilenr, currdir cdDir, dword value)
1058 {
1059 if (cdDir == OLDDIR)
1060 {
1061 m_vOldiid[dwFilenr].impdesc.TimeDateStamp = value;
1062 }
1063 else
1064 {
1065 m_vNewiid[dwFilenr].impdesc.TimeDateStamp = value;
1066 }
1067 }
1068
1069 template<int bits>
1070 dword ImportDirectory<bits>::getRvaOfName(dword dwFilenr, currdir cdDir) const
1071 {
1072 if (cdDir == OLDDIR)
1073 {
1074 return m_vOldiid[dwFilenr].impdesc.Name;
1075 }
1076 else
1077 {
1078 return m_vNewiid[dwFilenr].impdesc.Name;
1079 }
1080 }
1081
1082 template<int bits>
1083 void ImportDirectory<bits>::setRvaOfName(dword dwFilenr, currdir cdDir, dword value)
1084 {
1085 if (cdDir == OLDDIR)
1086 {
1087 m_vOldiid[dwFilenr].impdesc.Name = value;
1088 }
1089 else
1090 {
1091 m_vNewiid[dwFilenr].impdesc.Name = value;
1092 }
1093 }
1094
1095 /**
1096 * @param dwFilenr ID of the imported file.
1097 * @param dwFuncnr ID of the imported function.
1098 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
1099 * @return FirstThunk value of an imported function.
1100 **/
1101 template<int bits>
1102 dword ImportDirectory<bits>::getFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir) const
1103 {
1104 if (cdDir == OLDDIR) return m_vOldiid[dwFilenr].firstthunk[dwFuncnr].itd.Ordinal;
1105 else return m_vNewiid[dwFilenr].firstthunk[dwFuncnr].itd.Ordinal;
1106 }
1107
1108 template<int bits>
1109 void ImportDirectory<bits>::setFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir, dword value)
1110 {
1111 if (cdDir == OLDDIR) m_vOldiid[dwFilenr].firstthunk[dwFuncnr].itd.Ordinal = value;
1112 else m_vNewiid[dwFilenr].firstthunk[dwFuncnr].itd.Ordinal = value;
1113 }
1114
1115 /**
1116 * @param dwFilenr ID of the imported file.
1117 * @param dwFuncnr ID of the imported function.
1118 * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
1119 * @return OriginalFirstThunk value of an imported function.
1120 **/
1121 template<int bits>
1122 dword ImportDirectory<bits>::getOriginalFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir) const
1123 {
1124 if (cdDir == OLDDIR) return m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].itd.Ordinal;
1125 else return m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].itd.Ordinal;
1126 }
1127
1128 template<int bits>
1129 void ImportDirectory<bits>::setOriginalFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir, dword value)
1130 {
1131 if (cdDir == OLDDIR) m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].itd.Ordinal = value;
1132 else m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].itd.Ordinal = value;
1133 }
1134
1135 typedef ImportDirectory<32> ImportDirectory32;
1136 typedef ImportDirectory<64> ImportDirectory64;
1137}
1138
1139#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/MzHeader.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/MzHeader.cpp
new file mode 100755
index 0000000000..39fe54d80d
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/MzHeader.cpp
@@ -0,0 +1,584 @@
1/*
2* MzHeader.cpp - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#include "MzHeader.h"
14#include <iostream>
15
16namespace PeLib
17{
18 /**
19 * Reads data from an InputBuffer into the struct that represents the MZ header.
20 * It's required that the size of the input buffer is at least as big as the
21 * size of a MZ header. Otherwise we get undefined behaviour.
22 * @param ibBuffer InputBuffer that holds the data.
23 * @return A non-zero value is returned if a problem occured.
24 **/
25 void MzHeader::read(InputBuffer& ibBuffer)
26 {
27 ibBuffer >> m_idhHeader.e_magic;
28 ibBuffer >> m_idhHeader.e_cblp;
29 ibBuffer >> m_idhHeader.e_cp;
30 ibBuffer >> m_idhHeader.e_crlc;
31 ibBuffer >> m_idhHeader.e_cparhdr;
32 ibBuffer >> m_idhHeader.e_minalloc;
33 ibBuffer >> m_idhHeader.e_maxalloc;
34 ibBuffer >> m_idhHeader.e_ss;
35 ibBuffer >> m_idhHeader.e_sp;
36 ibBuffer >> m_idhHeader.e_csum;
37 ibBuffer >> m_idhHeader.e_ip;
38 ibBuffer >> m_idhHeader.e_cs;
39 ibBuffer >> m_idhHeader.e_lfarlc;
40 ibBuffer >> m_idhHeader.e_ovno;
41
42 for (unsigned int i=0;i<sizeof(m_idhHeader.e_res)/sizeof(m_idhHeader.e_res[0]);i++)
43 {
44 ibBuffer >> m_idhHeader.e_res[i];
45 }
46
47 ibBuffer >> m_idhHeader.e_oemid;
48 ibBuffer >> m_idhHeader.e_oeminfo;
49
50 for (unsigned int i=0;i<sizeof(m_idhHeader.e_res2)/sizeof(m_idhHeader.e_res2[0]);i++)
51 {
52 ibBuffer >> m_idhHeader.e_res2[i];
53 }
54
55 ibBuffer >> m_idhHeader.e_lfanew;
56 }
57
58 /**
59 * Tests if the currently loaded MZ header is a valid MZ header.
60 * Note that this function does not check if the address to the PE header is valid as this is not possible.
61 * Actually, the only thing this function checks is if the e_magic value is set to 0x5A4D (IMAGE_DOS_SIGNATURE).
62 * Everything else is not relevant for Windows 2000 and that's the system PeLib is focusing on for now.
63 * @return A boolean value that indicates if the MZ header is correct or not.
64 **/
65 bool MzHeader::isValid() const
66 {
67 // The only thing that matters on Windows 2K is the e_magic value. The entire rest is for DOS compatibility.
68 return isValid(e_magic);
69 }
70
71 bool MzHeader::isValid(Field f) const
72 {
73 if (f == e_magic)
74 {
75 return m_idhHeader.e_magic == PELIB_IMAGE_DOS_SIGNATURE;
76 }
77 else
78 {
79 return true;
80 }
81 }
82
83 /**
84 * Corrects all erroneous values of the current MZ header. Note that this function does not correct the
85 * pointer to the PE header.
86 * Actually, the only thing this function corrects is the e_magic value.
87 * Everything else is not relevant for Windows 2000 and that's the system PeLib is focusing on for now.
88 **/
89 void MzHeader::makeValid()
90 {
91 // The only thing that matters on Windows is the e_magic value. The entire rest is for DOS compatibility.
92 setMagicNumber(PELIB_IMAGE_DOS_SIGNATURE);
93 }
94
95 void MzHeader::makeValid(Field f)
96 {
97 if (f == e_magic)
98 {
99 setMagicNumber(PELIB_IMAGE_DOS_SIGNATURE);
100 }
101 }
102
103 /**
104 * Reads the MZ header from a file. Note that this function does not verify if a file is actually a MZ file.
105 * For this purpose see #PeFile::MzHeader::isValid. The reason for this is simple: Otherwise it might not
106 * be possible to load damaged PE files to repair them.
107 * @param strFilename Name of the file which will be read.
108 * @return A non-zero value is returned if a problem occured.
109 **/
110 int MzHeader::read(const std::string& strFilename)
111 {
112 std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
113
114 if (!ifFile)
115 {
116 return ERROR_OPENING_FILE;
117 }
118
119 if (fileSize(ifFile) < PELIB_IMAGE_DOS_HEADER::size())
120 {
121 return ERROR_INVALID_FILE;
122 }
123
124 ifFile.seekg(0, std::ios::beg);
125
126 originalOffset = 0;
127
128 std::vector<byte> vBuffer(PELIB_IMAGE_DOS_HEADER::size());
129 ifFile.read(reinterpret_cast<char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
130 ifFile.close();
131
132 InputBuffer ibBuffer(vBuffer);
133 read(ibBuffer);
134 return NO_ERROR;
135 }
136
137 /**
138 * Reads the MZ header from memory. A pointer to a location in memory is passed and the data
139 * at this location is treated like a MZ header structure. The MZ header does not need to be valid.
140 * @param pcBuffer Pointer to a MZ header.
141 * @param uiSize Length of the buffer.
142 * @return A non-zero value is returned if a problem occured.
143 **/
144 int MzHeader::read(unsigned char* pcBuffer, unsigned int uiSize, unsigned int originalOffs)
145 {
146 if (uiSize < PELIB_IMAGE_DOS_HEADER::size())
147 {
148 return ERROR_INVALID_FILE;
149 }
150
151 std::vector<byte> vBuffer(pcBuffer, pcBuffer + uiSize);
152 for (int i=0;i<0x40;i++) std::cout << std::hex << (int)vBuffer[i] << " ";
153
154 originalOffset = originalOffs;
155
156 InputBuffer ibBuffer(vBuffer);
157 read(ibBuffer);
158 return NO_ERROR;
159 }
160
161 /**
162 * Rebuilds the MZ header so that it can be written to a file. It's not guaranteed that the
163 * MZ header will be valid. If you want to make sure that the MZ header will be valid you
164 * must call #PeLib::MzHeader::makeValid first.
165 * @param vBuffer Buffer where the rebuilt MZ header will be stored.
166 **/
167 void MzHeader::rebuild(std::vector<byte>& vBuffer) const
168 {
169 OutputBuffer obBuffer(vBuffer);
170
171 obBuffer << m_idhHeader.e_magic;
172 obBuffer << m_idhHeader.e_cblp;
173 obBuffer << m_idhHeader.e_cp;
174 obBuffer << m_idhHeader.e_crlc;
175 obBuffer << m_idhHeader.e_cparhdr;
176 obBuffer << m_idhHeader.e_minalloc;
177 obBuffer << m_idhHeader.e_maxalloc;
178 obBuffer << m_idhHeader.e_ss;
179 obBuffer << m_idhHeader.e_sp;
180 obBuffer << m_idhHeader.e_csum;
181 obBuffer << m_idhHeader.e_ip;
182 obBuffer << m_idhHeader.e_cs;
183 obBuffer << m_idhHeader.e_lfarlc;
184 obBuffer << m_idhHeader.e_ovno;
185
186 for (unsigned int i=0;i<sizeof(m_idhHeader.e_res)/sizeof(m_idhHeader.e_res[0]);i++)
187 {
188 obBuffer << m_idhHeader.e_res[i];
189 }
190
191 obBuffer << m_idhHeader.e_oemid;
192 obBuffer << m_idhHeader.e_oeminfo;
193
194 for (unsigned int i=0;i<sizeof(m_idhHeader.e_res2)/sizeof(m_idhHeader.e_res2[0]);i++)
195 {
196 obBuffer << m_idhHeader.e_res2[i];
197 }
198
199 obBuffer << m_idhHeader.e_lfanew;
200 }
201
202 /**
203 * Returns the size of the MZ header. This size is actually always sizeof(IMAGE_DOS_HEADER) (== 0x40)
204 * because the MZ header is a header of constant size if you disregard the dos stub. If you want to know the
205 * size of the MZ header + the size of the dos stub check #PeLib::MzHeader::getAddressOfPeHeader.
206 * @return Size of the MZ header.
207 **/
208 unsigned int MzHeader::size() const
209 {
210 return sizeof(m_idhHeader);
211 }
212
213 /**
214 * Writes the current MZ header to a file. The file does not have to exist. If it doesn't exist
215 * it will be created.
216 * @param strFilename Name of the file the header will be written to.
217 * @param dwOffset Offset the header will be written to (defaults to 0).
218 * @return A non-zero value is returned if a problem occured.
219 **/
220 int MzHeader::write(const std::string& strFilename, dword dwOffset = 0) const
221 {
222 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
223
224 if (!ofFile)
225 {
226 ofFile.clear();
227 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
228 }
229 else
230 {
231 ofFile.close();
232 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
233 }
234
235 if (!ofFile)
236 {
237 return ERROR_OPENING_FILE;
238 }
239
240 ofFile.seekp(dwOffset, std::ios::beg);
241
242 std::vector<unsigned char> vBuffer;
243
244 rebuild(vBuffer);
245
246 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
247
248 ofFile.close();
249
250 return NO_ERROR;
251 }
252
253 /**
254 * Returns the MZ header's e_magic value.
255 **/
256 word MzHeader::getMagicNumber() const
257 {
258 return m_idhHeader.e_magic;
259 }
260
261 /**
262 * Returns the MZ header's e_cblp value.
263 **/
264 word MzHeader::getBytesOnLastPage() const
265 {
266 return m_idhHeader.e_cblp;
267 }
268
269 /**
270 * Returns the MZ header's e_cp value.
271 **/
272 word MzHeader::getPagesInFile() const
273 {
274 return m_idhHeader.e_cp;
275 }
276
277 /**
278 * Returns the MZ header's e_crlc value.
279 **/
280 word MzHeader::getRelocations() const
281 {
282 return m_idhHeader.e_crlc;
283 }
284
285 /**
286 * Returns the MZ header's e_cparhdr value.
287 **/
288 word MzHeader::getSizeOfHeader() const
289 {
290 return m_idhHeader.e_cparhdr;
291 }
292
293 /**
294 * Returns the MZ header's e_minalloc value.
295 **/
296 word MzHeader::getMinExtraParagraphs() const
297 {
298 return m_idhHeader.e_minalloc;
299 }
300
301 /**
302 * Returns the MZ header's e_maxalloc value.
303 **/
304 word MzHeader::getMaxExtraParagraphs() const
305 {
306 return m_idhHeader.e_maxalloc;
307 }
308
309 /**
310 * Returns the MZ header's e_ss value.
311 **/
312 word MzHeader::getSsValue() const
313 {
314 return m_idhHeader.e_ss;
315 }
316
317 /**
318 * Returns the MZ header's e_sp value.
319 **/
320 word MzHeader::getSpValue() const
321 {
322 return m_idhHeader.e_sp;
323 }
324
325 /**
326 * Returns the MZ header's e_csum value.
327 **/
328 word MzHeader::getChecksum() const
329 {
330 return m_idhHeader.e_csum;
331 }
332
333 /**
334 * Returns the MZ header's e_ip value.
335 **/
336 word MzHeader::getIpValue() const
337 {
338 return m_idhHeader.e_ip;
339 }
340
341 /**
342 * Returns the MZ header's e_cs value.
343 **/
344 word MzHeader::getCsValue() const
345 {
346 return m_idhHeader.e_cs;
347 }
348
349 /**
350 * Returns the MZ header's e_lfarlc value.
351 **/
352 word MzHeader::getAddrOfRelocationTable() const
353 {
354 return m_idhHeader.e_lfarlc;
355 }
356
357 /**
358 * Returns the MZ header's e_ovno value.
359 **/
360 word MzHeader::getOverlayNumber() const
361 {
362 return m_idhHeader.e_ovno;
363 }
364
365 /**
366 * Returns the MZ header's e_oemid value.
367 **/
368 word MzHeader::getOemIdentifier() const
369 {
370 return m_idhHeader.e_oemid;
371 }
372
373 /**
374 * Returns the MZ header's e_oeminfo value.
375 **/
376 word MzHeader::getOemInformation() const
377 {
378 return m_idhHeader.e_oeminfo;
379 }
380
381 /**
382 * Returns the MZ header's e_lfanew value.
383 **/
384 dword MzHeader::getAddressOfPeHeader() const
385 {
386 return m_idhHeader.e_lfanew;
387 }
388
389 /**
390 * Returns the MZ header's e_res[uiNr] value. If the parameter uiNr is out of range
391 * you will get undefined behaviour.
392 * @param uiNr The index of the word in the e_res array (valid range: 0-3)
393 **/
394 word MzHeader::getReservedWords1(unsigned int uiNr) const
395 {
396 return m_idhHeader.e_res[uiNr];
397 }
398
399 /**
400 * Returns the MZ header's e_res2[uiNr] value. If the parameter uiNr is out of range
401 * you will get undefined behaviour.
402 * @param uiNr The index of the word in the e_res array (valid range: 0-9)
403 **/
404 word MzHeader::getReservedWords2(unsigned int uiNr) const
405 {
406 return m_idhHeader.e_res2[uiNr];
407 }
408
409 /**
410 * Sets the MZ header's e_magic value.
411 * @param wValue The new value of e_magic.
412 **/
413 void MzHeader::setMagicNumber(word wValue)
414 {
415 m_idhHeader.e_magic = wValue;
416 }
417
418 /**
419 * Sets the MZ header's e_cblp value.
420 * @param wValue The new value of e_cblp.
421 **/
422 void MzHeader::setBytesOnLastPage(word wValue)
423 {
424 m_idhHeader.e_cblp = wValue;
425 }
426
427 /**
428 * Sets the MZ header's e_cp value.
429 * @param wValue The new value of e_cp.
430 **/
431 void MzHeader::setPagesInFile(word wValue)
432 {
433 m_idhHeader.e_cp = wValue;
434 }
435
436 /**
437 * Sets the MZ header's e_crlc value.
438 * @param wValue The new value of e_crlc.
439 **/
440 void MzHeader::setRelocations(word wValue)
441 {
442 m_idhHeader.e_crlc = wValue;
443 }
444
445 /**
446 * Sets the MZ header's e_cparhdr value.
447 * @param wValue The new value of e_cparhdr.
448 **/
449 void MzHeader::setSizeOfHeader(word wValue)
450 {
451 m_idhHeader.e_cparhdr = wValue;
452 }
453
454 /**
455 * Sets the MZ header's e_minalloc value.
456 * @param wValue The new value of e_minalloc.
457 **/
458 void MzHeader::setMinExtraParagraphs(word wValue)
459 {
460 m_idhHeader.e_minalloc = wValue;
461 }
462
463 /**
464 * Sets the MZ header's e_maxalloc value.
465 * @param wValue The new value of e_maxalloc.
466 **/
467 void MzHeader::setMaxExtraParagraphs(word wValue)
468 {
469 m_idhHeader.e_maxalloc = wValue;
470 }
471
472 /**
473 * Sets the MZ header's e_ss value.
474 * @param wValue The new value of e_ss.
475 **/
476 void MzHeader::setSsValue(word wValue)
477 {
478 m_idhHeader.e_ss = wValue;
479 }
480
481 /**
482 * Sets the MZ header's e_sp value.
483 * @param wValue The new value of e_sp.
484 **/
485 void MzHeader::setSpValue(word wValue)
486 {
487 m_idhHeader.e_sp = wValue;
488 }
489
490 /**
491 * Sets the MZ header's e_csum value.
492 * @param wValue The new value of e_csum.
493 **/
494 void MzHeader::setChecksum(word wValue)
495 {
496 m_idhHeader.e_csum = wValue;
497 }
498
499 /**
500 * Sets the MZ header's e_ip value.
501 * @param wValue The new value of e_ip.
502 **/
503 void MzHeader::setIpValue(word wValue)
504 {
505 m_idhHeader.e_ip = wValue;
506 }
507
508 /**
509 * Sets the MZ header's e_cs value.
510 * @param wValue The new value of e_cs.
511 **/
512 void MzHeader::setCsValue(word wValue)
513 {
514 m_idhHeader.e_cs = wValue;
515 }
516
517 /**
518 * Sets the MZ header's e_lfarlc value.
519 * @param wValue The new value of e_lfarlc.
520 **/
521 void MzHeader::setAddrOfRelocationTable(word wValue)
522 {
523 m_idhHeader.e_lfarlc = wValue;
524 }
525
526 /**
527 * Sets the MZ header's e_ovno value.
528 * @param wValue The new value of e_ovno.
529 **/
530 void MzHeader::setOverlayNumber(word wValue)
531 {
532 m_idhHeader.e_ovno = wValue;
533 }
534
535 /**
536 * Sets the MZ header's e_oemid value.
537 * @param wValue The new value of e_oemid.
538 **/
539 void MzHeader::setOemIdentifier(word wValue)
540 {
541 m_idhHeader.e_oemid = wValue;
542 }
543
544 /**
545 * Sets the MZ header's e_oeminfo value.
546 * @param wValue The new value of e_oeminfo.
547 **/
548 void MzHeader::setOemInformation(word wValue)
549 {
550 m_idhHeader.e_oeminfo = wValue;
551 }
552
553 /**
554 * Sets the MZ header's e_lfanew value.
555 * @param lValue The new value of e_lfanew.
556 **/
557 void MzHeader::setAddressOfPeHeader(dword lValue)
558 {
559 m_idhHeader.e_lfanew = lValue;
560 }
561
562 /**
563 * Sets the MZ header's e_res[uiNr] value. If the parameter uiNr is out of range
564 * you will get undefined behaviour.
565 * @param uiNr The index of the word in the e_res array (valid range: 0-3)
566 * @param wValue The new value of e_res[nr].
567 **/
568 void MzHeader::setReservedWords1(unsigned int uiNr, word wValue)
569 {
570 m_idhHeader.e_res[uiNr] = wValue;
571 }
572
573 /**
574 * Sets the MZ header's e_res2[uiNr] value. If the parameter uiNr is out of range
575 * you will get undefined behaviour.
576 * @param uiNr The index of the word in the e_res2 array (valid range: 0-9)
577 * @param wValue The new value of e_res[nr].
578 **/
579 void MzHeader::setReservedWords2(unsigned int uiNr, word wValue)
580 {
581 m_idhHeader.e_res2[uiNr] = wValue;
582 }
583
584}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/MzHeader.h b/utils/zenutils/libraries/pelib-0.9/pelib/MzHeader.h
new file mode 100755
index 0000000000..5aca6bfe59
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/MzHeader.h
@@ -0,0 +1,148 @@
1/*
2* MzHeader.h - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#ifndef MZHEADER_H
14#define MZHEADER_H
15
16#include "PeLibInc.h"
17
18namespace PeLib
19{
20 /// Class that handles the MZ header of files.
21 /**
22 * This class can read and modify MZ headers. It provides set- and get functions to access
23 * all individual members of a MZ header. Furthermore it's possible to validate and rebuild
24 * MZ headers.
25 **/
26 class MzHeader
27 {
28 private:
29 PELIB_IMAGE_DOS_HEADER m_idhHeader; ///< Stores all MZ header information.
30
31 /// Reads data from an InputBuffer into a MZ header struct.
32 void read(InputBuffer& ibBuffer);
33
34 /// Offset of the MZ header in the original file.
35 unsigned int originalOffset;
36
37 public:
38
39 enum Field {e_magic, e_cblp, e_cp, e_crlc, e_cparhdr, e_minalloc, e_maxalloc,
40 e_ss, e_sp, e_csum, e_ip, e_cs, e_lfarlc, e_ovno, e_res, e_oemid,
41 e_oeminfo, e_res2, e_lfanew};
42
43 /// Checks if the current MZ header is valid.
44 bool isValid() const; // EXPORT
45
46 bool isValid(Field field) const; // EXPORT _field
47
48 /// Corrects the current MZ header.
49 void makeValid(); // EXPORT
50
51 void makeValid(Field field); // EXPORT _field
52
53 /// Reads the MZ header of a file.
54 int read(const std::string& strFilename); // EXPORT
55
56 /// Reads the MZ header from a memory location.
57 int read(unsigned char* pcBuffer, unsigned int uiSize, unsigned int originalOffs = 0); // EXPORT _fromMemory
58
59 /// Rebuild the MZ header.
60 void rebuild(std::vector<byte>& vBuffer) const; // EXPORT
61
62 /// Returns the size of the current MZ header.
63 unsigned int size() const; // EXPORT
64
65 /// Writes the current MZ header to offset 0 of a file.
66 int write(const std::string& strFilename, dword dwOffset) const; // EXPORT
67
68 /// Gets the e_magic value of the MZ header.
69 word getMagicNumber() const; // EXPORT
70 /// Gets the e_cblp value of the MZ header.
71 word getBytesOnLastPage() const; // EXPORT
72 /// Gets the e_cp value of the MZ header.
73 word getPagesInFile() const; // EXPORT
74 /// Gets the e_crlc value of the MZ header.
75 word getRelocations() const; // EXPORT
76 /// Gets the e_cparhdr value of the MZ header.
77 word getSizeOfHeader() const; // EXPORT
78 /// Gets the e_minalloc value of the MZ header.
79 word getMinExtraParagraphs() const; // EXPORT
80 /// Gets the e_maxalloc value of the MZ header.
81 word getMaxExtraParagraphs() const; // EXPORT
82 /// Gets the e_ss value of the MZ header.
83 word getSsValue() const; // EXPORT
84 /// Gets the e_sp value of the MZ header.
85 word getSpValue() const; // EXPORT
86 /// Gets the e_csum value of the MZ header.
87 word getChecksum() const; // EXPORT
88 /// Gets the e_ip value of the MZ header.
89 word getIpValue() const; // EXPORT
90 /// Gets the e_cs value of the MZ header.
91 word getCsValue() const; // EXPORT
92 /// Gets the e_lfarlc value of the MZ header.
93 word getAddrOfRelocationTable() const; // EXPORT
94 /// Gets the e_ovnovalue of the MZ header.
95 word getOverlayNumber() const; // EXPORT
96 /// Gets the e_oemid value of the MZ header.
97 word getOemIdentifier() const; // EXPORT
98 /// Gets the e_oeminfo value of the MZ header.
99 word getOemInformation() const; // EXPORT
100 /// Gets the e_lfanew value of the MZ header.
101 dword getAddressOfPeHeader() const; // EXPORT
102 /// Gets the e_res of the MZ header.
103 word getReservedWords1(unsigned int uiNr) const; // EXPORT
104 /// Gets the e_res2 of the MZ header.
105 word getReservedWords2(unsigned int uiNr) const; // EXPORT
106
107 /// Sets the e_magic value of the MZ header.
108 void setMagicNumber(word wValue); // EXPORT
109 /// Sets the e_cblp value of the MZ header.
110 void setBytesOnLastPage(word wValue); // EXPORT
111 /// Sets the e_cp value of the MZ header.
112 void setPagesInFile(word wValue); // EXPORT
113 /// Sets the e_crlc value of the MZ header.
114 void setRelocations(word wValue); // EXPORT
115 /// Sets the e_cparhdr value of the MZ header.
116 void setSizeOfHeader(word wValue); // EXPORT
117 /// Sets the e_minalloc value of the MZ header.
118 void setMinExtraParagraphs(word wValue); // EXPORT
119 /// Sets the e_maxalloc value of the MZ header.
120 void setMaxExtraParagraphs(word wValue); // EXPORT
121 /// Sets the e_ss value of the MZ header.
122 void setSsValue(word wValue); // EXPORT
123 /// Sets the e_sp value of the MZ header.
124 void setSpValue(word wValue); // EXPORT
125 /// Sets the e_csum value of the MZ header.
126 void setChecksum(word wValue); // EXPORT
127 /// Sets the e_ip value of the MZ header.
128 void setIpValue(word wValue); // EXPORT
129 /// Sets the e_cs value of the MZ header.
130 void setCsValue(word wValue); // EXPORT
131 /// Sets the e_lfarlc value of the MZ header.
132 void setAddrOfRelocationTable(word wValue); // EXPORT
133 /// Sets the e_ovno value of the MZ header.
134 void setOverlayNumber(word wValue); // EXPORT
135 /// Sets the e_oemid value of the MZ header.
136 void setOemIdentifier(word wValue); // EXPORT
137 /// Sets the e_oeminfo value of the MZ header.
138 void setOemInformation(word wValue); // EXPORT
139 /// Sets the e_lfanew value of the MZ header.
140 void setAddressOfPeHeader(dword dwValue); // EXPORT
141 /// Sets the e_res value of the MZ header.
142 void setReservedWords1(unsigned int uiNr, word wValue); // EXPORT
143 /// Sets the e_res2 value of the MZ header.
144 void setReservedWords2(unsigned int uiNr, word wValue); // EXPORT
145 };
146}
147
148#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/PeFile.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/PeFile.cpp
new file mode 100755
index 0000000000..39f2488b81
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/PeFile.cpp
@@ -0,0 +1,169 @@
1/*
2* PeLib.cpp - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#include "PeFile.h"
14
15namespace PeLib
16{
17 PeFile::~PeFile()
18 {
19 }
20
21 PeFile32::PeFile32() : PeFileT<32>()
22 {
23 }
24
25 PeFile32::PeFile32(const std::string& strFlename) : PeFileT<32>(strFlename)
26 {
27 }
28
29 PeFile64::PeFile64() : PeFileT<64>()
30 {
31 }
32
33 PeFile64::PeFile64(const std::string& strFlename) : PeFileT<64>(strFlename)
34 {
35 }
36
37 /**
38 * @return A reference to the file's MZ header.
39 **/
40
41 const MzHeader& PeFile::mzHeader() const
42 {
43 return m_mzh;
44 }
45
46 /**
47 * @return A reference to the file's MZ header.
48 **/
49
50 MzHeader& PeFile::mzHeader()
51 {
52 return m_mzh;
53 }
54
55 /**
56 * @return A reference to the file's export directory.
57 **/
58
59 const ExportDirectory& PeFile::expDir() const
60 {
61 return m_expdir;
62 }
63
64 /**
65 * @return A reference to the file's export directory.
66 **/
67
68 ExportDirectory& PeFile::expDir()
69 {
70 return m_expdir;
71 }
72
73 /**
74 * @return A reference to the file's bound import directory.
75 **/
76
77 const BoundImportDirectory& PeFile::boundImpDir() const
78 {
79 return m_boundimpdir;
80 }
81
82 /**
83 * @return A reference to the file's bound import directory.
84 **/
85
86 BoundImportDirectory& PeFile::boundImpDir()
87 {
88 return m_boundimpdir;
89 }
90
91 /**
92 * @return A reference to the file's resource directory.
93 **/
94
95 const ResourceDirectory& PeFile::resDir() const
96 {
97 return m_resdir;
98 }
99
100 /**
101 * @return A reference to the file's resource directory.
102 **/
103
104 ResourceDirectory& PeFile::resDir()
105 {
106 return m_resdir;
107 }
108
109 /**
110 * @return A reference to the file's relocations directory.
111 **/
112
113 const RelocationsDirectory& PeFile::relocDir() const
114 {
115 return m_relocs;
116 }
117
118 /**
119 * @return A reference to the file's relocations directory.
120 **/
121
122 RelocationsDirectory& PeFile::relocDir()
123 {
124 return m_relocs;
125 }
126
127 /**
128 * @return A reference to the file's COM+ descriptor directory.
129 **/
130
131 const ComHeaderDirectory& PeFile::comDir() const
132 {
133 return m_comdesc;
134 }
135
136 /**
137 * @return A reference to the file's COM+ descriptor directory.
138 **/
139
140 ComHeaderDirectory & PeFile::comDir()
141 {
142 return m_comdesc;
143 }
144
145
146 const IatDirectory& PeFile::iatDir() const
147 {
148 return m_iat;
149 }
150
151
152 IatDirectory& PeFile::iatDir()
153 {
154 return m_iat;
155 }
156
157
158 const DebugDirectory& PeFile::debugDir() const
159 {
160 return m_debugdir;
161 }
162
163
164 DebugDirectory& PeFile::debugDir()
165 {
166 return m_debugdir;
167 }
168
169}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/PeFile.h b/utils/zenutils/libraries/pelib-0.9/pelib/PeFile.h
new file mode 100755
index 0000000000..a2b02cdfa8
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/PeFile.h
@@ -0,0 +1,451 @@
1/*
2* PeFile.h - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#ifndef PEFILE_H
14#define PEFILE_H
15
16#include "PeLibInc.h"
17#include "MzHeader.h"
18#include "PeHeader.h"
19#include "ImportDirectory.h"
20#include "ExportDirectory.h"
21#include "BoundImportDirectory.h"
22#include "ResourceDirectory.h"
23#include "RelocationsDirectory.h"
24#include "ComHeaderDirectory.h"
25#include "IatDirectory.h"
26#include "DebugDirectory.h"
27#include "TlsDirectory.h"
28
29namespace PeLib
30{
31 class PeFile32;
32 class PeFile64;
33
34 /**
35 * Visitor base class for PeFiles.
36 **/
37 class PeFileVisitor
38 {
39 public:
40 virtual void callback(PeFile32 &file){}
41 virtual void callback(PeFile64 &file){}
42 virtual ~PeFileVisitor(){}
43 };
44
45 /**
46 * Traits class that's used to decide of what type the PeHeader in a PeFile is.
47 **/
48 template<int>
49 struct PeFile_Traits;
50
51 template<>
52 struct PeFile_Traits<32>
53 {
54 typedef PeHeader32 PeHeader32_64;
55 };
56
57 template<>
58 struct PeFile_Traits<64>
59 {
60 typedef PeHeader64 PeHeader32_64;
61 };
62
63 /**
64 * This class represents the common structures of PE and PE+ files.
65 **/
66 class PeFile
67 {
68 protected:
69 std::string m_filename; ///< Name of the current file.
70 MzHeader m_mzh; ///< MZ header of the current file.
71 ExportDirectory m_expdir; ///< Export directory of the current file.
72 BoundImportDirectory m_boundimpdir; ///< BoundImportDirectory of the current file.
73 ResourceDirectory m_resdir; ///< ResourceDirectory of the current file.
74 RelocationsDirectory m_relocs; ///< Relocations directory of the current file.
75 ComHeaderDirectory m_comdesc; ///< COM+ descriptor directory of the current file.
76 IatDirectory m_iat; ///< Import address table of the current file.
77 DebugDirectory m_debugdir;
78 public:
79 virtual ~PeFile();
80
81 /// Returns the name of the current file.
82 virtual std::string getFileName() const = 0; // EXPORT
83 /// Changes the name of the current file.
84 virtual void setFileName(std::string strFilename) = 0; // EXPORT
85
86 virtual void visit(PeFileVisitor &v) = 0;
87
88 /// Reads the MZ header of the current file from disc.
89 virtual int readMzHeader() = 0; // EXPORT
90 /// Reads the export directory of the current file from disc.
91 virtual int readExportDirectory() = 0; // EXPORT
92 /// Reads the PE header of the current file from disc.
93 virtual int readPeHeader() = 0; // EXPORT
94 /// Reads the import directory of the current file from disc.
95 virtual int readImportDirectory() = 0; // EXPORT
96 /// Reads the bound import directory of the current file from disc.
97 virtual int readBoundImportDirectory() = 0; // EXPORT
98 /// Reads the resource directory of the current file from disc.
99 virtual int readResourceDirectory() = 0; // EXPORT
100 /// Reads the relocations directory of the current file from disc.
101 virtual int readRelocationsDirectory() = 0; // EXPORT
102 /// Reads the COM+ descriptor directory of the current file from disc.
103 virtual int readComHeaderDirectory() = 0; // EXPORT
104 /// Reads the IAT directory of the current file from disc.
105 virtual int readIatDirectory() = 0; // EXPORT
106 /// Reads the Debug directory of the current file.
107 virtual int readDebugDirectory() = 0; // EXPORT
108 virtual int readTlsDirectory() = 0; // EXPORT
109
110 virtual unsigned int getBits() const = 0;
111
112 /// Accessor function for the MZ header.
113 const MzHeader& mzHeader() const;
114 /// Accessor function for the MZ header.
115 MzHeader& mzHeader(); // EXPORT
116
117 /// Accessor function for the export directory.
118 const ExportDirectory& expDir() const;
119 /// Accessor function for the export directory.
120 ExportDirectory& expDir(); // EXPORT
121
122 /// Accessor function for the bound import directory.
123 const BoundImportDirectory& boundImpDir() const;
124 /// Accessor function for the bound import directory.
125 BoundImportDirectory& boundImpDir(); // EXPORT
126
127 /// Accessor function for the resource directory.
128 const ResourceDirectory& resDir() const;
129 /// Accessor function for the resource directory.
130 ResourceDirectory& resDir(); // EXPORT
131
132 /// Accessor function for the relocations directory.
133 const RelocationsDirectory& relocDir() const;
134 /// Accessor function for the relocations directory.
135 RelocationsDirectory& relocDir(); // EXPORT
136
137 /// Accessor function for the COM+ descriptor directory.
138 const ComHeaderDirectory& comDir() const;
139 /// Accessor function for the COM+ descriptor directory.
140 ComHeaderDirectory& comDir(); // EXPORT
141
142 /// Accessor function for the IAT directory.
143 const IatDirectory& iatDir() const;
144 /// Accessor function for the IAT directory.
145 IatDirectory& iatDir(); // EXPORT
146
147 /// Accessor function for the debug directory.
148 const DebugDirectory& debugDir() const;
149 /// Accessor function for the debug directory.
150 DebugDirectory& debugDir(); // EXPORT
151
152 };
153
154 /**
155 * This class implements the common structures of PE and PE+ files.
156 **/
157 template<int bits>
158 class PeFileT : public PeFile
159 {
160 typedef typename PeFile_Traits<bits>::PeHeader32_64 PeHeader32_64;
161
162 private:
163 PeHeader32_64 m_peh; ///< PE header of the current file.
164 ImportDirectory<bits> m_impdir; ///< Import directory of the current file.
165 TlsDirectory<bits> m_tlsdir;
166
167 public:
168 /// Default constructor which exists only for the sake of allowing to construct files without filenames.
169 PeFileT();
170
171 virtual ~PeFileT() {}
172
173 /// Initializes a PeFile with a filename
174 explicit PeFileT(const std::string& strFilename);
175
176 /// Returns the name of the current file.
177 std::string getFileName() const;
178 /// Changes the name of the current file.
179 void setFileName(std::string strFilename);
180
181 /// Reads the MZ header of the current file from disc.
182 int readMzHeader() ;
183 /// Reads the export directory of the current file from disc.
184 int readExportDirectory() ;
185 /// Reads the PE header of the current file from disc.
186 int readPeHeader() ;
187 /// Reads the import directory of the current file from disc.
188 int readImportDirectory() ;
189 /// Reads the bound import directory of the current file from disc.
190 int readBoundImportDirectory() ;
191 /// Reads the resource directory of the current file from disc.
192 int readResourceDirectory() ;
193 /// Reads the relocations directory of the current file from disc.
194 int readRelocationsDirectory() ;
195 /// Reads the COM+ descriptor directory of the current file from disc.
196 int readComHeaderDirectory() ;
197 /// Reads the IAT directory of the current file from disc.
198 int readIatDirectory() ;
199 /// Reads the Debug directory of the current file.
200 int readDebugDirectory() ;
201 int readTlsDirectory() ;
202
203 unsigned int getBits() const
204 {
205 return bits;
206 }
207
208 /// Accessor function for the PE header.
209 const PeHeader32_64& peHeader() const;
210 /// Accessor function for the PE header.
211 PeHeader32_64& peHeader();
212
213 /// Accessor function for the import directory.
214 const ImportDirectory<bits>& impDir() const;
215 /// Accessor function for the import directory.
216 ImportDirectory<bits>& impDir();
217
218 const TlsDirectory<bits>& tlsDir() const;
219 TlsDirectory<bits>& tlsDir();
220 };
221
222 /**
223 * This class is the main class for handling PE files.
224 **/
225 class PeFile32 : public PeFileT<32>
226 {
227 public:
228 /// Default constructor which exists only for the sake of allowing to construct files without filenames.
229 PeFile32();
230
231 /// Initializes a PeFile with a filename
232 explicit PeFile32(const std::string& strFlename);
233 virtual void visit(PeFileVisitor &v) { v.callback( *this ); }
234 };
235
236 /**
237 * This class is the main class for handling PE+ files.
238 **/
239 class PeFile64 : public PeFileT<64>
240 {
241 public:
242 /// Default constructor which exists only for the sake of allowing to construct files without filenames.
243 PeFile64();
244
245 /// Initializes a PeFile with a filename
246 explicit PeFile64(const std::string& strFlename);
247 virtual void visit(PeFileVisitor &v) { v.callback( *this ); }
248 };
249
250 //typedef PeFileT<32> PeFile32;
251 //typedef PeFileT<64> PeFile64;
252
253 /**
254 * @param strFilename Name of the current file.
255 **/
256 template<int bits>
257 PeFileT<bits>::PeFileT(const std::string& strFilename)
258 {
259 m_filename = strFilename;
260 }
261
262 template<int bits>
263 PeFileT<bits>::PeFileT()
264 {
265 }
266
267 template<int bits>
268 int PeFileT<bits>::readPeHeader()
269 {
270 return peHeader().read(getFileName(), mzHeader().getAddressOfPeHeader());
271 }
272
273
274 template<int bits>
275 int PeFileT<bits>::readImportDirectory()
276 {
277 if (peHeader().calcNumberOfRvaAndSizes() >= 2
278 && peHeader().getIddImportRva()
279 && peHeader().getIddImportSize())
280 {
281 return impDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddImportRva())), peHeader().getIddImportSize(), peHeader());
282 }
283 return ERROR_DIRECTORY_DOES_NOT_EXIST;
284 }
285
286 /**
287 * @return A reference to the file's PE header.
288 **/
289 template<int bits>
290 const typename PeFile_Traits<bits>::PeHeader32_64& PeFileT<bits>::peHeader() const
291 {
292 return m_peh;
293 }
294
295 /**
296 * @return A reference to the file's PE header.
297 **/
298 template<int bits>
299 typename PeFile_Traits<bits>::PeHeader32_64& PeFileT<bits>::peHeader()
300 {
301 return m_peh;
302 }
303
304 /**
305 * @return A reference to the file's import directory.
306 **/
307 template<int bits>
308 const ImportDirectory<bits>& PeFileT<bits>::impDir() const
309 {
310 return m_impdir;
311 }
312
313 /**
314 * @return A reference to the file's import directory.
315 **/
316 template<int bits>
317 ImportDirectory<bits>& PeFileT<bits>::impDir()
318 {
319 return m_impdir;
320 }
321
322 template<int bits>
323 const TlsDirectory<bits>& PeFileT<bits>::tlsDir() const
324 {
325 return m_tlsdir;
326 }
327
328 template<int bits>
329 TlsDirectory<bits>& PeFileT<bits>::tlsDir()
330 {
331 return m_tlsdir;
332 }
333
334 /**
335 * @return Filename of the current file.
336 **/
337 template<int bits>
338 std::string PeFileT<bits>::getFileName() const
339 {
340 return m_filename;
341 }
342
343 /**
344 * @param strFilename New filename.
345 **/
346 template<int bits>
347 void PeFileT<bits>::setFileName(std::string strFilename)
348 {
349 m_filename = strFilename;
350 }
351
352 template<int bits>
353 int PeFileT<bits>::readMzHeader()
354 {
355 return mzHeader().read(getFileName());
356 }
357
358 template<int bits>
359 int PeFileT<bits>::readExportDirectory()
360 {
361 if (peHeader().calcNumberOfRvaAndSizes() >= 1
362 && peHeader().getIddExportRva() && peHeader().getIddExportSize())
363 {
364 return expDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddExportRva())), peHeader().getIddExportSize(), peHeader());
365 }
366 return ERROR_DIRECTORY_DOES_NOT_EXIST;
367 }
368
369
370 template<int bits>
371 int PeFileT<bits>::readBoundImportDirectory()
372 {
373 if (peHeader().calcNumberOfRvaAndSizes() >= 12
374 && peHeader().getIddBoundImportRva() && peHeader().getIddBoundImportSize())
375 {
376 return boundImpDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddBoundImportRva())), peHeader().getIddBoundImportSize());
377 }
378 return ERROR_DIRECTORY_DOES_NOT_EXIST;
379 }
380
381 template<int bits>
382 int PeFileT<bits>::readResourceDirectory()
383 {
384 if (peHeader().calcNumberOfRvaAndSizes() >= 3
385 && peHeader().getIddResourceRva() && peHeader().getIddResourceSize())
386 {
387 return resDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddResourceRva())), peHeader().getIddResourceSize(), peHeader().getIddResourceRva());
388 }
389 return ERROR_DIRECTORY_DOES_NOT_EXIST;
390 }
391
392 template<int bits>
393 int PeFileT<bits>::readRelocationsDirectory()
394 {
395 if (peHeader().calcNumberOfRvaAndSizes() >= 6
396 && peHeader().getIddBaseRelocRva() && peHeader().getIddBaseRelocSize())
397 {
398 return relocDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddBaseRelocRva())), peHeader().getIddBaseRelocSize());
399 }
400 return ERROR_DIRECTORY_DOES_NOT_EXIST;
401 }
402
403 template<int bits>
404 int PeFileT<bits>::readComHeaderDirectory()
405 {
406 if (peHeader().calcNumberOfRvaAndSizes() >= 15
407 && peHeader().getIddComHeaderRva() && peHeader().getIddComHeaderSize())
408 {
409 return comDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddComHeaderRva())), peHeader().getIddComHeaderSize());
410 }
411 std::cout << peHeader().getIddComHeaderRva() << std::endl;
412 std::exit(0);
413 return ERROR_DIRECTORY_DOES_NOT_EXIST;
414 }
415
416 template<int bits>
417 int PeFileT<bits>::readIatDirectory()
418 {
419 if (peHeader().calcNumberOfRvaAndSizes() >= 13
420 && peHeader().getIddIatRva() && peHeader().getIddIatSize())
421 {
422 return iatDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddIatRva())), peHeader().getIddIatSize());
423 }
424 return ERROR_DIRECTORY_DOES_NOT_EXIST;
425 }
426
427 template<int bits>
428 int PeFileT<bits>::readDebugDirectory()
429 {
430 if (peHeader().calcNumberOfRvaAndSizes() >= 7
431 && peHeader().getIddDebugRva() && peHeader().getIddDebugSize())
432 {
433 return debugDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddDebugRva())), peHeader().getIddDebugSize());
434 }
435 return ERROR_DIRECTORY_DOES_NOT_EXIST;
436 }
437
438 template<int bits>
439 int PeFileT<bits>::readTlsDirectory()
440 {
441 if (peHeader().calcNumberOfRvaAndSizes() >= 10
442 && peHeader().getIddTlsRva() && peHeader().getIddTlsSize())
443 {
444 return tlsDir().read(getFileName(), static_cast<unsigned int>(peHeader().rvaToOffset(peHeader().getIddTlsRva())), peHeader().getIddTlsSize());
445 }
446 return ERROR_DIRECTORY_DOES_NOT_EXIST;
447 }
448
449}
450
451#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/PeHeader.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/PeHeader.cpp
new file mode 100755
index 0000000000..fe7011072c
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/PeHeader.cpp
@@ -0,0 +1,90 @@
1/*
2* PeHeader.cpp - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#include "PeLibInc.h"
14#include "PeHeader.h"
15
16namespace PeLib
17{
18 template<>
19 void PeHeaderT<32>::readBaseOfData(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<32>& header) const
20 {
21 ibBuffer >> header.OptionalHeader.BaseOfData;
22 }
23
24 template<>
25 void PeHeaderT<64>::readBaseOfData(InputBuffer&, PELIB_IMAGE_NT_HEADERS<64>&) const
26 {
27 }
28
29 template<>
30 void PeHeaderT<32>::rebuildBaseOfData(OutputBuffer& obBuffer) const
31 {
32 obBuffer << m_inthHeader.OptionalHeader.BaseOfData;
33 }
34
35 template<>
36 void PeHeaderT<64>::rebuildBaseOfData(OutputBuffer&) const
37 {
38 }
39
40 template<>
41 bool PeHeaderT<32>::isValid() const
42 {
43 return true;
44 }
45
46 template<>
47 bool PeHeaderT<64>::isValid() const
48 {
49 return true;
50 }
51
52 template<>
53 bool PeHeaderT<32>::isValid(unsigned int pehf) const
54 {
55 /*
56 if (pehf == NtSignature)
57 {
58 return m_inthHeader.Signature == IMAGE_NT_SIGNATURE;
59 }
60 else if (pehf == NumberOfSections)
61 {
62 return getNumberOfSections() == calcNumberOfSections();
63 } */
64 return false;
65 }
66
67 template<>
68 bool PeHeaderT<64>::isValid(unsigned int pehf) const
69 {
70 return false;
71 }
72
73 /**
74 * @return The BaseOfData value from the PE header.
75 **/
76 dword PeHeader32::getBaseOfData() const
77 {
78 return m_inthHeader.OptionalHeader.BaseOfData;
79 }
80
81 /**
82 * Changes the file's BaseOfData.
83 * @param dwValue New value.
84 **/
85 void PeHeader32::setBaseOfData(dword dwValue)
86 {
87 m_inthHeader.OptionalHeader.BaseOfData = dwValue;
88 }
89
90}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/PeHeader.h b/utils/zenutils/libraries/pelib-0.9/pelib/PeHeader.h
new file mode 100755
index 0000000000..08eaca4072
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/PeHeader.h
@@ -0,0 +1,2685 @@
1/*
2* PeHeader.h - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#ifndef PEHEADER_H
14#define PEHEADER_H
15
16#include "PeLibAux.h"
17
18namespace PeLib
19{
20 class PeHeader
21 {
22// protected:
23// virtual void readBaseOfData(InputBuffer& ibBuffer) = 0;
24// virtual void rebuildBaseOfData(OutputBuffer& obBuffer) const = 0;
25
26 public:
27 virtual ~PeHeader(){};
28 };
29
30 /// Class that handles the PE header of files.
31 /**
32 * This class can read and modify PE headers. It provides set- and get functions to access
33 * all individual members of a PE header. Furthermore it's possible to validate and rebuild
34 * PE headers. A PE header includes the IMAGE_Nt_HEADERS and the section definitions of a PE file.
35 * \todo getIdReservedRva
36 **/
37 template<int x>
38 class PeHeaderT : public PeHeader
39 {
40 private:
41 void readBaseOfData(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const;
42 void rebuildBaseOfData(OutputBuffer& obBuffer) const;
43
44 protected:
45 std::vector<PELIB_IMAGE_SECTION_HEADER> m_vIsh; ///< Stores section header information.
46 PELIB_IMAGE_NT_HEADERS<x> m_inthHeader; ///< Stores Nt header information.
47 dword m_uiOffset; ///< Equivalent to the value returned by #PeLib::MzHeader::getAddressOfPeFile
48
49 public:
50 typedef typename FieldSizes<x>::VAR4_8 VAR4_8;
51
52 PeHeaderT() : m_uiOffset(0)
53 {
54 }
55
56 /// Add a section to the header.
57 int addSection(const std::string& strName, dword dwSize); // EXPORT
58
59 unsigned int calcSizeOfImage() const; // EXPORT
60
61 /// Returns the unused space after the header.
62 unsigned int calcSpaceAfterHeader() const; // EXPORT
63
64 /// Returns the address of the physically first section (not the first defined section).
65 unsigned int calcStartOfCode() const; // EXPORT
66
67 /// Calculates the offset for a new section of size uiSize.
68 unsigned int calcOffset() const; // EXPORT
69
70 /// Calculates the Rva for a new section of size uiSize.
71 unsigned int calcRva() const; // EXPORT
72
73 /// Returns the number of sections in the current file.
74 word calcNumberOfSections() const; // EXPORT
75
76 void enlargeLastSection(unsigned int uiSize); // EXPORT
77
78 /// Returns the section Id of the section that contains the offset.
79 word getSectionWithOffset(VAR4_8 dwOffset) const; // EXPORT
80
81 /// Returns the number of the section which the given relative address points to.
82 word getSectionWithRva(VAR4_8 rva) const; // EXPORT
83
84 bool isValid() const; // EXPORT
85 bool isValid(unsigned int foo) const; // EXPORT
86
87 /// Corrects the current PE header.
88 void makeValid(dword dwOffset); // EXPORT
89
90 /// Converts a file offset to a relative virtual offset.
91 unsigned int offsetToRva(VAR4_8 dwOffset) const; // EXPORT
92
93 /// Converts a file offset to a virtual address.
94 unsigned int offsetToVa(VAR4_8 dwOffset) const; // EXPORT
95
96 /// Reads the PE header of a file.
97 int read(std::string strFilename, unsigned int uiOffset); // EXPORT
98
99 int read(const unsigned char* pcBuffer, unsigned int uiSize, unsigned int uiOffset); // EXPORT
100
101 void readHeader(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const;
102 void readDataDirectories(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const;
103 std::vector<PELIB_IMAGE_SECTION_HEADER> readSections(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const;
104
105 /// Rebuilds the current PE header.
106 void rebuild(std::vector<byte>& vBuffer) const; // EXPORT
107
108 /// Converts a relative virtual address to a file offset.
109 VAR4_8 rvaToOffset(VAR4_8 dwRva) const; // EXPORT
110
111 /// Converts a relative virtual address to a virtual address.
112 VAR4_8 rvaToVa(VAR4_8 dwRva) const; // EXPORT
113
114 /// Calculates the size for the current PE header including all section definitions.
115 unsigned int size() const;
116
117 VAR4_8 vaToRva(VAR4_8 dwRva) const; // EXPORT
118 VAR4_8 vaToOffset(VAR4_8 dwRva) const; // EXPORT
119
120 /// Save the PE header to a file.
121 int write(std::string strFilename, unsigned int uiOffset) const; // EXPORT
122
123 /// Writes sections to a file.
124 int writeSections(const std::string& strFilename) const; // EXPORT
125 /// Overwrites a section with new data.
126 int writeSectionData(const std::string& strFilename, word wSecnr, const std::vector<byte>& vBuffer) const; // EXPORT
127
128// header getters
129 /// Returns the Signature value of the header.
130 dword getNtSignature() const; // EXPORT
131 /// Returns the Machine value of the header.
132 word getMachine() const; // EXPORT
133 /// Returns the Sections value of the header.
134 word getNumberOfSections() const; // EXPORT
135 /// Returns the TimeDateStamp value of the header.
136 dword getTimeDateStamp() const; // EXPORT
137 /// Returns the PointerToSymbolTable value of the header.
138 dword getPointerToSymbolTable() const; // EXPORT
139 /// Returns the NumberOfSymbols value of the header.
140 dword getNumberOfSymbols() const; // EXPORT
141 /// Returns the SizeOfOptionalHeader value of the header.
142 word getSizeOfOptionalHeader() const; // EXPORT
143 /// Returns the Characteristics value of the header.
144 word getCharacteristics() const; // EXPORT
145
146 /// Returns the Magic value of the header.
147 word getMagic() const; // EXPORT
148 /// Returns the MajorLinkerVersion value of the header.
149 byte getMajorLinkerVersion() const; // EXPORT
150 /// Returns the MinorLinkerVersion value of the header.
151 byte getMinorLinkerVersion() const; // EXPORT
152 /// Returns the SizeOfCode value of the header.
153 dword getSizeOfCode() const; // EXPORT
154 /// Returns the SizeOfInitializedData value of the header.
155 dword getSizeOfInitializedData() const; // EXPORT
156 /// Returns the SizeOfUninitializedData value of the header.
157 dword getSizeOfUninitializedData() const; // EXPORT
158 /// Returns the AddressOfEntryPoint value of the header.
159 dword getAddressOfEntryPoint() const; // EXPORT
160 /// Returns the BaseOfCode value of the header.
161 dword getBaseOfCode() const; // EXPORT
162 /// Returns the ImageBase value of the header.
163 VAR4_8 getImageBase() const; // EXPORT
164 /// Returns the SectionAlignment value of the header.
165 dword getSectionAlignment() const; // EXPORT
166 /// Returns the FileAlignment value of the header.
167 dword getFileAlignment() const; // EXPORT
168 /// Returns the MajorOperatingSystemVersion value of the header.
169 word getMajorOperatingSystemVersion() const; // EXPORT
170 /// Returns the MinorOperatingSystemVersion value of the header.
171 word getMinorOperatingSystemVersion() const; // EXPORT
172 /// Returns the MajorImageVersion value of the header.
173 word getMajorImageVersion() const; // EXPORT
174 /// Returns the MinorImageVersion value of the header.
175 word getMinorImageVersion() const; // EXPORT
176 /// Returns the MajorSubsystemVersion value of the header.
177 word getMajorSubsystemVersion() const; // EXPORT
178 /// Returns the MinorSubsystemVersion value of the header.
179 word getMinorSubsystemVersion() const; // EXPORT
180 /// Returns the Reserved1 value of the header.
181 dword getWin32VersionValue() const; // EXPORT
182 /// Returns the SizeOfImage value of the header.
183 dword getSizeOfImage() const; // EXPORT
184 /// Returns the SizeOfHeaders value of the header.
185 dword getSizeOfHeaders() const; // EXPORT
186 /// Returns the CheckSum value of the header.
187 dword getCheckSum() const; // EXPORT
188 /// Returns the Subsystem value of the header.
189 word getSubsystem() const; // EXPORT
190 /// Returns the DllCharacteristics value of the header.
191 word getDllCharacteristics() const; // EXPORT
192 /// Returns the SizeOfStackReserve value of the header.
193 VAR4_8 getSizeOfStackReserve() const; // EXPORT
194 /// Returns the SizeOfStackCommit value of the header.
195 VAR4_8 getSizeOfStackCommit() const; // EXPORT
196 /// Returns the SizeOfHeapReserve value of the header.
197 VAR4_8 getSizeOfHeapReserve() const; // EXPORT
198 /// Returns the SizeOfHeapCommit value of the header.
199 VAR4_8 getSizeOfHeapCommit() const; // EXPORT
200 /// Returns the LoaderFlags value of the header.
201 dword getLoaderFlags() const; // EXPORT
202 /// Returns the NumberOfRvaAndSizes value of the header.
203 dword getNumberOfRvaAndSizes() const; // EXPORT
204 dword calcNumberOfRvaAndSizes() const; // EXPORT
205
206 void addDataDirectory(); // EXPORT
207 void removeDataDirectory(dword index); // EXPORT
208
209// image directory getters
210 /// Returns the relative virtual address of the image directory Export.
211 dword getIddExportRva() const; // EXPORT
212 /// Returns the size of the image directory Export.
213 dword getIddExportSize() const; // EXPORT
214 /// Returns the relative virtual address of the image directory Import.
215 dword getIddImportRva() const; // EXPORT
216 /// Returns the size of the image directory Import.
217 dword getIddImportSize() const; // EXPORT
218 /// Returns the relative virtual address of the image directory Resource.
219 dword getIddResourceRva() const; // EXPORT
220 /// Returns the size of the image directory Resource.
221 dword getIddResourceSize() const; // EXPORT
222 /// Returns the relative virtual address of the image directory Exception.
223 dword getIddExceptionRva() const; // EXPORT
224 /// Returns the size of the image directory Exception.
225 dword getIddExceptionSize() const; // EXPORT
226 /// Returns the relative virtual address of the image directory Security.
227 dword getIddSecurityRva() const; // EXPORT
228 /// Returns the size of the image directory Security.
229 dword getIddSecuritySize() const; // EXPORT
230 /// Returns the relative virtual address of the image directory Base Reloc.
231 dword getIddBaseRelocRva() const; // EXPORT
232 /// Returns the size of the image directory Base Reloc.
233 dword getIddBaseRelocSize() const; // EXPORT
234 /// Returns the relative virtual address of the image directory Debug.
235 dword getIddDebugRva() const; // EXPORT
236 /// Returns the size of the image directory Debug.
237 dword getIddDebugSize() const; // EXPORT
238 /// Returns the relative virtual address of the image directory Architecture.
239 dword getIddArchitectureRva() const; // EXPORT
240 /// Returns the size of the image directory Architecture.
241 dword getIddArchitectureSize() const; // EXPORT
242 /// Returns the relative virtual address of the image directory GlobalPtr.
243 dword getIddGlobalPtrRva() const; // EXPORT
244 /// Returns the size of the image directory GlobalPtr.
245 dword getIddGlobalPtrSize() const; // EXPORT
246 /// Returns the relative virtual address of the image directory Tls.
247 dword getIddTlsRva() const; // EXPORT
248 /// Returns the size of the image directory Tls.
249 dword getIddTlsSize() const; // EXPORT
250 /// Returns the relative virtual address of the image directory LoadConfig.
251 dword getIddLoadConfigRva() const; // EXPORT
252 /// Returns the size of the image directory LoadConfig.
253 dword getIddLoadConfigSize() const; // EXPORT
254 /// Returns the relative virtual address of the image directory BoundImport.
255 dword getIddBoundImportRva() const; // EXPORT
256 /// Returns the size of the image directory BoundImport.
257 dword getIddBoundImportSize() const; // EXPORT
258 /// Returns the relative virtual address of the image directory Iat.
259 dword getIddIatRva() const; // EXPORT
260 /// Returns the size of the image directory Iat.
261 dword getIddIatSize() const; // EXPORT
262 /// Returns the relative virtual address of the image directory DelayImport.
263 dword getIddDelayImportRva() const; // EXPORT
264 /// Returns the size of the image directory DelayImport.
265 dword getIddDelayImportSize() const; // EXPORT
266 /// Returns the relative virtual address of the image directory COM Descriptor.
267 dword getIddComHeaderRva() const; // EXPORT
268 /// Returns the size of the image directory COM Descriptor.
269 dword getIddComHeaderSize() const; // EXPORT
270
271 /// Returns the relative virtual address of an image directory.
272 dword getImageDataDirectoryRva(dword dwDirectory) const; // EXPORT
273 /// Returns the size of an image directory.
274 dword getImageDataDirectorySize(dword dwDirectory) const; // EXPORT
275
276 void setImageDataDirectoryRva(dword dwDirectory, dword value); // EXPORT
277 void setImageDataDirectorySize(dword dwDirectory, dword value); // EXPORT
278
279// section getters
280 /// Returns the name of a section.
281 std::string getSectionName(word uiSectionnr) const; // EXPORT
282 /// Returns the virtual size of a section.
283 dword getVirtualSize(word uiSectionnr) const; // EXPORT
284 /// Returns the virtual address of a section.
285 dword getVirtualAddress(word uiSectionnr) const; // EXPORT
286 /// Returns the size of a section's raw data.
287 dword getSizeOfRawData(word uiSectionnr) const; // EXPORT
288 /// Returns file offset of the data of a section.
289 dword getPointerToRawData(word uiSectionnr) const; // EXPORT
290 /// Returns the rva of the relocations of a section.
291 dword getPointerToRelocations(word uiSectionnr) const; // EXPORT
292 /// Returns the rva of the line numbers of a section.
293 dword getPointerToLinenumbers(word uiSectionnr) const; // EXPORT
294 /// Returns the number of relocations of a section.
295 dword getNumberOfRelocations(word uiSectionnr) const; // EXPORT
296 /// Returns the number of line numbers of a section.
297 dword getNumberOfLinenumbers(word uiSectionnr) const; // EXPORT
298 /// Returns the characteristics of a section.
299 dword getCharacteristics(word uiSectionnr) const; // EXPORT _section
300
301// header setters
302 /// Sets the Signature value of the header.
303 void setNtSignature(dword value); // EXPORT
304 /// Sets the Machine value of the header.
305 void setMachine(word value); // EXPORT
306 /// Sets the Sections value of the header.
307 void setNumberOfSections(word value); // EXPORT
308 /// Sets the TimeDateStamp value of the header.
309 void setTimeDateStamp(dword value); // EXPORT
310 /// Sets the PointerToSymbolTable value of the header.
311 void setPointerToSymbolTable(dword value); // EXPORT
312 /// Sets the NumberOfSymbols value of the header.
313 void setNumberOfSymbols(dword value); // EXPORT
314 /// Sets the SizeOfOptionalHeader value of the header.
315 void setSizeOfOptionalHeader(word value); // EXPORT
316 /// Sets the Characteristics value of the header.
317 void setCharacteristics(word value); // EXPORT _section
318
319 /// Sets the Magic value of the header.
320 void setMagic(word value); // EXPORT
321 /// Sets the MajorLinkerVersion value of the header.
322 void setMajorLinkerVersion(byte value); // EXPORT
323 /// Sets the MinorLinkerVersion value of the header.
324 void setMinorLinkerVersion(byte value); // EXPORT
325 /// Sets the SizeOfCode value of the header.
326 void setSizeOfCode(dword value); // EXPORT
327 /// Sets the SizeOfInitializedData value of the header.
328 void setSizeOfInitializedData(dword value); // EXPORT
329 /// Sets the SizeOfUninitializedData value of the header.
330 void setSizeOfUninitializedData(dword value); // EXPORT
331 /// Sets the AddressOfEntryPoint value of the header.
332 void setAddressOfEntryPoint(dword value); // EXPORT
333 /// Sets the BaseOfCode value of the header.
334 void setBaseOfCode(dword value); // EXPORT
335 /// Sets the ImageBase value of the header.
336 void setImageBase(VAR4_8 value); // EXPORT
337 /// Sets the SectionAlignment value of the header.
338 void setSectionAlignment(dword value); // EXPORT
339 /// Sets the FileAlignment value of the header.
340 void setFileAlignment(dword value); // EXPORT
341 /// Sets the MajorOperatingSystemVersion value of the header.
342 void setMajorOperatingSystemVersion(word value); // EXPORT
343 /// Sets the MinorOperatingSystemVersion value of the header.
344 void setMinorOperatingSystemVersion(word value); // EXPORT
345 /// Sets the MajorImageVersion value of the header.
346 void setMajorImageVersion(word value); // EXPORT
347 /// Sets the MinorImageVersion value of the header.
348 void setMinorImageVersion(word value); // EXPORT
349 /// Sets the MajorSubsystemVersion value of the header.
350 void setMajorSubsystemVersion(word value); // EXPORT
351 /// Sets the MinorSubsystemVersion value of the header.
352 void setMinorSubsystemVersion(word value); // EXPORT
353 /// Sets the Reserved1 value of the header.
354 void setWin32VersionValue(dword value); // EXPORT
355 /// Sets the SizeOfImage value of the header.
356 void setSizeOfImage(dword value); // EXPORT
357 /// Sets the SizeOfHeaders value of the header.
358 void setSizeOfHeaders(dword value); // EXPORT
359 /// Sets the CheckSum value of the header.
360 void setCheckSum(dword value); // EXPORT
361 /// Sets the Subsystem value of the header.
362 void setSubsystem(word value); // EXPORT
363 /// Sets the DllCharacteristics value of the header.
364 void setDllCharacteristics(word value); // EXPORT
365 /// Sets the SizeOfStackReserve value of the header.
366 void setSizeOfStackReserve(VAR4_8 value); // EXPORT
367 /// Sets the SizeOfStackCommit value of the header.
368 void setSizeOfStackCommit(VAR4_8 value); // EXPORT
369 /// Sets the SizeOfHeapReserve value of the header.
370 void setSizeOfHeapReserve(VAR4_8 value); // EXPORT
371 /// Sets the SizeOfHeapCommit value of the header.
372 void setSizeOfHeapCommit(VAR4_8 value); // EXPORT
373 /// Sets the LoaderFlags value of the header.
374 void setLoaderFlags(dword value); // EXPORT
375 /// Sets the NumberOfRvaAndSizes value of the header.
376 void setNumberOfRvaAndSizes(dword value); // EXPORT
377
378// image directory getters
379 void setIddDebugRva(dword dwValue); // EXPORT
380 void setIddDebugSize(dword dwValue); // EXPORT
381 void setIddDelayImportRva(dword dwValue); // EXPORT
382 void setIddDelayImportSize(dword dwValue); // EXPORT
383 void setIddExceptionRva(dword dwValue); // EXPORT
384 void setIddExceptionSize(dword dwValue); // EXPORT
385 void setIddGlobalPtrRva(dword dwValue); // EXPORT
386 void setIddGlobalPtrSize(dword dwValue); // EXPORT
387 void setIddIatRva(dword dwValue); // EXPORT
388 void setIddIatSize(dword dwValue); // EXPORT
389 void setIddLoadConfigRva(dword dwValue); // EXPORT
390 void setIddLoadConfigSize(dword dwValue); // EXPORT
391 void setIddResourceRva(dword dwValue); // EXPORT
392 void setIddResourceSize(dword dwValue); // EXPORT
393 void setIddSecurityRva(dword dwValue); // EXPORT
394 void setIddSecuritySize(dword dwValue); // EXPORT
395 void setIddTlsRva(dword dwValue); // EXPORT
396 void setIddTlsSize(dword dwValue); // EXPORT
397
398 void setIddImportRva(dword dwValue); // EXPORT
399 void setIddImportSize(dword dwValue); // EXPORT
400 void setIddExportRva(dword dwValue); // EXPORT
401 void setIddExportSize(dword dwValue); // EXPORT
402
403 void setIddBaseRelocRva(dword value); // EXPORT
404 void setIddBaseRelocSize(dword value); // EXPORT
405 void setIddArchitectureRva(dword value); // EXPORT
406 void setIddArchitectureSize(dword value); // EXPORT
407 void setIddComHeaderRva(dword value); // EXPORT
408 void setIddComHeaderSize(dword value); // EXPORT
409
410 /// Set the name of a section.
411 void setSectionName(word uiSectionnr, std::string strName); // EXPORT
412 /// Set the virtual size of a section.
413 void setVirtualSize(word uiSectionnr, dword dwValue); // EXPORT
414 /// Set the virtual address of a section.
415 void setVirtualAddress(word uiSectionnr, dword dwValue); // EXPORT
416 /// Set the size of raw data of a section.
417 void setSizeOfRawData(word uiSectionnr, dword dwValue); // EXPORT
418 /// Set the file offset of a section.
419 void setPointerToRawData(word uiSectionnr, dword dwValue); // EXPORT
420 /// Set the pointer to relocations of a section.
421 void setPointerToRelocations(word uiSectionnr, dword dwValue); // EXPORT
422 /// Set the pointer to linenumbers of a section.
423 void setPointerToLinenumbers(word uiSectionnr, dword dwValue); // EXPORT
424 /// Set the number of relocations a section.
425 void setNumberOfRelocations(word uiSectionnr, dword dwValue); // EXPORT
426 /// Set the number of linenumbers section.
427 void setNumberOfLinenumbers(word uiSectionnr, dword dwValue); // EXPORT
428 /// Set the characteristics of a section.
429 void setCharacteristics(word uiSectionnr, dword dwValue); // EXPORT
430 };
431
432 class PeHeader32 : public PeHeaderT<32>
433 {
434 public:
435 /// Returns the BaseOfData value of the header.
436 dword getBaseOfData() const; // EXPORT
437 /// Sets the BaseOfData value of the header.
438 void setBaseOfData(dword value); // EXPORT
439 };
440
441 class PeHeader64 : public PeHeaderT<64>
442 {
443 };
444
445 template<int x>
446 void PeHeaderT<x>::addDataDirectory()
447 {
448 m_inthHeader.dataDirectories.push_back(PELIB_IMAGE_DATA_DIRECTORY());
449 }
450
451 template<int x>
452 void PeHeaderT<x>::removeDataDirectory(dword index)
453 {
454 m_inthHeader.dataDirectories.erase(m_inthHeader.dataDirectories.begin() + index);
455 }
456
457 /**
458 * Adds a new section to the header. The physical and virtual address as well as the virtual
459 * size of the section will be determined automatically from the raw size. The section
460 * characteristics will be set to IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ |
461 * IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_CNT_CODE. All other values will be set to 0.
462 * Note: It's important that if the current header's FileAlignment and/or SectionAlignment values are
463 * 0 this function will fail.
464 * @param strName Name of the new section. If this name is longer than 8 bytes only the first 8 bytes will be used.
465 * @param dwSize Physical size of the new section in bytes.
466 * \todo Better code that handles files with 0 sections.
467 **/
468 template<int x>
469 int PeHeaderT<x>::addSection(const std::string& strName, dword dwSize)
470 {
471 unsigned int uiSecnr = calcNumberOfSections();
472
473 if (!getFileAlignment())
474 {
475 return ERROR_NO_FILE_ALIGNMENT;
476 }
477 else if (!getSectionAlignment())
478 {
479 return ERROR_NO_SECTION_ALIGNMENT;
480 }
481
482 if (uiSecnr) // Always allow 1 section.
483 {
484 if (uiSecnr == 0xFFFF)
485 {
486 return ERROR_TOO_MANY_SECTIONS;
487 }
488 else if (calcSpaceAfterHeader() < PELIB_IMAGE_SECTION_HEADER::size())
489 {
490 return ERROR_NOT_ENOUGH_SPACE;
491 }
492 }
493
494 dword dwOffset = calcOffset(/*dwSize*/);
495 dword dwRva = calcRva(/*dwSize*/);
496
497 PELIB_IMAGE_SECTION_HEADER ishdCurr;
498 m_vIsh.push_back(ishdCurr);
499
500 setSectionName(uiSecnr, strName);
501 setSizeOfRawData(uiSecnr, alignOffset(dwSize, getFileAlignment()));
502 setPointerToRawData(uiSecnr, dwOffset);
503 setVirtualSize(uiSecnr, alignOffset(dwSize, getSectionAlignment()));
504 setVirtualAddress(uiSecnr, dwRva);
505 setCharacteristics(uiSecnr, PELIB_IMAGE_SCN_MEM_WRITE | PELIB_IMAGE_SCN_MEM_READ | PELIB_IMAGE_SCN_CNT_INITIALIZED_DATA | PELIB_IMAGE_SCN_CNT_CODE);
506
507 return NO_ERROR;
508 }
509
510 /**
511 * Calculates a valid SizeOfImage value given the information from the current PE header.
512 * Note that this calculation works in Win2K but probably does not work in Win9X. I didn't test that though.
513 * @return Valid SizeOfImage value.
514 **/
515 template<int x>
516 unsigned int PeHeaderT<x>::calcSizeOfImage() const
517 {
518 // Major note here: It's possible for sections to exist with a Virtual Size of 0.
519 // That's why it's necessary to use std::max(Vsize, RawSize) here.
520 // An example for such a file is dbeng6.exe (made by Sybase).
521 // In this file each and every section has a VSize of 0 but it still runs.
522
523 std::vector<PELIB_IMAGE_SECTION_HEADER>::const_iterator ishLastSection = std::max_element(m_vIsh.begin(), m_vIsh.end(), std::mem_fun_ref(&PELIB_IMAGE_SECTION_HEADER::biggerVirtualAddress));
524 if (ishLastSection->VirtualSize != 0) return ishLastSection->VirtualAddress + ishLastSection->VirtualSize;
525 return ishLastSection->VirtualAddress + std::max(ishLastSection->VirtualSize, ishLastSection->SizeOfRawData);
526 }
527
528 /**
529 * Calculates the space between the last byte of the header and the first byte that's used for something
530 * else (that's either the first section or an image directory).
531 * @return Unused space after the header.
532 * \todo There are PE files with sections beginning at offset 0. They
533 * need to be considered.
534 **/
535 template<int x>
536 unsigned int PeHeaderT<x>::calcSpaceAfterHeader() const
537 {
538 return (calcStartOfCode() > size() + m_uiOffset) ? calcStartOfCode() - (size() + m_uiOffset) : 0;
539 }
540
541 /**
542 * Returns the first offset of the file that's actually used for something different than the header.
543 * That something is not necessarily code, it can be a data directory too.
544 * This offset can be the beginning of a section or the beginning of a directory.
545 * \todo Some optimizization is surely possible here.
546 * \todo There are PE files with sections beginning at offset 0. They
547 * need to be considered. Returning 0 for these files doesn't really make sense.
548 * So far these sections are disregarded.
549 **/
550 template<int x>
551 unsigned int PeHeaderT<x>::calcStartOfCode() const
552 {
553 unsigned int directories = calcNumberOfRvaAndSizes();
554 dword dwMinOffset = 0xFFFFFFFF;
555 if (directories >= 1 && getIddExportRva() && rvaToOffset(getIddExportRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddExportRva());
556 if (directories >= 2 && getIddImportRva() && rvaToOffset(getIddImportRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddImportRva());
557 if (directories >= 3 && getIddResourceRva() && rvaToOffset(getIddResourceRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddResourceRva());
558 if (directories >= 4 && getIddExceptionRva() && rvaToOffset(getIddExceptionRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddExceptionRva());
559 if (directories >= 5 && getIddSecurityRva() && rvaToOffset(getIddSecurityRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddSecurityRva());
560 if (directories >= 6 && getIddBaseRelocRva() && rvaToOffset(getIddBaseRelocRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddBaseRelocRva());
561 if (directories >= 7 && getIddDebugRva() && rvaToOffset(getIddDebugRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddDebugRva());
562 if (directories >= 8 && getIddArchitectureRva() && rvaToOffset(getIddArchitectureRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddArchitectureRva());
563 if (directories >= 9 && getIddGlobalPtrRva() && rvaToOffset(getIddGlobalPtrRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddGlobalPtrRva());
564 if (directories >= 10 && getIddTlsRva() && rvaToOffset(getIddTlsRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddTlsRva());
565 if (directories >= 11 && getIddLoadConfigRva() && rvaToOffset(getIddLoadConfigRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddLoadConfigRva());
566 if (directories >= 12 && getIddBoundImportRva() && rvaToOffset(getIddBoundImportRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddBoundImportRva());
567 if (directories >= 13 && getIddIatRva() && rvaToOffset(getIddIatRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddIatRva());
568 if (directories >= 14 && getIddDelayImportRva() && rvaToOffset(getIddDelayImportRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddDelayImportRva());
569 if (directories >= 15 && getIddComHeaderRva() && rvaToOffset(getIddComHeaderRva()) < dwMinOffset) dwMinOffset = rvaToOffset(getIddComHeaderRva());
570
571 for (word i=0;i<calcNumberOfSections();i++)
572 {
573 if ((getPointerToRawData(i) < dwMinOffset || dwMinOffset == 0xFFFFFFFF) && getSizeOfRawData(i))
574 {
575 if (getPointerToRawData(i)) dwMinOffset = getPointerToRawData(i);
576 }
577 }
578 return dwMinOffset;
579 }
580
581 /**
582 * Calculates the file offset for a new section. The file offset will already be aligned to the file's FileAlignment.
583 * @return Aligned file offset.
584 * \todo uiSize isn't used yet. Will be used later on to search for caves.
585 **/
586 template<int x>
587 unsigned int PeHeaderT<x>::calcOffset(/*unsigned int uiSize*/) const
588 {
589 unsigned int maxoffset = size();
590
591 for (word i=0;i<calcNumberOfSections();i++)
592 {
593 if (getPointerToRawData(i) + getSizeOfRawData(i) > maxoffset) maxoffset = getPointerToRawData(i) + getSizeOfRawData(i);
594 }
595
596 return alignOffset(maxoffset, getFileAlignment());
597 }
598
599 /**
600 * Calculates the Rva for a new section. The Rva will already be aligned to the file's SectionAlignment.
601 * \todo uiSize isn't used yet. Will be used later on to search for caves.
602 * @return Aligned Rva.
603 **/
604 template<int x>
605 unsigned int PeHeaderT<x>::calcRva(/*unsigned int uiSize*/) const
606 {
607 // Major note here: It's possible for sections to exist with a Virtual Size of 0.
608 // That's why it's necessary to use std::max(Vsize, RawSize) here.
609 // An example for such a file is dbeng6.exe (made by Sybase).
610 // In this file each and every section has a VSize of 0 but it still runs.
611
612 unsigned int maxoffset = size();
613 for (word i=0;i<calcNumberOfSections();i++)
614 {
615 if (getVirtualAddress(i) + std::max(getVirtualSize(i), getSizeOfRawData(i)) > maxoffset) maxoffset = getVirtualAddress(i) + std::max(getVirtualSize(i), getSizeOfRawData(i));
616 }
617
618 return alignOffset(maxoffset, getSectionAlignment());
619 }
620
621 /**
622 * Returns the number of currently defined sections. Note that this value can be different from the number
623 * of sections according to the header (see #PeLib::PeHeaderT<x>::getNumberOfSections).
624 * @return Number of currently defined sections.
625 **/
626 template<int x>
627 word PeHeaderT<x>::calcNumberOfSections() const
628 {
629 return static_cast<PeLib::word>(m_vIsh.size());
630 }
631
632 /**
633 * Enlarges the physically last section in the file.
634 * @param uiSize Additional size that's added to the section's size.
635 **/
636 template<int x>
637 void PeHeaderT<x>::enlargeLastSection(unsigned int uiSize)
638 {
639 std::vector<PELIB_IMAGE_SECTION_HEADER>::iterator ishLastSection = std::max_element(m_vIsh.begin(), m_vIsh.end(), std::mem_fun_ref(&PELIB_IMAGE_SECTION_HEADER::biggerFileOffset));
640 unsigned int uiRawDataSize = alignOffset(ishLastSection->SizeOfRawData + uiSize, getFileAlignment());
641
642 ishLastSection->SizeOfRawData = uiRawDataSize;
643 ishLastSection->VirtualSize = ishLastSection->SizeOfRawData;
644
645 setSizeOfImage(calcSizeOfImage());
646 }
647
648 /**
649 * Determines the section which contains the file offset.
650 * @param dwOffset File offset.
651 * @return Section Id of the section which contains the offset.
652 **/
653 template<int x>
654 word PeHeaderT<x>::getSectionWithOffset(VAR4_8 dwOffset) const
655 {
656 // Offset = 0 must be handled explicitly as there are files
657 // with sections that begin at offset 0, that means the section
658 // only exists in memory.
659
660 if (!dwOffset) return std::numeric_limits<word>::max();
661
662 for (word i=0;i<calcNumberOfSections();i++)
663 {
664 // Explicity exclude sections with raw pointer = 0.
665 dword rawptr = getPointerToRawData(i);
666 if (rawptr && rawptr <= dwOffset && rawptr + getSizeOfRawData(i) > dwOffset) return i;
667 }
668
669 return std::numeric_limits<word>::max();
670 }
671
672 /**
673 * Determines the section which contains the Rva.
674 * @param dwRva A relative virtual address.
675 * @return Section Id of the section which contains the Rva.
676 **/
677 template<int x>
678 word PeHeaderT<x>::getSectionWithRva(VAR4_8 dwRva) const
679 {
680 // Major note here: It's possible for sections to exist with a Virtual Size of 0.
681 // That's why it's necessary to use std::max(Vsize, RawSize) here.
682 // An example for such a file is dbeng6.exe (made by Sybase).
683 // In this file each and every section has a VSize of 0 but it still runs.
684
685 for (word i=0;i<calcNumberOfSections();i++)
686 {
687 // Weird VC++7 error doesn't allow me to use std::max here.
688 dword max = getVirtualSize(i) >= getSizeOfRawData(i) ? getVirtualSize(i) : getSizeOfRawData(i);
689 if (getVirtualAddress(i) <= dwRva && getVirtualAddress(i) + max > dwRva) return i;
690 }
691
692 return -1;
693 }
694
695 /**
696 * Corrects all faulty values of the current PE header. The following values will be corrected: NtSignature,
697 * NumberOfSections, SizeOfOptionalHeader, FileAlignment (will be aligned to n*0x200),
698 * SectionAlignment (will be aligned to n*0x1000), NumberOfRvaAndSizes, SizeOfHeaders, SizeOfImage,
699 * Magic, Characteristics.
700 * @param dwOffset Beginning of PeHeader (see #PeLib::MzHeader::getAddressOfPeHeader).
701 * \todo 32bit and 64bit versions.
702 **/
703 template<int x>
704 void PeHeaderT<x>::makeValid(dword dwOffset)
705 {
706 setNtSignature(PELIB_IMAGE_NT_SIGNATURE); // 'PE'
707 setMachine(PELIB_IMAGE_FILE_MACHINE_I386);
708 setNumberOfSections(calcNumberOfSections());
709
710 // Check if 64 bits.
711 setSizeOfOptionalHeader(PELIB_IMAGE_OPTIONAL_HEADER<x>::size() + calcNumberOfRvaAndSizes() * 8);
712
713 // Check if 64 bits.
714 dword dwCharacteristics = PELIB_IMAGE_FILE_EXECUTABLE_IMAGE | PELIB_IMAGE_FILE_32BIT_MACHINE;
715 setCharacteristics(dwCharacteristics);
716
717 // Check if 64 bits.
718 setMagic(PELIB_IMAGE_NT_OPTIONAL_HDR32_MAGIC);
719
720 // setImageBase(0x01000000);
721
722 // Align file and section alignment values
723 unsigned int dwAlignedOffset = alignOffset(getSectionAlignment(), 0x1000);
724 setSectionAlignment(dwAlignedOffset ? dwAlignedOffset : 0x1000);
725
726 dwAlignedOffset = alignOffset(getFileAlignment(), 0x200);
727 setFileAlignment(dwAlignedOffset ? dwAlignedOffset : 0x200);
728
729// setMajorSubsystemVersion(4);
730// setSubsystem(IMAGE_SUBSYSTEM_WINDOWS_GUI);
731 setNumberOfRvaAndSizes(calcNumberOfRvaAndSizes());
732
733 // Code below depends on code above. Don't change the order.
734 dword dwSizeOfHeaders = alignOffset(dwOffset + size(), getFileAlignment());
735 setSizeOfHeaders(dwSizeOfHeaders);
736
737 dword dwSizeOfImage = alignOffset(dwSizeOfHeaders, getSectionAlignment());
738
739 for (int i=0;i<calcNumberOfSections();i++)
740 {
741 dwSizeOfImage += alignOffset(getVirtualSize(i), getSectionAlignment());
742 }
743
744 dwSizeOfImage = alignOffset(dwSizeOfImage, getSectionAlignment());
745 setSizeOfImage(dwSizeOfImage);
746 }
747
748 template<int x>
749 unsigned int PeHeaderT<x>::offsetToRva(VAR4_8 dwOffset) const
750 {
751 if (dwOffset < calcStartOfCode()) return dwOffset;
752
753 PeLib::word uiSecnr = getSectionWithOffset(dwOffset);
754
755 if (uiSecnr == 0xFFFF) return -1;
756
757 return getVirtualAddress(uiSecnr) + dwOffset - getPointerToRawData(uiSecnr);
758 }
759
760 /**
761 * Converts a file offset to a virtual address.
762 * @param dwOffset File offset.
763 * @return Virtual Address.
764 **/
765 template<int x>
766 unsigned int PeHeaderT<x>::offsetToVa(VAR4_8 dwOffset) const
767 {
768 if (dwOffset < calcStartOfCode()) return getImageBase() + dwOffset;
769
770 PeLib::word uiSecnr = getSectionWithOffset(dwOffset);
771
772 if (uiSecnr == 0xFFFF) return -1;
773
774 return getImageBase() + getVirtualAddress(uiSecnr) + dwOffset - getPointerToRawData(uiSecnr);
775 }
776
777 template<int x>
778 void PeHeaderT<x>::readHeader(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const
779 {
780 ibBuffer >> header.Signature;
781
782 ibBuffer >> header.FileHeader.Machine;
783 ibBuffer >> header.FileHeader.NumberOfSections;
784 ibBuffer >> header.FileHeader.TimeDateStamp;
785 ibBuffer >> header.FileHeader.PointerToSymbolTable;
786 ibBuffer >> header.FileHeader.NumberOfSymbols;
787 ibBuffer >> header.FileHeader.SizeOfOptionalHeader;
788 ibBuffer >> header.FileHeader.Characteristics;
789 ibBuffer >> header.OptionalHeader.Magic;
790
791 ibBuffer >> header.OptionalHeader.MajorLinkerVersion;
792 ibBuffer >> header.OptionalHeader.MinorLinkerVersion;
793 ibBuffer >> header.OptionalHeader.SizeOfCode;
794 ibBuffer >> header.OptionalHeader.SizeOfInitializedData;
795 ibBuffer >> header.OptionalHeader.SizeOfUninitializedData;
796 ibBuffer >> header.OptionalHeader.AddressOfEntryPoint;
797 ibBuffer >> header.OptionalHeader.BaseOfCode;
798 readBaseOfData(ibBuffer, header);
799 ibBuffer >> header.OptionalHeader.ImageBase;
800 ibBuffer >> header.OptionalHeader.SectionAlignment;
801 ibBuffer >> header.OptionalHeader.FileAlignment;
802 ibBuffer >> header.OptionalHeader.MajorOperatingSystemVersion;
803 ibBuffer >> header.OptionalHeader.MinorOperatingSystemVersion;
804 ibBuffer >> header.OptionalHeader.MajorImageVersion;
805 ibBuffer >> header.OptionalHeader.MinorImageVersion;
806 ibBuffer >> header.OptionalHeader.MajorSubsystemVersion;
807 ibBuffer >> header.OptionalHeader.MinorSubsystemVersion;
808 ibBuffer >> header.OptionalHeader.Win32VersionValue;
809 ibBuffer >> header.OptionalHeader.SizeOfImage;
810 ibBuffer >> header.OptionalHeader.SizeOfHeaders;
811 ibBuffer >> header.OptionalHeader.CheckSum;
812 ibBuffer >> header.OptionalHeader.Subsystem;
813 ibBuffer >> header.OptionalHeader.DllCharacteristics;
814 ibBuffer >> header.OptionalHeader.SizeOfStackReserve;
815 ibBuffer >> header.OptionalHeader.SizeOfStackCommit;
816 ibBuffer >> header.OptionalHeader.SizeOfHeapReserve;
817 ibBuffer >> header.OptionalHeader.SizeOfHeapCommit;
818 ibBuffer >> header.OptionalHeader.LoaderFlags;
819 ibBuffer >> header.OptionalHeader.NumberOfRvaAndSizes;
820 }
821
822 template<int x>
823 void PeHeaderT<x>::readDataDirectories(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const
824 {
825 PELIB_IMAGE_DATA_DIRECTORY idd;
826
827 for (unsigned int i=0;i<header.OptionalHeader.NumberOfRvaAndSizes;i++)
828 {
829 ibBuffer >> idd.VirtualAddress;
830 ibBuffer >> idd.Size;
831 header.dataDirectories.push_back(idd);
832 }
833 }
834
835 template<int x>
836 std::vector<PELIB_IMAGE_SECTION_HEADER> PeHeaderT<x>::readSections(InputBuffer& ibBuffer, PELIB_IMAGE_NT_HEADERS<x>& header) const
837 {
838 const unsigned int nrSections = header.FileHeader.NumberOfSections;
839 PELIB_IMAGE_SECTION_HEADER ishCurr;
840
841 std::vector<PELIB_IMAGE_SECTION_HEADER> vIshdCurr;
842
843 for (unsigned int i=0;i<nrSections;i++)
844 {
845 ibBuffer.read(reinterpret_cast<char*>(ishCurr.Name), 8);
846 ibBuffer >> ishCurr.VirtualSize;
847 ibBuffer >> ishCurr.VirtualAddress;
848 ibBuffer >> ishCurr.SizeOfRawData;
849 ibBuffer >> ishCurr.PointerToRawData;
850 ibBuffer >> ishCurr.PointerToRelocations;
851 ibBuffer >> ishCurr.PointerToLinenumbers;
852 ibBuffer >> ishCurr.NumberOfRelocations;
853 ibBuffer >> ishCurr.NumberOfLinenumbers;
854 ibBuffer >> ishCurr.Characteristics;
855 vIshdCurr.push_back(ishCurr);
856 }
857
858 return vIshdCurr;
859 }
860
861 template<int x>
862 int PeHeaderT<x>::read(const unsigned char* pcBuffer, unsigned int uiSize, unsigned int uiOffset)
863 {
864 if (uiSize < m_inthHeader.size())
865 {
866 return ERROR_INVALID_FILE;
867 }
868
869 std::vector<unsigned char> vBuffer(pcBuffer, pcBuffer + m_inthHeader.size());
870
871 InputBuffer ibBuffer(vBuffer);
872 PELIB_IMAGE_NT_HEADERS<x> header;
873
874 readHeader(ibBuffer, header);
875
876 if (uiSize < m_inthHeader.size() + header.OptionalHeader.NumberOfRvaAndSizes * 8 + header.FileHeader.NumberOfSections * 0x28)
877 {
878 return ERROR_INVALID_FILE;
879 }
880
881 vBuffer.resize(header.OptionalHeader.NumberOfRvaAndSizes * 8 + header.FileHeader.NumberOfSections * 0x28);
882 vBuffer.assign(pcBuffer + m_inthHeader.size(), pcBuffer + m_inthHeader.size() + header.OptionalHeader.NumberOfRvaAndSizes * 8 + header.FileHeader.NumberOfSections * 0x28);
883
884 ibBuffer.setBuffer(vBuffer);
885
886 readDataDirectories(ibBuffer, header);
887
888 m_vIsh = readSections(ibBuffer, header);
889
890 std::swap(m_inthHeader, header);
891
892 m_uiOffset = uiOffset;
893
894 return NO_ERROR;
895 }
896
897 /**
898 * Reads the PE header from a file Note that this function does not verify if a file is actually a MZ file.
899 * For this purpose see #PeLib::PeHeaderT<x>::isValid. The only check this function makes is a check to see if
900 * the file is large enough to be a PE header. If the data is valid doesn't matter.
901 * @param strFilename Name of the file which will be read.
902 * @param uiOffset File offset of PE header (see #PeLib::MzHeader::getAddressOfPeHeader).
903 **/
904 template<int x>
905 int PeHeaderT<x>::read(std::string strFilename, unsigned int uiOffset)
906 {
907 std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
908
909 if (!ifFile)
910 {
911 return ERROR_OPENING_FILE;
912 }
913
914 // File too small
915 if (fileSize(ifFile) < uiOffset + m_inthHeader.size())
916 {
917 return ERROR_INVALID_FILE;
918 }
919
920 std::vector<unsigned char> vBuffer(m_inthHeader.size());
921
922 ifFile.seekg(uiOffset, std::ios::beg);
923 ifFile.read(reinterpret_cast<char*>(&vBuffer[0]), static_cast<std::streamsize>(vBuffer.size()));
924
925 InputBuffer ibBuffer(vBuffer);
926 PELIB_IMAGE_NT_HEADERS<x> header;
927
928 readHeader(ibBuffer, header);
929
930 vBuffer.resize(header.OptionalHeader.NumberOfRvaAndSizes * 8 + header.FileHeader.NumberOfSections * 0x28);
931
932 ifFile.read(reinterpret_cast<char*>(&vBuffer[0]), static_cast<std::streamsize>(vBuffer.size()));
933 if (!ifFile)
934 {
935 return ERROR_INVALID_FILE;
936 }
937
938 ibBuffer.setBuffer(vBuffer);
939
940 readDataDirectories(ibBuffer, header);
941
942 // Sections
943// const unsigned int nrSections = header.FileHeader.NumberOfSections;
944// if (fileSize(ifFile) < uiOffset + m_inthHeader.size() + nrSections * PELIB_IMAGE_SECTION_HEADER::size())
945// {
946// return ERROR_INVALID_FILE;
947// }
948
949 m_vIsh = readSections(ibBuffer, header);
950
951 std::swap(m_inthHeader, header);
952
953 m_uiOffset = uiOffset;
954
955 ifFile.close();
956
957 return NO_ERROR;
958 }
959
960 /**
961 * Rebuilds the PE header so that it can be written to a file. It's not guaranteed that the
962 * header will be valid. If you want to make sure that the header will be valid you
963 * must call #PeLib::PeHeaderT<x>::makeValid first.
964 * @param vBuffer Buffer where the rebuilt header will be stored.
965 **/
966 template<int x>
967 void PeHeaderT<x>::rebuild(std::vector<byte>& vBuffer) const
968 {
969 OutputBuffer obBuffer(vBuffer);
970
971 obBuffer << m_inthHeader.Signature;
972
973 obBuffer << m_inthHeader.FileHeader.Machine;
974 obBuffer << m_inthHeader.FileHeader.NumberOfSections;
975 obBuffer << m_inthHeader.FileHeader.TimeDateStamp;
976 obBuffer << m_inthHeader.FileHeader.PointerToSymbolTable;
977 obBuffer << m_inthHeader.FileHeader.NumberOfSymbols;
978 obBuffer << m_inthHeader.FileHeader.SizeOfOptionalHeader;
979 obBuffer << m_inthHeader.FileHeader.Characteristics;
980 obBuffer << m_inthHeader.OptionalHeader.Magic;
981 obBuffer << m_inthHeader.OptionalHeader.MajorLinkerVersion;
982 obBuffer << m_inthHeader.OptionalHeader.MinorLinkerVersion;
983 obBuffer << m_inthHeader.OptionalHeader.SizeOfCode;
984 obBuffer << m_inthHeader.OptionalHeader.SizeOfInitializedData;
985 obBuffer << m_inthHeader.OptionalHeader.SizeOfUninitializedData;
986 obBuffer << m_inthHeader.OptionalHeader.AddressOfEntryPoint;
987 obBuffer << m_inthHeader.OptionalHeader.BaseOfCode;
988 rebuildBaseOfData(obBuffer);
989// obBuffer << m_inthHeader.OptionalHeader.BaseOfData;
990 obBuffer << m_inthHeader.OptionalHeader.ImageBase;
991 obBuffer << m_inthHeader.OptionalHeader.SectionAlignment;
992 obBuffer << m_inthHeader.OptionalHeader.FileAlignment;
993 obBuffer << m_inthHeader.OptionalHeader.MajorOperatingSystemVersion;
994 obBuffer << m_inthHeader.OptionalHeader.MinorOperatingSystemVersion;
995 obBuffer << m_inthHeader.OptionalHeader.MajorImageVersion;
996 obBuffer << m_inthHeader.OptionalHeader.MinorImageVersion;
997 obBuffer << m_inthHeader.OptionalHeader.MajorSubsystemVersion;
998 obBuffer << m_inthHeader.OptionalHeader.MinorSubsystemVersion;
999 obBuffer << m_inthHeader.OptionalHeader.Win32VersionValue;
1000 obBuffer << m_inthHeader.OptionalHeader.SizeOfImage;
1001 obBuffer << m_inthHeader.OptionalHeader.SizeOfHeaders;
1002 obBuffer << m_inthHeader.OptionalHeader.CheckSum;
1003 obBuffer << m_inthHeader.OptionalHeader.Subsystem;
1004 obBuffer << m_inthHeader.OptionalHeader.DllCharacteristics;
1005 obBuffer << m_inthHeader.OptionalHeader.SizeOfStackReserve;
1006 obBuffer << m_inthHeader.OptionalHeader.SizeOfStackCommit;
1007 obBuffer << m_inthHeader.OptionalHeader.SizeOfHeapReserve;
1008 obBuffer << m_inthHeader.OptionalHeader.SizeOfHeapCommit;
1009 obBuffer << m_inthHeader.OptionalHeader.LoaderFlags;
1010 obBuffer << m_inthHeader.OptionalHeader.NumberOfRvaAndSizes;
1011
1012 // The 0x10 data directories
1013 for (unsigned int i=0;i<calcNumberOfRvaAndSizes();i++)
1014 {
1015 obBuffer << m_inthHeader.dataDirectories[i].VirtualAddress;
1016 obBuffer << m_inthHeader.dataDirectories[i].Size;
1017 }
1018
1019 // The section definitions
1020 const unsigned int nrSections = calcNumberOfSections();
1021 for (unsigned int i=0;i<nrSections;i++)
1022 {
1023 char temp[9] = {0};
1024 strcpy(temp, getSectionName(i).c_str());
1025 obBuffer.add(temp, 8);
1026 obBuffer << m_vIsh[i].VirtualSize;
1027 obBuffer << m_vIsh[i].VirtualAddress;
1028 obBuffer << m_vIsh[i].SizeOfRawData;
1029 obBuffer << m_vIsh[i].PointerToRawData;
1030 obBuffer << m_vIsh[i].PointerToRelocations;
1031 obBuffer << m_vIsh[i].PointerToLinenumbers;
1032 obBuffer << m_vIsh[i].NumberOfRelocations;
1033 obBuffer << m_vIsh[i].NumberOfLinenumbers;
1034 obBuffer << m_vIsh[i].Characteristics;
1035 }
1036 }
1037
1038 /**
1039 * Converts a relative virtual offset to a file offset.
1040 * @param dwRva A relative virtual offset.
1041 * @return A file offset.
1042 * \todo It's not always 0x1000.
1043 **/
1044 template<int x>
1045 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::rvaToOffset(VAR4_8 dwRva) const
1046 {
1047 // XXX: Not correct
1048 if (dwRva < 0x1000) return dwRva;
1049
1050 PeLib::word uiSecnr = getSectionWithRva(dwRva);
1051 if (uiSecnr == 0xFFFF || dwRva > getVirtualAddress(uiSecnr) + getSizeOfRawData(uiSecnr))
1052 {
1053 return std::numeric_limits<VAR4_8>::max();
1054 }
1055
1056 return getPointerToRawData(uiSecnr) + dwRva - getVirtualAddress(uiSecnr);
1057 }
1058
1059 /**
1060 * Converts a relative virtual offset to a virtual offset.
1061 * @param dwRva A relative virtual offset.
1062 * @return A virtual offset.
1063 **/
1064 template<int x>
1065 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::rvaToVa(VAR4_8 dwRva) const
1066 {
1067 return getImageBase() + dwRva;
1068 }
1069
1070 /**
1071 * Calculates the size of the current PE header. This includes the actual header and the section definitions.
1072 * @return Size of the current PE header.
1073 * \todo Better handling of files with less than 0x10 directories.
1074 **/
1075 template<int x>
1076 unsigned int PeHeaderT<x>::size() const
1077 {
1078 return m_inthHeader.size() + getNumberOfSections() * PELIB_IMAGE_SECTION_HEADER::size();
1079 }
1080
1081 // \todo Not sure if this works.
1082 template<int x>
1083 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::vaToRva(VAR4_8 dwRva) const
1084 {
1085 if (dwRva - getImageBase() < calcStartOfCode()) return dwRva - getImageBase();
1086
1087 if (getSectionWithRva(dwRva - getImageBase()) == 0xFFFF) return -1;
1088
1089 return dwRva - getImageBase();
1090 }
1091
1092 template<int x>
1093 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::vaToOffset(VAR4_8 dwRva) const
1094 {
1095 return rvaToOffset(dwRva - getImageBase());
1096 }
1097
1098 /**
1099 * Saves the PE header to a file. Note that this only saves the header information, if you have added sections
1100 * and want to save these to the file you have to call #PeLib::PeHeaderT<x>::saveSections too. This function also
1101 * does not verify if the PE header is correct. If you want to make sure that the current PE header is valid,
1102 * call #PeLib::PeHeaderT<x>::isValid and #PeLib::PeHeaderT<x>::makeValid first.
1103 * @param strFilename Filename of the file the header will be written to.
1104 * @param uiOffset File offset the header will be written to.
1105 **/
1106 template<int x>
1107 int PeHeaderT<x>::write(std::string strFilename, unsigned int uiOffset) const
1108 {
1109 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
1110
1111 if (!ofFile)
1112 {
1113 ofFile.clear();
1114 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
1115 }
1116 else
1117 {
1118 ofFile.close();
1119 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
1120 }
1121
1122 if (!ofFile)
1123 {
1124 return ERROR_OPENING_FILE;
1125 }
1126
1127 ofFile.seekp(uiOffset, std::ios::beg);
1128
1129 std::vector<unsigned char> vBuffer;
1130
1131 rebuild(vBuffer);
1132
1133 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
1134
1135 ofFile.close();
1136
1137 return NO_ERROR;
1138 }
1139
1140
1141 /**
1142 * Overwrites a section's data.
1143 * @param wSecnr Number of the section which will be overwritten.
1144 * @param strFilename Name of the file where the section will be written to.
1145 * @param wSecnr Number of the section that will be written.
1146 * @param vBuffer New data of the section.
1147 **/
1148 template<int x>
1149 int PeHeaderT<x>::writeSectionData(const std::string& strFilename, word wSecnr, const std::vector<byte>& vBuffer) const
1150 {
1151 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
1152
1153 if (!ofFile)
1154 {
1155 ofFile.clear();
1156 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
1157 }
1158 else
1159 {
1160 ofFile.close();
1161 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
1162 }
1163
1164 if (!ofFile)
1165 {
1166 ofFile.clear();
1167
1168 return ERROR_OPENING_FILE;
1169 }
1170
1171 ofFile.seekp(getPointerToRawData(wSecnr), std::ios::beg);
1172
1173 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), std::min(static_cast<unsigned int>(vBuffer.size()), getSizeOfRawData(wSecnr)));
1174
1175 ofFile.close();
1176
1177 return NO_ERROR;
1178 }
1179
1180 template<int x>
1181 int PeHeaderT<x>::writeSections(const std::string& strFilename) const
1182 {
1183 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
1184
1185 if (!ofFile)
1186 {
1187 ofFile.clear();
1188 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
1189 }
1190 else
1191 {
1192 ofFile.close();
1193 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
1194 }
1195
1196 if (!ofFile)
1197 {
1198 return ERROR_OPENING_FILE;
1199 }
1200
1201 unsigned int uiFilesize = fileSize(ofFile);
1202
1203 for (int i=0;i<calcNumberOfSections();i++)
1204 {
1205 if (uiFilesize < getPointerToRawData(i) + getSizeOfRawData(i))
1206 {
1207 unsigned int uiToWrite = getPointerToRawData(i) + getSizeOfRawData(i) - uiFilesize;
1208 std::vector<char> vBuffer(uiToWrite);
1209 ofFile.seekp(0, std::ios::end);
1210 ofFile.write(&vBuffer[0], static_cast<unsigned int>(vBuffer.size()));
1211 uiFilesize = getPointerToRawData(i) + getSizeOfRawData(i);
1212 }
1213 }
1214
1215 ofFile.close();
1216
1217 return NO_ERROR;
1218 }
1219
1220 /**
1221 * Returns the file's Nt signature.
1222 * @return The Nt signature value from the PE header.
1223 **/
1224 template<int x>
1225 dword PeHeaderT<x>::getNtSignature() const
1226 {
1227 return m_inthHeader.Signature;
1228 }
1229
1230 /**
1231 * Returns the file's machine.
1232 * @return The Machine value from the PE header.
1233 **/
1234 template<int x>
1235 word PeHeaderT<x>::getMachine() const
1236 {
1237 return m_inthHeader.FileHeader.Machine;
1238 }
1239
1240
1241 /**
1242 * Returns the file's number of sections as defined in the header. Note that this value can be different
1243 * from the number of defined sections (#see PeLib::PeHeaderT<x>::getNumberOfSections).
1244 * @return The NumberOfSections value from the PE header.
1245 **/
1246 template<int x>
1247 word PeHeaderT<x>::getNumberOfSections() const
1248 {
1249 return m_inthHeader.FileHeader.NumberOfSections;
1250 }
1251
1252 /**
1253 * Returns the file's TimeDateStamp.
1254 * @return The TimeDateStamp value from the PE header.
1255 **/
1256 template<int x>
1257 dword PeHeaderT<x>::getTimeDateStamp() const
1258 {
1259 return m_inthHeader.FileHeader.TimeDateStamp;
1260 }
1261
1262 /**
1263 * Returns the relative virtual address of the file's symbol table.
1264 * @return The PointerToSymbolTable value from the PE header.
1265 **/
1266 template<int x>
1267 dword PeHeaderT<x>::getPointerToSymbolTable() const
1268 {
1269 return m_inthHeader.FileHeader.PointerToSymbolTable;
1270 }
1271
1272 /**
1273 * Returns the number of symbols of the file's symbol table.
1274 * @return The NumberOfSymbols value from the PE header.
1275 **/
1276 template<int x>
1277 dword PeHeaderT<x>::getNumberOfSymbols() const
1278 {
1279 return m_inthHeader.FileHeader.NumberOfSymbols;
1280 }
1281
1282 /**
1283 * Returns the size of optional header of the file.
1284 * @return The SizeOfOptionalHeader value from the PE header.
1285 **/
1286 template<int x>
1287 word PeHeaderT<x>::getSizeOfOptionalHeader() const
1288 {
1289 return m_inthHeader.FileHeader.SizeOfOptionalHeader;
1290 }
1291
1292 /**
1293 * @return The Characteristics value from the PE header.
1294 **/
1295 template<int x>
1296 word PeHeaderT<x>::getCharacteristics() const
1297 {
1298 return m_inthHeader.FileHeader.Characteristics;
1299 }
1300
1301 /**
1302 * @return The Magic value from the PE header.
1303 **/
1304 template<int x>
1305 word PeHeaderT<x>::getMagic() const
1306 {
1307 return m_inthHeader.OptionalHeader.Magic;
1308 }
1309
1310 /**
1311 * @return The MajorLinkerVersion value from the PE header.
1312 **/
1313 template<int x>
1314 byte PeHeaderT<x>::getMajorLinkerVersion() const
1315 {
1316 return m_inthHeader.OptionalHeader.MajorLinkerVersion;
1317 }
1318
1319 /**
1320 * @return The MinorLinkerVersion value from the PE header.
1321 **/
1322 template<int x>
1323 byte PeHeaderT<x>::getMinorLinkerVersion() const
1324 {
1325 return m_inthHeader.OptionalHeader.MinorLinkerVersion;
1326 }
1327
1328 /**
1329 * @return The SizeOfCode value from the PE header.
1330 **/
1331 template<int x>
1332 dword PeHeaderT<x>::getSizeOfCode() const
1333 {
1334 return m_inthHeader.OptionalHeader.SizeOfCode;
1335 }
1336
1337 /**
1338 * @return The SizeOfInitializedData value from the PE header.
1339 **/
1340 template<int x>
1341 dword PeHeaderT<x>::getSizeOfInitializedData() const
1342 {
1343 return m_inthHeader.OptionalHeader.SizeOfInitializedData;
1344 }
1345
1346 /**
1347 * @return The SizeOfUninitializedData value from the PE header.
1348 **/
1349 template<int x>
1350 dword PeHeaderT<x>::getSizeOfUninitializedData() const
1351 {
1352 return m_inthHeader.OptionalHeader.SizeOfUninitializedData;
1353 }
1354
1355 /**
1356 * @return The AddressOfEntryPoint value from the PE header.
1357 **/
1358 template<int x>
1359 dword PeHeaderT<x>::getAddressOfEntryPoint() const
1360 {
1361 return m_inthHeader.OptionalHeader.AddressOfEntryPoint;
1362 }
1363
1364 /**
1365 * @return The BaseOfCode value from the PE header.
1366 **/
1367 template<int x>
1368 dword PeHeaderT<x>::getBaseOfCode() const
1369 {
1370 return m_inthHeader.OptionalHeader.BaseOfCode;
1371 }
1372
1373 /**
1374 * @return The ImageBase value from the PE header.
1375 **/
1376 template<int x>
1377 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::getImageBase() const
1378 {
1379 return m_inthHeader.OptionalHeader.ImageBase;
1380 }
1381
1382 /**
1383 * @return The SectionAlignment value from the PE header.
1384 **/
1385 template<int x>
1386 dword PeHeaderT<x>::getSectionAlignment() const
1387 {
1388 return m_inthHeader.OptionalHeader.SectionAlignment;
1389 }
1390
1391 /**
1392 * @return The FileAlignment value from the PE header.
1393 **/
1394 template<int x>
1395 dword PeHeaderT<x>::getFileAlignment() const
1396 {
1397 return m_inthHeader.OptionalHeader.FileAlignment;
1398 }
1399
1400 /**
1401 * @return The MajorOperatingSystemVersion value from the PE header.
1402 **/
1403 template<int x>
1404 word PeHeaderT<x>::getMajorOperatingSystemVersion() const
1405 {
1406 return m_inthHeader.OptionalHeader.MajorOperatingSystemVersion;
1407 }
1408
1409 /**
1410 * @return The MinorOperatingSystemVersion value from the PE header.
1411 **/
1412 template<int x>
1413 word PeHeaderT<x>::getMinorOperatingSystemVersion() const
1414 {
1415 return m_inthHeader.OptionalHeader.MinorOperatingSystemVersion;
1416 }
1417
1418 /**
1419 * @return The MajorImageVersion value from the PE header.
1420 **/
1421 template<int x>
1422 word PeHeaderT<x>::getMajorImageVersion() const
1423 {
1424 return m_inthHeader.OptionalHeader.MajorImageVersion;
1425 }
1426
1427 /**
1428 * @return The MinorImageVersion value from the PE header.
1429 **/
1430 template<int x>
1431 word PeHeaderT<x>::getMinorImageVersion() const
1432 {
1433 return m_inthHeader.OptionalHeader.MinorImageVersion;
1434 }
1435
1436 /**
1437 * @return The MajorSubsystemVersion value from the PE header.
1438 **/
1439 template<int x>
1440 word PeHeaderT<x>::getMajorSubsystemVersion() const
1441 {
1442 return m_inthHeader.OptionalHeader.MajorSubsystemVersion;
1443 }
1444
1445 /**
1446 * @return The MinorSubsystemVersion value from the PE header.
1447 **/
1448 template<int x>
1449 word PeHeaderT<x>::getMinorSubsystemVersion() const
1450 {
1451 return m_inthHeader.OptionalHeader.MinorSubsystemVersion;
1452 }
1453
1454 /**
1455 * @return The WinVersionValue value from the PE header.
1456 **/
1457 template<int x>
1458 dword PeHeaderT<x>::getWin32VersionValue() const
1459 {
1460 return m_inthHeader.OptionalHeader.Win32VersionValue;
1461 }
1462
1463 /**
1464 * @return The SizeOfImage value from the PE header.
1465 **/
1466 template<int x>
1467 dword PeHeaderT<x>::getSizeOfImage() const
1468 {
1469 return m_inthHeader.OptionalHeader.SizeOfImage;
1470 }
1471
1472 /**
1473 * @return The SizeOfHeaders value from the PE header.
1474 **/
1475 template<int x>
1476 dword PeHeaderT<x>::getSizeOfHeaders() const
1477 {
1478 return m_inthHeader.OptionalHeader.SizeOfHeaders;
1479 }
1480
1481 /**
1482 * @return The CheckSums value from the PE header.
1483 **/
1484 template<int x>
1485 dword PeHeaderT<x>::getCheckSum() const
1486 {
1487 return m_inthHeader.OptionalHeader.CheckSum;
1488 }
1489
1490 /**
1491 * @return The Subsystem value from the PE header.
1492 **/
1493 template<int x>
1494 word PeHeaderT<x>::getSubsystem() const
1495 {
1496 return m_inthHeader.OptionalHeader.Subsystem;
1497 }
1498
1499 /**
1500 * @return The DllCharacteristics value from the PE header.
1501 **/
1502 template<int x>
1503 word PeHeaderT<x>::getDllCharacteristics() const
1504 {
1505 return m_inthHeader.OptionalHeader.DllCharacteristics;
1506 }
1507
1508 /**
1509 * @return The SizeOfStackReserve value from the PE header.
1510 **/
1511 template<int x>
1512 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::getSizeOfStackReserve() const
1513 {
1514 return m_inthHeader.OptionalHeader.SizeOfStackReserve;
1515 }
1516
1517 /**
1518 * @return The SizeOfStackCommit value from the PE header.
1519 **/
1520 template<int x>
1521 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::getSizeOfStackCommit() const
1522 {
1523 return m_inthHeader.OptionalHeader.SizeOfStackCommit;
1524 }
1525
1526 /**
1527 * @return The SizeOfHeapReserve value from the PE header.
1528 **/
1529 template<int x>
1530 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::getSizeOfHeapReserve() const
1531 {
1532 return m_inthHeader.OptionalHeader.SizeOfHeapReserve;
1533 }
1534
1535 /**
1536 * @return The SizeOfHeapCommit value from the PE header.
1537 **/
1538 template<int x>
1539 typename FieldSizes<x>::VAR4_8 PeHeaderT<x>::getSizeOfHeapCommit() const
1540 {
1541 return m_inthHeader.OptionalHeader.SizeOfHeapCommit;
1542 }
1543
1544 /**
1545 * @return The LoaderFlags value from the PE header.
1546 **/
1547 template<int x>
1548 dword PeHeaderT<x>::getLoaderFlags() const
1549 {
1550 return m_inthHeader.OptionalHeader.LoaderFlags;
1551 }
1552
1553 /**
1554 * @return The NumberOfRvaAndSizes value from the PE header.
1555 **/
1556 template<int x>
1557 dword PeHeaderT<x>::getNumberOfRvaAndSizes() const
1558 {
1559 return m_inthHeader.OptionalHeader.NumberOfRvaAndSizes;
1560 }
1561
1562 template<int x>
1563 dword PeHeaderT<x>::calcNumberOfRvaAndSizes() const
1564 {
1565 return static_cast<dword>(m_inthHeader.dataDirectories.size());
1566 }
1567
1568 /**
1569 * Returns the relative virtual address of the current file's export directory.
1570 * @return The Rva of the Export directory.
1571 **/
1572 template<int x>
1573 dword PeHeaderT<x>::getIddExportRva() const
1574 {
1575 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
1576 }
1577
1578 /**
1579 * Returns the size of the current file's export directory.
1580 * @return The sizeof the Export directory.
1581 **/
1582 template<int x>
1583 dword PeHeaderT<x>::getIddExportSize() const
1584 {
1585 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
1586 }
1587
1588 /**
1589 * Returns the relative virtual address of the current file's import directory.
1590 * @return The Rva of the Import directory.
1591 **/
1592 template<int x>
1593 dword PeHeaderT<x>::getIddImportRva() const
1594 {
1595 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
1596 }
1597
1598 /**
1599 * Returns the size of the current file's import directory.
1600 * @return The size of the Import directory.
1601 **/
1602 template<int x>
1603 dword PeHeaderT<x>::getIddImportSize() const
1604 {
1605 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IMPORT].Size;
1606 }
1607
1608 /**
1609 * Returns the relative virtual address of the current file's resource directory.
1610 * @return The Rva of the Resource directory.
1611 **/
1612 template<int x>
1613 dword PeHeaderT<x>::getIddResourceRva() const
1614 {
1615 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
1616 }
1617
1618 /**
1619 * Returns the size of the current file'resource resource directory.
1620 * @return The size of the Resource directory.
1621 **/
1622 template<int x>
1623 dword PeHeaderT<x>::getIddResourceSize() const
1624 {
1625 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size;
1626 }
1627
1628 /**
1629 * Returns the relative virtual address of the current file's exception directory.
1630 * @return The Rva of the Exception directory.
1631 **/
1632 template<int x>
1633 dword PeHeaderT<x>::getIddExceptionRva() const
1634 {
1635 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress;
1636 }
1637
1638 /**
1639 * Returns the size of the current file's exception directory.
1640 * @return The size of the Exception directory.
1641 **/
1642 template<int x>
1643 dword PeHeaderT<x>::getIddExceptionSize() const
1644 {
1645 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size;
1646 }
1647
1648 /**
1649 * Returns the relative virtual address of the current file's security directory.
1650 * @return The Rva of the Security directory.
1651 **/
1652 template<int x>
1653 dword PeHeaderT<x>::getIddSecurityRva() const
1654 {
1655 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress;
1656 }
1657
1658 /**
1659 * Returns the size of the current file's security directory.
1660 * @return The size of the Security directory.
1661 **/
1662 template<int x>
1663 dword PeHeaderT<x>::getIddSecuritySize() const
1664 {
1665 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_SECURITY].Size;
1666 }
1667
1668 /**
1669 * Returns the relative virtual address of the current file's base reloc directory.
1670 * @return The Rva of the Base Reloc directory.
1671 **/
1672 template<int x>
1673 dword PeHeaderT<x>::getIddBaseRelocRva() const
1674 {
1675 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress;
1676 }
1677
1678 /**
1679 * Returns the size of the current file's base reloc directory.
1680 * @return The size of the Base Reloc directory.
1681 **/
1682 template<int x>
1683 dword PeHeaderT<x>::getIddBaseRelocSize() const
1684 {
1685 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
1686 }
1687
1688 /**
1689 * Returns the relative virtual address of the current file's debug directory.
1690 * @return The Rva of the Debug directory.
1691 **/
1692 template<int x>
1693 dword PeHeaderT<x>::getIddDebugRva() const
1694 {
1695 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress;
1696 }
1697
1698 /**
1699 * Returns the size of the current file's debug directory.
1700 * @return The size of the Debug directory.
1701 **/
1702 template<int x>
1703 dword PeHeaderT<x>::getIddDebugSize() const
1704 {
1705 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DEBUG].Size;
1706 }
1707
1708 /**
1709 * Returns the relative virtual address of the current file's Architecture directory.
1710 * @return The Rva of the Architecture directory.
1711 **/
1712 template<int x>
1713 dword PeHeaderT<x>::getIddArchitectureRva() const
1714 {
1715 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_ARCHITECTURE].VirtualAddress;
1716 }
1717
1718 /**
1719 * Returns the size of the current file's Architecture directory.
1720 * @return The size of the Architecture directory.
1721 **/
1722 template<int x>
1723 dword PeHeaderT<x>::getIddArchitectureSize() const
1724 {
1725 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_ARCHITECTURE].Size;
1726 }
1727
1728 /**
1729 * Returns the relative virtual address of the current file's global ptr directory.
1730 * @return The Rva of the GlobalPtr directory.
1731 **/
1732 template<int x>
1733 dword PeHeaderT<x>::getIddGlobalPtrRva() const
1734 {
1735 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_GLOBALPTR].VirtualAddress;
1736 }
1737
1738 /**
1739 * Returns the size of the current file's global ptr directory.
1740 * @return The size of the GlobalPtr directory.
1741 **/
1742 template<int x>
1743 dword PeHeaderT<x>::getIddGlobalPtrSize() const
1744 {
1745 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_GLOBALPTR].Size;
1746 }
1747
1748 /**
1749 * Returns the relative virtual address of the current file's TLS directory.
1750 * @return The Rva of the Tls directory.
1751 **/
1752 template<int x>
1753 dword PeHeaderT<x>::getIddTlsRva() const
1754 {
1755 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_TLS].VirtualAddress;
1756 }
1757
1758 /**
1759 * Returns the size of the current file's TLS directory.
1760 * @return The size of the Tls directory.
1761 **/
1762 template<int x>
1763 dword PeHeaderT<x>::getIddTlsSize() const
1764 {
1765 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_TLS].Size;
1766 }
1767
1768 /**
1769 * Returns the relative virtual address of the current file's load config directory.
1770 * @return The Rva of the LoadConfig directory.
1771 **/
1772 template<int x>
1773 dword PeHeaderT<x>::getIddLoadConfigRva() const
1774 {
1775 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].VirtualAddress;
1776 }
1777
1778 /**
1779 * Returns the size of the current file's load config directory.
1780 * @return The size of the LoadConfig directory.
1781 **/
1782 template<int x>
1783 dword PeHeaderT<x>::getIddLoadConfigSize() const
1784 {
1785 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].Size;
1786 }
1787
1788 /**
1789 * Returns the relative virtual address of the current file's bound import directory.
1790 * @return The Rva of the BoundImport directory.
1791 **/
1792 template<int x>
1793 dword PeHeaderT<x>::getIddBoundImportRva() const
1794 {
1795 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT].VirtualAddress;
1796 }
1797
1798 /**
1799 * Returns the size of the current file's bound import directory.
1800 * @return The size of the BoundImport directory.
1801 **/
1802 template<int x>
1803 dword PeHeaderT<x>::getIddBoundImportSize() const
1804 {
1805 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT].Size;
1806 }
1807
1808 /**
1809 * Returns the relative virtual address of the current file's IAT directory.
1810 * @return The Rva of the IAT directory.
1811 **/
1812 template<int x>
1813 dword PeHeaderT<x>::getIddIatRva() const
1814 {
1815 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress;
1816 }
1817
1818 /**
1819 * Returns the size of the current file's IAT directory.
1820 * @return The size of the IAT directory.
1821 **/
1822 template<int x>
1823 dword PeHeaderT<x>::getIddIatSize() const
1824 {
1825 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IAT].Size;
1826 }
1827
1828 /**
1829 * Returns the relative virtual address of the current file's Delay Import directory.
1830 * @return The Rva of the DelayImport directory.
1831 **/
1832 template<int x>
1833 dword PeHeaderT<x>::getIddDelayImportRva() const
1834 {
1835 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress;
1836 }
1837
1838 /**
1839 * Returns the size of the current file's Delay Import directory.
1840 * @return The size of the DelayImport directory.
1841 **/
1842 template<int x>
1843 dword PeHeaderT<x>::getIddDelayImportSize() const
1844 {
1845 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size;
1846 }
1847
1848 /**
1849 * Returns the relative virtual address of the current file's COM Descriptor directory.
1850 * @return The Rva of the COM Descriptor directory.
1851 **/
1852 template<int x>
1853 dword PeHeaderT<x>::getIddComHeaderRva() const
1854 {
1855 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress;
1856 }
1857
1858 /**
1859 * Returns the size of the current file's COM Descriptor directory.
1860 * @return The Rva of the COM Descriptor directory.
1861 **/
1862 template<int x>
1863 dword PeHeaderT<x>::getIddComHeaderSize() const
1864 {
1865 return m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size;
1866 }
1867
1868 /**
1869 * Returns the relative virtual address of an image directory.
1870 * @param dwDirectory The identifier of an image directory.
1871 * @return The Rva of the image directory.
1872 **/
1873 template<int x>
1874 dword PeHeaderT<x>::getImageDataDirectoryRva(dword dwDirectory) const
1875 {
1876 return m_inthHeader.dataDirectories[dwDirectory].VirtualAddress;
1877 }
1878
1879 template<int x>
1880 void PeHeaderT<x>::setImageDataDirectoryRva(dword dwDirectory, dword value)
1881 {
1882 m_inthHeader.dataDirectories[dwDirectory].VirtualAddress = value;
1883 }
1884
1885 /**
1886 * Returns the size of an image directory.
1887 * @param dwDirectory The identifier of an image directory.
1888 * @return The size of the image directory.
1889 **/
1890 template<int x>
1891 dword PeHeaderT<x>::getImageDataDirectorySize(dword dwDirectory) const
1892 {
1893 return m_inthHeader.dataDirectories[dwDirectory].Size;
1894 }
1895
1896 template<int x>
1897 void PeHeaderT<x>::setImageDataDirectorySize(dword dwDirectory, dword value)
1898 {
1899 m_inthHeader.dataDirectories[dwDirectory].Size = value;
1900 }
1901
1902 /**
1903 * Returns the name of the section which is specified by the parameter wSectionnr.
1904 * @param wSectionnr Index of the section.
1905 * @return The name of the section.
1906 **/
1907 template<int x>
1908 std::string PeHeaderT<x>::getSectionName(word wSectionnr) const
1909 {
1910 std::string sectionName = "";
1911
1912 for (unsigned int i=0;i<sizeof(m_vIsh[wSectionnr].Name);i++)
1913 {
1914 if (m_vIsh[wSectionnr].Name[i]) sectionName += m_vIsh[wSectionnr].Name[i];
1915 }
1916
1917 return sectionName;
1918 }
1919
1920 /**
1921 * Returns the virtual size of the section which is specified by the parameter wSectionnr.
1922 * @param wSectionnr Index of the section.
1923 * @return The virtual size of the section.
1924 **/
1925 template<int x>
1926 dword PeHeaderT<x>::getVirtualSize(word wSectionnr) const
1927 {
1928 return m_vIsh[wSectionnr].VirtualSize;
1929 }
1930
1931 /**
1932 * Returns the relative virtual address of the section which is specified by the parameter wSectionnr.
1933 * @param wSectionnr Index of the section.
1934 * @return The Rva of the section.
1935 **/
1936 template<int x>
1937 dword PeHeaderT<x>::getVirtualAddress(word wSectionnr) const
1938 {
1939 return m_vIsh[wSectionnr].VirtualAddress;
1940 }
1941
1942 /**
1943 * Returns the size of raw data of the section which is specified by the parameter wSectionnr.
1944 * @param wSectionnr Index of the section.
1945 * @return The size of raw data of the section.
1946 **/
1947 template<int x>
1948 dword PeHeaderT<x>::getSizeOfRawData(word wSectionnr) const
1949 {
1950 return m_vIsh[wSectionnr].SizeOfRawData;
1951 }
1952
1953 /**
1954 * Returns the file offset of the section which is specified by the parameter wSectionnr.
1955 * @param wSectionnr Index of the section.
1956 * @return The file offset of the section.
1957 **/
1958 template<int x>
1959 dword PeHeaderT<x>::getPointerToRawData(word wSectionnr) const
1960 {
1961 return m_vIsh[wSectionnr].PointerToRawData;
1962 }
1963
1964 /**
1965 * Returns the pointer to relocations of the section which is specified by the parameter wSectionnr.
1966 * @param wSectionnr Index of the section.
1967 * @return The pointer to relocations of the section.
1968 **/
1969 template<int x>
1970 dword PeHeaderT<x>::getPointerToRelocations(word wSectionnr) const
1971 {
1972 return m_vIsh[wSectionnr].PointerToRelocations;
1973 }
1974
1975 /**
1976 * Returns the poiner to line numbers of the section which is specified by the parameter wSectionnr.
1977 * @param wSectionnr Index of the section.
1978 * @return The pointer to line numbers of the section.
1979 **/
1980 template<int x>
1981 dword PeHeaderT<x>::getPointerToLinenumbers(word wSectionnr) const
1982 {
1983 return m_vIsh[wSectionnr].PointerToLinenumbers;
1984 }
1985
1986 /**
1987 * Returns the number of relocations of the section which is specified by the parameter wSectionnr.
1988 * @param wSectionnr Index of the section.
1989 * @return The number of relocations of the section.
1990 **/
1991 template<int x>
1992 dword PeHeaderT<x>::getNumberOfRelocations(word wSectionnr) const
1993 {
1994 return m_vIsh[wSectionnr].NumberOfRelocations;
1995 }
1996
1997 /**
1998 * Returns the number of line numbers of the section which is specified by the parameter wSectionnr.
1999 * @param wSectionnr Index of the section.
2000 * @return The number of line numbers of the section.
2001 **/
2002 template<int x>
2003 dword PeHeaderT<x>::getNumberOfLinenumbers(word wSectionnr) const
2004 {
2005 return m_vIsh[wSectionnr].NumberOfLinenumbers;
2006 }
2007
2008 /**
2009 * Returns the characteristics of the section which is specified by the parameter wSectionnr.
2010 * @param wSectionnr Index of the section.
2011 * @return The characteristics of the section.
2012 **/
2013 template<int x>
2014 dword PeHeaderT<x>::getCharacteristics(word wSectionnr) const
2015 {
2016 return m_vIsh[wSectionnr].Characteristics;
2017 }
2018
2019 /**
2020 * Changes the file's Nt signature.
2021 * @param dwValue New value.
2022 **/
2023 template<int x>
2024 void PeHeaderT<x>::setNtSignature(dword dwValue)
2025 {
2026 m_inthHeader.Signature = dwValue;
2027 }
2028
2029 /**
2030 * Changes the file's Machine.
2031 * @param wValue New value.
2032 **/
2033 template<int x>
2034 void PeHeaderT<x>::setMachine(word wValue)
2035 {
2036 m_inthHeader.FileHeader.Machine = wValue;
2037 }
2038
2039 /**
2040 * Changes the number of sections.
2041 * @param wValue New value.
2042 **/
2043 template<int x>
2044 void PeHeaderT<x>::setNumberOfSections(word wValue)
2045 {
2046 m_inthHeader.FileHeader.NumberOfSections = wValue;
2047 }
2048
2049 /**
2050 * Changes the file's TimeDateStamp.
2051 * @param dwValue New value.
2052 **/
2053 template<int x>
2054 void PeHeaderT<x>::setTimeDateStamp(dword dwValue)
2055 {
2056 m_inthHeader.FileHeader.TimeDateStamp = dwValue;
2057 }
2058
2059 /**
2060 * Changes the file's PointerToSymbolTable.
2061 * @param dwValue New value.
2062 **/
2063 template<int x>
2064 void PeHeaderT<x>::setPointerToSymbolTable(dword dwValue)
2065 {
2066 m_inthHeader.FileHeader.PointerToSymbolTable = dwValue;
2067 }
2068
2069 /**
2070 * Changes the file's NumberOfSymbols.
2071 * @param dwValue New value.
2072 **/
2073 template<int x>
2074 void PeHeaderT<x>::setNumberOfSymbols(dword dwValue)
2075 {
2076 m_inthHeader.FileHeader.NumberOfSymbols = dwValue;
2077 }
2078
2079 /**
2080 * Changes the file's SizeOfOptionalHeader.
2081 * @param wValue New value.
2082 **/
2083 template<int x>
2084 void PeHeaderT<x>::setSizeOfOptionalHeader(word wValue)
2085 {
2086 m_inthHeader.FileHeader.SizeOfOptionalHeader = wValue;
2087 }
2088
2089 /**
2090 * Changes the file's Characteristics.
2091 * @param wValue New value.
2092 **/
2093 template<int x>
2094 void PeHeaderT<x>::setCharacteristics(word wValue)
2095 {
2096 m_inthHeader.FileHeader.Characteristics = wValue;
2097 }
2098
2099 /**
2100 * Changes the file's Magic.
2101 * @param wValue New value.
2102 **/
2103 template<int x>
2104 void PeHeaderT<x>::setMagic(word wValue)
2105 {
2106 m_inthHeader.OptionalHeader.Magic = wValue;
2107 }
2108
2109 /**
2110 * Changes the file's MajorLinkerVersion.
2111 * @param bValue New value.
2112 **/
2113 template<int x>
2114 void PeHeaderT<x>::setMajorLinkerVersion(byte bValue)
2115 {
2116 m_inthHeader.OptionalHeader.MajorLinkerVersion = bValue;
2117 }
2118
2119 /**
2120 * Changes the file's MinorLinkerVersion.
2121 * @param bValue New value.
2122 **/
2123 template<int x>
2124 void PeHeaderT<x>::setMinorLinkerVersion(byte bValue)
2125 {
2126 m_inthHeader.OptionalHeader.MinorLinkerVersion = bValue;
2127 }
2128
2129 /**
2130 * Changes the file's SizeOfCode.
2131 * @param dwValue New value.
2132 **/
2133 template<int x>
2134 void PeHeaderT<x>::setSizeOfCode(dword dwValue)
2135 {
2136 m_inthHeader.OptionalHeader.SizeOfCode = dwValue;
2137 }
2138
2139 /**
2140 * Changes the file's SizeOfInitializedData.
2141 * @param dwValue New value.
2142 **/
2143 template<int x>
2144 void PeHeaderT<x>::setSizeOfInitializedData(dword dwValue)
2145 {
2146 m_inthHeader.OptionalHeader.SizeOfInitializedData = dwValue;
2147 }
2148
2149 /**
2150 * Changes the file's SizeOfUninitializedData.
2151 * @param dwValue New value.
2152 **/
2153 template<int x>
2154 void PeHeaderT<x>::setSizeOfUninitializedData(dword dwValue)
2155 {
2156 m_inthHeader.OptionalHeader.SizeOfUninitializedData = dwValue;
2157 }
2158
2159 /**
2160 * Changes the file's AddressOfEntryPoint.
2161 * @param dwValue New value.
2162 **/
2163 template<int x>
2164 void PeHeaderT<x>::setAddressOfEntryPoint(dword dwValue)
2165 {
2166 m_inthHeader.OptionalHeader.AddressOfEntryPoint = dwValue;
2167 }
2168
2169 /**
2170 * Changes the file's BaseOfCode.
2171 * @param dwValue New value.
2172 **/
2173 template<int x>
2174 void PeHeaderT<x>::setBaseOfCode(dword dwValue)
2175 {
2176 m_inthHeader.OptionalHeader.BaseOfCode = dwValue;
2177 }
2178
2179 /**
2180 * Changes the file's ImageBase.
2181 * @param dwValue New value.
2182 **/
2183 template<int x>
2184 void PeHeaderT<x>::setImageBase(typename FieldSizes<x>::VAR4_8 dwValue)
2185 {
2186 m_inthHeader.OptionalHeader.ImageBase = dwValue;
2187 }
2188
2189 /**
2190 * Changes the file's SectionAlignment.
2191 * @param dwValue New value.
2192 **/
2193 template<int x>
2194 void PeHeaderT<x>::setSectionAlignment(dword dwValue)
2195 {
2196 m_inthHeader.OptionalHeader.SectionAlignment = dwValue;
2197 }
2198
2199 /**
2200 * Changes the file's FileAlignment.
2201 * @param dwValue New value.
2202 **/
2203 template<int x>
2204 void PeHeaderT<x>::setFileAlignment(dword dwValue)
2205 {
2206 m_inthHeader.OptionalHeader.FileAlignment = dwValue;
2207 }
2208
2209 /**
2210 * Changes the file's MajorOperatingSystemVersion.
2211 * @param wValue New value.
2212 **/
2213 template<int x>
2214 void PeHeaderT<x>::setMajorOperatingSystemVersion(word wValue)
2215 {
2216 m_inthHeader.OptionalHeader.MajorOperatingSystemVersion = wValue;
2217 }
2218
2219 /**
2220 * Changes the file's MinorOperatingSystemVersion.
2221 * @param wValue New value.
2222 **/
2223 template<int x>
2224 void PeHeaderT<x>::setMinorOperatingSystemVersion(word wValue)
2225 {
2226 m_inthHeader.OptionalHeader.MinorOperatingSystemVersion = wValue;
2227 }
2228
2229 /**
2230 * Changes the file's MajorImageVersion.
2231 * @param wValue New value.
2232 **/
2233 template<int x>
2234 void PeHeaderT<x>::setMajorImageVersion(word wValue)
2235 {
2236 m_inthHeader.OptionalHeader.MajorImageVersion = wValue;
2237 }
2238
2239 /**
2240 * Changes the file's MinorImageVersion.
2241 * @param wValue New value.
2242 **/
2243 template<int x>
2244 void PeHeaderT<x>::setMinorImageVersion(word wValue)
2245 {
2246 m_inthHeader.OptionalHeader.MinorImageVersion = wValue;
2247 }
2248
2249 /**
2250 * Changes the file's MajorSubsystemVersion.
2251 * @param wValue New value.
2252 **/
2253 template<int x>
2254 void PeHeaderT<x>::setMajorSubsystemVersion(word wValue)
2255 {
2256 m_inthHeader.OptionalHeader.MajorSubsystemVersion = wValue;
2257 }
2258
2259 /**
2260 * Changes the file's MinorSubsystemVersion.
2261 * @param wValue New value.
2262 **/
2263 template<int x>
2264 void PeHeaderT<x>::setMinorSubsystemVersion(word wValue)
2265 {
2266 m_inthHeader.OptionalHeader.MinorSubsystemVersion = wValue;
2267 }
2268
2269 /**
2270 * Changes the file's Win32VersionValue.
2271 * @param dwValue New value.
2272 **/
2273 template<int x>
2274 void PeHeaderT<x>::setWin32VersionValue(dword dwValue)
2275 {
2276 m_inthHeader.OptionalHeader.Win32VersionValue = dwValue;
2277 }
2278
2279 /**
2280 * Changes the file's SizeOfImage.
2281 * @param dwValue New value.
2282 **/
2283 template<int x>
2284 void PeHeaderT<x>::setSizeOfImage(dword dwValue)
2285 {
2286 m_inthHeader.OptionalHeader.SizeOfImage = dwValue;
2287 }
2288
2289 /**
2290 * Changes the file's SizeOfHeaders.
2291 * @param dwValue New value.
2292 **/
2293 template<int x>
2294 void PeHeaderT<x>::setSizeOfHeaders(dword dwValue)
2295 {
2296 m_inthHeader.OptionalHeader.SizeOfHeaders = dwValue;
2297 }
2298
2299 /**
2300 * Changes the file's CheckSum.
2301 * @param dwValue New value.
2302 **/
2303 template<int x>
2304 void PeHeaderT<x>::setCheckSum(dword dwValue)
2305 {
2306 m_inthHeader.OptionalHeader.CheckSum = dwValue;
2307 }
2308
2309 /**
2310 * Changes the file's Subsystem.
2311 * @param wValue New value.
2312 **/
2313 template<int x>
2314 void PeHeaderT<x>::setSubsystem(word wValue)
2315 {
2316 m_inthHeader.OptionalHeader.Subsystem = wValue;
2317 }
2318
2319 /**
2320 * Changes the file's DllCharacteristics.
2321 * @param wValue New value.
2322 **/
2323 template<int x>
2324 void PeHeaderT<x>::setDllCharacteristics(word wValue)
2325 {
2326 m_inthHeader.OptionalHeader.DllCharacteristics = wValue;
2327 }
2328
2329 /**
2330 * Changes the file's SizeOfStackReserve.
2331 * @param dwValue New value.
2332 **/
2333 template<int x>
2334 void PeHeaderT<x>::setSizeOfStackReserve(typename FieldSizes<x>::VAR4_8 dwValue)
2335 {
2336 m_inthHeader.OptionalHeader.SizeOfStackReserve = dwValue;
2337 }
2338
2339 /**
2340 * Changes the file's SizeOfStackCommit.
2341 * @param dwValue New value.
2342 **/
2343 template<int x>
2344 void PeHeaderT<x>::setSizeOfStackCommit(typename FieldSizes<x>::VAR4_8 dwValue)
2345 {
2346 m_inthHeader.OptionalHeader.SizeOfStackCommit = dwValue;
2347 }
2348
2349 /**
2350 * Changes the file's SizeOfHeapReserve.
2351 * @param dwValue New value.
2352 **/
2353 template<int x>
2354 void PeHeaderT<x>::setSizeOfHeapReserve(typename FieldSizes<x>::VAR4_8 dwValue)
2355 {
2356 m_inthHeader.OptionalHeader.SizeOfHeapReserve = dwValue;
2357 }
2358
2359 /**
2360 * Changes the file's SizeOfHeapCommit.
2361 * @param dwValue New value.
2362 **/
2363 template<int x>
2364 void PeHeaderT<x>::setSizeOfHeapCommit(typename FieldSizes<x>::VAR4_8 dwValue)
2365 {
2366 m_inthHeader.OptionalHeader.SizeOfHeapCommit = dwValue;
2367 }
2368
2369 /**
2370 * Changes the file's LoaderFlags.
2371 * @param dwValue New value.
2372 **/
2373 template<int x>
2374 void PeHeaderT<x>::setLoaderFlags(dword dwValue)
2375 {
2376 m_inthHeader.OptionalHeader.LoaderFlags = dwValue;
2377 }
2378
2379 /**
2380 * Changes the file's NumberOfRvaAndSizes.
2381 * @param dwValue New value.
2382 **/
2383 template<int x>
2384 void PeHeaderT<x>::setNumberOfRvaAndSizes(dword dwValue)
2385 {
2386 m_inthHeader.OptionalHeader.NumberOfRvaAndSizes = dwValue;
2387 }
2388
2389 template<int x>
2390 void PeHeaderT<x>::setIddDebugRva(dword dwValue)
2391 {
2392 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress = dwValue;
2393 }
2394
2395 template<int x>
2396 void PeHeaderT<x>::setIddDebugSize(dword dwValue)
2397 {
2398 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DEBUG].Size = dwValue;
2399 }
2400
2401 template<int x>
2402 void PeHeaderT<x>::setIddDelayImportRva(dword dwValue)
2403 {
2404 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress = dwValue;
2405 }
2406
2407 template<int x>
2408 void PeHeaderT<x>::setIddDelayImportSize(dword dwValue)
2409 {
2410 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size = dwValue;
2411 }
2412
2413 template<int x>
2414 void PeHeaderT<x>::setIddExceptionRva(dword dwValue)
2415 {
2416 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXCEPTION].VirtualAddress = dwValue;
2417 }
2418
2419 template<int x>
2420 void PeHeaderT<x>::setIddExceptionSize(dword dwValue)
2421 {
2422 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size = dwValue;
2423 }
2424
2425 template<int x>
2426 void PeHeaderT<x>::setIddGlobalPtrRva(dword dwValue)
2427 {
2428 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_GLOBALPTR].VirtualAddress = dwValue;
2429 }
2430
2431 template<int x>
2432 void PeHeaderT<x>::setIddGlobalPtrSize(dword dwValue)
2433 {
2434 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_GLOBALPTR].Size = dwValue;
2435 }
2436
2437 template<int x>
2438 void PeHeaderT<x>::setIddIatRva(dword dwValue)
2439 {
2440 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress = dwValue;
2441 }
2442
2443 template<int x>
2444 void PeHeaderT<x>::setIddIatSize(dword dwValue)
2445 {
2446 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IAT].Size = dwValue;
2447 }
2448
2449 template<int x>
2450 void PeHeaderT<x>::setIddLoadConfigRva(dword dwValue)
2451 {
2452 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].VirtualAddress = dwValue;
2453 }
2454
2455 template<int x>
2456 void PeHeaderT<x>::setIddLoadConfigSize(dword dwValue)
2457 {
2458 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].Size = dwValue;
2459 }
2460
2461 template<int x>
2462 void PeHeaderT<x>::setIddResourceRva(dword dwValue)
2463 {
2464 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress = dwValue;
2465 }
2466
2467 template<int x>
2468 void PeHeaderT<x>::setIddResourceSize(dword dwValue)
2469 {
2470 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = dwValue;
2471 }
2472
2473 template<int x>
2474 void PeHeaderT<x>::setIddSecurityRva(dword dwValue)
2475 {
2476 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress = dwValue;
2477 }
2478
2479 template<int x>
2480 void PeHeaderT<x>::setIddSecuritySize(dword dwValue)
2481 {
2482 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_SECURITY].Size = dwValue;
2483 }
2484
2485 template<int x>
2486 void PeHeaderT<x>::setIddTlsRva(dword dwValue)
2487 {
2488 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_TLS].VirtualAddress = dwValue;
2489 }
2490
2491 template<int x>
2492 void PeHeaderT<x>::setIddTlsSize(dword dwValue)
2493 {
2494 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_TLS].Size = dwValue;
2495 }
2496
2497 /**
2498 * Changes the rva of the file's export directory.
2499 * @param dwValue New value.
2500 **/
2501 template<int x>
2502 void PeHeaderT<x>::setIddExportRva(dword dwValue)
2503 {
2504 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress = dwValue;
2505 }
2506
2507 /**
2508 * Changes the size of the file's export directory.
2509 * @param dwValue New value.
2510 **/
2511 template<int x>
2512 void PeHeaderT<x>::setIddExportSize(dword dwValue)
2513 {
2514 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_EXPORT].Size = dwValue;
2515 }
2516
2517 template<int x>
2518 void PeHeaderT<x>::setIddBaseRelocRva(dword value)
2519 {
2520 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress = value;
2521 }
2522
2523 template<int x>
2524 void PeHeaderT<x>::setIddBaseRelocSize(dword value)
2525 {
2526 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_BASERELOC].Size = value;
2527 }
2528
2529 template<int x>
2530 void PeHeaderT<x>::setIddArchitectureRva(dword value)
2531 {
2532 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_ARCHITECTURE].VirtualAddress = value;
2533 }
2534
2535 template<int x>
2536 void PeHeaderT<x>::setIddArchitectureSize(dword value)
2537 {
2538 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_ARCHITECTURE].Size = value;
2539 }
2540
2541 template<int x>
2542 void PeHeaderT<x>::setIddComHeaderRva(dword value)
2543 {
2544 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress = value;
2545 }
2546
2547 template<int x>
2548 void PeHeaderT<x>::setIddComHeaderSize(dword value)
2549 {
2550 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size = value;
2551 }
2552
2553 /**
2554 * Changes the rva of the file's import directory.
2555 * @param dwValue New value.
2556 **/
2557 template<int x>
2558 void PeHeaderT<x>::setIddImportRva(dword dwValue)
2559 {
2560 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress = dwValue;
2561 }
2562
2563 /**
2564 * Changes the size of the file's import directory.
2565 * @param dwValue New value.
2566 **/
2567 template<int x>
2568 void PeHeaderT<x>::setIddImportSize(dword dwValue)
2569 {
2570 m_inthHeader.dataDirectories[PELIB_IMAGE_DIRECTORY_ENTRY_IMPORT].Size = dwValue;
2571 }
2572
2573 /**
2574 * Changes the name of a section.
2575 * @param wSectionnr Identifier of the section
2576 * @param strName New name.
2577 **/
2578 template<int x>
2579 void PeHeaderT<x>::setSectionName(word wSectionnr, std::string strName)
2580 {
2581 strncpy(reinterpret_cast<char*>(m_vIsh[wSectionnr].Name), strName.c_str(), sizeof(m_vIsh[wSectionnr].Name));
2582 }
2583
2584 /**
2585 * Changes the virtual size of a section.
2586 * @param wSectionnr Identifier of the section
2587 * @param dwValue New value.
2588 **/
2589 template<int x>
2590 void PeHeaderT<x>::setVirtualSize(word wSectionnr, dword dwValue)
2591 {
2592 m_vIsh[wSectionnr].VirtualSize = dwValue;
2593 }
2594
2595 /**
2596 * Changes the virtual address of a section.
2597 * @param wSectionnr Identifier of the section
2598 * @param dwValue New value.
2599 **/
2600 template<int x>
2601 void PeHeaderT<x>::setVirtualAddress(word wSectionnr, dword dwValue)
2602 {
2603 m_vIsh[wSectionnr].VirtualAddress = dwValue;
2604 }
2605
2606 /**
2607 * Changes the size of raw data of a section.
2608 * @param wSectionnr Identifier of the section
2609 * @param dwValue New value.
2610 **/
2611 template<int x>
2612 void PeHeaderT<x>::setSizeOfRawData(word wSectionnr, dword dwValue)
2613 {
2614 m_vIsh[wSectionnr].SizeOfRawData = dwValue;
2615 }
2616
2617 /**
2618 * Changes the size of raw data of a section.
2619 * @param wSectionnr Identifier of the section
2620 * @param dwValue New value.
2621 **/
2622 template<int x>
2623 void PeHeaderT<x>::setPointerToRawData(word wSectionnr, dword dwValue)
2624 {
2625 m_vIsh[wSectionnr].PointerToRawData = dwValue;
2626 }
2627
2628 /**
2629 * Changes the pointer to relocations of a section.
2630 * @param wSectionnr Identifier of the section
2631 * @param dwValue New value.
2632 **/
2633 template<int x>
2634 void PeHeaderT<x>::setPointerToRelocations(word wSectionnr, dword dwValue)
2635 {
2636 m_vIsh[wSectionnr].PointerToRelocations = dwValue;
2637 }
2638
2639 /**
2640 * Changes the pointer to line numbers of a section.
2641 * @param wSectionnr Identifier of the section
2642 * @param dwValue New value.
2643 **/
2644 template<int x>
2645 void PeHeaderT<x>::setPointerToLinenumbers(word wSectionnr, dword dwValue)
2646 {
2647 m_vIsh[wSectionnr].PointerToLinenumbers = dwValue;
2648 }
2649
2650 /**
2651 * Changes the number of relocations of a section.
2652 * @param wSectionnr Identifier of the section
2653 * @param dwValue New value.
2654 **/
2655 template<int x>
2656 void PeHeaderT<x>::setNumberOfRelocations(word wSectionnr, dword dwValue)
2657 {
2658 m_vIsh[wSectionnr].NumberOfRelocations = dwValue;
2659 }
2660
2661 /**
2662 * Changes the number of line numbers of a section.
2663 * @param wSectionnr Identifier of the section
2664 * @param dwValue New value.
2665 **/
2666 template<int x>
2667 void PeHeaderT<x>::setNumberOfLinenumbers(word wSectionnr, dword dwValue)
2668 {
2669 m_vIsh[wSectionnr].NumberOfLinenumbers = dwValue;
2670 }
2671
2672 /**
2673 * Changes the characteristics of a section.
2674 * @param wSectionnr Identifier of the section
2675 * @param dwValue New value.
2676 **/
2677 template<int x>
2678 void PeHeaderT<x>::setCharacteristics(word wSectionnr, dword dwValue)
2679 {
2680 m_vIsh[wSectionnr].Characteristics = dwValue;
2681 }
2682
2683}
2684
2685#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/PeLib.h b/utils/zenutils/libraries/pelib-0.9/pelib/PeLib.h
new file mode 100755
index 0000000000..870c873606
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/PeLib.h
@@ -0,0 +1,27 @@
1/*
2* PeLib.h - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13
14/** \mainpage PeLib - An open-source C++ library to modify PE files.
15*
16* \section intro Introduction
17*
18* <b>What is PeLib?</b><br>
19* PeLib is an open source C++ library with the purpose to ease the access and modification of PE (Portable executable) files. This is done through a multitude of classes which represent all important PE header and directory structures and which provide the necessary functions to read, modify and write these structures. As this library is fully ISO C++ compliant it should compile with all popular compilers for the Windows platform. For people who don't use C++ in their projects a dynamic link library is provided which encapsulates all of PeLib's functionality so that projects using programming languages as diverse as Win32 assembler, C# or Delphi can still benefit from PeLib's power
20*/
21
22#ifndef PELIB_H
23#define PELIB_H
24
25#include "PeFile.h"
26
27#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/PeLibAux.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/PeLibAux.cpp
new file mode 100755
index 0000000000..1e06bae620
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/PeLibAux.cpp
@@ -0,0 +1,275 @@
1/*
2* PeLibAux.cpp - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#include "PeLibInc.h"
14#include "PeLibAux.h"
15#include "PeFile.h"
16
17#ifdef _MSC_VER
18 #include <ctype.h>
19#endif
20
21namespace PeLib
22{
23 const qword PELIB_IMAGE_ORDINAL_FLAGS<64>::IMAGE_ORDINAL_FLAG = 0x8000000000000000ULL;
24
25 bool PELIB_IMAGE_SECTION_HEADER::biggerFileOffset(const PELIB_IMAGE_SECTION_HEADER& ish) const
26 {
27 return PointerToRawData < ish.PointerToRawData;
28 }
29
30 bool PELIB_IMAGE_SECTION_HEADER::biggerVirtualAddress(const PELIB_IMAGE_SECTION_HEADER& ish) const
31 {
32 return VirtualAddress < ish.VirtualAddress;
33 }
34
35 unsigned int alignOffset(unsigned int uiOffset, unsigned int uiAlignment)
36 {
37 if (!uiAlignment) return uiAlignment;
38 return (uiOffset % uiAlignment) ? uiOffset + (uiAlignment - uiOffset % uiAlignment) : uiOffset;
39 }
40
41 unsigned int fileSize(const std::string& filename)
42 {
43 std::fstream file(filename.c_str());
44 file.seekg(0, std::ios::end);
45 return file.tellg();
46 }
47
48 unsigned int fileSize(std::ifstream& file)
49 {
50 unsigned int oldpos = file.tellg();
51 file.seekg(0, std::ios::end);
52 unsigned int filesize = file.tellg();
53 file.seekg(oldpos, std::ios::beg);
54 return filesize;
55 }
56
57 unsigned int fileSize(std::fstream& file)
58 {
59 unsigned int oldpos = file.tellg();
60 file.seekg(0, std::ios::end);
61 unsigned int filesize = file.tellg();
62 file.seekg(oldpos, std::ios::beg);
63 return filesize;
64 }
65
66 unsigned int fileSize(std::ofstream& file)
67 {
68 unsigned int oldpos = file.tellp();
69 file.seekp(0, std::ios::end);
70 unsigned int filesize = file.tellp();
71 file.seekp(oldpos, std::ios::beg);
72 return filesize;
73 }
74
75 bool isEqualNc(const std::string& s1, const std::string& s2)
76 {
77 std::string t1 = s1;
78 std::string t2 = s2;
79
80 // No std:: to make VC++ happy
81 #ifdef _MSC_VER
82 std::transform(t1.begin(), t1.end(), t1.begin(), toupper);
83 std::transform(t2.begin(), t2.end(), t2.begin(), toupper);
84 #else
85 // Weird syntax to make Borland C++ happy
86 std::transform(t1.begin(), t1.end(), t1.begin(), (int(*)(int))std::toupper);
87 std::transform(t2.begin(), t2.end(), t2.begin(), (int(*)(int))std::toupper);
88 #endif
89 return t1 == t2;
90 }
91
92 PELIB_IMAGE_DOS_HEADER::PELIB_IMAGE_DOS_HEADER()
93 {
94 e_magic = 0;
95 e_cblp = 0;
96 e_cp = 0;
97 e_crlc = 0;
98 e_cparhdr = 0;
99 e_minalloc = 0;
100 e_maxalloc = 0;
101 e_ss = 0;
102 e_sp = 0;
103 e_csum = 0;
104 e_ip = 0;
105 e_cs = 0;
106 e_lfarlc = 0;
107 e_ovno = 0;
108
109 for (unsigned int i=0;i<sizeof(e_res)/sizeof(e_res[0]);i++)
110 {
111 e_res[i] = 0;
112 }
113
114 e_oemid = 0;
115 e_oeminfo = 0;
116
117 for (unsigned int i=0;i<sizeof(e_res2)/sizeof(e_res2[0]);i++)
118 {
119 e_res2[i] = 0;
120 }
121
122 e_lfanew = 0;
123 }
124
125 PELIB_EXP_FUNC_INFORMATION::PELIB_EXP_FUNC_INFORMATION()
126 {
127 addroffunc = 0;
128 addrofname = 0;
129 ordinal = 0;
130 }
131
132 PELIB_IMAGE_RESOURCE_DIRECTORY::PELIB_IMAGE_RESOURCE_DIRECTORY()
133 {
134 Characteristics = 0;
135 TimeDateStamp = 0;
136 MajorVersion = 0;
137 MinorVersion = 0;
138 NumberOfNamedEntries = 0;
139 NumberOfIdEntries = 0;
140 }
141
142 PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY::PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY()
143 {
144 Name = 0;
145 OffsetToData = 0;
146 }
147
148 bool PELIB_IMG_RES_DIR_ENTRY::operator<(const PELIB_IMG_RES_DIR_ENTRY& first) const
149 {
150 if (irde.Name & PELIB_IMAGE_RESOURCE_NAME_IS_STRING && first.irde.Name & PELIB_IMAGE_RESOURCE_NAME_IS_STRING)
151 {
152 return wstrName < first.wstrName;
153 }
154 else if (irde.Name & PELIB_IMAGE_RESOURCE_NAME_IS_STRING)
155 {
156 return true;
157 }
158 else if (first.irde.Name & PELIB_IMAGE_RESOURCE_NAME_IS_STRING)
159 {
160 return false;
161 }
162 else
163 {
164 return irde.Name < first.irde.Name;
165 }
166 }
167
168 PELIB_IMAGE_BASE_RELOCATION::PELIB_IMAGE_BASE_RELOCATION()
169 {
170 VirtualAddress = 0;
171 SizeOfBlock = 0;
172 }
173
174 PELIB_IMAGE_COR20_HEADER::PELIB_IMAGE_COR20_HEADER()
175 {
176 cb = 0;
177 MajorRuntimeVersion = 0;
178 MinorRuntimeVersion = 0;
179 MetaData.VirtualAddress = 0;
180 MetaData.Size = 0;
181 Flags = 0;
182 EntryPointToken = 0;
183 Resources.VirtualAddress = 0;
184 Resources.Size = 0;
185 StrongNameSignature.VirtualAddress = 0;
186 StrongNameSignature.Size = 0;
187 CodeManagerTable.VirtualAddress = 0;
188 CodeManagerTable.Size = 0;
189 VTableFixups.VirtualAddress = 0;
190 VTableFixups.Size = 0;
191 ExportAddressTableJumps.VirtualAddress = 0;
192 ExportAddressTableJumps.Size = 0;
193 ManagedNativeHeader.VirtualAddress = 0;
194 ManagedNativeHeader.Size = 0;
195 }
196
197 /** Compares the passed filename to the struct's filename.
198 * @param strModuleName A filename.
199 * @return True, if the passed filename equals the struct's filename. The comparison is case-sensitive.
200 **/
201 bool PELIB_IMAGE_BOUND_DIRECTORY::equal(const std::string strModuleName) const
202 {
203 return this->strModuleName == strModuleName;
204 }
205
206 bool PELIB_EXP_FUNC_INFORMATION::equal(const std::string strFunctionName) const
207 {
208 return isEqualNc(this->funcname, strFunctionName);
209 }
210
211 /**
212 * @param strFilename Name of a file.
213 * @return Either PEFILE32, PEFILE64 or PEFILE_UNKNOWN
214 **/
215 unsigned int getFileType(const std::string strFilename)
216 {
217 word machine, magic;
218
219 PeFile32 pef(strFilename);
220 if (pef.readMzHeader() != NO_ERROR) return PEFILE_UNKNOWN;
221 if (pef.readPeHeader() != NO_ERROR) return PEFILE_UNKNOWN;
222
223 machine = pef.peHeader().getMachine();
224 magic = pef.peHeader().getMagic();
225
226 if (machine == PELIB_IMAGE_FILE_MACHINE_I386 && magic == PELIB_IMAGE_NT_OPTIONAL_HDR32_MAGIC)
227 {
228 return PEFILE32;
229 }
230 // 0x8664 == AMD64; no named constant yet
231 else if ((machine == 0x8664 || machine == PELIB_IMAGE_FILE_MACHINE_IA64) && magic == PELIB_IMAGE_NT_OPTIONAL_HDR64_MAGIC)
232 {
233 return PEFILE64;
234 }
235 else
236 {
237 return PEFILE_UNKNOWN;
238 }
239 }
240
241 /**
242 * Opens a PE file. The return type is either PeFile32 or PeFile64 object. If an error occurs the return
243 * value is 0.
244 * @param strFilename Name of a file.
245 * @return Either a PeFile32 object, a PeFil64 object or 0.
246 **/
247 PeFile* openPeFile(const std::string& strFilename)
248 {
249 unsigned int type = getFileType(strFilename);
250
251 if (type == PEFILE32)
252 {
253 return new PeFile32(strFilename);
254 }
255 else if (type == PEFILE64)
256 {
257 return new PeFile64(strFilename);
258 }
259 else
260 {
261 return 0;
262 }
263 }
264
265 unsigned int PELIB_IMAGE_BOUND_DIRECTORY::size() const
266 {
267 unsigned int size = 0;
268 for (unsigned int i=0;i<moduleForwarders.size();i++)
269 {
270 size += moduleForwarders[i].size();
271 }
272
273 return size + PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size() + strModuleName.size() + 1;
274 }
275}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/PeLibAux.h b/utils/zenutils/libraries/pelib-0.9/pelib/PeLibAux.h
new file mode 100755
index 0000000000..4aed866a7d
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/PeLibAux.h
@@ -0,0 +1,884 @@
1/*
2* PeLibAux.cpp - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#ifndef PELIBAUX_H
14#define PELIBAUX_H
15
16//#include "PeLibInc.h"
17//#include "PeHeader.h"
18#include "buffer/OutputBuffer.h"
19#include "buffer/InputBuffer.h"
20//#include "buffer/ResTree.h"
21#include <numeric>
22#include <limits>
23
24namespace PeLib
25{
26 enum errorCodes
27 {
28 NO_ERROR = 0,
29 ERROR_OPENING_FILE = -1,
30 ERROR_INVALID_FILE = -2,
31 ERROR_TOO_MANY_SECTIONS = -3,
32 ERROR_NOT_ENOUGH_SPACE = -4,
33 ERROR_NO_FILE_ALIGNMENT = -5,
34 ERROR_NO_SECTION_ALIGNMENT = -6,
35 ERROR_ENTRY_NOT_FOUND = -7,
36 ERROR_DUPLICATE_ENTRY = -8,
37 ERROR_DIRECTORY_DOES_NOT_EXIST = -9
38 };
39
40 class PeFile;
41 bool isEqualNc(const std::string& s1, const std::string& s2);
42
43// It's necessary to make sure that a byte has 8 bits and that the platform has a 8 bit type,
44// a 16bit type and a bit type. That's because binary PE files are pretty picky about their
45// structure.
46
47 #if CHAR_BIT == 8
48 #if UCHAR_MAX == 255
49 typedef unsigned char byte;
50 // typedef std::bitset<8> byte;
51 #else
52 #error You need to change some typedefs (Code: 8). Please read the PeLib documentation.
53 #endif
54
55 #if USHRT_MAX == 65535U
56 typedef unsigned short word;
57 // typedef std::bitset<16> word;
58 #else
59 #error You need to change some typedefs (Code: 16). Please read the PeLib documentation.
60 #endif
61
62 #if UINT_MAX == 4294967295UL
63 typedef unsigned int dword;
64 // typedef std::bitset<32> dword;
65 #else
66 #error You need to change some typedefs (Code: 32). Please read the PeLib documentation.
67 #endif
68
69 typedef unsigned long long qword;
70
71// #if ULLONG_MAX == 18446744073709551615
72// typedef unsigned long long qword;
73// #else
74// #error You need to change some typedefs (Code: 32). Please read the PeLib documentation.
75// #endif
76 #else
77 #error You need to change some typedefs. Please read the PeLib documentation.
78 #endif
79
80
81/* enum bits {BITS_BYTE = 8, BITS_WORD = 16, BITS_DWORD = 32};
82
83 template<bits value>
84 class DataType
85 {
86 private:
87 std::bitset<value> bsValue;
88 unsigned long ulValue;
89
90 public:
91 void operator=(unsigned long ulValue)
92 {
93 bsValue = ulValue;
94 }
95
96 operator unsigned long() const
97 {
98 return bsValue.to_ulong();
99 }
100
101 const int operator&()
102 {
103 ulValue = bsValue;
104 return ulValue;
105 }
106
107 };
108
109 typedef DataType<BITS_BYTE> byte;
110 typedef DataType<BITS_WORD> word;
111 typedef DataType<BITS_DWORD> dword;
112*/
113
114 enum {PEFILE32 = 32,
115 PEFILE64 = 64,
116 PEFILE_UNKNOWN = 0};
117
118 enum {BoundImportDirectoryId = 1,
119 ComHeaderDirectoryId,
120 ExportDirectoryId,
121 IatDirectoryId,
122 ImportDirectoryId,
123 MzHeaderId,
124 PeHeaderId,
125 RelocationsId,
126 PeFileId,
127 ResourceDirectoryId,
128 DebugDirectoryId,
129 TlsDirectoryId
130 };
131
132 const word PELIB_IMAGE_DOS_SIGNATURE = 0x5A4D;
133
134 const dword PELIB_IMAGE_NT_SIGNATURE = 0x00004550;
135
136 template<int bits>
137 struct PELIB_IMAGE_ORDINAL_FLAGS;
138
139 template<>
140 struct PELIB_IMAGE_ORDINAL_FLAGS<32>
141 {
142 static const dword IMAGE_ORDINAL_FLAG = 0x80000000;
143 };
144
145 template<>
146 struct PELIB_IMAGE_ORDINAL_FLAGS<64>
147 {
148 static const qword IMAGE_ORDINAL_FLAG;
149 };
150
151 const unsigned long PELIB_IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16;
152
153 const unsigned long PELIB_IMAGE_RESOURCE_NAME_IS_STRING = 0x80000000;
154
155 const unsigned long PELIB_IMAGE_RESOURCE_DATA_IS_DIRECTORY = 0x80000000;
156
157 enum
158 {
159 PELIB_IMAGE_DIRECTORY_ENTRY_EXPORT, // OK
160 PELIB_IMAGE_DIRECTORY_ENTRY_IMPORT, // OK
161 PELIB_IMAGE_DIRECTORY_ENTRY_RESOURCE, // OK
162 PELIB_IMAGE_DIRECTORY_ENTRY_EXCEPTION,
163 PELIB_IMAGE_DIRECTORY_ENTRY_SECURITY,
164 PELIB_IMAGE_DIRECTORY_ENTRY_BASERELOC, // OK
165 PELIB_IMAGE_DIRECTORY_ENTRY_DEBUG,
166 PELIB_IMAGE_DIRECTORY_ENTRY_ARCHITECTURE,
167 PELIB_IMAGE_DIRECTORY_ENTRY_GLOBALPTR,
168 PELIB_IMAGE_DIRECTORY_ENTRY_TLS,
169 PELIB_IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG,
170 PELIB_IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT, // OK
171 PELIB_IMAGE_DIRECTORY_ENTRY_IAT, // OK
172 PELIB_IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT,
173 PELIB_IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
174 };
175
176 enum
177 {
178 PELIB_IMAGE_SCN_TYPE_NO_PAD = 0x00000008,
179 PELIB_IMAGE_SCN_CNT_CODE = 0x00000020,
180 PELIB_IMAGE_SCN_CNT_INITIALIZED_DATA = 0x00000040,
181 PELIB_IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080,
182 PELIB_IMAGE_SCN_LNK_OTHER = 0x00000100,
183 PELIB_IMAGE_SCN_LNK_INFO = 0x00000200,
184 PELIB_IMAGE_SCN_LNK_REMOVE = 0x00000800,
185 PELIB_IMAGE_SCN_LNK_COMDAT = 0x00001000,
186 PELIB_IMAGE_SCN_NO_DEFER_SPEC_EXC = 0x00004000,
187 PELIB_IMAGE_SCN_GPREL = 0x00008000,
188 PELIB_IMAGE_SCN_MEM_FARDATA = 0x00008000,
189 PELIB_IMAGE_SCN_MEM_PURGEABLE = 0x00020000,
190 PELIB_IMAGE_SCN_MEM_16BIT = 0x00020000,
191 PELIB_IMAGE_SCN_MEM_LOCKED = 0x00040000,
192 PELIB_IMAGE_SCN_MEM_PRELOAD = 0x00080000,
193 PELIB_IMAGE_SCN_ALIGN_1BYTES = 0x00100000,
194 PELIB_IMAGE_SCN_ALIGN_2BYTES = 0x00200000,
195 PELIB_IMAGE_SCN_ALIGN_4BYTES = 0x00300000,
196 PELIB_IMAGE_SCN_ALIGN_8BYTES = 0x00400000,
197 PELIB_IMAGE_SCN_ALIGN_16BYTES = 0x00500000,
198 PELIB_IMAGE_SCN_ALIGN_BYTES = 0x00600000,
199 PELIB_IMAGE_SCN_ALIGN_64BYTES = 0x00700000,
200 PELIB_IMAGE_SCN_ALIGN_128BYTES = 0x00800000,
201 PELIB_IMAGE_SCN_ALIGN_256BYTES = 0x00900000,
202 PELIB_IMAGE_SCN_ALIGN_512BYTES = 0x00A00000,
203 PELIB_IMAGE_SCN_ALIGN_1024BYTES = 0x00B00000,
204 PELIB_IMAGE_SCN_ALIGN_2048BYTES = 0x00C00000,
205 PELIB_IMAGE_SCN_ALIGN_4096BYTES = 0x00D00000,
206 PELIB_IMAGE_SCN_ALIGN_8192BYTES = 0x00E00000,
207 PELIB_IMAGE_SCN_LNK_NRELOC_OVFL = 0x01000000,
208 PELIB_IMAGE_SCN_MEM_DISCARDABLE = 0x02000000,
209 PELIB_IMAGE_SCN_MEM_NOT_CACHED = 0x04000000,
210 PELIB_IMAGE_SCN_MEM_NOT_PAGED = 0x08000000,
211 PELIB_IMAGE_SCN_MEM_SHARED = 0x10000000,
212 PELIB_IMAGE_SCN_MEM_EXECUTE = 0x20000000,
213 PELIB_IMAGE_SCN_MEM_READ = 0x40000000,
214 PELIB_IMAGE_SCN_MEM_WRITE = 0x80000000
215 };
216
217 enum
218 {
219 PELIB_IMAGE_FILE_MACHINE_UNKNOWN = 0,
220 PELIB_IMAGE_FILE_MACHINE_I386 = 0x014c,
221 PELIB_IMAGE_FILE_MACHINE_R3000 = 0x0162,
222 PELIB_IMAGE_FILE_MACHINE_R4000 = 0x0166,
223 PELIB_IMAGE_FILE_MACHINE_R10000 = 0x0168,
224 PELIB_IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x0169,
225 PELIB_IMAGE_FILE_MACHINE_ALPHA = 0x0184,
226 PELIB_IMAGE_FILE_MACHINE_POWERPC = 0x01F0,
227 PELIB_IMAGE_FILE_MACHINE_SH3 = 0x01a2,
228 PELIB_IMAGE_FILE_MACHINE_SH3E = 0x01a4,
229 PELIB_IMAGE_FILE_MACHINE_SH4 = 0x01a6,
230 PELIB_IMAGE_FILE_MACHINE_ARM = 0x01c0,
231 PELIB_IMAGE_FILE_MACHINE_THUMB = 0x01c2,
232 PELIB_IMAGE_FILE_MACHINE_IA64 = 0x0200,
233 PELIB_IMAGE_FILE_MACHINE_MIPS16 = 0x0266,
234 PELIB_IMAGE_FILE_MACHINE_MIPSFPU = 0x0366,
235 PELIB_IMAGE_FILE_MACHINE_MIPSFPU16 = 0x0466,
236 PELIB_IMAGE_FILE_MACHINE_ALPHA64 = 0x0284,
237 PELIB_IMAGE_FILE_MACHINE_AXP64 = PELIB_IMAGE_FILE_MACHINE_ALPHA64
238 };
239
240 enum
241 {
242 PELIB_IMAGE_FILE_RELOCS_STRIPPED = 0x0001,
243 PELIB_IMAGE_FILE_EXECUTABLE_IMAGE = 0x0002,
244 PELIB_IMAGE_FILE_LINE_NUMS_STRIPPED = 0x0004,
245 PELIB_IMAGE_FILE_LOCAL_SYMS_STRIPPED = 0x0008,
246 PELIB_IMAGE_FILE_AGGRESIVE_WS_TRIM = 0x0010,
247 PELIB_IMAGE_FILE_LARGE_ADDRESS_AWARE = 0x0020,
248 PELIB_IMAGE_FILE_BYTES_REVERSED_LO = 0x0080,
249 PELIB_IMAGE_FILE_32BIT_MACHINE = 0x0100,
250 PELIB_IMAGE_FILE_DEBUG_STRIPPED = 0x0200,
251 PELIB_IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP = 0x0400,
252 PELIB_IMAGE_FILE_NET_RUN_FROM_SWAP = 0x0800,
253 PELIB_IMAGE_FILE_SYSTEM = 0x1000,
254 PELIB_IMAGE_FILE_DLL = 0x2000,
255 PELIB_IMAGE_FILE_UP_SYSTEM_ONLY = 0x4000,
256 PELIB_IMAGE_FILE_BYTES_REVERSED_HI = 0x8000
257 };
258
259 enum
260 {
261 PELIB_IMAGE_NT_OPTIONAL_HDR32_MAGIC = 0x10b,
262 PELIB_IMAGE_NT_OPTIONAL_HDR64_MAGIC = 0x20b,
263 PELIB_IMAGE_ROM_OPTIONAL_HDR_MAGIC = 0x107
264 };
265
266 enum
267 {
268 PELIB_IMAGE_SUBSYSTEM_UNKNOWN = 0,
269 PELIB_IMAGE_SUBSYSTEM_NATIVE = 1,
270 PELIB_IMAGE_SUBSYSTEM_WINDOWS_GUI = 2,
271 PELIB_IMAGE_SUBSYSTEM_WINDOWS_CUI = 3,
272 PELIB_IMAGE_SUBSYSTEM_OS2_CUI = 5,
273 PELIB_IMAGE_SUBSYSTEM_POSIX_CUI = 7,
274 PELIB_IMAGE_SUBSYSTEM_NATIVE_WINDOWS = 8,
275 PELIB_IMAGE_SUBSYSTEM_WINDOWS_CE_GUI = 9
276 };
277
278 enum
279 {
280 PELIB_RT_CURSOR = 1, // 1
281 PELIB_RT_BITMAP, // 2
282 PELIB_RT_ICON, // 3
283 PELIB_RT_MENU, // 4
284 PELIB_RT_DIALOG, // 5
285 PELIB_RT_STRING, // 6
286 PELIB_RT_FONTDIR, // 7
287 PELIB_RT_FONT, // 8
288 PELIB_RT_ACCELERATOR, // 9
289 PELIB_RT_RCDATA, // 10
290 PELIB_RT_MESSAGETABLE, // 11
291 PELIB_RT_GROUP_CURSOR, // 12
292 PELIB_RT_GROUP_ICON = 14, // 14
293 PELIB_RT_VERSION = 16,
294 PELIB_RT_DLGINCLUDE,
295 PELIB_RT_PLUGPLAY = 19,
296 PELIB_RT_VXD,
297 PELIB_RT_ANICURSOR,
298 PELIB_RT_ANIICON,
299 PELIB_RT_HTML,
300 PELIB_RT_MANIFEST
301 };
302
303 template<typename T>
304 unsigned int accumulate(unsigned int size, const T& v)
305 {
306 return size + v.size();
307 }
308
309
310 struct PELIB_IMAGE_DOS_HEADER
311 {
312 word e_magic;
313 word e_cblp;
314 word e_cp;
315 word e_crlc;
316 word e_cparhdr;
317 word e_minalloc;
318 word e_maxalloc;
319 word e_ss;
320 word e_sp;
321 word e_csum;
322 word e_ip;
323 word e_cs;
324 word e_lfarlc;
325 word e_ovno;
326 word e_res[4];
327 word e_oemid;
328 word e_oeminfo;
329 word e_res2[10];
330 dword e_lfanew;
331
332 PELIB_IMAGE_DOS_HEADER();
333
334 static inline unsigned int size() {return 64;}
335 };
336
337 struct PELIB_IMAGE_FILE_HEADER
338 {
339 word Machine;
340 word NumberOfSections;
341 dword TimeDateStamp;
342 dword PointerToSymbolTable;
343 dword NumberOfSymbols;
344 word SizeOfOptionalHeader;
345 word Characteristics;
346
347 PELIB_IMAGE_FILE_HEADER()
348 {
349 Machine = 0;
350 NumberOfSections = 0;
351 TimeDateStamp = 0;
352 PointerToSymbolTable = 0;
353 NumberOfSymbols = 0;
354 SizeOfOptionalHeader = 0;
355 Characteristics = 0;
356 }
357
358 static inline unsigned int size() {return 20;}
359 };
360
361 struct PELIB_IMAGE_DATA_DIRECTORY
362 {
363 dword VirtualAddress;
364 dword Size;
365
366 PELIB_IMAGE_DATA_DIRECTORY()
367 {
368 VirtualAddress = 0;
369 Size = 0;
370 }
371
372 static inline unsigned int size() {return 8;}
373 };
374
375 template<int>
376 struct FieldSizes;
377
378 template<>
379 struct FieldSizes<32>
380 {
381 typedef dword VAR4_8;
382 };
383
384 template<>
385 struct FieldSizes<64>
386 {
387 typedef qword VAR4_8;
388 };
389
390 template<int x>
391 struct PELIB_IMAGE_OPTIONAL_HEADER_BASE
392 {
393 typedef typename FieldSizes<x>::VAR4_8 VAR4_8;
394
395 word Magic;
396 byte MajorLinkerVersion;
397 byte MinorLinkerVersion;
398 dword SizeOfCode;
399 dword SizeOfInitializedData;
400 dword SizeOfUninitializedData;
401 dword AddressOfEntryPoint;
402 dword BaseOfCode;
403 dword BaseOfData;
404 VAR4_8 ImageBase;
405 dword SectionAlignment;
406 dword FileAlignment;
407 word MajorOperatingSystemVersion;
408 word MinorOperatingSystemVersion;
409 word MajorImageVersion;
410 word MinorImageVersion;
411 word MajorSubsystemVersion;
412 word MinorSubsystemVersion;
413 dword Win32VersionValue;
414 dword SizeOfImage;
415 dword SizeOfHeaders;
416 dword CheckSum;
417 word Subsystem;
418 word DllCharacteristics;
419 VAR4_8 SizeOfStackReserve;
420 VAR4_8 SizeOfStackCommit;
421 VAR4_8 SizeOfHeapReserve;
422 VAR4_8 SizeOfHeapCommit;
423 dword LoaderFlags;
424 dword NumberOfRvaAndSizes;
425// PELIB_IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
426
427 PELIB_IMAGE_OPTIONAL_HEADER_BASE();
428 };
429
430 template<int x>
431 PELIB_IMAGE_OPTIONAL_HEADER_BASE<x>::PELIB_IMAGE_OPTIONAL_HEADER_BASE()
432 {
433 Magic = 0;
434 MajorLinkerVersion = 0;
435 MinorLinkerVersion = 0;
436 SizeOfCode = 0;
437 SizeOfInitializedData = 0;
438 SizeOfUninitializedData = 0;
439 AddressOfEntryPoint = 0;
440 BaseOfCode = 0;
441// BaseOfData = 0;
442 ImageBase = 0;
443 SectionAlignment = 0;
444 FileAlignment = 0;
445 MajorOperatingSystemVersion = 0;
446 MinorOperatingSystemVersion = 0;
447 MajorImageVersion = 0;
448 MinorImageVersion = 0;
449 MajorSubsystemVersion = 0;
450 MinorSubsystemVersion = 0;
451 Win32VersionValue = 0;
452 SizeOfImage = 0;
453 SizeOfHeaders = 0;
454 CheckSum = 0;
455 Subsystem = 0;
456 DllCharacteristics = 0;
457 SizeOfStackReserve = 0;
458 SizeOfStackCommit = 0;
459 SizeOfHeapReserve = 0;
460 SizeOfHeapCommit = 0;
461 LoaderFlags = 0;
462 NumberOfRvaAndSizes = 0;
463 }
464
465 template<int>
466 struct PELIB_IMAGE_OPTIONAL_HEADER;
467
468 template<>
469 struct PELIB_IMAGE_OPTIONAL_HEADER<32> : public PELIB_IMAGE_OPTIONAL_HEADER_BASE<32>
470 {
471 dword BaseOfData;
472
473 static inline unsigned int size() {return 224 - 0x10 * 8;}
474 };
475
476 template<>
477 struct PELIB_IMAGE_OPTIONAL_HEADER<64> : public PELIB_IMAGE_OPTIONAL_HEADER_BASE<64>
478 {
479 static inline unsigned int size() {return 240 - 0x10 * 8;}
480 };
481
482 template<int x>
483 struct PELIB_IMAGE_NT_HEADERS
484 {
485 dword Signature;
486 PELIB_IMAGE_FILE_HEADER FileHeader;
487 PELIB_IMAGE_OPTIONAL_HEADER<x> OptionalHeader;
488 std::vector<PELIB_IMAGE_DATA_DIRECTORY> dataDirectories;
489
490 unsigned int size() const
491 {
492 return sizeof(dword)
493 + PELIB_IMAGE_FILE_HEADER::size()
494 + PELIB_IMAGE_OPTIONAL_HEADER<x>::size()
495 + static_cast<unsigned int>(dataDirectories.size()) * PELIB_IMAGE_DATA_DIRECTORY::size();
496 }
497
498 PELIB_IMAGE_NT_HEADERS()
499 {
500 Signature = 0;
501 }
502 };
503
504 const unsigned int PELIB_IMAGE_SIZEOF_SHORT_NAME = 8;
505
506 struct PELIB_IMAGE_SECTION_HEADER
507 {
508 byte Name[PELIB_IMAGE_SIZEOF_SHORT_NAME];
509 dword VirtualSize;
510 dword VirtualAddress;
511 dword SizeOfRawData;
512 dword PointerToRawData;
513 dword PointerToRelocations;
514 dword PointerToLinenumbers;
515 word NumberOfRelocations;
516 word NumberOfLinenumbers;
517 dword Characteristics;
518
519 PELIB_IMAGE_SECTION_HEADER()
520 {
521 VirtualSize = 0;
522 VirtualAddress = 0;
523 SizeOfRawData = 0;
524 PointerToRawData = 0;
525 PointerToRelocations = 0;
526 PointerToLinenumbers = 0;
527 NumberOfRelocations = 0;
528 NumberOfLinenumbers = 0;
529 Characteristics = 0;
530 }
531
532 static inline unsigned int size() {return 40;}
533 bool biggerFileOffset(const PELIB_IMAGE_SECTION_HEADER& ish) const;
534 bool biggerVirtualAddress(const PELIB_IMAGE_SECTION_HEADER& ish) const;
535 };
536
537 template<int bits>
538 struct PELIB_IMAGE_THUNK_DATA
539 {
540 typename FieldSizes<bits>::VAR4_8 Ordinal;
541
542 PELIB_IMAGE_THUNK_DATA()
543 {
544 Ordinal = 0;
545 }
546
547 static inline unsigned int size() {return 4;}
548 };
549
550 struct PELIB_IMAGE_IMPORT_DESCRIPTOR
551 {
552 dword OriginalFirstThunk;
553 dword TimeDateStamp;
554 dword ForwarderChain;
555 dword Name;
556 dword FirstThunk;
557
558 PELIB_IMAGE_IMPORT_DESCRIPTOR()
559 {
560 OriginalFirstThunk = 0;
561 TimeDateStamp = 0;
562 ForwarderChain = 0;
563 Name = 0;
564 FirstThunk = 0;
565 }
566
567 static inline unsigned int size() {return 20;}
568 };
569
570 struct PELIB_IMAGE_EXPORT_DIRECTORY
571 {
572 dword Characteristics;
573 dword TimeDateStamp;
574 word MajorVersion;
575 word MinorVersion;
576 dword Name;
577 dword Base;
578 dword NumberOfFunctions;
579 dword NumberOfNames;
580 dword AddressOfFunctions;
581 dword AddressOfNames;
582 dword AddressOfNameOrdinals;
583
584 PELIB_IMAGE_EXPORT_DIRECTORY()
585 {
586 Characteristics = 0;
587 TimeDateStamp = 0;
588 MajorVersion = 0;
589 MinorVersion = 0;
590 Name = 0;
591 Base = 0;
592 NumberOfFunctions = 0;
593 NumberOfNames = 0;
594 AddressOfFunctions = 0;
595 NumberOfNames = 0;
596 AddressOfNameOrdinals = 0;
597 }
598
599 static inline unsigned int size() {return 40;}
600 };
601
602 struct PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR
603 {
604 dword TimeDateStamp;
605 word OffsetModuleName;
606 word NumberOfModuleForwarderRefs;
607
608 PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR()
609 {
610 TimeDateStamp = 0;
611 OffsetModuleName = 0;
612 NumberOfModuleForwarderRefs = 0;
613 }
614
615 static unsigned int size()
616 {
617 return 8;
618 }
619 };
620
621 // Stores all necessary information about a BoundImport field.
622 struct PELIB_IMAGE_BOUND_DIRECTORY
623 {
624 PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR ibdDescriptor; ///< Information about the imported file.
625 std::string strModuleName; ///< Name of the imported file.
626 std::vector<PELIB_IMAGE_BOUND_DIRECTORY> moduleForwarders;
627
628 // Will be used in std::find_if
629 // Passing by-reference not possible (see C++ Standard Core Language Defect Reports, Revision 29, Issue 106)
630 /// Compares the passed filename to the struct's filename.
631 bool equal(const std::string strModuleName) const;
632
633 unsigned int size() const;
634 };
635
636 struct PELIB_EXP_FUNC_INFORMATION
637 {
638 dword addroffunc;
639 dword addrofname;
640 word ordinal;
641 std::string funcname;
642
643 PELIB_EXP_FUNC_INFORMATION();
644
645 bool equal(const std::string strFunctionName) const;
646 inline unsigned int size() const
647 {
648 unsigned int uiSize = 4;
649 if (addroffunc) uiSize += 2;// + 4;
650 if (!funcname.empty()) uiSize += 4 + (unsigned int)funcname.size() + 1;
651 return uiSize;
652 }
653 };
654
655 struct PELIB_IMAGE_RESOURCE_DIRECTORY
656 {
657 dword Characteristics;
658 dword TimeDateStamp;
659 word MajorVersion;
660 word MinorVersion;
661 word NumberOfNamedEntries;
662 word NumberOfIdEntries;
663
664 PELIB_IMAGE_RESOURCE_DIRECTORY();
665
666 static inline unsigned int size() {return 16;}
667 };
668
669 struct PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY
670 {
671 dword Name;
672 dword OffsetToData;
673 PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY();
674 static inline unsigned int size() {return 8;}
675 };
676
677 const unsigned int PELIB_IMAGE_SIZEOF_BASE_RELOCATION = 8;
678
679 struct PELIB_IMG_RES_DIR_ENTRY
680 {
681 PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY irde;
682 std::string wstrName;
683
684 bool operator<(const PELIB_IMG_RES_DIR_ENTRY& first) const;
685
686 };
687
688 struct PELIB_IMAGE_BASE_RELOCATION
689 {
690 dword VirtualAddress;
691 dword SizeOfBlock;
692
693 PELIB_IMAGE_BASE_RELOCATION();
694 static inline unsigned int size() {return 8;}
695 };
696
697 struct PELIB_IMAGE_COR20_HEADER
698 {
699 dword cb;
700 word MajorRuntimeVersion;
701 word MinorRuntimeVersion;
702 PELIB_IMAGE_DATA_DIRECTORY MetaData;
703 dword Flags;
704 dword EntryPointToken;
705 PELIB_IMAGE_DATA_DIRECTORY Resources;
706 PELIB_IMAGE_DATA_DIRECTORY StrongNameSignature;
707 PELIB_IMAGE_DATA_DIRECTORY CodeManagerTable;
708 PELIB_IMAGE_DATA_DIRECTORY VTableFixups;
709 PELIB_IMAGE_DATA_DIRECTORY ExportAddressTableJumps;
710 PELIB_IMAGE_DATA_DIRECTORY ManagedNativeHeader;
711
712 PELIB_IMAGE_COR20_HEADER();
713 static inline unsigned int size() {return 72;}
714 };
715
716 // Used to store a file's export table.
717 struct PELIB_IMAGE_EXP_DIRECTORY
718 {
719 /// The IMAGE_EXPORTED_DIRECTORY of a file's export table.
720 PELIB_IMAGE_EXPORT_DIRECTORY ied;
721 /// The original filename of current file.
722 std::string name;
723 std::vector<PELIB_EXP_FUNC_INFORMATION> functions;
724 inline unsigned int size() const
725 {
726 return PELIB_IMAGE_EXPORT_DIRECTORY::size() + name.size() + 1 +
727 std::accumulate(functions.begin(), functions.end(), 0, accumulate<PELIB_EXP_FUNC_INFORMATION>);
728 }
729 };
730
731 // Used for parsing a file's import table. It combines the function name, the hint
732 // and the IMAGE_THUNK_DATA of an imported function.
733 template<int bits>
734 struct PELIB_THUNK_DATA
735 {
736 /// The IMAGE_THUNK_DATA struct of an imported function.
737 PELIB_IMAGE_THUNK_DATA<bits> itd;
738 /// The hint of an imported function.
739 word hint;
740 /// The function name of an imported function.
741 std::string fname;
742
743 bool equalHint(word wHint) const
744 {
745 return hint == wHint;
746// return itd.Ordinal == (wHint | IMAGE_ORDINAL_FLAGS<bits>::IMAGE_ORDINAL_FLAG);
747 }
748
749 bool equalFunctionName(std::string strFunctionName) const
750 {
751 return isEqualNc(fname, strFunctionName);
752 }
753
754 unsigned int size() const {return PELIB_IMAGE_THUNK_DATA<bits>::size() + fname.size() + 1 + sizeof(hint);}
755 };
756
757 // Used to store a file's import table. Every struct of this sort
758 // can store import information of one DLL.
759 template<int bits>
760 struct PELIB_IMAGE_IMPORT_DIRECTORY
761 {
762 /// The IMAGE_IMPORT_DESCRIPTOR of an imported DLL.
763 PELIB_IMAGE_IMPORT_DESCRIPTOR impdesc;
764 /// The name of an imported DLL.
765 std::string name;
766 /// All original first thunk values of an imported DLL.
767 std::vector<PELIB_THUNK_DATA<bits> > originalfirstthunk;
768 /// All first thunk value of an imported DLL.
769 std::vector<PELIB_THUNK_DATA<bits> > firstthunk;
770
771// bool operator==(std::string strFilename) const;
772 inline unsigned int size() const
773 {
774 return PELIB_IMAGE_IMPORT_DESCRIPTOR::size() + name.size() + 1 + // descriptor + dllname
775 std::accumulate(originalfirstthunk.begin(), originalfirstthunk.end(), 0, accumulate<PELIB_THUNK_DATA<bits> >) + // thunks (PeLib uses only one thunk)
776 PELIB_IMAGE_THUNK_DATA<bits>::size(); // zero-termination
777 }
778
779 bool operator==(std::string strFilename) const
780 {
781 return isEqualNc(this->name, strFilename);
782 }
783 };
784
785 struct PELIB_IMAGE_RESOURCE_DATA_ENTRY
786 {
787 dword OffsetToData;
788 dword Size;
789 dword CodePage;
790 dword Reserved;
791
792 static inline unsigned int size() {return 16;}
793 };
794
795 struct PELIB_IMAGE_RESOURCE_DATA
796 {
797 PELIB_IMAGE_RESOURCE_DATA_ENTRY irdEntry;
798 std::vector<byte> vData;
799 };
800
801 struct IMG_BASE_RELOC
802 {
803 PELIB_IMAGE_BASE_RELOCATION ibrRelocation;
804 std::vector<word> vRelocData;
805 };
806
807 struct PELIB_IMAGE_DEBUG_DIRECTORY
808 {
809 dword Characteristics;
810 dword TimeDateStamp;
811 word MajorVersion;
812 word MinorVersion;
813 dword Type;
814 dword SizeOfData;
815 dword AddressOfRawData;
816 dword PointerToRawData;
817
818 static unsigned int size() {return 28;}
819 };
820
821 struct PELIB_IMG_DEBUG_DIRECTORY
822 {
823 PELIB_IMAGE_DEBUG_DIRECTORY idd;
824 std::vector<byte> data;
825 };
826
827 template<int bits>
828 struct PELIB_IMAGE_TLS_DIRECTORY_BASE
829 {
830 typename FieldSizes<bits>::VAR4_8 StartAddressOfRawData;
831 typename FieldSizes<bits>::VAR4_8 EndAddressOfRawData;
832 typename FieldSizes<bits>::VAR4_8 AddressOfIndex;
833 typename FieldSizes<bits>::VAR4_8 AddressOfCallBacks;
834 dword SizeOfZeroFill;
835 dword Characteristics;
836 };
837
838 template<int bits>
839 struct PELIB_IMAGE_TLS_DIRECTORY;// : public PELIB_IMAGE_TLS_DIRECTORY_BASE<bits>
840
841 template<>
842 struct PELIB_IMAGE_TLS_DIRECTORY<32> : public PELIB_IMAGE_TLS_DIRECTORY_BASE<32>
843 {
844// enum {size = 24};
845 static unsigned int size(){return 24;}
846 };
847
848 template<>
849 struct PELIB_IMAGE_TLS_DIRECTORY<64> : public PELIB_IMAGE_TLS_DIRECTORY_BASE<64>
850 {
851// enum {size = 40};
852 static unsigned int size(){return 40;}
853 };
854
855 unsigned int fileSize(const std::string& filename);
856 unsigned int fileSize(std::ifstream& file);
857 unsigned int fileSize(std::ofstream& file);
858 unsigned int fileSize(std::fstream& file);
859 unsigned int alignOffset(unsigned int uiOffset, unsigned int uiAlignment);
860
861 /// Determines if a file is a 32bit or 64bit PE file.
862 unsigned int getFileType(const std::string strFilename);
863
864 /// Opens a PE file.
865 PeFile* openPeFile(const std::string& strFilename);
866
867 /* enum MzHeader_Field {e_magic, e_cblp, e_cp, e_crlc, e_cparhdr, e_minalloc, e_maxalloc,
868 e_ss, e_sp, e_csum, e_ip, e_cs, e_lfarlc, e_ovno, e_res, e_oemid,
869 e_oeminfo, e_res2, e_lfanew};
870 enum PeHeader_Field {NtSignature, Machine, NumberOfSections, TimeDateStamp, PointerToSymbolTable,
871 NumberOfSymbols, SizeOfOptionalHeader, Characteristics, Magic,
872 MajorLinkerVersion, MinorLinkerVersion, SizeOfCode, SizeOfInitializedData,
873 SizeOfUninitializedData, AddressOfEntryPoint, BaseOfCode, BaseOfData, ImageBase,
874 SectionAlignment, FileAlignment, MajorOperatingSystemVersion, MinorOperatingSystemVersion,
875 MajorImageVersion, MinorImageVersion, MajorSubsystemVersion, MinorSubsystemVersion,
876 Win32VersionValue, SizeOfImage, SizeOfHeaders, CheckSum, Subsystem, DllCharacteristics,
877 SizeOfStackReserve, SizeOfStackCommit, SizeOfHeapReserve, SizeOfHeapCommit,
878 LoaderFlags, NumberOfRvaAndSizes, DataDirectoryRva, DataDirectorySize};
879 enum Section_Field {SectionName, VirtualSize, VirtualAddress, SizeOfRawData, PointerToRawData, PointerToRelocations,
880 PointerToLinenumbers, NumberOfRelocations, NumberOfLinenumbers, SectionCharacteristics};
881*/
882}
883
884#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/PeLibInc.h b/utils/zenutils/libraries/pelib-0.9/pelib/PeLibInc.h
new file mode 100755
index 0000000000..84538bd2dd
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/PeLibInc.h
@@ -0,0 +1,32 @@
1/*
2* PeLibInc.h - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#ifndef STD_H
14#define STD_H
15
16#ifdef _MSC_VER
17 #ifndef for
18 #define for if (0) {} else for
19 #endif
20#endif
21
22#include <algorithm>
23#include <climits>
24#include <fstream>
25#include <iostream>
26#include <string>
27#include <vector>
28#include <functional>
29// #include "PeLib.h"
30#include "PeLibAux.h"
31
32#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/RelocationsDirectory.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/RelocationsDirectory.cpp
new file mode 100755
index 0000000000..d8b5035abf
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/RelocationsDirectory.cpp
@@ -0,0 +1,211 @@
1/*
2* Relocations.cpp - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#include "PeLibInc.h"
14#include "RelocationsDirectory.h"
15
16namespace PeLib
17{
18 void RelocationsDirectory::setRelocationData(unsigned int ulRelocation, unsigned int ulDataNumber, word wData)
19 {
20 m_vRelocations[ulRelocation].vRelocData[ulDataNumber] = wData;
21 }
22
23 void RelocationsDirectory::read(InputBuffer& inputbuffer, unsigned int uiSize)
24 {
25 IMG_BASE_RELOC ibrCurr;
26
27 std::vector<IMG_BASE_RELOC> vCurrReloc;
28
29 do
30 {
31 inputbuffer >> ibrCurr.ibrRelocation.VirtualAddress;
32 inputbuffer >> ibrCurr.ibrRelocation.SizeOfBlock;
33
34 ibrCurr.vRelocData.clear();
35
36 // That's not how to check if there are relocations, some DLLs start at VA 0.
37 // if (!ibrCurr.ibrRelocation.VirtualAddress) break;
38
39 for (unsigned int i=0;i<(ibrCurr.ibrRelocation.SizeOfBlock - PELIB_IMAGE_SIZEOF_BASE_RELOCATION) / sizeof(word);i++)
40 {
41 word wData;
42 inputbuffer >> wData;
43 ibrCurr.vRelocData.push_back(wData);
44 }
45
46 vCurrReloc.push_back(ibrCurr);
47 } while (ibrCurr.ibrRelocation.VirtualAddress && inputbuffer.get() < uiSize);
48
49 std::swap(vCurrReloc, m_vRelocations);
50 }
51
52 // TODO: Return value is wrong if buffer was too small.
53 int RelocationsDirectory::read(const unsigned char* buffer, unsigned int buffersize)
54 {
55 std::vector<unsigned char> vRelocDirectory(buffer, buffer + buffersize);
56
57 InputBuffer ibBuffer(vRelocDirectory);
58 read(ibBuffer, buffersize);
59
60 return NO_ERROR;
61 }
62
63 int RelocationsDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize)
64 {
65 std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
66 unsigned int ulFileSize = fileSize(ifFile);
67
68 if (!ifFile)
69 {
70 return ERROR_OPENING_FILE;
71 }
72
73 if (ulFileSize < uiOffset + uiSize)
74 {
75 return ERROR_INVALID_FILE;
76 }
77
78 ifFile.seekg(uiOffset, std::ios::beg);
79
80 std::vector<unsigned char> vRelocDirectory(uiSize);
81 ifFile.read(reinterpret_cast<char*>(&vRelocDirectory[0]), uiSize);
82
83 InputBuffer ibBuffer(vRelocDirectory);
84 read(ibBuffer, uiSize);
85
86 return NO_ERROR;
87 }
88
89 unsigned int RelocationsDirectory::size() const
90 {
91 unsigned int size = static_cast<unsigned int>(m_vRelocations.size()) * PELIB_IMAGE_BASE_RELOCATION::size();
92
93 for (unsigned int i=0;i<m_vRelocations.size();i++)
94 {
95 size += static_cast<unsigned int>(m_vRelocations[i].vRelocData.size()) * sizeof(word);
96 }
97
98 return size;
99 }
100
101 void RelocationsDirectory::rebuild(std::vector<byte>& vBuffer) const
102 {
103 OutputBuffer obBuffer(vBuffer);
104
105 for (unsigned int i=0;i<m_vRelocations.size();i++)
106 {
107 obBuffer << m_vRelocations[i].ibrRelocation.VirtualAddress;
108 obBuffer << m_vRelocations[i].ibrRelocation.SizeOfBlock;
109
110 for (unsigned int j=0;j<m_vRelocations[i].vRelocData.size();j++)
111 {
112 obBuffer << m_vRelocations[i].vRelocData[j];
113 }
114 }
115 }
116
117 unsigned int RelocationsDirectory::calcNumberOfRelocations() const
118 {
119 return static_cast<unsigned int>(m_vRelocations.size());
120 }
121
122 dword RelocationsDirectory::getVirtualAddress(unsigned int ulRelocation) const
123 {
124 return m_vRelocations[ulRelocation].ibrRelocation.VirtualAddress;
125 }
126
127 dword RelocationsDirectory::getSizeOfBlock(unsigned int ulRelocation) const
128 {
129 return m_vRelocations[ulRelocation].ibrRelocation.SizeOfBlock;
130 }
131
132 unsigned int RelocationsDirectory::calcNumberOfRelocationData(unsigned int ulRelocation) const
133 {
134 return static_cast<unsigned int>(m_vRelocations[ulRelocation].vRelocData.size());
135 }
136
137 word RelocationsDirectory::getRelocationData(unsigned int ulRelocation, unsigned int ulDataNumber) const
138 {
139 return m_vRelocations[ulRelocation].vRelocData[ulDataNumber];
140 }
141
142 void RelocationsDirectory::setVirtualAddress(unsigned int ulRelocation, dword dwValue)
143 {
144 m_vRelocations[ulRelocation].ibrRelocation.VirtualAddress = dwValue;
145 }
146
147 void RelocationsDirectory::setSizeOfBlock(unsigned int ulRelocation, dword dwValue)
148 {
149 m_vRelocations[ulRelocation].ibrRelocation.SizeOfBlock = dwValue;
150 }
151
152 void RelocationsDirectory::addRelocation()
153 {
154 IMG_BASE_RELOC newrelocation;
155 m_vRelocations.push_back(newrelocation);
156 }
157
158 void RelocationsDirectory::addRelocationData(unsigned int ulRelocation, word wValue)
159 {
160 m_vRelocations[ulRelocation].vRelocData.push_back(wValue);
161 }
162
163/* void RelocationsDirectory::removeRelocationData(unsigned int ulRelocation, word wValue)
164 {
165 // If you get an error with Borland C++ here you have two options: Upgrade your compiler
166 // or use the commented line instead of the line below.
167 m_vRelocations[ulRelocation].vRelocData.erase(std::remove(m_vRelocations[ulRelocation].vRelocData.begin(), m_vRelocations[ulRelocation].vRelocData.end(), wValue), m_vRelocations[ulRelocation].vRelocData.end());
168 }
169*/
170 void RelocationsDirectory::removeRelocation(unsigned int index)
171 {
172 m_vRelocations.erase(m_vRelocations.begin() + index);
173 }
174
175 void RelocationsDirectory::removeRelocationData(unsigned int relocindex, unsigned int dataindex)
176 {
177 m_vRelocations[relocindex].vRelocData.erase(m_vRelocations[relocindex].vRelocData.begin() + dataindex);
178 }
179
180 int RelocationsDirectory::write(const std::string& strFilename, unsigned int uiOffset) const
181 {
182 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
183
184 if (!ofFile)
185 {
186 ofFile.clear();
187 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
188 }
189 else
190 {
191 ofFile.close();
192 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
193 }
194
195 if (!ofFile)
196 {
197 return ERROR_OPENING_FILE;
198 }
199
200 ofFile.seekp(uiOffset, std::ios::beg);
201
202 std::vector<unsigned char> vBuffer;
203 rebuild(vBuffer);
204
205 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<std::streamsize>(vBuffer.size()));
206
207 ofFile.close();
208
209 return NO_ERROR;
210 }
211}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/RelocationsDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/RelocationsDirectory.h
new file mode 100755
index 0000000000..60383381a3
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/RelocationsDirectory.h
@@ -0,0 +1,70 @@
1/*
2* Relocations.h - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#ifndef RELOCATIONSDIRECTORY_H
14#define RELOCATIONSDIRECTORY_H
15
16namespace PeLib
17{
18 /// Class that handles the relocations directory.
19 /**
20 * This class handles the relocations directory.
21 **/
22 class RelocationsDirectory
23 {
24 private:
25 std::vector<IMG_BASE_RELOC> m_vRelocations; ///< Used to store the relocation data.
26
27 void read(InputBuffer& inputbuffer, unsigned int uiSize);
28
29 public:
30 /// Returns the number of relocations in the relocations directory.
31 unsigned int calcNumberOfRelocations() const; // EXPORT
32 /// Returns the number of relocation data entries of a specific relocation.
33 unsigned int calcNumberOfRelocationData(unsigned int ulRelocation) const; // EXPORT
34
35 /// Read a file's relocations directory.
36 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize); // EXPORT
37 int read(const unsigned char* buffer, unsigned int buffersize); // EXPORT
38 /// Rebuilds the relocations directory.
39 void rebuild(std::vector<byte>& vBuffer) const; // EXPORT
40 /// Returns the size of the relocations directory.
41 unsigned int size() const; // EXPORT
42 /// Writes the relocations directory to a file.
43 int write(const std::string& strFilename, unsigned int dwOffset) const; // EXPORT
44
45 /// Returns the VA of a relocation.
46 dword getVirtualAddress(unsigned int ulRelocation) const; // EXPORT
47 /// Returns the SizeOfBlock value of a relocation.
48 dword getSizeOfBlock(unsigned int ulRelocation) const; // EXPORT
49 /// Returns the RelocationData of a relocation.
50 word getRelocationData(unsigned int ulRelocation, unsigned int ulDataNumber) const; // EXPORT
51
52 /// Changes the relocation data of a relocation.
53 void setRelocationData(unsigned int ulRelocation, unsigned int ulDataNumber, word wData); // EXPORT
54
55 /// Changes the VirtualAddress of a relocation.
56 void setVirtualAddress(unsigned int ulRelocation, dword dwValue); // EXPORT
57 /// Changes the SizeOfBlock of a relocation.
58 void setSizeOfBlock(unsigned int ulRelocation, dword dwValue); // EXPORT
59
60 void addRelocation(); // EXPORT
61 /// Adds new data to a relocation.
62 void addRelocationData(unsigned int ulRelocation, word wValue); // EXPORT
63 /// Removes data from a relocation.
64// void removeRelocationData(unsigned int ulRelocation, word wValue); // EXPORT
65 void removeRelocation(unsigned int index); // EXPORT
66 void removeRelocationData(unsigned int relocindex, unsigned int dataindex); // EXPORT
67 };
68}
69
70#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/ResourceDirectory.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/ResourceDirectory.cpp
new file mode 100755
index 0000000000..5e4d3010bf
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/ResourceDirectory.cpp
@@ -0,0 +1,1497 @@
1/*
2* ResourceDirectory.h - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#include "ResourceDirectory.h"
14
15namespace PeLib
16{
17// -------------------------------------------------- ResourceChild -------------------------------------------
18
19 ResourceChild::ResourceChild()
20 {
21 }
22
23 ResourceChild::ResourceChild(const ResourceChild& rhs)
24 {
25 if (dynamic_cast<ResourceNode*>(rhs.child))
26 {
27 ResourceNode* oldnode = static_cast<ResourceNode*>(rhs.child);
28
29 entry = rhs.entry;
30
31 child = new ResourceNode;
32 child->uiElementRva = rhs.child->getElementRva();
33 static_cast<ResourceNode*>(child)->header = oldnode->header;
34 static_cast<ResourceNode*>(child)->children = oldnode->children;
35 }
36 else
37 {
38 ResourceLeaf* oldnode = static_cast<ResourceLeaf*>(rhs.child);
39
40 child = new ResourceLeaf;
41 child->uiElementRva = rhs.child->getElementRva();
42 static_cast<ResourceLeaf*>(child)->m_data = oldnode->m_data;
43 static_cast<ResourceLeaf*>(child)->entry = oldnode->entry;
44 }
45 }
46
47 ResourceChild& ResourceChild::operator=(const ResourceChild& rhs)
48 {
49 if (this != &rhs)
50 {
51 if (dynamic_cast<ResourceNode*>(rhs.child))
52 {
53 ResourceNode* oldnode = static_cast<ResourceNode*>(rhs.child);
54
55 entry = rhs.entry;
56
57 child = new ResourceNode;
58 child->uiElementRva = rhs.child->getElementRva();
59 static_cast<ResourceNode*>(child)->header = oldnode->header;
60 static_cast<ResourceNode*>(child)->children = oldnode->children;
61 }
62 else
63 {
64 ResourceLeaf* oldnode = static_cast<ResourceLeaf*>(rhs.child);
65
66 child = new ResourceLeaf;
67 child->uiElementRva = rhs.child->getElementRva();
68 static_cast<ResourceLeaf*>(child)->m_data = oldnode->m_data;
69 static_cast<ResourceLeaf*>(child)->entry = oldnode->entry;
70 }
71 }
72
73 return *this;
74 }
75
76 ResourceChild::~ResourceChild()
77 {
78 delete child;
79 }
80
81 /**
82 * Compares the resource child's id to the parameter dwId.
83 * @param dwId ID of a resource.
84 * @return True, if the resource child's id equals the parameter.
85 **/
86 bool ResourceChild::equalId(dword dwId) const
87 {
88 return entry.irde.Name == dwId;
89 }
90
91 /**
92 * Compares the resource child's name to the parameter strName.
93 * @param strName ID of a resource.
94 * @return True, if the resource child's name equals the parameter.
95 **/
96 bool ResourceChild::equalName(std::string strName) const
97 {
98 return entry.wstrName == strName;
99 }
100
101 /**
102 * Returns true if the resource was given a name.
103 **/
104 bool ResourceChild::isNamedResource() const
105 {
106 return entry.wstrName.size() != 0;
107 }
108
109 /**
110 * The children of a resource must be ordered in a certain way. First come the named resources
111 * in sorted order, afterwards followed the unnamed resources in sorted order.
112 **/
113 bool ResourceChild::operator<(const ResourceChild& rc) const
114 {
115 if (this->isNamedResource() && !rc.isNamedResource())
116 {
117 return true;
118 }
119 else if (!this->isNamedResource() && rc.isNamedResource())
120 {
121 return false;
122 }
123 else if (this->isNamedResource() && rc.isNamedResource())
124 {
125 return this->entry.wstrName < rc.entry.wstrName;
126 }
127 else
128 {
129 return this->entry.irde.Name < rc.entry.irde.Name;
130 }
131 }
132
133/* unsigned int ResourceChild::size() const
134 {
135 return PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY::size()
136 + child->size()
137 + (entry.wstrName.size() ? entry.wstrName.size() + 2 : 0);
138 }
139*/
140// -------------------------------------------------- ResourceElement -------------------------------------------
141
142 /**
143 * Returns the RVA of a ResourceElement. This is the RVA where the ResourceElement can be
144 * found in the file.
145 * @return RVA of the ResourceElement.
146 **/
147 unsigned int ResourceElement::getElementRva() const
148 {
149 return uiElementRva;
150 }
151
152// -------------------------------------------------- ResourceLeaf -------------------------------------------
153
154 /**
155 * Checks if a ResourceElement is a leaf or not.
156 * @return Always returns true.
157 **/
158 bool ResourceLeaf::isLeaf() const
159 {
160 return true;
161 }
162
163 /**
164 * Reads the next resource leaf from the InputBuffer.
165 * @param inpBuffer An InputBuffer that holds the complete resource directory.
166 * @param uiOffset Offset of the resource leaf that's to be read.
167 * @param uiRva RVA of the beginning of the resource directory.
168 * @param pad Used for debugging purposes.
169 **/
170 int ResourceLeaf::read(InputBuffer& inpBuffer, unsigned int uiOffset, unsigned int uiRva/*, const std::string& pad*/)
171 {
172// std::cout << pad << "Leaf:" << std::endl;
173
174 // Invalid leaf.
175 if (uiOffset + PELIB_IMAGE_RESOURCE_DATA_ENTRY::size() > inpBuffer.size())
176 {
177 return 1;
178 }
179
180 uiElementRva = uiOffset + uiRva;
181
182 inpBuffer.set(uiOffset);
183
184 inpBuffer >> entry.OffsetToData;
185 inpBuffer >> entry.Size;
186 inpBuffer >> entry.CodePage;
187 inpBuffer >> entry.Reserved;
188
189/* std::cout << pad << std::hex << "Offset: " << entry.OffsetToData << std::endl;
190 std::cout << pad << std::hex << "Size: " << entry.Size << std::endl;
191 std::cout << pad << std::hex << "CodePage: " << entry.CodePage << std::endl;
192 std::cout << pad << std::hex << "Reserved: " << entry.Reserved << std::endl;
193*/
194 // Invalid leaf.
195 if (entry.OffsetToData - uiRva + entry.Size > inpBuffer.size())
196 {
197// std::cout << entry.OffsetToData << " XXX " << uiRva << " - " << entry.Size << " - " << inpBuffer.size() << std::endl;
198 return 1;
199 }
200
201// std::cout << entry.OffsetToData << " - " << uiRva << " - " << entry.Size << " - " << inpBuffer.size() << std::endl;
202 inpBuffer.set(entry.OffsetToData - uiRva);
203 m_data.assign(inpBuffer.data() + inpBuffer.get(), inpBuffer.data() + inpBuffer.get() + entry.Size);
204// std::cout << pad << std::hex << "Vector: " << m_data.size() << std::endl;
205// std::copy(m_data.begin(), m_data.end(), std::ostream_iterator<int>(std::cout << std::hex, " "));
206 return 0;
207 }
208
209 /**
210 * Rebuilds the current resource leaf.
211 * @param obBuffer OutputBuffer where the rebuilt resource leaf is stored.
212 * @param uiOffset Offset of the resource leaf inside the resource directory.
213 * @param uiRva RVA of the resource directory.
214 **/
215 void ResourceLeaf::rebuild(OutputBuffer& obBuffer, unsigned int& uiOffset, unsigned int uiRva, const std::string&) const
216 {
217// std::cout << std::hex << pad << "Leaf: " << uiOffset << std::endl;
218 uiOffset += PELIB_IMAGE_RESOURCE_DATA_ENTRY::size();
219
220// obBuffer << entry.OffsetToData;
221// obBuffer << uiOffset;
222 obBuffer << uiRva + uiOffset + (uiOffset % 4);
223 obBuffer << entry.Size;
224 obBuffer << entry.CodePage;
225 obBuffer << entry.Reserved;
226
227 while (uiOffset % 4)
228 {
229 uiOffset++;
230 obBuffer << (byte)0;
231 }
232
233 uiOffset += static_cast<unsigned int>(m_data.size());
234
235 for (unsigned int i=0;i<m_data.size();i++)
236 {
237 obBuffer << m_data[i];
238 }
239// std::cout << "LeafChild: " << std::endl;
240 }
241
242 void ResourceLeaf::makeValid()
243 {
244 entry.Size = static_cast<unsigned int>(m_data.size());
245 }
246
247/* /// Returns the size of a resource leaf.
248 unsigned int ResourceLeaf::size() const
249 {
250 return PELIB_IMAGE_RESOURCE_DATA_ENTRY::size() + m_data.size();
251 }
252*/
253
254 /**
255 * Returns a vector that contains the raw data of a resource leaf.
256 * @return Raw data of the resource.
257 **/
258 std::vector<byte> ResourceLeaf::getData() const
259 {
260 return m_data;
261 }
262
263 /**
264 * Overwrites the raw data of a resource.
265 * @param vData New data of the resource.
266 **/
267 void ResourceLeaf::setData(const std::vector<byte>& vData)
268 {
269 m_data = vData;
270 }
271
272 /**
273 * Returns the leaf's OffsetToData value. That's the RVA where the raw data of the resource
274 * can be found.
275 * @return The leaf's OffsetToData value.
276 **/
277 dword ResourceLeaf::getOffsetToData() const
278 {
279 return entry.OffsetToData;
280 }
281
282 /**
283 * Returns the leaf's Size value. That's the size of the raw data of the resource.
284 * @return The leaf's Size value.
285 **/
286 dword ResourceLeaf::getSize() const
287 {
288 return entry.Size;
289 }
290
291 /**
292 * Returns the leaf's CodePage value.
293 * @return The leaf's CodePage value.
294 **/
295 dword ResourceLeaf::getCodePage() const
296 {
297 return entry.CodePage;
298 }
299
300 /**
301 * Returns the leaf's Reserved value.
302 * @return The leaf's Reserved value.
303 **/
304 dword ResourceLeaf::getReserved() const
305 {
306 return entry.Reserved;
307 }
308
309 /**
310 * Sets the leaf's OffsetToData value.
311 * @param dwValue The leaf's new OffsetToData value.
312 **/
313 void ResourceLeaf::setOffsetToData(dword dwValue)
314 {
315 entry.OffsetToData = dwValue;
316 }
317
318 /**
319 * Sets the leaf's Size value.
320 * @param dwValue The leaf's new Size value.
321 **/
322 void ResourceLeaf::setSize(dword dwValue)
323 {
324 entry.Size = dwValue;
325 }
326
327 /**
328 * Sets the leaf's CodePage value.
329 * @param dwValue The leaf's new CodePage value.
330 **/
331 void ResourceLeaf::setCodePage(dword dwValue)
332 {
333 entry.CodePage = dwValue;
334 }
335
336 /**
337 * Sets the leaf's Reserved value.
338 * @param dwValue The leaf's new Reserved value.
339 **/
340 void ResourceLeaf::setReserved(dword dwValue)
341 {
342 entry.Reserved = dwValue;
343 }
344
345
346// -------------------------------------------------- ResourceNode -------------------------------------------
347
348 /**
349 * Checks if a ResourceElement is a leaf or not.
350 * @return Always returns false.
351 **/
352 bool ResourceNode::isLeaf() const
353 {
354 return false;
355 }
356
357 /**
358 * Sorts the node's children and corrects the node's header.
359 **/
360 void ResourceNode::makeValid()
361 {
362 std::sort(children.begin(), children.end());
363 header.NumberOfNamedEntries = static_cast<PeLib::word>(std::count_if(children.begin(), children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource)));
364 header.NumberOfIdEntries = static_cast<unsigned int>(children.size()) - header.NumberOfNamedEntries;
365 }
366
367 /**
368 * Rebuilds the current resource node.
369 * @param obBuffer OutputBuffer where the rebuilt resource node is stored.
370 * @param uiOffset Offset of the resource node inside the resource directory.
371 * @param uiRva RVA of the resource directory.
372 * @param pad Used for debugging.
373 **/
374 void ResourceNode::rebuild(OutputBuffer& obBuffer, unsigned int& uiOffset, unsigned int uiRva, const std::string& pad) const
375 {
376/* std::cout << std::hex << pad << uiOffset << std::endl;
377
378 std::cout << std::hex << pad << "header.Characteristics: " << header.Characteristics << std::endl;
379 std::cout << std::hex << pad << "header.TimeDateStamp: " << header.TimeDateStamp << std::endl;
380 std::cout << std::hex << pad << "header.MajorVersion: " << header.MajorVersion << std::endl;
381 std::cout << std::hex << pad << "header.MinorVersion: " << header.MinorVersion << std::endl;
382 std::cout << std::hex << pad << "header.NumberOfNamedEntries: " << header.NumberOfNamedEntries << std::endl;
383 std::cout << std::hex << pad << "header.NumberOfIdEntries: " << header.NumberOfIdEntries << std::endl;
384*/
385 obBuffer << header.Characteristics;
386 obBuffer << header.TimeDateStamp;
387 obBuffer << header.MajorVersion;
388 obBuffer << header.MinorVersion;
389 //std::cout << pad << "Children: " << children.size() << std::endl;
390 //std::cout << pad << std::count_if(children.begin(), children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource)) << std::endl;
391 //std::cout << pad << children.size() - std::count_if(children.begin(), children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource)) << std::endl;
392// obBuffer << std::count_if(children.begin(), children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource));
393// obBuffer << children.size() - std::count_if(children.begin(), children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource));
394 obBuffer << header.NumberOfNamedEntries;
395 obBuffer << header.NumberOfIdEntries;
396
397 uiOffset += PELIB_IMAGE_RESOURCE_DIRECTORY::size();
398
399 for (unsigned int i=0;i<children.size();i++)
400 {
401 obBuffer << (dword)0;
402 obBuffer << (dword)0;
403 }
404
405 unsigned int newoffs = (uiOffset + children.size() * 8);
406
407 for (unsigned int i=0;i<children.size();i++)
408 {
409 if (!children[i].entry.wstrName.size())
410 {
411 obBuffer.update(uiOffset, children[i].entry.irde.Name);
412 }
413 else
414 {
415 obBuffer.update(uiOffset, newoffs | PELIB_IMAGE_RESOURCE_NAME_IS_STRING);
416 obBuffer << (word)children[i].entry.wstrName.size();
417 newoffs += 2;
418 for (unsigned int j=0;j<children[i].entry.wstrName.size();j++)
419 {
420// std::cout << children[i].entry.wstrName[j];
421 obBuffer << (word)children[i].entry.wstrName[j];
422 newoffs += 2;
423 }
424 }
425 uiOffset += 4;
426// obBuffer << children[i].entry.OffsetToData;
427 obBuffer.update(uiOffset, newoffs | (children[i].entry.irde.OffsetToData & PELIB_IMAGE_RESOURCE_DATA_IS_DIRECTORY));
428 uiOffset += 4;
429 children[i].child->rebuild(obBuffer, newoffs, uiRva, pad + " ");
430 }
431 uiOffset = newoffs;
432 }
433
434 /**
435 * Reads the next resource node from the InputBuffer.
436 * @param inpBuffer An InputBuffer that holds the complete resource directory.
437 * @param uiOffset Offset of the resource node that's to be read.
438 * @param uiRva RVA of the beginning of the resource directory.
439 * @param pad Something I need for debugging. Will be removed soon.
440 **/
441 int ResourceNode::read(InputBuffer& inpBuffer, unsigned int uiOffset, unsigned int uiRva/*, const std::string& pad*/)
442 {
443 // Not enough space to be a valid node.
444 if (uiOffset + PELIB_IMAGE_RESOURCE_DIRECTORY::size() > inpBuffer.size())
445 {
446 return 1;
447 }
448
449 uiElementRva = uiOffset + uiRva;
450
451 inpBuffer.set(uiOffset);
452
453 inpBuffer >> header.Characteristics;
454 inpBuffer >> header.TimeDateStamp;
455 inpBuffer >> header.MajorVersion;
456 inpBuffer >> header.MinorVersion;
457 inpBuffer >> header.NumberOfNamedEntries;
458 inpBuffer >> header.NumberOfIdEntries;
459
460 // Not enough space to be a valid node.
461 if (uiOffset + PELIB_IMAGE_RESOURCE_DIRECTORY::size()
462 + (header.NumberOfNamedEntries + header.NumberOfIdEntries) * PELIB_IMAGE_RESOURCE_DIRECTORY_ENTRY::size()
463 > inpBuffer.size())
464 {
465 return 1;
466 }
467
468// std::cout << std::hex << pad << "Characteristics: " << header.Characteristics << std::endl;
469// std::cout << std::hex << pad << "TimeDateStamp: " << header.TimeDateStamp << std::endl;
470// std::cout << std::hex << pad << "MajorVersion: " << header.MajorVersion << std::endl;
471// std::cout << std::hex << pad << "MinorVersion: " << header.MinorVersion << std::endl;
472// std::cout << std::hex << pad << "NumberOfNamedEntries: " << header.NumberOfNamedEntries << std::endl;
473// std::cout << std::hex << pad << "NumberOfIdEntries: " << header.NumberOfIdEntries << std::endl;
474
475 for (int i=0;i<header.NumberOfNamedEntries + header.NumberOfIdEntries;i++)
476 {
477 ResourceChild rc;
478 inpBuffer >> rc.entry.irde.Name;
479 inpBuffer >> rc.entry.irde.OffsetToData;
480
481 unsigned int lastPos = inpBuffer.get();
482
483 if (rc.entry.irde.Name & PELIB_IMAGE_RESOURCE_NAME_IS_STRING)
484 {
485 // Enough space to read string length?
486 if ((rc.entry.irde.Name & ~PELIB_IMAGE_RESOURCE_NAME_IS_STRING) + 2 < inpBuffer.size())
487 {
488 inpBuffer.set(rc.entry.irde.Name & ~PELIB_IMAGE_RESOURCE_NAME_IS_STRING);
489 word strlen;
490 inpBuffer >> strlen;
491
492 // Enough space to read string?
493 if ((rc.entry.irde.Name & ~PELIB_IMAGE_RESOURCE_NAME_IS_STRING) + 2 * strlen < inpBuffer.size())
494 {
495 wchar_t c;
496 for (word i=0;i<strlen;i++)
497 {
498 inpBuffer >> c;
499 rc.entry.wstrName += c;
500 }
501 }
502 }
503
504// std::wcout << rc.entry.wstrName << std::endl;
505
506// std::cout << strlen << std::endl;
507 inpBuffer.set(lastPos);
508 }
509
510 if (rc.entry.irde.OffsetToData & PELIB_IMAGE_RESOURCE_DATA_IS_DIRECTORY)
511 {
512 rc.child = new ResourceNode;
513 rc.child->read(inpBuffer, rc.entry.irde.OffsetToData & ~PELIB_IMAGE_RESOURCE_DATA_IS_DIRECTORY, uiRva/*, pad + " "*/);
514 }
515 else
516 {
517 rc.child = new ResourceLeaf;
518 rc.child->read(inpBuffer, rc.entry.irde.OffsetToData, uiRva/*, pad + " "*/);
519 }
520// std::cout << std::hex << pad << "Entry " << i << "(Name): " << rc.entry.irde.Name << std::endl;
521// std::cout << std::hex << pad << "Entry " << i << "(Offset): " << rc.entry.irde.OffsetToData << std::endl;
522
523 children.push_back(rc);
524 inpBuffer.set(lastPos);
525 }
526
527 return 0;
528 }
529
530 /**
531 * Returns the number of children of the current node. Note that this number is the number
532 * of defined children, not the value from the header.
533 * @return Number of node's children.
534 **/
535 unsigned int ResourceNode::getNumberOfChildren() const
536 {
537 return static_cast<unsigned int>(children.size());
538 }
539
540 /**
541 * Adds another child to the current node.
542 **/
543 void ResourceNode::addChild()
544 {
545 ResourceChild c;
546 c.child = 0;
547 children.push_back(c);
548 }
549
550 /**
551 * Returns a node's child.
552 * @param uiIndex Index of the child.
553 * @return The child identified by uiIndex. This child can be either a ResourceNode or a ResourceLeaf.
554 **/
555 ResourceElement* ResourceNode::getChild(unsigned int uiIndex)
556 {
557 return children[uiIndex].child;
558 }
559
560 /**
561 * Removes a child from the current node.
562 * @param uiIndex Index of the child.
563 **/
564 void ResourceNode::removeChild(unsigned int uiIndex)
565 {
566 children.erase(children.begin() + uiIndex);
567 }
568
569 /**
570 * Returns the name of a child.
571 * @param uiIndex Index of the child.
572 * @return Either the name of the specified child or an empty string.
573 **/
574 std::string ResourceNode::getChildName(unsigned int uiIndex) const
575 {
576 return children[uiIndex].entry.wstrName;
577 }
578
579 /**
580 * Returns the Name value of a child.
581 * @param uiIndex Index of the child.
582 * @return Name value of a child.
583 **/
584 dword ResourceNode::getOffsetToChildName(unsigned int uiIndex) const
585 {
586 return children[uiIndex].entry.irde.Name;
587 }
588
589 /**
590 * Returns the OffsetToData value of a child.
591 * @param uiIndex Index of the child.
592 * @return OffsetToData value of a child.
593 **/
594 dword ResourceNode::getOffsetToChildData(unsigned int uiIndex) const
595 {
596 return children[uiIndex].entry.irde.OffsetToData;
597 }
598
599
600 /**
601 * Sets the name of a child.
602 * @param uiIndex Index of the child.
603 * @param strNewName New name of the resource.
604 **/
605 void ResourceNode::setChildName(unsigned int uiIndex, const std::string& strNewName)
606 {
607 children[uiIndex].entry.wstrName = strNewName;
608 }
609
610 /**
611 * Sets the Name value of a child.
612 * @param uiIndex Index of the child.
613 * @param dwNewOffset New Name value of the resource.
614 **/
615 void ResourceNode::setOffsetToChildName(unsigned int uiIndex, dword dwNewOffset)
616 {
617 children[uiIndex].entry.irde.Name = dwNewOffset;
618 }
619
620 /**
621 * Sets the OffsetToData value of a child.
622 * @param uiIndex Index of the child.
623 * @param dwNewOffset New OffsetToData value of the resource.
624 **/
625 void ResourceNode::setOffsetToChildData(unsigned int uiIndex, dword dwNewOffset)
626 {
627 children[uiIndex].entry.irde.OffsetToData = dwNewOffset;
628 }
629
630 /**
631 * Returns the Characteristics value of the node.
632 * @return Characteristics value of the node.
633 **/
634 dword ResourceNode::getCharacteristics() const
635 {
636 return header.Characteristics;
637 }
638
639 /**
640 * Returns the TimeDateStamp value of the node.
641 * @return TimeDateStamp value of the node.
642 **/
643 dword ResourceNode::getTimeDateStamp() const
644 {
645 return header.TimeDateStamp;
646 }
647
648 /**
649 * Returns the MajorVersion value of the node.
650 * @return MajorVersion value of the node.
651 **/
652 word ResourceNode::getMajorVersion() const
653 {
654 return header.MajorVersion;
655 }
656
657 /**
658 * Returns the MinorVersion value of the node.
659 * @return MinorVersion value of the node.
660 **/
661 word ResourceNode::getMinorVersion() const
662 {
663 return header.MinorVersion;
664 }
665
666 /**
667 * Returns the NumberOfNamedEntries value of the node.
668 * @return NumberOfNamedEntries value of the node.
669 **/
670 word ResourceNode::getNumberOfNamedEntries() const
671 {
672 return header.NumberOfNamedEntries;
673 }
674
675 /**
676 * Returns the NumberOfIdEntries value of the node.
677 * @return NumberOfIdEntries value of the node.
678 **/
679 word ResourceNode::getNumberOfIdEntries() const
680 {
681 return header.NumberOfIdEntries;
682 }
683
684 /**
685 * Sets the Characteristics value of the node.
686 * @param value New Characteristics value of the node.
687 **/
688 void ResourceNode::setCharacteristics(dword value)
689 {
690 header.Characteristics = value;
691 }
692
693 /**
694 * Sets the TimeDateStamp value of the node.
695 * @param value New TimeDateStamp value of the node.
696 **/
697 void ResourceNode::setTimeDateStamp(dword value)
698 {
699 header.TimeDateStamp = value;
700 }
701
702 /**
703 * Sets the MajorVersion value of the node.
704 * @param value New MajorVersion value of the node.
705 **/
706 void ResourceNode::setMajorVersion(word value)
707 {
708 header.MajorVersion = value;
709 }
710
711 /**
712 * Sets the MinorVersion value of the node.
713 * @param value New MinorVersion value of the node.
714 **/
715 void ResourceNode::setMinorVersion(word value)
716 {
717 header.MinorVersion = value;
718 }
719
720 /**
721 * Sets the NumberOfNamedEntries value of the node.
722 * @param value New NumberOfNamedEntries value of the node.
723 **/
724 void ResourceNode::setNumberOfNamedEntries(word value)
725 {
726 header.NumberOfNamedEntries = value;
727 }
728
729 /**
730 * Sets the NumberOfIdEntries value of the node.
731 * @param value New NumberOfIdEntries value of the node.
732 **/
733 void ResourceNode::setNumberOfIdEntries(word value)
734 {
735 header.NumberOfIdEntries = value;
736 }
737
738
739/* /// Returns the size of a resource node.
740 unsigned int ResourceNode::size() const
741 {
742 if (children.size())
743 {
744 std::cout << std::accumulate(children.begin(), children.end(), 0, accumulate<ResourceChild>) << std::endl;
745 return PELIB_IMAGE_RESOURCE_DIRECTORY::size()
746 + std::accumulate(children.begin(), children.end(), 0, accumulate<ResourceChild>);
747 }
748 else
749 {
750 return 0;
751 }
752 }
753*/
754// -------------------------------------------------- ResourceDirectory -------------------------------------------
755
756 /**
757 * Returns the root node of the resource directory.
758 * @return Root node of the resource directory.
759 **/
760 ResourceNode* ResourceDirectory::getRoot()
761 {
762 return &m_rnRoot;
763 }
764
765 /**
766 * Correctly sorts the resource nodes of the resource tree. This function should be called
767 * before calling rebuild.
768 **/
769 void ResourceDirectory::makeValid()
770 {
771 m_rnRoot.makeValid();
772 }
773
774 /**
775 * Reads the resource directory from a file.
776 * @param strFilename Name of the file.
777 * @param uiOffset File offset of the resource directory.
778 * @param uiSize Raw size of the resource directory.
779 * @param uiResDirRva RVA of the beginning of the resource directory.
780 **/
781 int ResourceDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, unsigned int uiResDirRva)
782 {
783 if (!uiSize || !uiOffset)
784 {
785 return 1;
786 }
787
788 std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
789
790 if (!ifFile)
791 {
792// throw Exceptions::CannotOpenFile(ResourceDirectoryId, __LINE__);
793 return 1;
794 }
795
796 if (fileSize(ifFile) < uiOffset + uiSize)
797 {
798// throw Exceptions::InvalidFormat(ResourceDirectoryId, __LINE__);
799 return 1;
800 }
801
802 ifFile.seekg(uiOffset, std::ios::beg);
803
804 PELIB_IMAGE_RESOURCE_DIRECTORY irdCurrRoot;
805
806 std::vector<byte> vResourceDirectory(uiSize);
807 ifFile.read(reinterpret_cast<char*>(&vResourceDirectory[0]), uiSize);
808
809 InputBuffer inpBuffer(vResourceDirectory);
810
811// ResourceNode currNode;
812 return m_rnRoot.read(inpBuffer, 0, uiResDirRva/*, ""*/);
813// std::swap(currNode, m_rnRoot);
814 }
815
816 /**
817 * Rebuilds the resource directory.
818 * @param vBuffer Buffer the source directory will be written to.
819 * @param uiRva RVA of the resource directory.
820 **/
821 void ResourceDirectory::rebuild(std::vector<byte>& vBuffer, unsigned int uiRva) const
822 {
823 OutputBuffer obBuffer(vBuffer);
824 unsigned int offs = 0;
825// std::cout << "Root: " << m_rnRoot.children.size() << std::endl;
826 m_rnRoot.rebuild(obBuffer, offs, uiRva, "");
827 }
828
829 /**
830 * Returns the size of the entire rebuilt resource directory. That's the size of the entire
831 * structure as it's written back to a file.
832 **/
833/* unsigned int ResourceDirectory::size() const
834 {
835 return m_rnRoot.size();
836 }
837*/
838 /**
839 * Writes the current resource directory back into a file.
840 * @param strFilename Name of the output file.
841 * @param uiOffset File offset where the resource directory will be written to.
842 * @param uiRva RVA of the file offset.
843 **/
844 int ResourceDirectory::write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva) const
845 {
846 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
847
848 if (!ofFile)
849 {
850 ofFile.clear();
851 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
852 }
853 else
854 {
855 ofFile.close();
856 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
857 }
858
859 if (!ofFile)
860 {
861 return ERROR_OPENING_FILE;
862 }
863
864 ofFile.seekp(uiOffset, std::ios::beg);
865
866 std::vector<unsigned char> vBuffer;
867 rebuild(vBuffer, uiRva);
868
869 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
870
871 ofFile.close();
872
873 return 0;
874 }
875
876 /**
877 * Adds another resource type. The new resource type is identified by the ID dwResTypeId.
878 * @param dwResTypeId ID which identifies the resource type.
879 **/
880 int ResourceDirectory::addResourceType(dword dwResTypeId)
881 {
882 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalId), dwResTypeId));
883 if (Iter != m_rnRoot.children.end())
884 {
885 return 1;
886 // throw Exceptions::EntryAlreadyExists(ResourceDirectoryId, __LINE__);
887 }
888
889 ResourceChild rcCurr;
890 rcCurr.child = new ResourceNode;
891 rcCurr.entry.irde.Name = dwResTypeId;
892 m_rnRoot.children.push_back(rcCurr);
893
894 return 0;
895 }
896
897 /**
898 * Adds another resource type. The new resource type is identified by the name strResTypeName.
899 * @param strResTypeName Name which identifies the resource type.
900 **/
901 int ResourceDirectory::addResourceType(const std::string& strResTypeName)
902 {
903 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalName), strResTypeName));
904 if (Iter != m_rnRoot.children.end())
905 {
906 return 1;
907// throw Exceptions::EntryAlreadyExists(ResourceDirectoryId, __LINE__);
908 }
909
910 ResourceChild rcCurr;
911 rcCurr.entry.wstrName = strResTypeName;
912 rcCurr.child = new ResourceNode;
913 m_rnRoot.children.push_back(rcCurr);
914
915 return 0;
916 }
917
918 /**
919 * Removes the resource type identified by the ID dwResTypeId.
920 * @param dwResTypeId ID which identifies the resource type.
921 **/
922 int ResourceDirectory::removeResourceType(dword dwResTypeId)
923 {
924 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalId), dwResTypeId));
925 if (Iter == m_rnRoot.children.end())
926 {
927 return 1;
928// throw Exceptions::ResourceTypeDoesNotExist(ResourceDirectoryId, __LINE__);
929 }
930
931 bool isNamed = false;
932 if (Iter->isNamedResource()) isNamed = true;
933
934 m_rnRoot.children.erase(Iter);
935
936 if (isNamed) m_rnRoot.header.NumberOfNamedEntries = static_cast<PeLib::word>(m_rnRoot.children.size());
937 else m_rnRoot.header.NumberOfIdEntries = static_cast<PeLib::word>(m_rnRoot.children.size());
938
939 return 0;
940 }
941
942 /**
943 * Removes the resource type identified by the name strResTypeName.
944 * @param strResTypeName Name which identifies the resource type.
945 **/
946 int ResourceDirectory::removeResourceType(const std::string& strResTypeName)
947 {
948 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalName), strResTypeName));
949 if (Iter == m_rnRoot.children.end())
950 {
951 return 1;
952 // throw Exceptions::ResourceTypeDoesNotExist(ResourceDirectoryId, __LINE__);
953 }
954
955 bool isNamed = false;
956 if (Iter->isNamedResource()) isNamed = true;
957
958 m_rnRoot.children.erase(Iter);
959
960 if (isNamed) m_rnRoot.header.NumberOfNamedEntries = static_cast<PeLib::word>(m_rnRoot.children.size());
961 else m_rnRoot.header.NumberOfIdEntries = static_cast<PeLib::word>(m_rnRoot.children.size());
962
963 return 0;
964 }
965
966 /**
967 * Removes the resource type identified by the index uiIndex.
968 * @param uiIndex Index which identifies the resource type.
969 **/
970 int ResourceDirectory::removeResourceTypeByIndex(unsigned int uiIndex)
971 {
972 bool isNamed = false;
973 if (m_rnRoot.children[uiIndex].isNamedResource()) isNamed = true;
974
975 m_rnRoot.children.erase(m_rnRoot.children.begin() + uiIndex);
976
977 if (isNamed) m_rnRoot.header.NumberOfNamedEntries = static_cast<PeLib::word>(m_rnRoot.children.size());
978 else m_rnRoot.header.NumberOfIdEntries = static_cast<PeLib::word>(m_rnRoot.children.size());
979
980 return 0;
981 }
982
983 /**
984 * Adds another resource to the resource tree. The first parameter identifies the resource type
985 * of the new resource, the second parameter identifies the resource itself.
986 * @param dwResTypeId ID of the resource type.
987 * @param dwResId ID of the resource.
988 **/
989 int ResourceDirectory::addResource(dword dwResTypeId, dword dwResId)
990 {
991 ResourceChild rcCurr;
992 rcCurr.entry.irde.Name = dwResId;
993 return addResourceT(dwResTypeId, dwResId, rcCurr);
994 }
995
996 /**
997 * Adds another resource to the resource tree. The first parameter identifies the resource type
998 * of the new resource, the second parameter identifies the resource itself.
999 * @param dwResTypeId ID of the resource type.
1000 * @param strResName Name of the resource.
1001 **/
1002 int ResourceDirectory::addResource(dword dwResTypeId, const std::string& strResName)
1003 {
1004 ResourceChild rcCurr;
1005 rcCurr.entry.wstrName = strResName;
1006 return addResourceT(dwResTypeId, strResName, rcCurr);
1007 }
1008
1009 /**
1010 * Adds another resource to the resource tree. The first parameter identifies the resource type
1011 * of the new resource, the second parameter identifies the resource itself.
1012 * @param strResTypeName Name of the resource type.
1013 * @param dwResId ID of the resource.
1014 **/
1015 int ResourceDirectory::addResource(const std::string& strResTypeName, dword dwResId)
1016 {
1017 ResourceChild rcCurr;
1018 rcCurr.entry.irde.Name = dwResId;
1019 return addResourceT(strResTypeName, dwResId, rcCurr);
1020 }
1021
1022 /**
1023 * Adds another resource to the resource tree. The first parameter identifies the resource type
1024 * of the new resource, the second parameter identifies the resource itself.
1025 * @param strResTypeName Name of the resource type.
1026 * @param strResName Name of the resource.
1027 **/
1028 int ResourceDirectory::addResource(const std::string& strResTypeName, const std::string& strResName)
1029 {
1030 ResourceChild rcCurr;
1031 rcCurr.entry.wstrName = strResName;
1032 return addResourceT(strResTypeName, strResName, rcCurr);
1033 }
1034
1035 /**
1036 * Removes a resource from the resource tree. The first parameter identifies the resource type
1037 * of the new resource, the second parameter identifies the resource itself.
1038 * @param dwResTypeIndex ID of the resource type.
1039 * @param dwResId ID of the resource.
1040 **/
1041 int ResourceDirectory::removeResource(dword dwResTypeIndex, dword dwResId)
1042 {
1043 return removeResourceT(dwResTypeIndex, dwResId);
1044 }
1045
1046 /**
1047 * Removes a resource from the resource tree. The first parameter identifies the resource type
1048 * of the new resource, the second parameter identifies the resource itself.
1049 * @param dwResTypeIndex ID of the resource type.
1050 * @param strResName Name of the resource.
1051 **/
1052 int ResourceDirectory::removeResource(dword dwResTypeIndex, const std::string& strResName)
1053 {
1054 return removeResourceT(dwResTypeIndex, strResName);
1055 }
1056
1057 /**
1058 * Removes a resource from the resource tree. The first parameter identifies the resource type
1059 * of the new resource, the second parameter identifies the resource itself.
1060 * @param strResTypeName Name of the resource type.
1061 * @param dwResId ID of the resource.
1062 **/
1063 int ResourceDirectory::removeResource(const std::string& strResTypeName, dword dwResId)
1064 {
1065 return removeResourceT(strResTypeName, dwResId);
1066 }
1067
1068 /**
1069 * Removes a resource from the resource tree. The first parameter identifies the resource type
1070 * of the new resource, the second parameter identifies the resource itself.
1071 * @param strResTypeName Name of the resource type.
1072 * @param strResName Name of the resource.
1073 **/
1074 int ResourceDirectory::removeResource(const std::string& strResTypeName, const std::string& strResName)
1075 {
1076 return removeResourceT(strResTypeName, strResName);
1077 }
1078
1079 /**
1080 * Returns the number of resource types.
1081 **/
1082 unsigned int ResourceDirectory::getNumberOfResourceTypes() const
1083 {
1084 return static_cast<unsigned int>(m_rnRoot.children.size());
1085 }
1086
1087 /**
1088 * Returns the ID of a resource type which was specified through an index.
1089 * The valid range of the parameter uiIndex is 0...getNumberOfResourceTypes() - 1.
1090 * Leaving the invalid range leads to undefined behaviour.
1091 * @param uiIndex Index which identifies a resource type.
1092 * @return The ID of the specified resource type.
1093 **/
1094 dword ResourceDirectory::getResourceTypeIdByIndex(unsigned int uiIndex) const
1095 {
1096 return m_rnRoot.children[uiIndex].entry.irde.Name;
1097 }
1098
1099 /**
1100 * Returns the name of a resource type which was specified through an index.
1101 * The valid range of the parameter uiIndex is 0...getNumberOfResourceTypes() - 1.
1102 * Leaving the invalid range leads to undefined behaviour.
1103 * @param uiIndex Index which identifies a resource type.
1104 * @return The name of the specified resource type.
1105 **/
1106 std::string ResourceDirectory::getResourceTypeNameByIndex(unsigned int uiIndex) const
1107 {
1108 return m_rnRoot.children[uiIndex].entry.wstrName;
1109 }
1110
1111 /**
1112 * Converts the ID of a resource type to an index.
1113 * @param dwResTypeId ID of the resource type.
1114 * @return Index of that resource type.
1115 **/
1116 int ResourceDirectory::resourceTypeIdToIndex(dword dwResTypeId) const
1117 {
1118 std::vector<ResourceChild>::const_iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalId), dwResTypeId));
1119 if (Iter == m_rnRoot.children.end()) return -1;
1120 return static_cast<unsigned int>(std::distance(m_rnRoot.children.begin(), Iter));
1121 }
1122
1123 /**
1124 * Converts the name of a resource type to an index.
1125 * @param strResTypeName ID of the resource type.
1126 * @return Index of that resource type.
1127 **/
1128 int ResourceDirectory::resourceTypeNameToIndex(const std::string& strResTypeName) const
1129 {
1130 std::vector<ResourceChild>::const_iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalName), strResTypeName));
1131 if (Iter == m_rnRoot.children.end()) return -1;
1132 return static_cast<unsigned int>(std::distance(m_rnRoot.children.begin(), Iter));
1133 }
1134
1135 /**
1136 * Returns the number of resources of a specific resource type.
1137 * @param dwId ID of the resource type.
1138 * @return Number of resources of resource type dwId.
1139 **/
1140 unsigned int ResourceDirectory::getNumberOfResources(dword dwId) const
1141 {
1142// std::vector<ResourceChild>::const_iterator IterD = m_rnRoot.children.begin();
1143// std::cout << dwId << std::endl;
1144// while (IterD != m_rnRoot.children.end())
1145// {
1146// std::cout << IterD->entry.irde.Name << std::endl;
1147// ++IterD;
1148// }
1149
1150 std::vector<ResourceChild>::const_iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalId), dwId));
1151 if (Iter == m_rnRoot.children.end())
1152 {
1153 return 0xFFFFFFFF;
1154 }
1155 else
1156 {
1157 ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child);
1158 return static_cast<unsigned int>(currNode->children.size());
1159 }
1160 }
1161
1162 /**
1163 * Returns the number of resources of a specific resource type.
1164 * @param strResTypeName Name of the resource type.
1165 * @return Number of resources of resource type strResTypeName.
1166 **/
1167 unsigned int ResourceDirectory::getNumberOfResources(const std::string& strResTypeName) const
1168 {
1169 std::vector<ResourceChild>::const_iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(&ResourceChild::equalName), strResTypeName));
1170 if (Iter == m_rnRoot.children.end())
1171 {
1172 return 0xFFFFFFFF;
1173 }
1174 else
1175 {
1176 ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child);
1177 return static_cast<unsigned int>(currNode->children.size());
1178 }
1179 }
1180
1181 /**
1182 * Returns the number of resources of a resource type which was specified through an index.
1183 * The valid range of the parameter uiIndex is 0...getNumberOfResourceTypes() - 1.
1184 * Leaving the invalid range leads to undefined behaviour.
1185 * @param uiIndex Index which identifies a resource type.
1186 * @return The number of resources of the specified resource type.
1187 **/
1188 unsigned int ResourceDirectory::getNumberOfResourcesByIndex(unsigned int uiIndex) const
1189 {
1190 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiIndex].child);
1191 return static_cast<unsigned int>(currNode->children.size());
1192 }
1193
1194 /**
1195 * Gets the resource data of a specific resource.
1196 * @param dwResTypeId Identifies the resource type of the resource.
1197 * @param dwResId Identifies the resource.
1198 * @param data Vector where the data is stored.
1199 **/
1200 void ResourceDirectory::getResourceData(dword dwResTypeId, dword dwResId, std::vector<byte>& data) const
1201 {
1202 getResourceDataT(dwResTypeId, dwResId, data);
1203 }
1204
1205 /**
1206 * Gets the resource data of a specific resource.
1207 * @param dwResTypeId Identifies the resource type of the resource.
1208 * @param strResName Identifies the resource.
1209 * @param data Vector where the data is stored.
1210 **/
1211 void ResourceDirectory::getResourceData(dword dwResTypeId, const std::string& strResName, std::vector<byte>& data) const
1212 {
1213 getResourceDataT(dwResTypeId, strResName, data);
1214 }
1215
1216 /**
1217 * Gets the resource data of a specific resource.
1218 * @param strResTypeName Identifies the resource type of the resource.
1219 * @param dwResId Identifies the resource.
1220 * @param data Vector where the data is stored.
1221 **/
1222 void ResourceDirectory::getResourceData(const std::string& strResTypeName, dword dwResId, std::vector<byte>& data) const
1223 {
1224 getResourceDataT(strResTypeName, dwResId, data);
1225 }
1226
1227 /**
1228 * Gets the resource data of a specific resource.
1229 * @param strResTypeName Identifies the resource type of the resource.
1230 * @param strResName Identifies the resource.
1231 * @param data Vector where the data is stored.
1232 **/
1233 void ResourceDirectory::getResourceData(const std::string& strResTypeName, const std::string& strResName, std::vector<byte>& data) const
1234 {
1235 getResourceDataT(strResTypeName, strResName, data);
1236 }
1237
1238 /**
1239 * Gets the resource data of a specific resource by index.
1240 * The valid range of the parameter uiResTypeIndex is 0...getNumberOfResourceTypes() - 1.
1241 * The valid range of the parameter uiResIndex is 0...getNumberOfResources() - 1.
1242 * Leaving the invalid range leads to undefined behaviour.
1243 * @param uiResTypeIndex Identifies the resource type of the resource.
1244 * @param uiResIndex Identifies the resource.
1245 * @param data Vector where the data is stored.
1246 **/
1247 void ResourceDirectory::getResourceDataByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, std::vector<byte>& data) const
1248 {
1249 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiResTypeIndex].child);
1250 currNode = static_cast<ResourceNode*>(currNode->children[uiResIndex].child);
1251 ResourceLeaf* currLeaf = static_cast<ResourceLeaf*>(currNode->children[0].child);
1252
1253 data.assign(currLeaf->m_data.begin(), currLeaf->m_data.end());
1254 }
1255
1256 /**
1257 * Sets the resource data of a specific resource.
1258 * @param dwResTypeId Identifies the resource type of the resource.
1259 * @param dwResId Identifies the resource.
1260 * @param data The new resource data.
1261 **/
1262 void ResourceDirectory::setResourceData(dword dwResTypeId, dword dwResId, std::vector<byte>& data)
1263 {
1264 setResourceDataT(dwResTypeId, dwResId, data);
1265 }
1266
1267 /**
1268 * Sets the resource data of a specific resource.
1269 * @param dwResTypeId Identifies the resource type of the resource.
1270 * @param strResName Identifies the resource.
1271 * @param data The new resource data.
1272 **/
1273 void ResourceDirectory::setResourceData(dword dwResTypeId, const std::string& strResName, std::vector<byte>& data)
1274 {
1275 setResourceDataT(dwResTypeId, strResName, data);
1276 }
1277
1278 /**
1279 * Sets the resource data of a specific resource.
1280 * @param strResTypeName Identifies the resource type of the resource.
1281 * @param dwResId Identifies the resource.
1282 * @param data The new resource data.
1283 **/
1284 void ResourceDirectory::setResourceData(const std::string& strResTypeName, dword dwResId, std::vector<byte>& data)
1285 {
1286 setResourceDataT(strResTypeName, dwResId, data);
1287 }
1288
1289 /**
1290 * Sets the resource data of a specific resource.
1291 * @param strResTypeName Identifies the resource type of the resource.
1292 * @param strResName Identifies the resource.
1293 * @param data The new resource data.
1294 **/
1295 void ResourceDirectory::setResourceData(const std::string& strResTypeName, const std::string& strResName, std::vector<byte>& data)
1296 {
1297 setResourceDataT(strResTypeName, strResName, data);
1298 }
1299
1300 /**
1301 * Sets the resource data of a specific resource by index.
1302 * The valid range of the parameter uiResTypeIndex is 0...getNumberOfResourceTypes() - 1.
1303 * The valid range of the parameter uiResIndex is 0...getNumberOfResources() - 1.
1304 * Leaving the invalid range leads to undefined behaviour.
1305 * @param uiResTypeIndex Identifies the resource type of the resource.
1306 * @param uiResIndex Identifies the resource.
1307 * @param data The new resource data.
1308 **/
1309 void ResourceDirectory::setResourceDataByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, std::vector<byte>& data)
1310 {
1311 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiResTypeIndex].child);
1312 currNode = static_cast<ResourceNode*>(currNode->children[uiResIndex].child);
1313 ResourceLeaf* currLeaf = static_cast<ResourceLeaf*>(currNode->children[0].child);
1314 currLeaf->m_data.assign(data.begin(), data.end());
1315 }
1316
1317 /**
1318 * Gets the ID of a specific resource.
1319 * @param dwResTypeId Identifies the resource type of the resource.
1320 * @param strResName Identifies the resource.
1321 * @return ID of the specified resource.
1322 **/
1323 dword ResourceDirectory::getResourceId(dword dwResTypeId, const std::string& strResName) const
1324 {
1325 return getResourceIdT(dwResTypeId, strResName);
1326 }
1327
1328 /**
1329 * Gets the ID of a specific resource.
1330 * @param strResTypeName Identifies the resource type of the resource.
1331 * @param strResName Identifies the resource.
1332 * @return ID of the specified resource.
1333 **/
1334 dword ResourceDirectory::getResourceId(const std::string& strResTypeName, const std::string& strResName) const
1335 {
1336 return getResourceIdT(strResTypeName, strResName);
1337 }
1338
1339 /**
1340 * Gets the ID of a specific resource by index.
1341 * @param uiResTypeIndex Identifies the resource type of the resource.
1342 * @param uiResIndex Identifies the resource.
1343 * @return ID of the specified resource.
1344 **/
1345 dword ResourceDirectory::getResourceIdByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex) const
1346 {
1347 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiResTypeIndex].child);
1348 return currNode->children[uiResIndex].entry.irde.Name;
1349 }
1350
1351 /**
1352 * Sets the ID of a specific resource.
1353 * @param dwResTypeId Identifies the resource type of the resource.
1354 * @param dwResId Identifies the resource.
1355 * @param dwNewResId New ID of the resource.
1356 **/
1357 void ResourceDirectory::setResourceId(dword dwResTypeId, dword dwResId, dword dwNewResId)
1358 {
1359 setResourceIdT(dwResTypeId, dwResId, dwNewResId);
1360 }
1361
1362 /**
1363 * Sets the ID of a specific resource.
1364 * @param dwResTypeId Identifies the resource type of the resource.
1365 * @param strResName Identifies the resource.
1366 * @param dwNewResId New ID of the resource.
1367 **/
1368 void ResourceDirectory::setResourceId(dword dwResTypeId, const std::string& strResName, dword dwNewResId)
1369 {
1370 setResourceIdT(dwResTypeId, strResName, dwNewResId);
1371 }
1372
1373 /**
1374 * Sets the ID of a specific resource.
1375 * @param strResTypeName Identifies the resource type of the resource.
1376 * @param dwResId Identifies the resource.
1377 * @param dwNewResId New ID of the resource.
1378 **/
1379 void ResourceDirectory::setResourceId(const std::string& strResTypeName, dword dwResId, dword dwNewResId)
1380 {
1381 setResourceIdT(strResTypeName, dwResId, dwNewResId);
1382 }
1383
1384 /**
1385 * Sets the ID of a specific resource.
1386 * @param strResTypeName Identifies the resource type of the resource.
1387 * @param strResName Identifies the resource.
1388 * @param dwNewResId New ID of the resource.
1389 **/
1390 void ResourceDirectory::setResourceId(const std::string& strResTypeName, const std::string& strResName, dword dwNewResId)
1391 {
1392 setResourceIdT(strResTypeName, strResName, dwNewResId);
1393 }
1394
1395 /**
1396 * Sets the ID of a specific resource by index.
1397 * @param uiResTypeIndex Identifies the resource type of the resource.
1398 * @param uiResIndex Identifies the resource.
1399 * @param dwNewResId New ID of the specified resource.
1400 **/
1401 void ResourceDirectory::setResourceIdByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, dword dwNewResId)
1402 {
1403 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiResTypeIndex].child);
1404 currNode->children[uiResIndex].entry.irde.Name = dwNewResId;
1405 }
1406
1407 /**
1408 * Gets the Name of a specific resource.
1409 * @param dwResTypeId Identifies the resource type of the resource.
1410 * @param dwResId Identifies the resource.
1411 * @return Name of the specified resource.
1412 **/
1413 std::string ResourceDirectory::getResourceName(dword dwResTypeId, dword dwResId) const
1414 {
1415 return getResourceNameT(dwResTypeId, dwResId);
1416 }
1417
1418 /**
1419 * Gets the Name of a specific resource.
1420 * @param strResTypeName Identifies the resource type of the resource.
1421 * @param dwResId Identifies the resource.
1422 * @return Name of the specified resource.
1423 **/
1424 std::string ResourceDirectory::getResourceName(const std::string& strResTypeName, dword dwResId) const
1425 {
1426 return getResourceNameT(strResTypeName, dwResId);
1427 }
1428
1429 /**
1430 * Gets the name of a specific resource by index.
1431 * @param uiResTypeIndex Identifies the resource type of the resource.
1432 * @param uiResIndex Identifies the resource.
1433 * @return Name of the specified resource.
1434 **/
1435 std::string ResourceDirectory::getResourceNameByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex) const
1436 {
1437 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiResTypeIndex].child);
1438 return currNode->children[uiResIndex].entry.wstrName;
1439 }
1440
1441 /**
1442 * Sets the name of a specific resource.
1443 * @param dwResTypeId Identifies the resource type of the resource.
1444 * @param dwResId Identifies the resource.
1445 * @param strNewResName New name of the specified resource.
1446 **/
1447 void ResourceDirectory::setResourceName(dword dwResTypeId, dword dwResId, const std::string& strNewResName)
1448 {
1449 setResourceNameT(dwResTypeId, dwResId, strNewResName);
1450 }
1451
1452 /**
1453 * Sets the name of a specific resource.
1454 * @param dwResTypeId Identifies the resource type of the resource.
1455 * @param strResName Identifies the resource.
1456 * @param strNewResName New name of the specified resource.
1457 **/
1458 void ResourceDirectory::setResourceName(dword dwResTypeId, const std::string& strResName, const std::string& strNewResName)
1459 {
1460 setResourceNameT(dwResTypeId, strResName, strNewResName);
1461 }
1462
1463 /**
1464 * Sets the name of a specific resource.
1465 * @param strResTypeName Identifies the resource type of the resource.
1466 * @param dwResId Identifies the resource.
1467 * @param strNewResName New name of the specified resource.
1468 **/
1469 void ResourceDirectory::setResourceName(const std::string& strResTypeName, dword dwResId, const std::string& strNewResName)
1470 {
1471 setResourceNameT(strResTypeName, dwResId, strNewResName);
1472 }
1473
1474 /**
1475 * Sets the name of a specific resource.
1476 * @param strResTypeName Identifies the resource type of the resource.
1477 * @param strResName Identifies the resource.
1478 * @param strNewResName New name of the specified resource.
1479 **/
1480 void ResourceDirectory::setResourceName(const std::string& strResTypeName, const std::string& strResName, const std::string& strNewResName)
1481 {
1482 setResourceNameT(strResTypeName, strResName, strNewResName);
1483 }
1484
1485 /**
1486 * Sets the name of a specific resource by index.
1487 * @param uiResTypeIndex Identifies the resource type of the resource.
1488 * @param uiResIndex Identifies the resource.
1489 * @param strNewResName New name of the specified resource.
1490 **/
1491 void ResourceDirectory::setResourceNameByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, const std::string& strNewResName)
1492 {
1493 ResourceNode* currNode = static_cast<ResourceNode*>(m_rnRoot.children[uiResTypeIndex].child);
1494 currNode->children[uiResIndex].entry.wstrName = strNewResName;
1495 }
1496
1497}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/ResourceDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/ResourceDirectory.h
new file mode 100755
index 0000000000..a0bba4c9b3
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/ResourceDirectory.h
@@ -0,0 +1,735 @@
1/*
2* ResourceDirectory.cpp - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#ifndef RESOURCEDIRECTORY_H
14#define RESOURCEDIRECTORY_H
15
16#include "PeLibInc.h"
17
18namespace PeLib
19{
20 class ResourceElement;
21
22 /// The class ResourceChild is used to store information about a resource node.
23 class ResourceChild
24 {
25 friend class ResourceElement;
26 friend class ResourceDirectory;
27 friend class ResourceNode;
28 friend class ResourceLeaf;
29
30 /// Stores name and offset of a resource node.
31 PELIB_IMG_RES_DIR_ENTRY entry;
32 /// A pointer to one of the node's child nodes.
33 ResourceElement* child;
34
35 public:
36 /// Function which compares a resource ID to the node's resource ID.
37 bool equalId(dword wId) const; // EXPORT
38 /// Function which compares a string to the node's resource name.
39 bool equalName(std::string strName) const; // EXPORT
40 /// Predicate that determines if a child is identified by name or by ID.
41 bool isNamedResource() const; // EXPORT
42 /// Used for sorting a node's children.
43 bool operator<(const ResourceChild& rc) const; // EXPORT
44 /// Returns the size of a resource child.
45// unsigned int size() const;
46
47 /// Standard constructor. Does absolutely nothing.
48 ResourceChild();
49 /// Makes a deep copy of a ResourceChild object.
50 ResourceChild(const ResourceChild& rhs);
51 /// Makes a deep copy of a ResourceChild object.
52 ResourceChild& operator=(const ResourceChild& rhs);
53 /// Deletes a ResourceChild object.
54 ~ResourceChild();
55 };
56
57 /// Base class for ResourceNode and ResourceLeaf, the elements of the resource tree.
58 /// \todo write
59 class ResourceElement
60 {
61 friend class ResourceChild;
62 friend class ResourceNode;
63 friend class ResourceLeaf;
64
65 protected:
66 /// Stores RVA of the resource element in the file.
67 unsigned int uiElementRva;
68
69 /// Reads the next resource element from the InputBuffer.
70 virtual int read(InputBuffer&, unsigned int, unsigned int/*, const std::string&*/) = 0;
71 /// Writes the next resource element into the OutputBuffer.
72 virtual void rebuild(OutputBuffer&, unsigned int&, unsigned int, const std::string&) const = 0;
73
74 public:
75 /// Returns the RVA of the element in the file.
76 unsigned int getElementRva() const; // EXPORT
77 /// Indicates if the resource element is a leaf or a node.
78 virtual bool isLeaf() const = 0; // EXPORT
79 /// Corrects erroneous valeus in the ResourceElement.
80 virtual void makeValid() = 0; // EXPORT
81 /// Returns the size of a resource element.
82// virtual unsigned int size() const = 0;
83 /// Necessary virtual destructor.
84 virtual ~ResourceElement() {}
85 };
86
87 /// ResourceLeafs represent the leafs of the resource tree: The actual resources.
88 class ResourceLeaf : public ResourceElement
89 {
90 friend class ResourceChild;
91 friend class ResourceDirectory;
92 template<typename T> friend struct fixNumberOfEntries;
93
94 private:
95 /// The resource data.
96 std::vector<byte> m_data;
97 /// PeLib equivalent of the Win32 structure IMAGE_RESOURCE_DATA_ENTRY
98 PELIB_IMAGE_RESOURCE_DATA_ENTRY entry;
99
100 protected:
101 int read(InputBuffer& inpBuffer, unsigned int uiOffset, unsigned int rva/*, const std::string&*/);
102 /// Writes the next resource leaf into the OutputBuffer.
103 void rebuild(OutputBuffer&, unsigned int& uiOffset, unsigned int uiRva, const std::string&) const;
104
105 public:
106 /// Indicates if the resource element is a leaf or a node.
107 bool isLeaf() const; // EXPORT
108 /// Corrects erroneous valeus in the ResourceLeaf.
109 void makeValid(); // EXPORT
110 /// Reads the next resource leaf from the InputBuffer.
111 /// Returns the size of a resource lead.
112// unsigned int size() const;
113
114 /// Returns the resource data of this resource leaf.
115 std::vector<byte> getData() const; // EXPORT
116 /// Sets the resource data of this resource leaf.
117 void setData(const std::vector<byte>& vData); // EXPORT
118
119 /// Returns the OffsetToData value of this resource leaf.
120 dword getOffsetToData() const; // EXPORT
121 /// Returns the Size value of this resource leaf.
122 dword getSize() const; // EXPORT
123 /// Returns the CodePage value of this resource leaf.
124 dword getCodePage() const; // EXPORT
125 /// Returns the Reserved value of this resource leaf.
126 dword getReserved() const; // EXPORT
127
128 /// Sets the OffsetToData value of this resource leaf.
129 void setOffsetToData(dword dwValue); // EXPORT
130 /// Sets the Size value of this resource leaf.
131 void setSize(dword dwValue); // EXPORT
132 /// Sets the CodePage value of this resource leaf.
133 void setCodePage(dword dwValue); // EXPORT
134 /// Sets the Reserved value of this resource leaf.
135 void setReserved(dword dwValue); // EXPORT
136 };
137
138 /// ResourceNodes represent the nodes in the resource tree.
139 class ResourceNode : public ResourceElement
140 {
141 friend class ResourceChild;
142 friend class ResourceDirectory;
143 template<typename T> friend struct fixNumberOfEntries;
144
145 /// The node's children.
146 std::vector<ResourceChild> children;
147 /// The node's header. Equivalent to IMAGE_RESOURCE_DIRECTORY from the Win32 API.
148 PELIB_IMAGE_RESOURCE_DIRECTORY header;
149
150 protected:
151 /// Reads the next resource node.
152 int read(InputBuffer& inpBuffer, unsigned int uiOffset, unsigned int rva/*, const std::string&*/);
153 /// Writes the next resource node into the OutputBuffer.
154 void rebuild(OutputBuffer&, unsigned int& uiOffset, unsigned int uiRva, const std::string&) const;
155
156 public:
157 /// Indicates if the resource element is a leaf or a node.
158 bool isLeaf() const; // EXPORT
159 /// Corrects erroneous valeus in the ResourceNode.
160 void makeValid(); // EXPORT
161
162 /// Returns the node's number of children.
163 unsigned int getNumberOfChildren() const; // EXPORT
164 /// Adds another child to node.
165 void addChild(); // EXPORT
166 /// Returns a node's child.
167 ResourceElement* getChild(unsigned int uiIndex); // EXPORT
168 /// Removes a node's child.
169 void removeChild(unsigned int uiIndex); // EXPORT
170
171 /// Returns the name of one of the node's children.
172 std::string getChildName(unsigned int uiIndex) const; // EXPORT
173 /// Returns the Name value of one of the node's children.
174 dword getOffsetToChildName(unsigned int uiIndex) const; // EXPORT
175 /// Returns the OffsetToData value of one of the node's children.
176 dword getOffsetToChildData(unsigned int uiIndex) const; // EXPORT
177
178 /// Sets the name of one of the node's children.
179 void setChildName(unsigned int uiIndex, const std::string& strNewName); // EXPORT
180 /// Sets the Name value of one of the node's children.
181 void setOffsetToChildName(unsigned int uiIndex, dword dwNewOffset); // EXPORT
182 /// Sets the OffsetToData value of one of the node's children.
183 void setOffsetToChildData(unsigned int uiIndex, dword dwNewOffset); // EXPORT
184
185 /// Returns the node's Characteristics value.
186 dword getCharacteristics() const; // EXPORT
187 /// Returns the node's TimeDateStamp value.
188 dword getTimeDateStamp() const; // EXPORT
189 /// Returns the node's MajorVersion value.
190 word getMajorVersion() const; // EXPORT
191 /// Returns the node's MinorVersion value.
192 word getMinorVersion() const; // EXPORT
193 /// Returns the node's NumberOfNamedEntries value.
194 word getNumberOfNamedEntries() const; // EXPORT
195 /// Returns the node's NumberOfIdEntries value.
196 word getNumberOfIdEntries() const; // EXPORT
197
198 /// Sets the node's Characteristics value.
199 void setCharacteristics(dword value); // EXPORT
200 /// Sets the node's TimeDateStamp value.
201 void setTimeDateStamp(dword value); // EXPORT
202 /// Sets the node's MajorVersion value.
203 void setMajorVersion(word value); // EXPORT
204 /// Sets the node's MinorVersion value.
205 void setMinorVersion(word value); // EXPORT
206 /// Sets the node's NumberOfNamedEntries value.
207 void setNumberOfNamedEntries(word value); // EXPORT
208 /// Sets the node's NumberOfIdEntries value.
209 void setNumberOfIdEntries(word value); // EXPORT
210
211 /// Returns the size of a resource node.
212// unsigned int size() const;
213 };
214
215 /// Auxiliary functor which is used to search through the resource tree.
216 /**
217 * Traits class for the template functions of ResourceDirectory.
218 * It's used to find out which function to use when searching for resource nodes or resource leafs
219 * in a node's children vector.
220 **/
221 template<typename T>
222 struct ResComparer
223 {
224 /// Pointer to a member function of ResourceChild
225 typedef bool(ResourceChild::*CompFunc)(T) const;
226
227 /// Return 0 for all unspecialized versions of ResComparer.
228 static CompFunc comp();
229 };
230
231 /// Auxiliary functor which is used to search through the resource tree.
232 /**
233 * ResComparer<dword> is used when a resource element is searched for by ID.
234 **/
235 template<>
236 struct ResComparer<dword>
237 {
238 /// Pointer to a member function of ResourceChild
239 typedef bool(ResourceChild::*CompFunc)(dword) const;
240
241 /// Return the address of the ResourceChild member function that compares the ids of resource elements.
242 static CompFunc comp()
243 {
244 return &ResourceChild::equalId;
245 }
246 };
247
248 /// Auxiliary functor which is used to search through the resource tree.
249 /**
250 * This specializd version of ResComparer is used when a resource element is searched for by name.
251 **/
252 template<>
253 struct ResComparer<std::string>
254 {
255 /// Pointer to a member function of ResourceChild
256 typedef bool(ResourceChild::*CompFunc)(std::string) const;
257
258 /// Return the address of the ResourceChild member function that compares the names of resource elements.
259 static CompFunc comp()
260 {
261 return &ResourceChild::equalName;
262 }
263 };
264
265 /// Unspecialized function that's used as base template for the specialized versions below.
266 template<typename T>
267 struct fixNumberOfEntries
268 {
269 /// Fixes a resource node's header.
270 static void fix(ResourceNode*);
271 };
272
273 /// Fixes NumberOfIdEntries value of a node.
274 template<>
275 struct fixNumberOfEntries<dword>
276 {
277 /// Fixes a resource node's NumberOfIdEntries value.
278 static void fix(ResourceNode* node)
279 {
280 node->header.NumberOfIdEntries = (unsigned int)node->children.size() - std::count_if(node->children.begin(), node->children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource));
281 }
282 };
283
284 /// Fixes NumberOfNamedEntries value of a node.
285 template<>
286 struct fixNumberOfEntries<std::string>
287 {
288 /// Fixes a resource node's NumberOfNamedEntries value.
289 static void fix(ResourceNode* node)
290 {
291 node->header.NumberOfNamedEntries = static_cast<PeLib::word>(std::count_if(node->children.begin(), node->children.end(), std::mem_fun_ref(&ResourceChild::isNamedResource)));
292 }
293 };
294
295 /// Class that represents the resource directory of a PE file.
296 /**
297 * The class ResourceDirectory represents the resource directory of a PE file. This class is fundamentally
298 * different from the other classes of the PeLib library due to the structure of the ResourceDirectory.
299 * For once, it's possible to manipulate the ResourceDirectory through a set of "high level" functions and
300 * and through a set of "low level" functions. The "high level" functions are the functions inside the
301 * ResourceDirectory class with the exception of getRoot.<br><br>
302 * getRoot on the other hand is the first "low level" function. Use it to retrieve the root node of the
303 * resource tree. Then you can traverse through the tree and manipulate individual nodes and leafs
304 * directly using the functions provided by the classes ResourceNode and ResourceLeaf.<br><br>
305 * There's another difference between the ResourceDirectory class and the other PeLib classes, which is
306 * once again caused by the special structure of the PE resource directory. The nodes of the resource
307 * tree must be in a certain order. Manipulating the resource tree does not directly sort the nodes
308 * correctly as this would cause more trouble than it fixes. That means it's your responsibility to
309 * fix the resource tree after manipulating it. PeLib makes the job easy for you, just call the
310 * ResourceDirectory::makeValid function.<br><br>
311 * You might also wonder why there's no size() function in this class. I did not forget it. It's just
312 * that it's impossible to calculate the size of the resource directory without rebuilding it. So why
313 * should PeLib do this if you can do it just as easily by calling rebuild() and then checking the length
314 * of the returned vector.<br><br>
315 * There are also different ways to serialize (rebuild) the resource tree as it's not a fixed structure
316 * that can easily be minimized like most other PE directories.<br><br>
317 * This means it's entirely possible that the resource tree you read from a file differs from the one
318 * PeLib creates. This might cause a minor issue. The original resource tree might be smaller (due to
319 * different padding) so it's crucial that you check if there's enough space in the original resource
320 * directory before you write the rebuilt resource directory back to the file.
321 **/
322 class ResourceDirectory
323 {
324 private:
325 /// The root node of the resource directory.
326 ResourceNode m_rnRoot;
327
328 // Prepare for some crazy syntax below to make Digital Mars happy.
329
330 /// Retrieves an iterator to a specified resource child.
331 template<typename S, typename T>
332 std::vector<ResourceChild>::const_iterator locateResourceT(S restypeid, T resid) const;
333
334 /// Retrieves an iterator to a specified resource child.
335 template<typename S, typename T>
336 std::vector<ResourceChild>::iterator locateResourceT(S restypeid, T resid);
337
338 /// Adds a new resource.
339 template<typename S, typename T>
340 int addResourceT(S restypeid, T resid, ResourceChild& rc);
341
342 /// Removes new resource.
343 template<typename S, typename T>
344 int removeResourceT(S restypeid, T resid);
345
346 /// Returns the data of a resource.
347 template<typename S, typename T>
348 int getResourceDataT(S restypeid, T resid, std::vector<byte>& data) const;
349
350 /// Sets the data of a resource.
351 template<typename S, typename T>
352 int setResourceDataT(S restypeid, T resid, std::vector<byte>& data);
353
354 /// Returns the ID of a resource.
355 template<typename S, typename T>
356 dword getResourceIdT(S restypeid, T resid) const;
357
358 /// Sets the ID of a resource.
359 template<typename S, typename T>
360 int setResourceIdT(S restypeid, T resid, dword dwNewResId);
361
362 /// Returns the name of a resource.
363 template<typename S, typename T>
364 std::string getResourceNameT(S restypeid, T resid) const;
365
366 /// Sets the name of a resource.
367 template<typename S, typename T>
368 int setResourceNameT(S restypeid, T resid, std::string strNewResName);
369
370 public:
371 ResourceNode* getRoot();
372 /// Corrects a erroneous resource directory.
373 void makeValid();
374 /// Reads the resource directory from a file.
375 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, unsigned int uiResDirRva);
376 /// Rebuilds the resource directory.
377 void rebuild(std::vector<byte>& vBuffer, unsigned int uiRva) const;
378 /// Returns the size of the rebuilt resource directory.
379// unsigned int size() const;
380 /// Writes the resource directory to a file.
381 int write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva) const;
382
383 /// Adds a new resource type.
384 int addResourceType(dword dwResTypeId);
385 /// Adds a new resource type.
386 int addResourceType(const std::string& strResTypeName);
387
388 /// Removes a resource type and all of it's resources.
389 int removeResourceType(dword dwResTypeId);
390 /// Removes a resource type and all of it's resources.
391 int removeResourceType(const std::string& strResTypeName);
392
393 /// Removes a resource type and all of it's resources.
394 int removeResourceTypeByIndex(unsigned int uiIndex);
395
396 /// Adds a new resource.
397 int addResource(dword dwResTypeId, dword dwResId);
398 /// Adds a new resource.
399 int addResource(dword dwResTypeId, const std::string& strResName);
400 /// Adds a new resource.
401 int addResource(const std::string& strResTypeName, dword dwResId);
402 /// Adds a new resource.
403 int addResource(const std::string& strResTypeName, const std::string& strResName);
404
405 /// Removes a resource.
406 int removeResource(dword dwResTypeId, dword dwResId);
407 /// Removes a resource.
408 int removeResource(dword dwResTypeId, const std::string& strResName);
409 /// Removes a resource.
410 int removeResource(const std::string& strResTypeName, dword dwResId);
411 /// Removes a resource.
412 int removeResource(const std::string& strResTypeName, const std::string& strResName);
413
414 /// Returns the number of resource types.
415 unsigned int getNumberOfResourceTypes() const;
416
417 /// Returns the ID of a resource type.
418 dword getResourceTypeIdByIndex(unsigned int uiIndex) const;
419 /// Returns the name of a resource type.
420 std::string getResourceTypeNameByIndex(unsigned int uiIndex) const;
421
422 /// Converts a resource type ID to an index.
423 int resourceTypeIdToIndex(dword dwResTypeId) const;
424 /// Converts a resource type name to an index.
425 int resourceTypeNameToIndex(const std::string& strResTypeName) const;
426
427 /// Returns the number of resources of a certain resource type.
428 unsigned int getNumberOfResources(dword dwId) const;
429 /// Returns the number of resources of a certain resource type.
430 unsigned int getNumberOfResources(const std::string& strResTypeName) const;
431
432 /// Returns the number of resources of a certain resource type.
433 unsigned int getNumberOfResourcesByIndex(unsigned int uiIndex) const;
434
435 /// Returns the data of a certain resource.
436 void getResourceData(dword dwResTypeId, dword dwResId, std::vector<byte>& data) const;
437 /// Returns the data of a certain resource.
438 void getResourceData(dword dwResTypeId, const std::string& strResName, std::vector<byte>& data) const;
439 /// Returns the data of a certain resource.
440 void getResourceData(const std::string& strResTypeName, dword dwResId, std::vector<byte>& data) const;
441 /// Returns the data of a certain resource.
442 void getResourceData(const std::string& strResTypeName, const std::string& strResName, std::vector<byte>& data) const;
443
444 /// Returns the data of a certain resource.
445 void getResourceDataByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, std::vector<byte>& data) const;
446
447 /// Sets the data of a certain resource.
448 void setResourceData(dword dwResTypeId, dword dwResId, std::vector<byte>& data);
449 /// Sets the data of a certain resource.
450 void setResourceData(dword dwResTypeId, const std::string& strResName, std::vector<byte>& data);
451 /// Sets the data of a certain resource.
452 void setResourceData(const std::string& strResTypeName, dword dwResId, std::vector<byte>& data);
453 /// Sets the data of a certain resource.
454 void setResourceData(const std::string& strResTypeName, const std::string& strResName, std::vector<byte>& data);
455
456 /// Sets the data of a certain resource.
457 void setResourceDataByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, std::vector<byte>& data);
458
459 /// Returns the ID of a certain resource.
460 dword getResourceId(dword dwResTypeId, const std::string& strResName) const;
461 /// Returns the ID of a certain resource.
462 dword getResourceId(const std::string& strResTypeName, const std::string& strResName) const;
463
464 /// Returns the ID of a certain resource.
465 dword getResourceIdByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex) const;
466
467 /// Sets the ID of a certain resource.
468 void setResourceId(dword dwResTypeId, dword dwResId, dword dwNewResId);
469 /// Sets the ID of a certain resource.
470 void setResourceId(dword dwResTypeId, const std::string& strResName, dword dwNewResId);
471 /// Sets the ID of a certain resource.
472 void setResourceId(const std::string& strResTypeName, dword dwResId, dword dwNewResId);
473 /// Sets the ID of a certain resource.
474 void setResourceId(const std::string& strResTypeName, const std::string& strResName, dword dwNewResId);
475
476 /// Sets the ID of a certain resource.
477 void setResourceIdByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, dword dwNewResId);
478
479 /// Returns the name of a certain resource.
480 std::string getResourceName(dword dwResTypeId, dword dwResId) const;
481 /// Returns the name of a certain resource.
482 std::string getResourceName(const std::string& strResTypeName, dword dwResId) const;
483
484 /// Returns the name of a certain resource.
485 std::string getResourceNameByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex) const;
486
487 /// Sets the name of a certain resource.
488 void setResourceName(dword dwResTypeId, dword dwResId, const std::string& strNewResName);
489 /// Sets the name of a certain resource.
490 void setResourceName(dword dwResTypeId, const std::string& strResName, const std::string& strNewResName);
491 /// Sets the name of a certain resource.
492 void setResourceName(const std::string& strResTypeName, dword dwResId, const std::string& strNewResName);
493 /// Sets the name of a certain resource.
494 void setResourceName(const std::string& strResTypeName, const std::string& strResName, const std::string& strNewResName);
495
496 /// Sets the name of a certain resource.
497 void setResourceNameByIndex(unsigned int uiResTypeIndex, unsigned int uiResIndex, const std::string& strNewResName);
498 };
499
500 /**
501 * Looks through the entire resource tree and returns a const_iterator to the resource specified
502 * by the parameters.
503 * @param restypeid Identifier of the resource type (either ID or name).
504 * @param resid Identifier of the resource (either ID or name).
505 * @return A const_iterator to the specified resource.
506 **/
507 template<typename S, typename T>
508 std::vector<ResourceChild>::const_iterator ResourceDirectory::locateResourceT(S restypeid, T resid) const
509 {
510 typedef bool(ResourceChild::*CompFunc1)(S) const;
511 typedef bool(ResourceChild::*CompFunc2)(T) const;
512
513 CompFunc1 comp1 = ResComparer<S>::comp();
514 CompFunc2 comp2 = ResComparer<T>::comp();
515
516 std::vector<ResourceChild>::const_iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(comp1), restypeid));
517 if (Iter == m_rnRoot.children.end())
518 {
519 return Iter;
520 }
521
522 ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child);
523 std::vector<ResourceChild>::const_iterator ResIter = std::find_if(currNode->children.begin(), currNode->children.end(), std::bind2nd(std::mem_fun_ref(comp2), resid));
524 if (ResIter == currNode->children.end())
525 {
526 return ResIter;
527 }
528
529 return ResIter;
530 }
531
532 /**
533 * Looks through the entire resource tree and returns an iterator to the resource specified
534 * by the parameters.
535 * @param restypeid Identifier of the resource type (either ID or name).
536 * @param resid Identifier of the resource (either ID or name).
537 * @return An iterator to the specified resource.
538 **/
539 template<typename S, typename T>
540 std::vector<ResourceChild>::iterator ResourceDirectory::locateResourceT(S restypeid, T resid)
541 {
542 typedef bool(ResourceChild::*CompFunc1)(S) const;
543 typedef bool(ResourceChild::*CompFunc2)(T) const;
544
545 CompFunc1 comp1 = ResComparer<S>::comp();
546 CompFunc2 comp2 = ResComparer<T>::comp();
547
548 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(comp1), restypeid));
549 if (Iter == m_rnRoot.children.end())
550 {
551 return Iter;
552 }
553
554 ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child);
555 std::vector<ResourceChild>::iterator ResIter = std::find_if(currNode->children.begin(), currNode->children.end(), std::bind2nd(std::mem_fun_ref(comp2), resid));
556 if (ResIter == currNode->children.end())
557 {
558 return ResIter;
559 }
560
561 return ResIter;
562 }
563
564 /**
565 * Adds a new resource, resource type and ID are specified by the parameters.
566 * @param restypeid Identifier of the resource type (either ID or name).
567 * @param resid Identifier of the resource (either ID or name).
568 * @param rc ResourceChild that will be added.
569 **/
570 template<typename S, typename T>
571 int ResourceDirectory::addResourceT(S restypeid, T resid, ResourceChild& rc)
572 {
573 typedef bool(ResourceChild::*CompFunc1)(S) const;
574 typedef bool(ResourceChild::*CompFunc2)(T) const;
575
576 CompFunc1 comp1 = ResComparer<S>::comp();
577 CompFunc2 comp2 = ResComparer<T>::comp();
578
579 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(comp1), restypeid));
580 if (Iter == m_rnRoot.children.end())
581 {
582 return 1;
583 // throw Exceptions::ResourceTypeDoesNotExist(ResourceDirectoryId, __LINE__);
584 }
585
586 ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child);
587 std::vector<ResourceChild>::iterator ResIter = std::find_if(currNode->children.begin(), currNode->children.end(), std::bind2nd(std::mem_fun_ref(comp2), resid));
588 if (ResIter != currNode->children.end())
589 {
590 return 1;
591// throw Exceptions::EntryAlreadyExists(ResourceDirectoryId, __LINE__);
592 }
593
594 rc.child = new ResourceNode;
595 ResourceChild rlnew;
596 rlnew.child = new ResourceLeaf;
597 ResourceNode* currNode2 = static_cast<ResourceNode*>(rc.child);
598 currNode2->children.push_back(rlnew);
599 currNode->children.push_back(rc);
600
601 fixNumberOfEntries<T>::fix(currNode);
602 fixNumberOfEntries<T>::fix(currNode2);
603
604 return 0;
605 }
606
607 /**
608 * Removes a resource, resource type and ID are specified by the parameters.
609 * @param restypeid Identifier of the resource type (either ID or name).
610 * @param resid Identifier of the resource (either ID or name).
611 **/
612 template<typename S, typename T>
613 int ResourceDirectory::removeResourceT(S restypeid, T resid)
614 {
615 typedef bool(ResourceChild::*CompFunc1)(S) const;
616 typedef bool(ResourceChild::*CompFunc2)(T) const;
617
618 CompFunc1 comp1 = ResComparer<S>::comp();
619 CompFunc2 comp2 = ResComparer<T>::comp();
620
621 std::vector<ResourceChild>::iterator Iter = std::find_if(m_rnRoot.children.begin(), m_rnRoot.children.end(), std::bind2nd(std::mem_fun_ref(comp1), restypeid));
622 if (Iter == m_rnRoot.children.end())
623 {
624 return 1;
625 //throw Exceptions::ResourceTypeDoesNotExist(ResourceDirectoryId, __LINE__);
626 }
627
628 ResourceNode* currNode = static_cast<ResourceNode*>(Iter->child);
629 std::vector<ResourceChild>::iterator ResIter = std::find_if(currNode->children.begin(), currNode->children.end(), std::bind2nd(std::mem_fun_ref(comp2), resid));
630 if (ResIter == currNode->children.end())
631 {
632 return 1;
633 // throw Exceptions::InvalidName(ResourceDirectoryId, __LINE__);
634 }
635
636 currNode->children.erase(ResIter);
637
638 fixNumberOfEntries<T>::fix(currNode);
639
640 return 0;
641 }
642
643 /**
644 * Returns the data of a resource, resource type and ID are specified by the parameters.
645 * @param restypeid Identifier of the resource type (either ID or name).
646 * @param resid Identifier of the resource (either ID or name).
647 * @param data The data of the resource will be written into this vector.
648 **/
649 template<typename S, typename T>
650 int ResourceDirectory::getResourceDataT(S restypeid, T resid, std::vector<byte>& data) const
651 {
652 std::vector<ResourceChild>::const_iterator ResIter = locateResourceT(restypeid, resid);
653 ResourceNode* currNode = static_cast<ResourceNode*>(ResIter->child);
654 ResourceLeaf* currLeaf = static_cast<ResourceLeaf*>(currNode->children[0].child);
655 data.assign(currLeaf->m_data.begin(), currLeaf->m_data.end());
656
657 return 0;
658 }
659
660 /**
661 * Sets the data of a resource, resource type and ID are specified by the parameters.
662 * @param restypeid Identifier of the resource type (either ID or name).
663 * @param resid Identifier of the resource (either ID or name).
664 * @param data The new data of the resource is taken from this vector.
665 **/
666 template<typename S, typename T>
667 int ResourceDirectory::setResourceDataT(S restypeid, T resid, std::vector<byte>& data)
668 {
669 std::vector<ResourceChild>::iterator ResIter = locateResourceT(restypeid, resid);
670 ResourceNode* currNode = static_cast<ResourceNode*>(ResIter->child);
671 ResourceLeaf* currLeaf = static_cast<ResourceLeaf*>(currNode->children[0].child);
672 currLeaf->m_data.assign(data.begin(), data.end());
673
674 return 0;
675 }
676
677 /**
678 * Returns the id of a resource, resource type and ID are specified by the parameters.
679 * Note: Calling this function with resid == the ID of the resource makes no sense at all.
680 * @param restypeid Identifier of the resource type (either ID or name).
681 * @param resid Identifier of the resource (either ID or name).
682 * @return The ID of the specified resource.
683 **/
684 template<typename S, typename T>
685 dword ResourceDirectory::getResourceIdT(S restypeid, T resid) const
686 {
687 std::vector<ResourceChild>::const_iterator ResIter = locateResourceT(restypeid, resid);
688 return ResIter->entry.irde.Name;
689 }
690
691 /**
692 * Sets the id of a resource, resource type and ID are specified by the parameters.
693 * @param restypeid Identifier of the resource type (either ID or name).
694 * @param resid Identifier of the resource (either ID or name).
695 * @param dwNewResId New ID of the resource.
696 **/
697 template<typename S, typename T>
698 int ResourceDirectory::setResourceIdT(S restypeid, T resid, dword dwNewResId)
699 {
700 std::vector<ResourceChild>::iterator ResIter = locateResourceT(restypeid, resid);
701 ResIter->entry.irde.Name = dwNewResId;
702 return 0;
703 }
704
705 /**
706 * Returns the name of a resource, resource type and ID are specified by the parameters.
707 * Note: Calling this function with resid == the name of the resource makes no sense at all.
708 * @param restypeid Identifier of the resource type (either ID or name).
709 * @param resid Identifier of the resource (either ID or name).
710 * @return The name of the specified resource.
711 **/
712 template<typename S, typename T>
713 std::string ResourceDirectory::getResourceNameT(S restypeid, T resid) const
714 {
715 std::vector<ResourceChild>::const_iterator ResIter = locateResourceT(restypeid, resid);
716 return ResIter->entry.wstrName;
717 }
718
719 /**
720 * Sets the name of a resource, resource type and ID are specified by the parameters.
721 * @param restypeid Identifier of the resource type (either ID or name).
722 * @param resid Identifier of the resource (either ID or name).
723 * @param strNewResName The new name of the resource.
724 **/
725 template<typename S, typename T>
726 int ResourceDirectory::setResourceNameT(S restypeid, T resid, std::string strNewResName)
727 {
728 std::vector<ResourceChild>::iterator ResIter = locateResourceT(restypeid, resid);
729 ResIter->entry.wstrName = strNewResName;
730
731 return 0;
732 }
733}
734
735#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/TlsDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/TlsDirectory.h
new file mode 100755
index 0000000000..ebea929f94
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/TlsDirectory.h
@@ -0,0 +1,304 @@
1/*
2* TlsDirectory.h - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#ifndef TLSDIRECTORY_H
14#define TLSDIRECTORY_H
15
16namespace PeLib
17{
18 /// Class that handles the TLS directory.
19 /**
20 * This class handles the TLS (Thread Local Storage) directory.
21 **/
22 template<int bits>
23 class TlsDirectory
24 {
25 private:
26 PELIB_IMAGE_TLS_DIRECTORY<bits> m_tls; ///< Structure that holds all information about the directory.
27
28 void read(InputBuffer& inputbuffer);
29
30 public:
31 /// Reads a file's TLS directory.
32 int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize); // EXPORT
33 int read(unsigned char* buffer, unsigned int buffersize); // EXPORT
34 /// Rebuilds the TLS directory.
35 void rebuild(std::vector<byte>& vBuffer) const; // EXPORT
36 /// Returns the size of the TLS Directory.
37 unsigned int size() const; // EXPORT
38 /// Writes the TLS directory to a file.
39 int write(const std::string& strFilename, unsigned int dwOffset) const; // EXPORT
40
41 /// Returns the StartAddressOfRawData value of the TLS header.
42 dword getStartAddressOfRawData() const; // EXPORT
43 /// Returns the EndAddressOfRawData value of the TLS header.
44 dword getEndAddressOfRawData() const; // EXPORT
45 /// Returns the AddressOfIndex value of the TLS header.
46 dword getAddressOfIndex() const; // EXPORT
47 /// Returns the AddressOfCallBacks value of the TLS header.
48 dword getAddressOfCallBacks() const; // EXPORT
49 /// Returns the SizeOfZeroFill value of the TLS header.
50 dword getSizeOfZeroFill() const; // EXPORT
51 /// Returns the Characteristics value of the TLS header.
52 dword getCharacteristics() const; // EXPORT
53
54 /// Sets the StartAddressOfRawData value of the TLS header.
55 void setStartAddressOfRawData(dword dwValue); // EXPORT
56 /// Sets the EndAddressOfRawData value of the TLS header.
57 void setEndAddressOfRawData(dword dwValue); // EXPORT
58 /// Sets the AddressOfIndex value of the TLS header.
59 void setAddressOfIndex(dword dwValue); // EXPORT
60 /// Sets the AddressOfCallBacks value of the TLS header.
61 void setAddressOfCallBacks(dword dwValue); // EXPORT
62 /// Sets the SizeOfZeroFill value of the TLS header.
63 void setSizeOfZeroFill(dword dwValue); // EXPORT
64 /// Sets the Characteristics value of the TLS header.
65 void setCharacteristics(dword dwValue); // EXPORT
66 };
67
68 template<int bits>
69 void TlsDirectory<bits>::read(InputBuffer& inputBuffer)
70 {
71 PELIB_IMAGE_TLS_DIRECTORY<bits> itdCurr;
72
73 inputBuffer >> itdCurr.StartAddressOfRawData;
74 inputBuffer >> itdCurr.EndAddressOfRawData;
75 inputBuffer >> itdCurr.AddressOfIndex;
76 inputBuffer >> itdCurr.AddressOfCallBacks;
77 inputBuffer >> itdCurr.SizeOfZeroFill;
78 inputBuffer >> itdCurr.Characteristics;
79
80 std::swap(itdCurr, m_tls);
81 }
82
83 template<int bits>
84 int TlsDirectory<bits>::read(unsigned char* buffer, unsigned int buffersize)
85 {
86 if (buffersize < PELIB_IMAGE_TLS_DIRECTORY<bits>::size())
87 {
88 return ERROR_INVALID_FILE;
89 }
90
91 std::vector<byte> vTlsDirectory(buffer, buffer + buffersize);
92
93 InputBuffer ibBuffer(vTlsDirectory);
94 read(ibBuffer);
95 return NO_ERROR;
96 }
97
98 /**
99 * Reads a file's TLS directory.
100 * @param strFilename Name of the file.
101 * @param uiOffset File offset of the TLS directory.
102 * @param uiSize Size of the TLS directory.
103 **/
104 template<int bits>
105 int TlsDirectory<bits>::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize)
106 {
107 std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
108 unsigned int ulFileSize = fileSize(ifFile);
109
110 if (!ifFile)
111 {
112 return ERROR_OPENING_FILE;
113 }
114
115 if (ulFileSize < uiOffset + uiSize)
116 {
117 return ERROR_INVALID_FILE;
118 }
119
120 ifFile.seekg(uiOffset, std::ios::beg);
121
122 std::vector<byte> vTlsDirectory(uiSize);
123 ifFile.read(reinterpret_cast<char*>(&vTlsDirectory[0]), uiSize);
124
125 InputBuffer ibBuffer(vTlsDirectory);
126 read(ibBuffer);
127 return NO_ERROR;
128 }
129
130 /**
131 * Rebuilds the current TLS Directory.
132 * @param vBuffer Buffer where the TLS directory will be written to.
133 **/
134 template<int bits>
135 void TlsDirectory<bits>::rebuild(std::vector<byte>& vBuffer) const
136 {
137 OutputBuffer obBuffer(vBuffer);
138
139 obBuffer << m_tls.StartAddressOfRawData;
140 obBuffer << m_tls.EndAddressOfRawData;
141 obBuffer << m_tls.AddressOfIndex;
142 obBuffer << m_tls.AddressOfCallBacks;
143 obBuffer << m_tls.SizeOfZeroFill;
144 obBuffer << m_tls.Characteristics;
145 }
146
147 /**
148 * Returns the size of the TLS directory. Due to the static nature of this structure the return value
149 * will always be 24.
150 * @return Size in bytes.
151 **/
152 template<int bits>
153 unsigned int TlsDirectory<bits>::size() const
154 {
155 return PELIB_IMAGE_TLS_DIRECTORY<bits>::size();
156 }
157
158 /**
159 * @param strFilename Name of the file.
160 * @param dwOffset File offset the TLS Directory will be written to.
161 **/
162 template<int bits>
163 int TlsDirectory<bits>::write(const std::string& strFilename, unsigned int dwOffset) const
164 {
165 std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
166
167 if (!ofFile)
168 {
169 ofFile.clear();
170 ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
171 }
172 else
173 {
174 ofFile.close();
175 ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
176 }
177
178 if (!ofFile)
179 {
180 return ERROR_OPENING_FILE;
181 }
182
183 ofFile.seekp(dwOffset, std::ios::beg);
184
185 std::vector<unsigned char> vBuffer;
186 rebuild(vBuffer);
187
188 ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), vBuffer.size());
189
190 ofFile.close();
191
192 return NO_ERROR;
193 }
194
195 /**
196 * @return The StartAddressOfRawData value of the TLS directory.
197 **/
198 template<int bits>
199 dword TlsDirectory<bits>::getStartAddressOfRawData() const
200 {
201 return m_tls.StartAddressOfRawData;
202 }
203
204 /**
205 * @return The EndAddressOfRawData value of the TLS directory.
206 **/
207 template<int bits>
208 dword TlsDirectory<bits>::getEndAddressOfRawData() const
209 {
210 return m_tls.EndAddressOfRawData;
211 }
212
213 /**
214 * @return The AddressOfIndex value of the TLS directory.
215 **/
216 template<int bits>
217 dword TlsDirectory<bits>::getAddressOfIndex() const
218 {
219 return m_tls.AddressOfIndex;
220 }
221
222 /**
223 * @return The AddressOfCallBacks value of the TLS directory.
224 **/
225 template<int bits>
226 dword TlsDirectory<bits>::getAddressOfCallBacks() const
227 {
228 return m_tls.AddressOfCallBacks;
229 }
230
231 /**
232 * @return The SizeOfZeroFill value of the TLS directory.
233 **/
234 template<int bits>
235 dword TlsDirectory<bits>::getSizeOfZeroFill() const
236 {
237 return m_tls.SizeOfZeroFill;
238 }
239
240 /**
241 * @return The Characteristics value of the TLS directory.
242 **/
243 template<int bits>
244 dword TlsDirectory<bits>::getCharacteristics() const
245 {
246 return m_tls.Characteristics;
247 }
248
249 /**
250 * @param dwValue The new StartAddressOfRawData value of the TLS directory.
251 **/
252 template<int bits>
253 void TlsDirectory<bits>::setStartAddressOfRawData(dword dwValue)
254 {
255 m_tls.StartAddressOfRawData = dwValue;
256 }
257
258 /**
259 * @param dwValue The new EndAddressOfRawData value of the TLS directory.
260 **/
261 template<int bits>
262 void TlsDirectory<bits>::setEndAddressOfRawData(dword dwValue)
263 {
264 m_tls.EndAddressOfRawData = dwValue;
265 }
266
267 /**
268 * @param dwValue The new AddressOfIndex value of the TLS directory.
269 **/
270 template<int bits>
271 void TlsDirectory<bits>::setAddressOfIndex(dword dwValue)
272 {
273 m_tls.AddressOfIndex = dwValue;
274 }
275
276 /**
277 * @param dwValue The new AddressOfCallBacks value of the TLS directory.
278 **/
279 template<int bits>
280 void TlsDirectory<bits>::setAddressOfCallBacks(dword dwValue)
281 {
282 m_tls.AddressOfCallBacks = dwValue;
283 }
284
285 /**
286 * @param dwValue The new SizeOfZeroFill value of the TLS directory.
287 **/
288 template<int bits>
289 void TlsDirectory<bits>::setSizeOfZeroFill(dword dwValue)
290 {
291 m_tls.SizeOfZeroFill = dwValue;
292 }
293
294 /**
295 * @param dwValue The new Characteristics value of the TLS directory.
296 **/
297 template<int bits>
298 void TlsDirectory<bits>::setCharacteristics(dword dwValue)
299 {
300 m_tls.Characteristics = dwValue;
301 }
302
303}
304#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/buffer/InputBuffer.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/buffer/InputBuffer.cpp
new file mode 100755
index 0000000000..ae2584edb1
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/buffer/InputBuffer.cpp
@@ -0,0 +1,58 @@
1/*
2* InputBuffer.cpp - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#include "InputBuffer.h"
14
15namespace PeLib
16{
17 unsigned long InputBuffer::get()
18 {
19 return ulIndex;
20 }
21
22 InputBuffer::InputBuffer(std::vector<unsigned char>& vBuffer) : m_vBuffer(vBuffer), ulIndex(0)
23 {
24 }
25
26 const unsigned char* InputBuffer::data() const
27 {
28 return &m_vBuffer[0];
29 }
30
31 unsigned long InputBuffer::size()
32 {
33 return static_cast<unsigned long>(m_vBuffer.size());
34 }
35
36 void InputBuffer::read(char* lpBuffer, unsigned long ulSize)
37 {
38 std::copy(&m_vBuffer[ulIndex], &m_vBuffer[ulIndex + ulSize], lpBuffer);
39 ulIndex += ulSize;
40 }
41
42 void InputBuffer::reset()
43 {
44 m_vBuffer.clear();
45 }
46
47 void InputBuffer::set(unsigned long ulIndex)
48 {
49 this->ulIndex = ulIndex;
50 }
51
52 void InputBuffer::setBuffer(std::vector<unsigned char>& vBuffer)
53 {
54 m_vBuffer = vBuffer;
55 ulIndex = 0;
56 }
57}
58
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/buffer/InputBuffer.h b/utils/zenutils/libraries/pelib-0.9/pelib/buffer/InputBuffer.h
new file mode 100755
index 0000000000..fc5a14e357
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/buffer/InputBuffer.h
@@ -0,0 +1,52 @@
1/*
2* InputBuffer.h - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#ifndef INPUTBUFFER_H
14#define INPUTBUFFER_H
15
16#include <vector>
17#include <iterator>
18#include <cassert>
19
20namespace PeLib
21{
22 class InputBuffer
23 {
24 private:
25 std::vector<unsigned char>& m_vBuffer;
26 unsigned long ulIndex;
27
28 public:
29 InputBuffer(std::vector<unsigned char>& vBuffer);
30
31 const unsigned char* data() const;
32 unsigned long size();
33
34 template<typename T>
35 InputBuffer& operator>>(T& value)
36 {
37 assert(ulIndex + sizeof(value) <= m_vBuffer.size());
38 value = *(T*)(&m_vBuffer[ulIndex]);//reinterpret_cast<T*>(&m_vBuffer[ulIndex]);
39 ulIndex += sizeof(T);
40 return *this;
41 }
42
43 void read(char* lpBuffer, unsigned long ulSize);
44 void reset();
45 void set(unsigned long ulIndex);
46 unsigned long get();
47 void setBuffer(std::vector<unsigned char>& vBuffer);
48// void updateData(unsigned long ulIndex,
49 };
50}
51
52#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/buffer/OutputBuffer.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/buffer/OutputBuffer.cpp
new file mode 100755
index 0000000000..b47fbb6ff8
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/buffer/OutputBuffer.cpp
@@ -0,0 +1,41 @@
1/*
2* OutputBuffer.cpp - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#include "OutputBuffer.h"
14
15namespace PeLib
16{
17 OutputBuffer::OutputBuffer(std::vector<unsigned char>& vBuffer) : m_vBuffer(vBuffer)
18 {
19 m_vBuffer.clear();
20 }
21
22 const unsigned char* OutputBuffer::data() const
23 {
24 return &m_vBuffer[0];
25 }
26
27 unsigned long OutputBuffer::size()
28 {
29 return static_cast<unsigned long>(m_vBuffer.size());
30 }
31
32 void OutputBuffer::add(const char* lpBuffer, unsigned long ulSize)
33 {
34 std::copy(lpBuffer, lpBuffer + ulSize, std::back_inserter(m_vBuffer));
35 }
36
37 void OutputBuffer::reset()
38 {
39 m_vBuffer.clear();
40 }
41}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/buffer/OutputBuffer.h b/utils/zenutils/libraries/pelib-0.9/pelib/buffer/OutputBuffer.h
new file mode 100755
index 0000000000..f1ab99039b
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/buffer/OutputBuffer.h
@@ -0,0 +1,51 @@
1/*
2* OutputBuffer.h - Part of the PeLib library.
3*
4* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
5* All rights reserved.
6*
7* This software is licensed under the zlib/libpng License.
8* For more details see http://www.opensource.org/licenses/zlib-license.php
9* or the license information file (license.htm) in the root directory
10* of PeLib.
11*/
12
13#ifndef OUTPUTBUFFER_H
14#define OUTPUTBUFFER_H
15
16#include <vector>
17#include <iterator>
18
19namespace PeLib
20{
21 class OutputBuffer
22 {
23 private:
24 std::vector<unsigned char>& m_vBuffer;
25
26 public:
27 OutputBuffer(std::vector<unsigned char>& vBuffer);
28 const unsigned char* data() const;
29 unsigned long size();
30
31 template<typename T>
32 OutputBuffer& operator<<(const T& value)
33 {
34 const unsigned char* p = reinterpret_cast<const unsigned char*>(&value);
35 std::copy(p, p + sizeof(value), std::back_inserter(m_vBuffer));
36 return *this;
37 }
38 void add(const char* lpBuffer, unsigned long ulSize);
39 void reset();
40 void resize(unsigned int uiSize);
41 void set(unsigned int uiPosition);
42
43 template<typename T>
44 void update(unsigned long ulIndex, const T& value)
45 {
46 *(T*)(&m_vBuffer[ulIndex]) = value;
47 }
48 };
49}
50
51#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/changelog.txt b/utils/zenutils/libraries/pelib-0.9/pelib/changelog.txt
new file mode 100755
index 0000000000..37a7c36229
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/changelog.txt
@@ -0,0 +1,321 @@
1PeLib 0.09 alpha (February 09, 2005)
2
3Added:
4- Added PeHeaderT<x>::setIddBaseRelocRva(dword value)
5- Added PeHeaderT<x>::setIddBaseRelocSize(dword value)
6- Added PeHeaderT<x>::setIddArchitectureRva(dword value)
7- Added PeHeaderT<x>::setIddArchitectureSize(dword value)
8- Added PeHeaderT<x>::setIddComHeaderRva(dword value)
9- Added PeHeaderT<x>::setIddComHeaderSize(dword value)
10- Added void PeHeaderT<x>::setImageDataDirectoryRva(dword dwDirectory, dword value)
11- Added void PeHeaderT<x>::setImageDataDirectorySize(dword dwDirectory, dword value)
12- Added bool PeHeaderT<x>::isValid() const
13- Added int PeHeaderT<x>::read(const unsigned char* pcBuffer, unsigned int uiSize, unsigned int uiOffset);
14- Added int BoundImportDirectory::read(unsigned char* pcBuffer, unsigned int uiSize);
15- Added int BoundImportDirectory::read(InputBuffer& inpBuffer, unsigned char* data, unsigned int dwSize);
16- Added unsigned int BoundImportDirectory::totalModules()
17- Added DebugDirectory::setData to set the debug data of individual entries in the DebugDirectory.
18- Added DebugDirectory::getData to get the debug data of individual entries in the DebugDirectory.
19- Added int IatDirectory::read(unsigned char* buffer, unsigned int buffersize)
20- Optimized the size and rebuild methods to avoid duplicate strings for files that appear
21 more than once in the BoundImport Directory.
22- Added two read functions to TlsDirectory and updated the return values of the old read function.
23- Added two read functions to ComHeaderDirectory and updated the return values of the old read function.
24- Added two read functions to RelocationsDirectory and updated the return values of the old read function.
25- Added void RelocationsDirectory::addRelocation()
26- Added void RelocationsDirectory::removeRelocation(unsigned int index)
27- Added void DebugDirectory::clear()
28- Added void ExportDirectory::removeFunction(unsigned int index)
29- Added void ExportDirectory::clear()
30- Added unsigned int ExportDirectory::calcNumberOfFunctions()
31- Added void ExportDirectory::setAddressOfNameOrdinals(dword value)
32
33Bugfixes:
34- Fixed a bug in TlsDirectory<bits>::size()
35- Fixed a bug in PeHeaderT<64>::isValid(dword)
36- Fixed a bug in PeHeaderT<bits>::removeDataDirectory(dword)
37- Fixed a bug in BoundImportDirectory::rebuild()
38- Fixed a bug in BoundImportDirectory::read() (Potential buffer overflow)
39- Fixed a bug in BoundImportDirectory::read() (Bug caused incorrect results when reading the directory more than once)
40- Fixed a bug when reading the debug data of individual DebugDirectory entries.
41- Fixed a bug that caused non-existing data directories to be read (PeFile).
42- Fixed a bug that caused problems when reading import directories that were located close to the end of the file (ImportDirectory).
43- Fixed a minor bug in PeHeader::calcSizeOfImage
44- Fixed some return values and removed all exception handling blocks.
45
46Changes:
47- Changed return values of PeHeader::addSection
48- Changed return values of PeHeader::read
49- Changed behaviour: PeHeader::m_uiOffset is initialized to 0 in default constructors.
50- Changed return value of BoundImportDirectory::getNumberOfModules() from int to unsigned int
51- Changed name of BoundImportDirectory::getNumberOfModules to calcNumberOfModules
52- Changed the return values of the PeFile::read* functions.
53- Renamed IatDirectory::removeAll to IatDirectory::clear
54- Renamed IatDirectory::numberOfAddresses to IatDirectory::calcNumberOfAddresses
55- Changed the parameter types of IatDirectory::getAddress from dword to unsigned int
56- Changed the parameter types of IatDirectory::removeAddress from dword to unsigned int
57- All constants taken from windows.h that were redefined in PeLibAux.h now have the prefix PELIB_ to avoid
58 conflicts with windows.h if both files are included to a project.
59- Changed PELIB_IMAGE_TLS_DIRECTORY<bits>::size from an enum to a function.
60- Changed the name of RelocationsDirectory::getNumberOfRelocationData to calcNumberOfRelocationData
61- Changed void RelocationsDirectory::removeRelocationData(unsigned int ulRelocation, word wValue)
62 to void RelocationsDirectory::removeRelocationData(unsigned int relocindex, unsigned int dataindex)
63- Removed dword ExportDirectory::getNumberOfNameOrdinals()
64- Removed dword ExportDirectory::getNumberOfAddressOfFunctionNames()
65- Removed dword ExportDirectory::getNumberOfAddressOfFunctions()
66- Changed the parameters of some functions in ExportDirectory from dword to unsigned int.
67
68
69January 16, 2005 PeLib 0.08 alpha
70
71Added:
72- Added std::string ExportDirectory::getNameString()
73- Added resource type RT_MANIFEST to PeLibAux.h
74- Added the following functions of PeHeaderT<int x>: setIddDebugRva, setIddDebugSize,
75 setIddDelayImportRva, setIddDelayImportSize, setIddExceptionRva, setIddExceptionSize, setIddGlobalPtrRva,
76 setIddGlobalPtrSize, setIddIatRva, setIddIatSize, setIddLoadConfigRva, setIddLoadConfigSize,
77 setIddResourceRva, setIddResourceSize, setIddResourceRva, setIddResourceSize, setIddSecurityRva,
78 setIddSecuritySize, setIddTlsRva, setIddTlsSize
79- ImportDirectory32 and ImportDirectory64 are now available.
80- Added ImportDirectory<bits>::setFileName(dword, currdir, const std::string&)
81- Added ImportDirectory<bits>::setFirstThunk(dword, currdir, dword)
82- Added ImportDirectory<bits>::setForwarderChain(dword, currdir, dword)
83- Added ImportDirectory<bits>::setRvaOfName(dword, currdir, dword)
84- Added ImportDirectory<bits>::setOriginalFirstThunk(dword, currdir, dword)
85- Added ImportDirectory<bits>::setTimeDateStamp(dword, currdir, dword)
86- Added ImportDirectory<bits>::setOriginalFirstThunk(dword, dword, currdir, dword)
87- Added ImportDirectory<bits>::setFirstThunk(dword, dword, currdir, dword)
88- Added ImportDirectory<bits>::setFunctionHint(dword, dword, currdir, word)
89- Added ImportDirectory<bits>::setFunctionName(dword, dword, currdir, const std::string&)
90- Added dword BoundImportDirectory::getTimeDateStamp(dword dwBidnr, dword forwardedModule) const
91- Added word BoundImportDirectory::getOffsetModuleName(dword dwBidnr, dword forwardedModule) const
92- Added word BoundImportDirectory::getNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule) const
93- Added std::string BoundImportDirectory::getModuleName(dword dwBidnr, dword forwardedModule) const
94- Added void BoundImportDirectory::setTimeDateStamp(dword dwBidnr, dword forwardedModule, dword dwTds)
95- Added void BoundImportDirectory::setOffsetModuleName(dword dwBidnr, dword forwardedModule, word wOmn)
96- Added void BoundImportDirectory::setNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule, word wMfr)
97- Added void BoundImportDirectory::setModuleName(dword dwBidnr, dword forwardedModule, const std::string& strModuleName)
98- Added word calcNumberOfModuleForwarderRefs(dword dwBidnr) const
99- Added void addForwardedModule(dword dwBidnr, const std::string& name, dword timeStamp = 0, word offsetModuleName = 0, word forwardedModules = 0)
100- Added void removeForwardedModule(dword dwBidnr, word forwardedModule)
101- Added PeHeaderT<x>::addDataDirectory()
102- Added PeHeaderT<x>::removeDataDirectory(dword)
103
104Bugfixes:
105- Fixed a bug in MzHeader::isValid
106- Fixed a bug in PeHeaderT<x>::size()
107- Fixed a bug in PeHeaderT<x>::calcRva()
108- Fixed a bug in PeHeaderT<x>::calcSizeOfImage()
109- Fixed a bug in PeHeaderT<x>::getSectionName(dword)
110- Fixed a bug in PeHeaderT<x>::calcStartOfCode()
111- Fixed a bug in PELIB_THUNK_DATA<bits>::bool equalHint(word wHint) const
112- Fixed a bug in PELIB_IMAGE_THUNK_DATA<bits>::bool equalHint(word wHint) const
113- Fixed a bug in int ImportDirectory<bits>::removeFunction(const std::string& strFilename, word wHint)
114- Fixed a bug in int ImportDirectory<bits>::removeFile(const std::string& strFilename)
115- Function hints are now properly added when rebuilding import directories.
116- Reading and rebuilding bound import directories now works with forwarded modules.
117
118Changes:
119- Changed behaviour: Removed all exceptions from the MzHeader class. The functions work with return values now.
120- Changed behaviour: The MzHeader::read() functions stopped checking if the MzHeader begins with "MZ".
121- Changed behaviour: PeHeaderT<int x>::addSection(std::string, dword) doesn't use exceptions anymore.
122 Return values now indicate if the function succeeded or failed.
123- Changed behaviour: PeHeaderT<int x>::getSectionWithOffset(dword) doesn't use exceptions anymore.
124 Return values now indicate if the function succeeded or failed.
125- Changed behaviour: PeHeaderT<int x>::getSectionWithRva(dword) doesn't use exceptions anymore.
126 Return values now indicate if the function succeeded or failed.
127- Changed behaviour: PeHeaderT<int x>::rvaToOffset(dword) doesn't use exceptions anymore.
128 Return values now indicate if the function succeeded or failed.
129- Changed behaviour: PeHeaderT<int x>::write(std::string, unsigned int) doesn't use exceptions anymore.
130 Return values now indicate if the function succeeded or failed.
131- Changed behaviour: PeHeaderT<int x>::writeSectionData(const std::string& strFilename, word wSecnr,
132 const std::vector<byte>& vBuffer) doesn't use exceptions anymore.
133 Return values now indicate if the function succeeded or failed.
134- Changed behaviour: PeHeaderT<int x>::writeSections(std::string) doesn't use exceptions anymore.
135 Return values now indicate if the function succeeded or failed.
136- Changed behaviour: Return value of PeHeaderT<x>::calcSpaceAfterHeader() changed from unsigned long
137 to unsigned int.
138- Changed behaviour: Return value of PeHeaderT<x>::calcStartOfCode() changed from unsigned long
139 to unsigned int.
140- Changed behaviour: Return value of PeHeaderT<x>::calcOffset() changed from unsigned long
141 to unsigned int.
142- Changed behaviour: Return value of PeHeaderT<x>::offsetToRva(dword) changed from unsigned long
143 to unsigned int.
144- Changed behaviour: Return value of PeHeaderT<x>::offsetToVa(dword) changed from unsigned long
145 to unsigned int.
146- Renamed ExportDirectory::setName(std::string) to ExportDirectory::setNameString(std::string)
147- Renamed the PeHeaderT::getId* functions to PeHeaderT::getIdd*
148- Renamed PeHeaderT::getImageDirectoryRva to PeHeaderT::getImageDataDirectoryRva
149- Renamed PeHeaderT::getImageDirectorySize to PeHeaderT::getImageDataDirectorySize
150- Renamed void PeHeaderT<x>::setWinVersionValue(dword dwValue) to void PeHeaderT<x>::setWin32VersionValue(dword dwValue)
151- Renamed the following functions of PeHeaderT<int x>: setIdImportRva to setIddImportRva,
152 setIdImportSize to setIddImportSize, setIdExportRva to setIddExportRva, setIdExportSize to setIddExportSize
153- Renamed dword ImportDirectory<bits>::getName to dword ImportDirectory<bits>::getRvaOfName
154- Changed behaviour: All removeFunction and removeFile functions from ImportDirectory.h return int instead
155 of void now.
156- Changed behavior: ResourceDirectory::resourceTypeNameToIndex returns int instead of unsigned int.
157
158-------------------------------------------------------------------------------------------------------------
159
160July 18, 2004 PeLib 0.07 alpha
161
162Added:
163- Full support of the PE+ format.
164- ImportDirectory::getName(string, currdir)
165- ImportDirectory::getFirstThunk(dword, currdir)
166- ImportDirectory::getOriginalFirstThunk(dword, currdir)
167- ImportDirectory::getForwarderChain(dword, currdir)
168- ImportDirectory::getName(dword, currdir)
169- ImportDirectory::getTimeDateStamp(dword, currdir)
170- PeLib::getFileType(string)
171- PeLib::openPeFile(string)
172- Added class PeFileVisitor
173- Added PeFile::visit(PeFileVisitor&)
174
175Bugfixes:
176- Fixed a bug in PeHeader::rvaToOffset
177
178Changes:
179- Renamed ImportDirectory::OLD to PeLib::OLDDIR and ImportDirectory::NEW to PeLib::NEWDIR
180- Renamed Relocations to RelocationsDirectory
181- Renamed ImportAddressTable to IatDirectory
182- Renamed ComDescriptor to ComHeader
183- Renamed PeFile::comDescDir to PeFile::comDir
184- Changed unsigned long ExportDirectory::getFunctionIndex to unsigned int ExportDirectory::getFunctionIndex
185
186-------------------------------------------------------------------------------------------------------------
187
188July 4, 2004 PeLib 0.06 alpha
189
190Added:
191- TlsDirectory class
192
193Changes:
194- ResourceElement::read and ResourceElement::rebuild are now protected.
195
196Bugfixes:
197- Fixed a bug in PeHeader::rvaToOffset
198
199-------------------------------------------------------------------------------------------------------------
200
201June 26, 2004 PeLib 0.05 alpha
202
203Added:
204- Constructor, Copy constructor, assignment operator and destructor for ResourceChild.
205- ResourceDirectory::getRoot()
206- ResourceElement::isLeaf()
207- ResourceElement::getElementRva
208- 10 new functions in ResourceLeaf.
209- 22 new functions in ResourceNode.
210- Added the RT_* constants which identify resource types to PeLibAux.h
211- Added a new example (examples/ResourceTree) which shows how to use low level ResourceDirectory functions.
212- Added PELIB_IMAGE_DEBUG_DIRECTORY and PELIB_IMG_DEBUG_DIRECTORY
213- Added the new class DebugDirectory which handles the debug directory of PE files.
214- Added readDebugDirectory() and debugDir() to PeFile.
215
216Removed:
217- ~ResourceNode()
218
219-------------------------------------------------------------------------------------------------------------
220
221June 12, 2004 PeLib 0.04 alpha
222
223New:
224- Finally implemented the class ResourceDirectory. That means lots of new functions I won't explicitly list here.
225 Check the documentation.
226
227Removed:
228- The files buffer/ResTree.cpp and buffer/ResTree.h are obsolete and were removed.
229
230Bugfixes:
231- Fixed PeHeader::calcStartOfCode
232- Fixed PeHeader::getSectionWithRva
233
234Changes:
235- Changed PeHeader::read to throw an exception if the NT signature is not 'PE'\0\0
236- Changed the 2nd parameter of void MzHeader::read(unsigned char*, unsigned long) from unsigned long to unsigned int.
237- Changed the return value of MzHeader::size from long to int.
238- Changed parameters of MzHeader::getReservedWords1, MzHeader::getReservedWords2, MzHeader::setReservedWords1 and
239 MzHeader::setReservedWords2 from long to int.
240- Changed MzHeader::read(std::string) to MzHeader::read(const std::string&)
241- Changed return value of BoundImportDirectory::getModuleIndex from long to int.
242- Changed return value of BoundImportDirectory::size from long to int.
243- Changed return value of ComDescriptor::size from long to int.
244- Changed return value of ImportAddressTable::size from long to int.
245- Changed return value of Relocations::getNumberOfRelocations from long to int.
246- Changed return value of Relocations::getNumberOfRelocationData from long to int.
247- Changed return value of Relocations::size from long to int.
248- Changed parameter of Relocations::getVirtualAddress from long to int.
249- Changed parameter of Relocations::getSizeOfBlock from long to int.
250- Changed parameter of Relocations::getRelocationData from long to int.
251- Changed parameters of Relocations::setRelocationData from long to int.
252- Changed parameters of Relocations::setVirtualAddress from long to int.
253- Changed parameters of Relocations::setSizeOfBlock from long to int.
254- Changed parameters of Relocations::addRelocationData from long to int.
255- Changed parameters of Relocations::removeRelocationData from long to int.
256- Changed return value of ExportDirectory::getFunctionIndex(const std::string&) const from unsigned int to int.
257
258-------------------------------------------------------------------------------------------------------------
259
260May 31, 2004: PeLib 0.03 alpha
261
262Bugfixes:
263- Fixed some bugs in FileDump.cpp
264
265Changes:
266- Modified PeLibAux.cpp to make PeLib VC++ 7.1 compatible.
267- Changed vector access from .at to operator[] all over the project.
268 Real undefined behaviour is probably better than spontaniously terminating applications.
269
270New:
271- Added makefiles for Borland C++ commandline tools (tested on version 5.6.4)
272- Added makefiles for Digital Mars Compiler (tested on version 8.38n)
273 Note that support for DMC is not yet complete. PeLib compiles though, the examples don't yet but the
274 reason for this is that I am unable to correctly specifiy the PeLib object files when compiling.
275- Added makefiles for Visual C++ 7.1 (tested on compiler Version 13.10.3052)
276
277-------------------------------------------------------------------------------------------------------------
278
279Mai 1, 2004: PeLib 0.02 alpha
280
281Bugfixes:
282- Fixed a bug in FileDump's and OON2's makefile.g++
283- Fixed ImportDirectory::size
284- Changed parameter of PELIB_THUNK_DATA::equalHint from dword to word
285- Fixed a bug in PeHeader::read (PeLib always assumed 0x10 data directories in version 0.01 alpha)
286
287Changes:
288- Slightly changed ImportDirectory::removeFile (Changed function's signature)
289- Moved the definitions of byte, word and dword into the PeLib namespace.
290- Renamed PELIB_THUNK_DATA::equalName to PELIB_THUNK_DATA::equalFunctionName
291- Started to add size() functions to structs defined in PeLibAux.h
292- Moved PeFile::writeSectionData to PeHeader::writeSectionData
293- Moved PeFile::writeSections to PeHeader::writeSections
294
295New:
296- Added ImportDirectory::hasFunction
297- Wrote BoundImportDirectory::size
298- Added accumulate function to PeLibAux.h
299- Added PELIB_IMAGE_SECTION_HEADER::biggerFileOffset
300- Added PELIB_IMAGE_SECTION_HEADER::biggerVirtualAddress
301- Added PeHeader::calcSizeOfImage
302- Added PeHeader::enlargeLastSection
303
304Removed:
305- Removed PeFile::write
306- Removed PeFile::writeImportDirectory
307
308Other changes:
309- Rewrote parts of ImportDirectory::read
310- Rewrote ImportDirectory::removeFunction (both version).
311- Changed std::ios:: to std::ios_base:: in ImportDirectory
312- Changed ImportDirectory::addFunction (both versions)
313- Changed ExportDirectory::rebuild
314- Changed ExportDirectory::size
315- Rewrote ImportDirectory::size
316- Rewrote PeHeader::size
317- Rewrote ComDescriptor::size
318
319-------------------------------------------------------------------------------------------------------------
320
321April 9, 2004: PeLib 0.01 alpha Initial release \ No newline at end of file
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/license.htm b/utils/zenutils/libraries/pelib-0.9/pelib/license.htm
new file mode 100755
index 0000000000..2978aa7920
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/license.htm
@@ -0,0 +1,35 @@
1<html>
2<body>
3<h1>The zlib/libpng License</h1>
4
5<tt>
6
7<p>Copyright (c) 2004 - Sebastian Porst</p>
8
9 <p>This software is provided 'as-is', without any express or implied
10 warranty. In no event will the authors be held liable for any damages
11 arising from the use of this software.</p>
12
13 <p>Permission is granted to anyone to use this software for any purpose,
14 including commercial applications, and to alter it and redistribute it
15 freely, subject to the following restrictions:</p>
16
17<blockquote>
18
19 <p>1. The origin of this software must not be misrepresented; you must not
20 claim that you wrote the original software. If you use this software
21 in a product, an acknowledgment in the product documentation would be
22 appreciated but is not required.</p>
23
24 <p>2. Altered source versions must be plainly marked as such, and must not be
25 misrepresented as being the original software.</p>
26
27 <p>3. This notice may not be removed or altered from any source
28 distribution.</p>
29
30</blockquote>
31
32</tt>
33
34</body>
35</html> \ No newline at end of file
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/readme.txt b/utils/zenutils/libraries/pelib-0.9/pelib/readme.txt
new file mode 100755
index 0000000000..b26a3e5287
--- /dev/null
+++ b/utils/zenutils/libraries/pelib-0.9/pelib/readme.txt
@@ -0,0 +1,44 @@
1PeLib - Version 0.09 (alpha release)
2=========================================
3
4Copyright 2004 by Sebastian Porst
5WWW: http://www.pelib.com
6E-Mail: webmaster@the-interweb.com
7
8=========================================
9
101. What is PeLib?
112. Where can I find a documentation of PeLib DLL?
123. Which license is used for PeLib?
134. Which compilers are being supported?
145. How do I compile PeLib?
15
161. What is PeLib DLL?
17 PeLib is an open-source C++ library to modify
18 PE files. See http://www.pelib.com for more details.
19
202. Where can I find a documentation of PeLib DLL?
21 http://www.pelib.com
22
233. All parts of PeLib are distributed under the zlib/libpng license.
24 See license.htm for details.
25
264. The following compilers have been tested:
27 MingW with g++ 3.2.3
28 Visual C++ 7.1 / Compiler version 13.10.3052
29 Borland C++ 5.6.4 (currently not supported)
30 Digital Mars Compiler 8.38n (currently not supported)
31
325. Go into the PeLib/source directory and enter the following lines
33 depending on which compiler you use.
34
35 g++: make -f makefile.g++
36 Borland C++: make -f makefile.bcc (currently not supported)
37 Visual C++ 7.1: nmake makefile.vc7
38 Digital Mars: make makefile.dmc (currently not supported)
39
40 If the compilation is succesful there should be some *.o/*.obj files
41 and (if you used g++) a PeLib.a file in the lib directory.
42 Then go to the examples directory and pick one example (I
43 suggest FileDump) and try to build it with the same make
44 command as above. \ No newline at end of file
diff --git a/utils/zenutils/libraries/zlib123/CMakeLists.txt b/utils/zenutils/libraries/zlib123/CMakeLists.txt
new file mode 100755
index 0000000000..05e949567d
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/CMakeLists.txt
@@ -0,0 +1,19 @@
1PROJECT(zlib)
2
3# source files for zlib
4SET(zlib_src
5 zlib/adler32.c
6 zlib/compress.c
7 zlib/crc32.c
8 zlib/deflate.c
9 zlib/gzio.c
10 zlib/infback.c
11 zlib/inffast.c
12 zlib/inflate.c
13 zlib/inftrees.c
14 zlib/trees.c
15 zlib/uncompr.c
16 zlib/zutil.c
17)
18
19ADD_LIBRARY(zlib ${zlib_src})
diff --git a/utils/zenutils/libraries/zlib123/zlib/ChangeLog b/utils/zenutils/libraries/zlib123/zlib/ChangeLog
new file mode 100755
index 0000000000..1ac946309b
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/ChangeLog
@@ -0,0 +1,855 @@
1
2 ChangeLog file for zlib
3
4Changes in 1.2.3 (18 July 2005)
5- Apply security vulnerability fixes to contrib/infback9 as well
6- Clean up some text files (carriage returns, trailing space)
7- Update testzlib, vstudio, masmx64, and masmx86 in contrib [Vollant]
8
9Changes in 1.2.2.4 (11 July 2005)
10- Add inflatePrime() function for starting inflation at bit boundary
11- Avoid some Visual C warnings in deflate.c
12- Avoid more silly Visual C warnings in inflate.c and inftrees.c for 64-bit
13 compile
14- Fix some spelling errors in comments [Betts]
15- Correct inflateInit2() error return documentation in zlib.h
16- Added zran.c example of compressed data random access to examples
17 directory, shows use of inflatePrime()
18- Fix cast for assignments to strm->state in inflate.c and infback.c
19- Fix zlibCompileFlags() in zutil.c to use 1L for long shifts [Oberhumer]
20- Move declarations of gf2 functions to right place in crc32.c [Oberhumer]
21- Add cast in trees.c t avoid a warning [Oberhumer]
22- Avoid some warnings in fitblk.c, gun.c, gzjoin.c in examples [Oberhumer]
23- Update make_vms.com [Zinser]
24- Initialize state->write in inflateReset() since copied in inflate_fast()
25- Be more strict on incomplete code sets in inflate_table() and increase
26 ENOUGH and MAXD -- this repairs a possible security vulnerability for
27 invalid inflate input. Thanks to Tavis Ormandy and Markus Oberhumer for
28 discovering the vulnerability and providing test cases.
29- Add ia64 support to configure for HP-UX [Smith]
30- Add error return to gzread() for format or i/o error [Levin]
31- Use malloc.h for OS/2 [Necasek]
32
33Changes in 1.2.2.3 (27 May 2005)
34- Replace 1U constants in inflate.c and inftrees.c for 64-bit compile
35- Typecast fread() return values in gzio.c [Vollant]
36- Remove trailing space in minigzip.c outmode (VC++ can't deal with it)
37- Fix crc check bug in gzread() after gzungetc() [Heiner]
38- Add the deflateTune() function to adjust internal compression parameters
39- Add a fast gzip decompressor, gun.c, to examples (use of inflateBack)
40- Remove an incorrect assertion in examples/zpipe.c
41- Add C++ wrapper in infback9.h [Donais]
42- Fix bug in inflateCopy() when decoding fixed codes
43- Note in zlib.h how much deflateSetDictionary() actually uses
44- Remove USE_DICT_HEAD in deflate.c (would mess up inflate if used)
45- Add _WIN32_WCE to define WIN32 in zconf.in.h [Spencer]
46- Don't include stderr.h or errno.h for _WIN32_WCE in zutil.h [Spencer]
47- Add gzdirect() function to indicate transparent reads
48- Update contrib/minizip [Vollant]
49- Fix compilation of deflate.c when both ASMV and FASTEST [Oberhumer]
50- Add casts in crc32.c to avoid warnings [Oberhumer]
51- Add contrib/masmx64 [Vollant]
52- Update contrib/asm586, asm686, masmx86, testzlib, vstudio [Vollant]
53
54Changes in 1.2.2.2 (30 December 2004)
55- Replace structure assignments in deflate.c and inflate.c with zmemcpy to
56 avoid implicit memcpy calls (portability for no-library compilation)
57- Increase sprintf() buffer size in gzdopen() to allow for large numbers
58- Add INFLATE_STRICT to check distances against zlib header
59- Improve WinCE errno handling and comments [Chang]
60- Remove comment about no gzip header processing in FAQ
61- Add Z_FIXED strategy option to deflateInit2() to force fixed trees
62- Add updated make_vms.com [Coghlan], update README
63- Create a new "examples" directory, move gzappend.c there, add zpipe.c,
64 fitblk.c, gzlog.[ch], gzjoin.c, and zlib_how.html.
65- Add FAQ entry and comments in deflate.c on uninitialized memory access
66- Add Solaris 9 make options in configure [Gilbert]
67- Allow strerror() usage in gzio.c for STDC
68- Fix DecompressBuf in contrib/delphi/ZLib.pas [ManChesTer]
69- Update contrib/masmx86/inffas32.asm and gvmat32.asm [Vollant]
70- Use z_off_t for adler32_combine() and crc32_combine() lengths
71- Make adler32() much faster for small len
72- Use OS_CODE in deflate() default gzip header
73
74Changes in 1.2.2.1 (31 October 2004)
75- Allow inflateSetDictionary() call for raw inflate
76- Fix inflate header crc check bug for file names and comments
77- Add deflateSetHeader() and gz_header structure for custom gzip headers
78- Add inflateGetheader() to retrieve gzip headers
79- Add crc32_combine() and adler32_combine() functions
80- Add alloc_func, free_func, in_func, out_func to Z_PREFIX list
81- Use zstreamp consistently in zlib.h (inflate_back functions)
82- Remove GUNZIP condition from definition of inflate_mode in inflate.h
83 and in contrib/inflate86/inffast.S [Truta, Anderson]
84- Add support for AMD64 in contrib/inflate86/inffas86.c [Anderson]
85- Update projects/README.projects and projects/visualc6 [Truta]
86- Update win32/DLL_FAQ.txt [Truta]
87- Avoid warning under NO_GZCOMPRESS in gzio.c; fix typo [Truta]
88- Deprecate Z_ASCII; use Z_TEXT instead [Truta]
89- Use a new algorithm for setting strm->data_type in trees.c [Truta]
90- Do not define an exit() prototype in zutil.c unless DEBUG defined
91- Remove prototype of exit() from zutil.c, example.c, minigzip.c [Truta]
92- Add comment in zlib.h for Z_NO_FLUSH parameter to deflate()
93- Fix Darwin build version identification [Peterson]
94
95Changes in 1.2.2 (3 October 2004)
96- Update zlib.h comments on gzip in-memory processing
97- Set adler to 1 in inflateReset() to support Java test suite [Walles]
98- Add contrib/dotzlib [Ravn]
99- Update win32/DLL_FAQ.txt [Truta]
100- Update contrib/minizip [Vollant]
101- Move contrib/visual-basic.txt to old/ [Truta]
102- Fix assembler builds in projects/visualc6/ [Truta]
103
104Changes in 1.2.1.2 (9 September 2004)
105- Update INDEX file
106- Fix trees.c to update strm->data_type (no one ever noticed!)
107- Fix bug in error case in inflate.c, infback.c, and infback9.c [Brown]
108- Add "volatile" to crc table flag declaration (for DYNAMIC_CRC_TABLE)
109- Add limited multitasking protection to DYNAMIC_CRC_TABLE
110- Add NO_vsnprintf for VMS in zutil.h [Mozilla]
111- Don't declare strerror() under VMS [Mozilla]
112- Add comment to DYNAMIC_CRC_TABLE to use get_crc_table() to initialize
113- Update contrib/ada [Anisimkov]
114- Update contrib/minizip [Vollant]
115- Fix configure to not hardcode directories for Darwin [Peterson]
116- Fix gzio.c to not return error on empty files [Brown]
117- Fix indentation; update version in contrib/delphi/ZLib.pas and
118 contrib/pascal/zlibpas.pas [Truta]
119- Update mkasm.bat in contrib/masmx86 [Truta]
120- Update contrib/untgz [Truta]
121- Add projects/README.projects [Truta]
122- Add project for MS Visual C++ 6.0 in projects/visualc6 [Cadieux, Truta]
123- Update win32/DLL_FAQ.txt [Truta]
124- Update list of Z_PREFIX symbols in zconf.h [Randers-Pehrson, Truta]
125- Remove an unnecessary assignment to curr in inftrees.c [Truta]
126- Add OS/2 to exe builds in configure [Poltorak]
127- Remove err dummy parameter in zlib.h [Kientzle]
128
129Changes in 1.2.1.1 (9 January 2004)
130- Update email address in README
131- Several FAQ updates
132- Fix a big fat bug in inftrees.c that prevented decoding valid
133 dynamic blocks with only literals and no distance codes --
134 Thanks to "Hot Emu" for the bug report and sample file
135- Add a note to puff.c on no distance codes case.
136
137Changes in 1.2.1 (17 November 2003)
138- Remove a tab in contrib/gzappend/gzappend.c
139- Update some interfaces in contrib for new zlib functions
140- Update zlib version number in some contrib entries
141- Add Windows CE definition for ptrdiff_t in zutil.h [Mai, Truta]
142- Support shared libraries on Hurd and KFreeBSD [Brown]
143- Fix error in NO_DIVIDE option of adler32.c
144
145Changes in 1.2.0.8 (4 November 2003)
146- Update version in contrib/delphi/ZLib.pas and contrib/pascal/zlibpas.pas
147- Add experimental NO_DIVIDE #define in adler32.c
148 - Possibly faster on some processors (let me know if it is)
149- Correct Z_BLOCK to not return on first inflate call if no wrap
150- Fix strm->data_type on inflate() return to correctly indicate EOB
151- Add deflatePrime() function for appending in the middle of a byte
152- Add contrib/gzappend for an example of appending to a stream
153- Update win32/DLL_FAQ.txt [Truta]
154- Delete Turbo C comment in README [Truta]
155- Improve some indentation in zconf.h [Truta]
156- Fix infinite loop on bad input in configure script [Church]
157- Fix gzeof() for concatenated gzip files [Johnson]
158- Add example to contrib/visual-basic.txt [Michael B.]
159- Add -p to mkdir's in Makefile.in [vda]
160- Fix configure to properly detect presence or lack of printf functions
161- Add AS400 support [Monnerat]
162- Add a little Cygwin support [Wilson]
163
164Changes in 1.2.0.7 (21 September 2003)
165- Correct some debug formats in contrib/infback9
166- Cast a type in a debug statement in trees.c
167- Change search and replace delimiter in configure from % to # [Beebe]
168- Update contrib/untgz to 0.2 with various fixes [Truta]
169- Add build support for Amiga [Nikl]
170- Remove some directories in old that have been updated to 1.2
171- Add dylib building for Mac OS X in configure and Makefile.in
172- Remove old distribution stuff from Makefile
173- Update README to point to DLL_FAQ.txt, and add comment on Mac OS X
174- Update links in README
175
176Changes in 1.2.0.6 (13 September 2003)
177- Minor FAQ updates
178- Update contrib/minizip to 1.00 [Vollant]
179- Remove test of gz functions in example.c when GZ_COMPRESS defined [Truta]
180- Update POSTINC comment for 68060 [Nikl]
181- Add contrib/infback9 with deflate64 decoding (unsupported)
182- For MVS define NO_vsnprintf and undefine FAR [van Burik]
183- Add pragma for fdopen on MVS [van Burik]
184
185Changes in 1.2.0.5 (8 September 2003)
186- Add OF to inflateBackEnd() declaration in zlib.h
187- Remember start when using gzdopen in the middle of a file
188- Use internal off_t counters in gz* functions to properly handle seeks
189- Perform more rigorous check for distance-too-far in inffast.c
190- Add Z_BLOCK flush option to return from inflate at block boundary
191- Set strm->data_type on return from inflate
192 - Indicate bits unused, if at block boundary, and if in last block
193- Replace size_t with ptrdiff_t in crc32.c, and check for correct size
194- Add condition so old NO_DEFLATE define still works for compatibility
195- FAQ update regarding the Windows DLL [Truta]
196- INDEX update: add qnx entry, remove aix entry [Truta]
197- Install zlib.3 into mandir [Wilson]
198- Move contrib/zlib_dll_FAQ.txt to win32/DLL_FAQ.txt; update [Truta]
199- Adapt the zlib interface to the new DLL convention guidelines [Truta]
200- Introduce ZLIB_WINAPI macro to allow the export of functions using
201 the WINAPI calling convention, for Visual Basic [Vollant, Truta]
202- Update msdos and win32 scripts and makefiles [Truta]
203- Export symbols by name, not by ordinal, in win32/zlib.def [Truta]
204- Add contrib/ada [Anisimkov]
205- Move asm files from contrib/vstudio/vc70_32 to contrib/asm386 [Truta]
206- Rename contrib/asm386 to contrib/masmx86 [Truta, Vollant]
207- Add contrib/masm686 [Truta]
208- Fix offsets in contrib/inflate86 and contrib/masmx86/inffas32.asm
209 [Truta, Vollant]
210- Update contrib/delphi; rename to contrib/pascal; add example [Truta]
211- Remove contrib/delphi2; add a new contrib/delphi [Truta]
212- Avoid inclusion of the nonstandard <memory.h> in contrib/iostream,
213 and fix some method prototypes [Truta]
214- Fix the ZCR_SEED2 constant to avoid warnings in contrib/minizip
215 [Truta]
216- Avoid the use of backslash (\) in contrib/minizip [Vollant]
217- Fix file time handling in contrib/untgz; update makefiles [Truta]
218- Update contrib/vstudio/vc70_32 to comply with the new DLL guidelines
219 [Vollant]
220- Remove contrib/vstudio/vc15_16 [Vollant]
221- Rename contrib/vstudio/vc70_32 to contrib/vstudio/vc7 [Truta]
222- Update README.contrib [Truta]
223- Invert the assignment order of match_head and s->prev[...] in
224 INSERT_STRING [Truta]
225- Compare TOO_FAR with 32767 instead of 32768, to avoid 16-bit warnings
226 [Truta]
227- Compare function pointers with 0, not with NULL or Z_NULL [Truta]
228- Fix prototype of syncsearch in inflate.c [Truta]
229- Introduce ASMINF macro to be enabled when using an ASM implementation
230 of inflate_fast [Truta]
231- Change NO_DEFLATE to NO_GZCOMPRESS [Truta]
232- Modify test_gzio in example.c to take a single file name as a
233 parameter [Truta]
234- Exit the example.c program if gzopen fails [Truta]
235- Add type casts around strlen in example.c [Truta]
236- Remove casting to sizeof in minigzip.c; give a proper type
237 to the variable compared with SUFFIX_LEN [Truta]
238- Update definitions of STDC and STDC99 in zconf.h [Truta]
239- Synchronize zconf.h with the new Windows DLL interface [Truta]
240- Use SYS16BIT instead of __32BIT__ to distinguish between
241 16- and 32-bit platforms [Truta]
242- Use far memory allocators in small 16-bit memory models for
243 Turbo C [Truta]
244- Add info about the use of ASMV, ASMINF and ZLIB_WINAPI in
245 zlibCompileFlags [Truta]
246- Cygwin has vsnprintf [Wilson]
247- In Windows16, OS_CODE is 0, as in MSDOS [Truta]
248- In Cygwin, OS_CODE is 3 (Unix), not 11 (Windows32) [Wilson]
249
250Changes in 1.2.0.4 (10 August 2003)
251- Minor FAQ updates
252- Be more strict when checking inflateInit2's windowBits parameter
253- Change NO_GUNZIP compile option to NO_GZIP to cover deflate as well
254- Add gzip wrapper option to deflateInit2 using windowBits
255- Add updated QNX rule in configure and qnx directory [Bonnefoy]
256- Make inflate distance-too-far checks more rigorous
257- Clean up FAR usage in inflate
258- Add casting to sizeof() in gzio.c and minigzip.c
259
260Changes in 1.2.0.3 (19 July 2003)
261- Fix silly error in gzungetc() implementation [Vollant]
262- Update contrib/minizip and contrib/vstudio [Vollant]
263- Fix printf format in example.c
264- Correct cdecl support in zconf.in.h [Anisimkov]
265- Minor FAQ updates
266
267Changes in 1.2.0.2 (13 July 2003)
268- Add ZLIB_VERNUM in zlib.h for numerical preprocessor comparisons
269- Attempt to avoid warnings in crc32.c for pointer-int conversion
270- Add AIX to configure, remove aix directory [Bakker]
271- Add some casts to minigzip.c
272- Improve checking after insecure sprintf() or vsprintf() calls
273- Remove #elif's from crc32.c
274- Change leave label to inf_leave in inflate.c and infback.c to avoid
275 library conflicts
276- Remove inflate gzip decoding by default--only enable gzip decoding by
277 special request for stricter backward compatibility
278- Add zlibCompileFlags() function to return compilation information
279- More typecasting in deflate.c to avoid warnings
280- Remove leading underscore from _Capital #defines [Truta]
281- Fix configure to link shared library when testing
282- Add some Windows CE target adjustments [Mai]
283- Remove #define ZLIB_DLL in zconf.h [Vollant]
284- Add zlib.3 [Rodgers]
285- Update RFC URL in deflate.c and algorithm.txt [Mai]
286- Add zlib_dll_FAQ.txt to contrib [Truta]
287- Add UL to some constants [Truta]
288- Update minizip and vstudio [Vollant]
289- Remove vestigial NEED_DUMMY_RETURN from zconf.in.h
290- Expand use of NO_DUMMY_DECL to avoid all dummy structures
291- Added iostream3 to contrib [Schwardt]
292- Replace rewind() with fseek() for WinCE [Truta]
293- Improve setting of zlib format compression level flags
294 - Report 0 for huffman and rle strategies and for level == 0 or 1
295 - Report 2 only for level == 6
296- Only deal with 64K limit when necessary at compile time [Truta]
297- Allow TOO_FAR check to be turned off at compile time [Truta]
298- Add gzclearerr() function [Souza]
299- Add gzungetc() function
300
301Changes in 1.2.0.1 (17 March 2003)
302- Add Z_RLE strategy for run-length encoding [Truta]
303 - When Z_RLE requested, restrict matches to distance one
304 - Update zlib.h, minigzip.c, gzopen(), gzdopen() for Z_RLE
305- Correct FASTEST compilation to allow level == 0
306- Clean up what gets compiled for FASTEST
307- Incorporate changes to zconf.in.h [Vollant]
308 - Refine detection of Turbo C need for dummy returns
309 - Refine ZLIB_DLL compilation
310 - Include additional header file on VMS for off_t typedef
311- Try to use _vsnprintf where it supplants vsprintf [Vollant]
312- Add some casts in inffast.c
313- Enchance comments in zlib.h on what happens if gzprintf() tries to
314 write more than 4095 bytes before compression
315- Remove unused state from inflateBackEnd()
316- Remove exit(0) from minigzip.c, example.c
317- Get rid of all those darn tabs
318- Add "check" target to Makefile.in that does the same thing as "test"
319- Add "mostlyclean" and "maintainer-clean" targets to Makefile.in
320- Update contrib/inflate86 [Anderson]
321- Update contrib/testzlib, contrib/vstudio, contrib/minizip [Vollant]
322- Add msdos and win32 directories with makefiles [Truta]
323- More additions and improvements to the FAQ
324
325Changes in 1.2.0 (9 March 2003)
326- New and improved inflate code
327 - About 20% faster
328 - Does not allocate 32K window unless and until needed
329 - Automatically detects and decompresses gzip streams
330 - Raw inflate no longer needs an extra dummy byte at end
331 - Added inflateBack functions using a callback interface--even faster
332 than inflate, useful for file utilities (gzip, zip)
333 - Added inflateCopy() function to record state for random access on
334 externally generated deflate streams (e.g. in gzip files)
335 - More readable code (I hope)
336- New and improved crc32()
337 - About 50% faster, thanks to suggestions from Rodney Brown
338- Add deflateBound() and compressBound() functions
339- Fix memory leak in deflateInit2()
340- Permit setting dictionary for raw deflate (for parallel deflate)
341- Fix const declaration for gzwrite()
342- Check for some malloc() failures in gzio.c
343- Fix bug in gzopen() on single-byte file 0x1f
344- Fix bug in gzread() on concatenated file with 0x1f at end of buffer
345 and next buffer doesn't start with 0x8b
346- Fix uncompress() to return Z_DATA_ERROR on truncated input
347- Free memory at end of example.c
348- Remove MAX #define in trees.c (conflicted with some libraries)
349- Fix static const's in deflate.c, gzio.c, and zutil.[ch]
350- Declare malloc() and free() in gzio.c if STDC not defined
351- Use malloc() instead of calloc() in zutil.c if int big enough
352- Define STDC for AIX
353- Add aix/ with approach for compiling shared library on AIX
354- Add HP-UX support for shared libraries in configure
355- Add OpenUNIX support for shared libraries in configure
356- Use $cc instead of gcc to build shared library
357- Make prefix directory if needed when installing
358- Correct Macintosh avoidance of typedef Byte in zconf.h
359- Correct Turbo C memory allocation when under Linux
360- Use libz.a instead of -lz in Makefile (assure use of compiled library)
361- Update configure to check for snprintf or vsnprintf functions and their
362 return value, warn during make if using an insecure function
363- Fix configure problem with compile-time knowledge of HAVE_UNISTD_H that
364 is lost when library is used--resolution is to build new zconf.h
365- Documentation improvements (in zlib.h):
366 - Document raw deflate and inflate
367 - Update RFCs URL
368 - Point out that zlib and gzip formats are different
369 - Note that Z_BUF_ERROR is not fatal
370 - Document string limit for gzprintf() and possible buffer overflow
371 - Note requirement on avail_out when flushing
372 - Note permitted values of flush parameter of inflate()
373- Add some FAQs (and even answers) to the FAQ
374- Add contrib/inflate86/ for x86 faster inflate
375- Add contrib/blast/ for PKWare Data Compression Library decompression
376- Add contrib/puff/ simple inflate for deflate format description
377
378Changes in 1.1.4 (11 March 2002)
379- ZFREE was repeated on same allocation on some error conditions.
380 This creates a security problem described in
381 http://www.zlib.org/advisory-2002-03-11.txt
382- Returned incorrect error (Z_MEM_ERROR) on some invalid data
383- Avoid accesses before window for invalid distances with inflate window
384 less than 32K.
385- force windowBits > 8 to avoid a bug in the encoder for a window size
386 of 256 bytes. (A complete fix will be available in 1.1.5).
387
388Changes in 1.1.3 (9 July 1998)
389- fix "an inflate input buffer bug that shows up on rare but persistent
390 occasions" (Mark)
391- fix gzread and gztell for concatenated .gz files (Didier Le Botlan)
392- fix gzseek(..., SEEK_SET) in write mode
393- fix crc check after a gzeek (Frank Faubert)
394- fix miniunzip when the last entry in a zip file is itself a zip file
395 (J Lillge)
396- add contrib/asm586 and contrib/asm686 (Brian Raiter)
397 See http://www.muppetlabs.com/~breadbox/software/assembly.html
398- add support for Delphi 3 in contrib/delphi (Bob Dellaca)
399- add support for C++Builder 3 and Delphi 3 in contrib/delphi2 (Davide Moretti)
400- do not exit prematurely in untgz if 0 at start of block (Magnus Holmgren)
401- use macro EXTERN instead of extern to support DLL for BeOS (Sander Stoks)
402- added a FAQ file
403
404- Support gzdopen on Mac with Metrowerks (Jason Linhart)
405- Do not redefine Byte on Mac (Brad Pettit & Jason Linhart)
406- define SEEK_END too if SEEK_SET is not defined (Albert Chin-A-Young)
407- avoid some warnings with Borland C (Tom Tanner)
408- fix a problem in contrib/minizip/zip.c for 16-bit MSDOS (Gilles Vollant)
409- emulate utime() for WIN32 in contrib/untgz (Gilles Vollant)
410- allow several arguments to configure (Tim Mooney, Frodo Looijaard)
411- use libdir and includedir in Makefile.in (Tim Mooney)
412- support shared libraries on OSF1 V4 (Tim Mooney)
413- remove so_locations in "make clean" (Tim Mooney)
414- fix maketree.c compilation error (Glenn, Mark)
415- Python interface to zlib now in Python 1.5 (Jeremy Hylton)
416- new Makefile.riscos (Rich Walker)
417- initialize static descriptors in trees.c for embedded targets (Nick Smith)
418- use "foo-gz" in example.c for RISCOS and VMS (Nick Smith)
419- add the OS/2 files in Makefile.in too (Andrew Zabolotny)
420- fix fdopen and halloc macros for Microsoft C 6.0 (Tom Lane)
421- fix maketree.c to allow clean compilation of inffixed.h (Mark)
422- fix parameter check in deflateCopy (Gunther Nikl)
423- cleanup trees.c, use compressed_len only in debug mode (Christian Spieler)
424- Many portability patches by Christian Spieler:
425 . zutil.c, zutil.h: added "const" for zmem*
426 . Make_vms.com: fixed some typos
427 . Make_vms.com: msdos/Makefile.*: removed zutil.h from some dependency lists
428 . msdos/Makefile.msc: remove "default rtl link library" info from obj files
429 . msdos/Makefile.*: use model-dependent name for the built zlib library
430 . msdos/Makefile.emx, nt/Makefile.emx, nt/Makefile.gcc:
431 new makefiles, for emx (DOS/OS2), emx&rsxnt and mingw32 (Windows 9x / NT)
432- use define instead of typedef for Bytef also for MSC small/medium (Tom Lane)
433- replace __far with _far for better portability (Christian Spieler, Tom Lane)
434- fix test for errno.h in configure (Tim Newsham)
435
436Changes in 1.1.2 (19 March 98)
437- added contrib/minzip, mini zip and unzip based on zlib (Gilles Vollant)
438 See http://www.winimage.com/zLibDll/unzip.html
439- preinitialize the inflate tables for fixed codes, to make the code
440 completely thread safe (Mark)
441- some simplifications and slight speed-up to the inflate code (Mark)
442- fix gzeof on non-compressed files (Allan Schrum)
443- add -std1 option in configure for OSF1 to fix gzprintf (Martin Mokrejs)
444- use default value of 4K for Z_BUFSIZE for 16-bit MSDOS (Tim Wegner + Glenn)
445- added os2/Makefile.def and os2/zlib.def (Andrew Zabolotny)
446- add shared lib support for UNIX_SV4.2MP (MATSUURA Takanori)
447- do not wrap extern "C" around system includes (Tom Lane)
448- mention zlib binding for TCL in README (Andreas Kupries)
449- added amiga/Makefile.pup for Amiga powerUP SAS/C PPC (Andreas Kleinert)
450- allow "make install prefix=..." even after configure (Glenn Randers-Pehrson)
451- allow "configure --prefix $HOME" (Tim Mooney)
452- remove warnings in example.c and gzio.c (Glenn Randers-Pehrson)
453- move Makefile.sas to amiga/Makefile.sas
454
455Changes in 1.1.1 (27 Feb 98)
456- fix macros _tr_tally_* in deflate.h for debug mode (Glenn Randers-Pehrson)
457- remove block truncation heuristic which had very marginal effect for zlib
458 (smaller lit_bufsize than in gzip 1.2.4) and degraded a little the
459 compression ratio on some files. This also allows inlining _tr_tally for
460 matches in deflate_slow.
461- added msdos/Makefile.w32 for WIN32 Microsoft Visual C++ (Bob Frazier)
462
463Changes in 1.1.0 (24 Feb 98)
464- do not return STREAM_END prematurely in inflate (John Bowler)
465- revert to the zlib 1.0.8 inflate to avoid the gcc 2.8.0 bug (Jeremy Buhler)
466- compile with -DFASTEST to get compression code optimized for speed only
467- in minigzip, try mmap'ing the input file first (Miguel Albrecht)
468- increase size of I/O buffers in minigzip.c and gzio.c (not a big gain
469 on Sun but significant on HP)
470
471- add a pointer to experimental unzip library in README (Gilles Vollant)
472- initialize variable gcc in configure (Chris Herborth)
473
474Changes in 1.0.9 (17 Feb 1998)
475- added gzputs and gzgets functions
476- do not clear eof flag in gzseek (Mark Diekhans)
477- fix gzseek for files in transparent mode (Mark Diekhans)
478- do not assume that vsprintf returns the number of bytes written (Jens Krinke)
479- replace EXPORT with ZEXPORT to avoid conflict with other programs
480- added compress2 in zconf.h, zlib.def, zlib.dnt
481- new asm code from Gilles Vollant in contrib/asm386
482- simplify the inflate code (Mark):
483 . Replace ZALLOC's in huft_build() with single ZALLOC in inflate_blocks_new()
484 . ZALLOC the length list in inflate_trees_fixed() instead of using stack
485 . ZALLOC the value area for huft_build() instead of using stack
486 . Simplify Z_FINISH check in inflate()
487
488- Avoid gcc 2.8.0 comparison bug a little differently than zlib 1.0.8
489- in inftrees.c, avoid cc -O bug on HP (Farshid Elahi)
490- in zconf.h move the ZLIB_DLL stuff earlier to avoid problems with
491 the declaration of FAR (Gilles VOllant)
492- install libz.so* with mode 755 (executable) instead of 644 (Marc Lehmann)
493- read_buf buf parameter of type Bytef* instead of charf*
494- zmemcpy parameters are of type Bytef*, not charf* (Joseph Strout)
495- do not redeclare unlink in minigzip.c for WIN32 (John Bowler)
496- fix check for presence of directories in "make install" (Ian Willis)
497
498Changes in 1.0.8 (27 Jan 1998)
499- fixed offsets in contrib/asm386/gvmat32.asm (Gilles Vollant)
500- fix gzgetc and gzputc for big endian systems (Markus Oberhumer)
501- added compress2() to allow setting the compression level
502- include sys/types.h to get off_t on some systems (Marc Lehmann & QingLong)
503- use constant arrays for the static trees in trees.c instead of computing
504 them at run time (thanks to Ken Raeburn for this suggestion). To create
505 trees.h, compile with GEN_TREES_H and run "make test".
506- check return code of example in "make test" and display result
507- pass minigzip command line options to file_compress
508- simplifying code of inflateSync to avoid gcc 2.8 bug
509
510- support CC="gcc -Wall" in configure -s (QingLong)
511- avoid a flush caused by ftell in gzopen for write mode (Ken Raeburn)
512- fix test for shared library support to avoid compiler warnings
513- zlib.lib -> zlib.dll in msdos/zlib.rc (Gilles Vollant)
514- check for TARGET_OS_MAC in addition to MACOS (Brad Pettit)
515- do not use fdopen for Metrowerks on Mac (Brad Pettit))
516- add checks for gzputc and gzputc in example.c
517- avoid warnings in gzio.c and deflate.c (Andreas Kleinert)
518- use const for the CRC table (Ken Raeburn)
519- fixed "make uninstall" for shared libraries
520- use Tracev instead of Trace in infblock.c
521- in example.c use correct compressed length for test_sync
522- suppress +vnocompatwarnings in configure for HPUX (not always supported)
523
524Changes in 1.0.7 (20 Jan 1998)
525- fix gzseek which was broken in write mode
526- return error for gzseek to negative absolute position
527- fix configure for Linux (Chun-Chung Chen)
528- increase stack space for MSC (Tim Wegner)
529- get_crc_table and inflateSyncPoint are EXPORTed (Gilles Vollant)
530- define EXPORTVA for gzprintf (Gilles Vollant)
531- added man page zlib.3 (Rick Rodgers)
532- for contrib/untgz, fix makedir() and improve Makefile
533
534- check gzseek in write mode in example.c
535- allocate extra buffer for seeks only if gzseek is actually called
536- avoid signed/unsigned comparisons (Tim Wegner, Gilles Vollant)
537- add inflateSyncPoint in zconf.h
538- fix list of exported functions in nt/zlib.dnt and mdsos/zlib.def
539
540Changes in 1.0.6 (19 Jan 1998)
541- add functions gzprintf, gzputc, gzgetc, gztell, gzeof, gzseek, gzrewind and
542 gzsetparams (thanks to Roland Giersig and Kevin Ruland for some of this code)
543- Fix a deflate bug occurring only with compression level 0 (thanks to
544 Andy Buckler for finding this one).
545- In minigzip, pass transparently also the first byte for .Z files.
546- return Z_BUF_ERROR instead of Z_OK if output buffer full in uncompress()
547- check Z_FINISH in inflate (thanks to Marc Schluper)
548- Implement deflateCopy (thanks to Adam Costello)
549- make static libraries by default in configure, add --shared option.
550- move MSDOS or Windows specific files to directory msdos
551- suppress the notion of partial flush to simplify the interface
552 (but the symbol Z_PARTIAL_FLUSH is kept for compatibility with 1.0.4)
553- suppress history buffer provided by application to simplify the interface
554 (this feature was not implemented anyway in 1.0.4)
555- next_in and avail_in must be initialized before calling inflateInit or
556 inflateInit2
557- add EXPORT in all exported functions (for Windows DLL)
558- added Makefile.nt (thanks to Stephen Williams)
559- added the unsupported "contrib" directory:
560 contrib/asm386/ by Gilles Vollant <info@winimage.com>
561 386 asm code replacing longest_match().
562 contrib/iostream/ by Kevin Ruland <kevin@rodin.wustl.edu>
563 A C++ I/O streams interface to the zlib gz* functions
564 contrib/iostream2/ by Tyge Løvset <Tyge.Lovset@cmr.no>
565 Another C++ I/O streams interface
566 contrib/untgz/ by "Pedro A. Aranda Guti\irrez" <paag@tid.es>
567 A very simple tar.gz file extractor using zlib
568 contrib/visual-basic.txt by Carlos Rios <c_rios@sonda.cl>
569 How to use compress(), uncompress() and the gz* functions from VB.
570- pass params -f (filtered data), -h (huffman only), -1 to -9 (compression
571 level) in minigzip (thanks to Tom Lane)
572
573- use const for rommable constants in deflate
574- added test for gzseek and gztell in example.c
575- add undocumented function inflateSyncPoint() (hack for Paul Mackerras)
576- add undocumented function zError to convert error code to string
577 (for Tim Smithers)
578- Allow compilation of gzio with -DNO_DEFLATE to avoid the compression code.
579- Use default memcpy for Symantec MSDOS compiler.
580- Add EXPORT keyword for check_func (needed for Windows DLL)
581- add current directory to LD_LIBRARY_PATH for "make test"
582- create also a link for libz.so.1
583- added support for FUJITSU UXP/DS (thanks to Toshiaki Nomura)
584- use $(SHAREDLIB) instead of libz.so in Makefile.in (for HPUX)
585- added -soname for Linux in configure (Chun-Chung Chen,
586- assign numbers to the exported functions in zlib.def (for Windows DLL)
587- add advice in zlib.h for best usage of deflateSetDictionary
588- work around compiler bug on Atari (cast Z_NULL in call of s->checkfn)
589- allow compilation with ANSI keywords only enabled for TurboC in large model
590- avoid "versionString"[0] (Borland bug)
591- add NEED_DUMMY_RETURN for Borland
592- use variable z_verbose for tracing in debug mode (L. Peter Deutsch).
593- allow compilation with CC
594- defined STDC for OS/2 (David Charlap)
595- limit external names to 8 chars for MVS (Thomas Lund)
596- in minigzip.c, use static buffers only for 16-bit systems
597- fix suffix check for "minigzip -d foo.gz"
598- do not return an error for the 2nd of two consecutive gzflush() (Felix Lee)
599- use _fdopen instead of fdopen for MSC >= 6.0 (Thomas Fanslau)
600- added makelcc.bat for lcc-win32 (Tom St Denis)
601- in Makefile.dj2, use copy and del instead of install and rm (Frank Donahoe)
602- Avoid expanded $Id$. Use "rcs -kb" or "cvs admin -kb" to avoid Id expansion.
603- check for unistd.h in configure (for off_t)
604- remove useless check parameter in inflate_blocks_free
605- avoid useless assignment of s->check to itself in inflate_blocks_new
606- do not flush twice in gzclose (thanks to Ken Raeburn)
607- rename FOPEN as F_OPEN to avoid clash with /usr/include/sys/file.h
608- use NO_ERRNO_H instead of enumeration of operating systems with errno.h
609- work around buggy fclose on pipes for HP/UX
610- support zlib DLL with BORLAND C++ 5.0 (thanks to Glenn Randers-Pehrson)
611- fix configure if CC is already equal to gcc
612
613Changes in 1.0.5 (3 Jan 98)
614- Fix inflate to terminate gracefully when fed corrupted or invalid data
615- Use const for rommable constants in inflate
616- Eliminate memory leaks on error conditions in inflate
617- Removed some vestigial code in inflate
618- Update web address in README
619
620Changes in 1.0.4 (24 Jul 96)
621- In very rare conditions, deflate(s, Z_FINISH) could fail to produce an EOF
622 bit, so the decompressor could decompress all the correct data but went
623 on to attempt decompressing extra garbage data. This affected minigzip too.
624- zlibVersion and gzerror return const char* (needed for DLL)
625- port to RISCOS (no fdopen, no multiple dots, no unlink, no fileno)
626- use z_error only for DEBUG (avoid problem with DLLs)
627
628Changes in 1.0.3 (2 Jul 96)
629- use z_streamp instead of z_stream *, which is now a far pointer in MSDOS
630 small and medium models; this makes the library incompatible with previous
631 versions for these models. (No effect in large model or on other systems.)
632- return OK instead of BUF_ERROR if previous deflate call returned with
633 avail_out as zero but there is nothing to do
634- added memcmp for non STDC compilers
635- define NO_DUMMY_DECL for more Mac compilers (.h files merged incorrectly)
636- define __32BIT__ if __386__ or i386 is defined (pb. with Watcom and SCO)
637- better check for 16-bit mode MSC (avoids problem with Symantec)
638
639Changes in 1.0.2 (23 May 96)
640- added Windows DLL support
641- added a function zlibVersion (for the DLL support)
642- fixed declarations using Bytef in infutil.c (pb with MSDOS medium model)
643- Bytef is define's instead of typedef'd only for Borland C
644- avoid reading uninitialized memory in example.c
645- mention in README that the zlib format is now RFC1950
646- updated Makefile.dj2
647- added algorithm.doc
648
649Changes in 1.0.1 (20 May 96) [1.0 skipped to avoid confusion]
650- fix array overlay in deflate.c which sometimes caused bad compressed data
651- fix inflate bug with empty stored block
652- fix MSDOS medium model which was broken in 0.99
653- fix deflateParams() which could generated bad compressed data.
654- Bytef is define'd instead of typedef'ed (work around Borland bug)
655- added an INDEX file
656- new makefiles for DJGPP (Makefile.dj2), 32-bit Borland (Makefile.b32),
657 Watcom (Makefile.wat), Amiga SAS/C (Makefile.sas)
658- speed up adler32 for modern machines without auto-increment
659- added -ansi for IRIX in configure
660- static_init_done in trees.c is an int
661- define unlink as delete for VMS
662- fix configure for QNX
663- add configure branch for SCO and HPUX
664- avoid many warnings (unused variables, dead assignments, etc...)
665- no fdopen for BeOS
666- fix the Watcom fix for 32 bit mode (define FAR as empty)
667- removed redefinition of Byte for MKWERKS
668- work around an MWKERKS bug (incorrect merge of all .h files)
669
670Changes in 0.99 (27 Jan 96)
671- allow preset dictionary shared between compressor and decompressor
672- allow compression level 0 (no compression)
673- add deflateParams in zlib.h: allow dynamic change of compression level
674 and compression strategy.
675- test large buffers and deflateParams in example.c
676- add optional "configure" to build zlib as a shared library
677- suppress Makefile.qnx, use configure instead
678- fixed deflate for 64-bit systems (detected on Cray)
679- fixed inflate_blocks for 64-bit systems (detected on Alpha)
680- declare Z_DEFLATED in zlib.h (possible parameter for deflateInit2)
681- always return Z_BUF_ERROR when deflate() has nothing to do
682- deflateInit and inflateInit are now macros to allow version checking
683- prefix all global functions and types with z_ with -DZ_PREFIX
684- make falloc completely reentrant (inftrees.c)
685- fixed very unlikely race condition in ct_static_init
686- free in reverse order of allocation to help memory manager
687- use zlib-1.0/* instead of zlib/* inside the tar.gz
688- make zlib warning-free with "gcc -O3 -Wall -Wwrite-strings -Wpointer-arith
689 -Wconversion -Wstrict-prototypes -Wmissing-prototypes"
690- allow gzread on concatenated .gz files
691- deflateEnd now returns Z_DATA_ERROR if it was premature
692- deflate is finally (?) fully deterministic (no matches beyond end of input)
693- Document Z_SYNC_FLUSH
694- add uninstall in Makefile
695- Check for __cpluplus in zlib.h
696- Better test in ct_align for partial flush
697- avoid harmless warnings for Borland C++
698- initialize hash_head in deflate.c
699- avoid warning on fdopen (gzio.c) for HP cc -Aa
700- include stdlib.h for STDC compilers
701- include errno.h for Cray
702- ignore error if ranlib doesn't exist
703- call ranlib twice for NeXTSTEP
704- use exec_prefix instead of prefix for libz.a
705- renamed ct_* as _tr_* to avoid conflict with applications
706- clear z->msg in inflateInit2 before any error return
707- initialize opaque in example.c, gzio.c, deflate.c and inflate.c
708- fixed typo in zconf.h (_GNUC__ => __GNUC__)
709- check for WIN32 in zconf.h and zutil.c (avoid farmalloc in 32-bit mode)
710- fix typo in Make_vms.com (f$trnlnm -> f$getsyi)
711- in fcalloc, normalize pointer if size > 65520 bytes
712- don't use special fcalloc for 32 bit Borland C++
713- use STDC instead of __GO32__ to avoid redeclaring exit, calloc, etc...
714- use Z_BINARY instead of BINARY
715- document that gzclose after gzdopen will close the file
716- allow "a" as mode in gzopen.
717- fix error checking in gzread
718- allow skipping .gz extra-field on pipes
719- added reference to Perl interface in README
720- put the crc table in FAR data (I dislike more and more the medium model :)
721- added get_crc_table
722- added a dimension to all arrays (Borland C can't count).
723- workaround Borland C bug in declaration of inflate_codes_new & inflate_fast
724- guard against multiple inclusion of *.h (for precompiled header on Mac)
725- Watcom C pretends to be Microsoft C small model even in 32 bit mode.
726- don't use unsized arrays to avoid silly warnings by Visual C++:
727 warning C4746: 'inflate_mask' : unsized array treated as '__far'
728 (what's wrong with far data in far model?).
729- define enum out of inflate_blocks_state to allow compilation with C++
730
731Changes in 0.95 (16 Aug 95)
732- fix MSDOS small and medium model (now easier to adapt to any compiler)
733- inlined send_bits
734- fix the final (:-) bug for deflate with flush (output was correct but
735 not completely flushed in rare occasions).
736- default window size is same for compression and decompression
737 (it's now sufficient to set MAX_WBITS in zconf.h).
738- voidp -> voidpf and voidnp -> voidp (for consistency with other
739 typedefs and because voidnp was not near in large model).
740
741Changes in 0.94 (13 Aug 95)
742- support MSDOS medium model
743- fix deflate with flush (could sometimes generate bad output)
744- fix deflateReset (zlib header was incorrectly suppressed)
745- added support for VMS
746- allow a compression level in gzopen()
747- gzflush now calls fflush
748- For deflate with flush, flush even if no more input is provided.
749- rename libgz.a as libz.a
750- avoid complex expression in infcodes.c triggering Turbo C bug
751- work around a problem with gcc on Alpha (in INSERT_STRING)
752- don't use inline functions (problem with some gcc versions)
753- allow renaming of Byte, uInt, etc... with #define.
754- avoid warning about (unused) pointer before start of array in deflate.c
755- avoid various warnings in gzio.c, example.c, infblock.c, adler32.c, zutil.c
756- avoid reserved word 'new' in trees.c
757
758Changes in 0.93 (25 June 95)
759- temporarily disable inline functions
760- make deflate deterministic
761- give enough lookahead for PARTIAL_FLUSH
762- Set binary mode for stdin/stdout in minigzip.c for OS/2
763- don't even use signed char in inflate (not portable enough)
764- fix inflate memory leak for segmented architectures
765
766Changes in 0.92 (3 May 95)
767- don't assume that char is signed (problem on SGI)
768- Clear bit buffer when starting a stored block
769- no memcpy on Pyramid
770- suppressed inftest.c
771- optimized fill_window, put longest_match inline for gcc
772- optimized inflate on stored blocks.
773- untabify all sources to simplify patches
774
775Changes in 0.91 (2 May 95)
776- Default MEM_LEVEL is 8 (not 9 for Unix) as documented in zlib.h
777- Document the memory requirements in zconf.h
778- added "make install"
779- fix sync search logic in inflateSync
780- deflate(Z_FULL_FLUSH) now works even if output buffer too short
781- after inflateSync, don't scare people with just "lo world"
782- added support for DJGPP
783
784Changes in 0.9 (1 May 95)
785- don't assume that zalloc clears the allocated memory (the TurboC bug
786 was Mark's bug after all :)
787- let again gzread copy uncompressed data unchanged (was working in 0.71)
788- deflate(Z_FULL_FLUSH), inflateReset and inflateSync are now fully implemented
789- added a test of inflateSync in example.c
790- moved MAX_WBITS to zconf.h because users might want to change that.
791- document explicitly that zalloc(64K) on MSDOS must return a normalized
792 pointer (zero offset)
793- added Makefiles for Microsoft C, Turbo C, Borland C++
794- faster crc32()
795
796Changes in 0.8 (29 April 95)
797- added fast inflate (inffast.c)
798- deflate(Z_FINISH) now returns Z_STREAM_END when done. Warning: this
799 is incompatible with previous versions of zlib which returned Z_OK.
800- work around a TurboC compiler bug (bad code for b << 0, see infutil.h)
801 (actually that was not a compiler bug, see 0.81 above)
802- gzread no longer reads one extra byte in certain cases
803- In gzio destroy(), don't reference a freed structure
804- avoid many warnings for MSDOS
805- avoid the ERROR symbol which is used by MS Windows
806
807Changes in 0.71 (14 April 95)
808- Fixed more MSDOS compilation problems :( There is still a bug with
809 TurboC large model.
810
811Changes in 0.7 (14 April 95)
812- Added full inflate support.
813- Simplified the crc32() interface. The pre- and post-conditioning
814 (one's complement) is now done inside crc32(). WARNING: this is
815 incompatible with previous versions; see zlib.h for the new usage.
816
817Changes in 0.61 (12 April 95)
818- workaround for a bug in TurboC. example and minigzip now work on MSDOS.
819
820Changes in 0.6 (11 April 95)
821- added minigzip.c
822- added gzdopen to reopen a file descriptor as gzFile
823- added transparent reading of non-gziped files in gzread.
824- fixed bug in gzread (don't read crc as data)
825- fixed bug in destroy (gzio.c) (don't return Z_STREAM_END for gzclose).
826- don't allocate big arrays in the stack (for MSDOS)
827- fix some MSDOS compilation problems
828
829Changes in 0.5:
830- do real compression in deflate.c. Z_PARTIAL_FLUSH is supported but
831 not yet Z_FULL_FLUSH.
832- support decompression but only in a single step (forced Z_FINISH)
833- added opaque object for zalloc and zfree.
834- added deflateReset and inflateReset
835- added a variable zlib_version for consistency checking.
836- renamed the 'filter' parameter of deflateInit2 as 'strategy'.
837 Added Z_FILTERED and Z_HUFFMAN_ONLY constants.
838
839Changes in 0.4:
840- avoid "zip" everywhere, use zlib instead of ziplib.
841- suppress Z_BLOCK_FLUSH, interpret Z_PARTIAL_FLUSH as block flush
842 if compression method == 8.
843- added adler32 and crc32
844- renamed deflateOptions as deflateInit2, call one or the other but not both
845- added the method parameter for deflateInit2.
846- added inflateInit2
847- simplied considerably deflateInit and inflateInit by not supporting
848 user-provided history buffer. This is supported only in deflateInit2
849 and inflateInit2.
850
851Changes in 0.3:
852- prefix all macro names with Z_
853- use Z_FINISH instead of deflateEnd to finish compression.
854- added Z_HUFFMAN_ONLY
855- added gzerror()
diff --git a/utils/zenutils/libraries/zlib123/zlib/FAQ b/utils/zenutils/libraries/zlib123/zlib/FAQ
new file mode 100755
index 0000000000..15d043615e
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/FAQ
@@ -0,0 +1,339 @@
1
2 Frequently Asked Questions about zlib
3
4
5If your question is not there, please check the zlib home page
6http://www.zlib.org which may have more recent information.
7The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html
8
9
10 1. Is zlib Y2K-compliant?
11
12 Yes. zlib doesn't handle dates.
13
14 2. Where can I get a Windows DLL version?
15
16 The zlib sources can be compiled without change to produce a DLL.
17 See the file win32/DLL_FAQ.txt in the zlib distribution.
18 Pointers to the precompiled DLL are found in the zlib web site at
19 http://www.zlib.org.
20
21 3. Where can I get a Visual Basic interface to zlib?
22
23 See
24 * http://www.dogma.net/markn/articles/zlibtool/zlibtool.htm
25 * contrib/visual-basic.txt in the zlib distribution
26 * win32/DLL_FAQ.txt in the zlib distribution
27
28 4. compress() returns Z_BUF_ERROR.
29
30 Make sure that before the call of compress, the length of the compressed
31 buffer is equal to the total size of the compressed buffer and not
32 zero. For Visual Basic, check that this parameter is passed by reference
33 ("as any"), not by value ("as long").
34
35 5. deflate() or inflate() returns Z_BUF_ERROR.
36
37 Before making the call, make sure that avail_in and avail_out are not
38 zero. When setting the parameter flush equal to Z_FINISH, also make sure
39 that avail_out is big enough to allow processing all pending input.
40 Note that a Z_BUF_ERROR is not fatal--another call to deflate() or
41 inflate() can be made with more input or output space. A Z_BUF_ERROR
42 may in fact be unavoidable depending on how the functions are used, since
43 it is not possible to tell whether or not there is more output pending
44 when strm.avail_out returns with zero.
45
46 6. Where's the zlib documentation (man pages, etc.)?
47
48 It's in zlib.h for the moment, and Francis S. Lin has converted it to a
49 web page zlib.html. Volunteers to transform this to Unix-style man pages,
50 please contact us (zlib@gzip.org). Examples of zlib usage are in the files
51 example.c and minigzip.c.
52
53 7. Why don't you use GNU autoconf or libtool or ...?
54
55 Because we would like to keep zlib as a very small and simple
56 package. zlib is rather portable and doesn't need much configuration.
57
58 8. I found a bug in zlib.
59
60 Most of the time, such problems are due to an incorrect usage of
61 zlib. Please try to reproduce the problem with a small program and send
62 the corresponding source to us at zlib@gzip.org . Do not send
63 multi-megabyte data files without prior agreement.
64
65 9. Why do I get "undefined reference to gzputc"?
66
67 If "make test" produces something like
68
69 example.o(.text+0x154): undefined reference to `gzputc'
70
71 check that you don't have old files libz.* in /usr/lib, /usr/local/lib or
72 /usr/X11R6/lib. Remove any old versions, then do "make install".
73
7410. I need a Delphi interface to zlib.
75
76 See the contrib/delphi directory in the zlib distribution.
77
7811. Can zlib handle .zip archives?
79
80 Not by itself, no. See the directory contrib/minizip in the zlib
81 distribution.
82
8312. Can zlib handle .Z files?
84
85 No, sorry. You have to spawn an uncompress or gunzip subprocess, or adapt
86 the code of uncompress on your own.
87
8813. How can I make a Unix shared library?
89
90 make clean
91 ./configure -s
92 make
93
9414. How do I install a shared zlib library on Unix?
95
96 After the above, then:
97
98 make install
99
100 However, many flavors of Unix come with a shared zlib already installed.
101 Before going to the trouble of compiling a shared version of zlib and
102 trying to install it, you may want to check if it's already there! If you
103 can #include <zlib.h>, it's there. The -lz option will probably link to it.
104
10515. I have a question about OttoPDF.
106
107 We are not the authors of OttoPDF. The real author is on the OttoPDF web
108 site: Joel Hainley, jhainley@myndkryme.com.
109
11016. Can zlib decode Flate data in an Adobe PDF file?
111
112 Yes. See http://www.fastio.com/ (ClibPDF), or http://www.pdflib.com/ .
113 To modify PDF forms, see http://sourceforge.net/projects/acroformtool/ .
114
11517. Why am I getting this "register_frame_info not found" error on Solaris?
116
117 After installing zlib 1.1.4 on Solaris 2.6, running applications using zlib
118 generates an error such as:
119
120 ld.so.1: rpm: fatal: relocation error: file /usr/local/lib/libz.so:
121 symbol __register_frame_info: referenced symbol not found
122
123 The symbol __register_frame_info is not part of zlib, it is generated by
124 the C compiler (cc or gcc). You must recompile applications using zlib
125 which have this problem. This problem is specific to Solaris. See
126 http://www.sunfreeware.com for Solaris versions of zlib and applications
127 using zlib.
128
12918. Why does gzip give an error on a file I make with compress/deflate?
130
131 The compress and deflate functions produce data in the zlib format, which
132 is different and incompatible with the gzip format. The gz* functions in
133 zlib on the other hand use the gzip format. Both the zlib and gzip
134 formats use the same compressed data format internally, but have different
135 headers and trailers around the compressed data.
136
13719. Ok, so why are there two different formats?
138
139 The gzip format was designed to retain the directory information about
140 a single file, such as the name and last modification date. The zlib
141 format on the other hand was designed for in-memory and communication
142 channel applications, and has a much more compact header and trailer and
143 uses a faster integrity check than gzip.
144
14520. Well that's nice, but how do I make a gzip file in memory?
146
147 You can request that deflate write the gzip format instead of the zlib
148 format using deflateInit2(). You can also request that inflate decode
149 the gzip format using inflateInit2(). Read zlib.h for more details.
150
15121. Is zlib thread-safe?
152
153 Yes. However any library routines that zlib uses and any application-
154 provided memory allocation routines must also be thread-safe. zlib's gz*
155 functions use stdio library routines, and most of zlib's functions use the
156 library memory allocation routines by default. zlib's Init functions allow
157 for the application to provide custom memory allocation routines.
158
159 Of course, you should only operate on any given zlib or gzip stream from a
160 single thread at a time.
161
16222. Can I use zlib in my commercial application?
163
164 Yes. Please read the license in zlib.h.
165
16623. Is zlib under the GNU license?
167
168 No. Please read the license in zlib.h.
169
17024. The license says that altered source versions must be "plainly marked". So
171 what exactly do I need to do to meet that requirement?
172
173 You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h. In
174 particular, the final version number needs to be changed to "f", and an
175 identification string should be appended to ZLIB_VERSION. Version numbers
176 x.x.x.f are reserved for modifications to zlib by others than the zlib
177 maintainers. For example, if the version of the base zlib you are altering
178 is "1.2.3.4", then in zlib.h you should change ZLIB_VERNUM to 0x123f, and
179 ZLIB_VERSION to something like "1.2.3.f-zachary-mods-v3". You can also
180 update the version strings in deflate.c and inftrees.c.
181
182 For altered source distributions, you should also note the origin and
183 nature of the changes in zlib.h, as well as in ChangeLog and README, along
184 with the dates of the alterations. The origin should include at least your
185 name (or your company's name), and an email address to contact for help or
186 issues with the library.
187
188 Note that distributing a compiled zlib library along with zlib.h and
189 zconf.h is also a source distribution, and so you should change
190 ZLIB_VERSION and ZLIB_VERNUM and note the origin and nature of the changes
191 in zlib.h as you would for a full source distribution.
192
19325. Will zlib work on a big-endian or little-endian architecture, and can I
194 exchange compressed data between them?
195
196 Yes and yes.
197
19826. Will zlib work on a 64-bit machine?
199
200 It should. It has been tested on 64-bit machines, and has no dependence
201 on any data types being limited to 32-bits in length. If you have any
202 difficulties, please provide a complete problem report to zlib@gzip.org
203
20427. Will zlib decompress data from the PKWare Data Compression Library?
205
206 No. The PKWare DCL uses a completely different compressed data format
207 than does PKZIP and zlib. However, you can look in zlib's contrib/blast
208 directory for a possible solution to your problem.
209
21028. Can I access data randomly in a compressed stream?
211
212 No, not without some preparation. If when compressing you periodically
213 use Z_FULL_FLUSH, carefully write all the pending data at those points,
214 and keep an index of those locations, then you can start decompression
215 at those points. You have to be careful to not use Z_FULL_FLUSH too
216 often, since it can significantly degrade compression.
217
21829. Does zlib work on MVS, OS/390, CICS, etc.?
219
220 We don't know for sure. We have heard occasional reports of success on
221 these systems. If you do use it on one of these, please provide us with
222 a report, instructions, and patches that we can reference when we get
223 these questions. Thanks.
224
22530. Is there some simpler, easier to read version of inflate I can look at
226 to understand the deflate format?
227
228 First off, you should read RFC 1951. Second, yes. Look in zlib's
229 contrib/puff directory.
230
23131. Does zlib infringe on any patents?
232
233 As far as we know, no. In fact, that was originally the whole point behind
234 zlib. Look here for some more information:
235
236 http://www.gzip.org/#faq11
237
23832. Can zlib work with greater than 4 GB of data?
239
240 Yes. inflate() and deflate() will process any amount of data correctly.
241 Each call of inflate() or deflate() is limited to input and output chunks
242 of the maximum value that can be stored in the compiler's "unsigned int"
243 type, but there is no limit to the number of chunks. Note however that the
244 strm.total_in and strm_total_out counters may be limited to 4 GB. These
245 counters are provided as a convenience and are not used internally by
246 inflate() or deflate(). The application can easily set up its own counters
247 updated after each call of inflate() or deflate() to count beyond 4 GB.
248 compress() and uncompress() may be limited to 4 GB, since they operate in a
249 single call. gzseek() and gztell() may be limited to 4 GB depending on how
250 zlib is compiled. See the zlibCompileFlags() function in zlib.h.
251
252 The word "may" appears several times above since there is a 4 GB limit
253 only if the compiler's "long" type is 32 bits. If the compiler's "long"
254 type is 64 bits, then the limit is 16 exabytes.
255
25633. Does zlib have any security vulnerabilities?
257
258 The only one that we are aware of is potentially in gzprintf(). If zlib
259 is compiled to use sprintf() or vsprintf(), then there is no protection
260 against a buffer overflow of a 4K string space, other than the caller of
261 gzprintf() assuring that the output will not exceed 4K. On the other
262 hand, if zlib is compiled to use snprintf() or vsnprintf(), which should
263 normally be the case, then there is no vulnerability. The ./configure
264 script will display warnings if an insecure variation of sprintf() will
265 be used by gzprintf(). Also the zlibCompileFlags() function will return
266 information on what variant of sprintf() is used by gzprintf().
267
268 If you don't have snprintf() or vsnprintf() and would like one, you can
269 find a portable implementation here:
270
271 http://www.ijs.si/software/snprintf/
272
273 Note that you should be using the most recent version of zlib. Versions
274 1.1.3 and before were subject to a double-free vulnerability.
275
27634. Is there a Java version of zlib?
277
278 Probably what you want is to use zlib in Java. zlib is already included
279 as part of the Java SDK in the java.util.zip package. If you really want
280 a version of zlib written in the Java language, look on the zlib home
281 page for links: http://www.zlib.org/
282
28335. I get this or that compiler or source-code scanner warning when I crank it
284 up to maximally-pedantic. Can't you guys write proper code?
285
286 Many years ago, we gave up attempting to avoid warnings on every compiler
287 in the universe. It just got to be a waste of time, and some compilers
288 were downright silly. So now, we simply make sure that the code always
289 works.
290
29136. Valgrind (or some similar memory access checker) says that deflate is
292 performing a conditional jump that depends on an uninitialized value.
293 Isn't that a bug?
294
295 No. That is intentional for performance reasons, and the output of
296 deflate is not affected. This only started showing up recently since
297 zlib 1.2.x uses malloc() by default for allocations, whereas earlier
298 versions used calloc(), which zeros out the allocated memory.
299
30037. Will zlib read the (insert any ancient or arcane format here) compressed
301 data format?
302
303 Probably not. Look in the comp.compression FAQ for pointers to various
304 formats and associated software.
305
30638. How can I encrypt/decrypt zip files with zlib?
307
308 zlib doesn't support encryption. The original PKZIP encryption is very weak
309 and can be broken with freely available programs. To get strong encryption,
310 use GnuPG, http://www.gnupg.org/ , which already includes zlib compression.
311 For PKZIP compatible "encryption", look at http://www.info-zip.org/
312
31339. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings?
314
315 "gzip" is the gzip format, and "deflate" is the zlib format. They should
316 probably have called the second one "zlib" instead to avoid confusion
317 with the raw deflate compressed data format. While the HTTP 1.1 RFC 2616
318 correctly points to the zlib specification in RFC 1950 for the "deflate"
319 transfer encoding, there have been reports of servers and browsers that
320 incorrectly produce or expect raw deflate data per the deflate
321 specficiation in RFC 1951, most notably Microsoft. So even though the
322 "deflate" transfer encoding using the zlib format would be the more
323 efficient approach (and in fact exactly what the zlib format was designed
324 for), using the "gzip" transfer encoding is probably more reliable due to
325 an unfortunate choice of name on the part of the HTTP 1.1 authors.
326
327 Bottom line: use the gzip format for HTTP 1.1 encoding.
328
32940. Does zlib support the new "Deflate64" format introduced by PKWare?
330
331 No. PKWare has apparently decided to keep that format proprietary, since
332 they have not documented it as they have previous compression formats.
333 In any case, the compression improvements are so modest compared to other
334 more modern approaches, that it's not worth the effort to implement.
335
33641. Can you please sign these lengthy legal documents and fax them back to us
337 so that we can use your software in our product?
338
339 No. Go away. Shoo.
diff --git a/utils/zenutils/libraries/zlib123/zlib/INDEX b/utils/zenutils/libraries/zlib123/zlib/INDEX
new file mode 100755
index 0000000000..4d7eac44bc
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/INDEX
@@ -0,0 +1,51 @@
1ChangeLog history of changes
2FAQ Frequently Asked Questions about zlib
3INDEX this file
4Makefile makefile for Unix (generated by configure)
5Makefile.in makefile for Unix (template for configure)
6README guess what
7algorithm.txt description of the (de)compression algorithm
8configure configure script for Unix
9zconf.in.h template for zconf.h (used by configure)
10
11amiga/ makefiles for Amiga SAS C
12as400/ makefiles for IBM AS/400
13msdos/ makefiles for MSDOS
14old/ makefiles for various architectures and zlib documentation
15 files that have not yet been updated for zlib 1.2.x
16projects/ projects for various Integrated Development Environments
17qnx/ makefiles for QNX
18win32/ makefiles for Windows
19
20 zlib public header files (must be kept):
21zconf.h
22zlib.h
23
24 private source files used to build the zlib library:
25adler32.c
26compress.c
27crc32.c
28crc32.h
29deflate.c
30deflate.h
31gzio.c
32infback.c
33inffast.c
34inffast.h
35inffixed.h
36inflate.c
37inflate.h
38inftrees.c
39inftrees.h
40trees.c
41trees.h
42uncompr.c
43zutil.c
44zutil.h
45
46 source files for sample programs:
47example.c
48minigzip.c
49
50 unsupported contribution by third parties
51See contrib/README.contrib
diff --git a/utils/zenutils/libraries/zlib123/zlib/Makefile b/utils/zenutils/libraries/zlib123/zlib/Makefile
new file mode 100755
index 0000000000..a4954c8f97
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/Makefile
@@ -0,0 +1,154 @@
1# Makefile for zlib
2# Copyright (C) 1995-2005 Jean-loup Gailly.
3# For conditions of distribution and use, see copyright notice in zlib.h
4
5# To compile and test, type:
6# ./configure; make test
7# The call of configure is optional if you don't have special requirements
8# If you wish to build zlib as a shared library, use: ./configure -s
9
10# To use the asm code, type:
11# cp contrib/asm?86/match.S ./match.S
12# make LOC=-DASMV OBJA=match.o
13
14# To install /usr/local/lib/libz.* and /usr/local/include/zlib.h, type:
15# make install
16# To install in $HOME instead of /usr/local, use:
17# make install prefix=$HOME
18
19CC=cc
20
21CFLAGS=-O
22#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7
23#CFLAGS=-g -DDEBUG
24#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \
25# -Wstrict-prototypes -Wmissing-prototypes
26
27LDFLAGS=libz.a
28LDSHARED=$(CC)
29CPP=$(CC) -E
30
31LIBS=libz.a
32SHAREDLIB=libz.so
33SHAREDLIBV=libz.so.1.2.3
34SHAREDLIBM=libz.so.1
35
36AR=ar rc
37RANLIB=ranlib
38TAR=tar
39SHELL=/bin/sh
40EXE=
41
42prefix = /usr/local
43exec_prefix = ${prefix}
44libdir = ${exec_prefix}/lib
45includedir = ${prefix}/include
46mandir = ${prefix}/share/man
47man3dir = ${mandir}/man3
48
49OBJS = adler32.o compress.o crc32.o gzio.o uncompr.o deflate.o trees.o \
50 zutil.o inflate.o infback.o inftrees.o inffast.o
51
52OBJA =
53# to use the asm code: make OBJA=match.o
54
55TEST_OBJS = example.o minigzip.o
56
57all: example$(EXE) minigzip$(EXE)
58
59check: test
60test: all
61 @LD_LIBRARY_PATH=.:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \
62 echo hello world | ./minigzip | ./minigzip -d || \
63 echo ' *** minigzip test FAILED ***' ; \
64 if ./example; then \
65 echo ' *** zlib test OK ***'; \
66 else \
67 echo ' *** zlib test FAILED ***'; \
68 fi
69
70libz.a: $(OBJS) $(OBJA)
71 $(AR) $@ $(OBJS) $(OBJA)
72 -@ ($(RANLIB) $@ || true) >/dev/null 2>&1
73
74match.o: match.S
75 $(CPP) match.S > _match.s
76 $(CC) -c _match.s
77 mv _match.o match.o
78 rm -f _match.s
79
80$(SHAREDLIBV): $(OBJS)
81 $(LDSHARED) -o $@ $(OBJS)
82 rm -f $(SHAREDLIB) $(SHAREDLIBM)
83 ln -s $@ $(SHAREDLIB)
84 ln -s $@ $(SHAREDLIBM)
85
86example$(EXE): example.o $(LIBS)
87 $(CC) $(CFLAGS) -o $@ example.o $(LDFLAGS)
88
89minigzip$(EXE): minigzip.o $(LIBS)
90 $(CC) $(CFLAGS) -o $@ minigzip.o $(LDFLAGS)
91
92install: $(LIBS)
93 -@if [ ! -d $(exec_prefix) ]; then mkdir -p $(exec_prefix); fi
94 -@if [ ! -d $(includedir) ]; then mkdir -p $(includedir); fi
95 -@if [ ! -d $(libdir) ]; then mkdir -p $(libdir); fi
96 -@if [ ! -d $(man3dir) ]; then mkdir -p $(man3dir); fi
97 cp zlib.h zconf.h $(includedir)
98 chmod 644 $(includedir)/zlib.h $(includedir)/zconf.h
99 cp $(LIBS) $(libdir)
100 cd $(libdir); chmod 755 $(LIBS)
101 -@(cd $(libdir); $(RANLIB) libz.a || true) >/dev/null 2>&1
102 cd $(libdir); if test -f $(SHAREDLIBV); then \
103 rm -f $(SHAREDLIB) $(SHAREDLIBM); \
104 ln -s $(SHAREDLIBV) $(SHAREDLIB); \
105 ln -s $(SHAREDLIBV) $(SHAREDLIBM); \
106 (ldconfig || true) >/dev/null 2>&1; \
107 fi
108 cp zlib.3 $(man3dir)
109 chmod 644 $(man3dir)/zlib.3
110# The ranlib in install is needed on NeXTSTEP which checks file times
111# ldconfig is for Linux
112
113uninstall:
114 cd $(includedir); \
115 cd $(libdir); rm -f libz.a; \
116 if test -f $(SHAREDLIBV); then \
117 rm -f $(SHAREDLIBV) $(SHAREDLIB) $(SHAREDLIBM); \
118 fi
119 cd $(man3dir); rm -f zlib.3
120
121mostlyclean: clean
122clean:
123 rm -f *.o *~ example$(EXE) minigzip$(EXE) \
124 libz.* foo.gz so_locations \
125 _match.s maketree contrib/infback9/*.o
126
127maintainer-clean: distclean
128distclean: clean
129 cp -p Makefile.in Makefile
130 cp -p zconf.in.h zconf.h
131 rm -f .DS_Store
132
133tags:
134 etags *.[ch]
135
136depend:
137 makedepend -- $(CFLAGS) -- *.[ch]
138
139# DO NOT DELETE THIS LINE -- make depend depends on it.
140
141adler32.o: zlib.h zconf.h
142compress.o: zlib.h zconf.h
143crc32.o: crc32.h zlib.h zconf.h
144deflate.o: deflate.h zutil.h zlib.h zconf.h
145example.o: zlib.h zconf.h
146gzio.o: zutil.h zlib.h zconf.h
147inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
148inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
149infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
150inftrees.o: zutil.h zlib.h zconf.h inftrees.h
151minigzip.o: zlib.h zconf.h
152trees.o: deflate.h zutil.h zlib.h zconf.h trees.h
153uncompr.o: zlib.h zconf.h
154zutil.o: zutil.h zlib.h zconf.h
diff --git a/utils/zenutils/libraries/zlib123/zlib/Makefile.in b/utils/zenutils/libraries/zlib123/zlib/Makefile.in
new file mode 100755
index 0000000000..a4954c8f97
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/Makefile.in
@@ -0,0 +1,154 @@
1# Makefile for zlib
2# Copyright (C) 1995-2005 Jean-loup Gailly.
3# For conditions of distribution and use, see copyright notice in zlib.h
4
5# To compile and test, type:
6# ./configure; make test
7# The call of configure is optional if you don't have special requirements
8# If you wish to build zlib as a shared library, use: ./configure -s
9
10# To use the asm code, type:
11# cp contrib/asm?86/match.S ./match.S
12# make LOC=-DASMV OBJA=match.o
13
14# To install /usr/local/lib/libz.* and /usr/local/include/zlib.h, type:
15# make install
16# To install in $HOME instead of /usr/local, use:
17# make install prefix=$HOME
18
19CC=cc
20
21CFLAGS=-O
22#CFLAGS=-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7
23#CFLAGS=-g -DDEBUG
24#CFLAGS=-O3 -Wall -Wwrite-strings -Wpointer-arith -Wconversion \
25# -Wstrict-prototypes -Wmissing-prototypes
26
27LDFLAGS=libz.a
28LDSHARED=$(CC)
29CPP=$(CC) -E
30
31LIBS=libz.a
32SHAREDLIB=libz.so
33SHAREDLIBV=libz.so.1.2.3
34SHAREDLIBM=libz.so.1
35
36AR=ar rc
37RANLIB=ranlib
38TAR=tar
39SHELL=/bin/sh
40EXE=
41
42prefix = /usr/local
43exec_prefix = ${prefix}
44libdir = ${exec_prefix}/lib
45includedir = ${prefix}/include
46mandir = ${prefix}/share/man
47man3dir = ${mandir}/man3
48
49OBJS = adler32.o compress.o crc32.o gzio.o uncompr.o deflate.o trees.o \
50 zutil.o inflate.o infback.o inftrees.o inffast.o
51
52OBJA =
53# to use the asm code: make OBJA=match.o
54
55TEST_OBJS = example.o minigzip.o
56
57all: example$(EXE) minigzip$(EXE)
58
59check: test
60test: all
61 @LD_LIBRARY_PATH=.:$(LD_LIBRARY_PATH) ; export LD_LIBRARY_PATH; \
62 echo hello world | ./minigzip | ./minigzip -d || \
63 echo ' *** minigzip test FAILED ***' ; \
64 if ./example; then \
65 echo ' *** zlib test OK ***'; \
66 else \
67 echo ' *** zlib test FAILED ***'; \
68 fi
69
70libz.a: $(OBJS) $(OBJA)
71 $(AR) $@ $(OBJS) $(OBJA)
72 -@ ($(RANLIB) $@ || true) >/dev/null 2>&1
73
74match.o: match.S
75 $(CPP) match.S > _match.s
76 $(CC) -c _match.s
77 mv _match.o match.o
78 rm -f _match.s
79
80$(SHAREDLIBV): $(OBJS)
81 $(LDSHARED) -o $@ $(OBJS)
82 rm -f $(SHAREDLIB) $(SHAREDLIBM)
83 ln -s $@ $(SHAREDLIB)
84 ln -s $@ $(SHAREDLIBM)
85
86example$(EXE): example.o $(LIBS)
87 $(CC) $(CFLAGS) -o $@ example.o $(LDFLAGS)
88
89minigzip$(EXE): minigzip.o $(LIBS)
90 $(CC) $(CFLAGS) -o $@ minigzip.o $(LDFLAGS)
91
92install: $(LIBS)
93 -@if [ ! -d $(exec_prefix) ]; then mkdir -p $(exec_prefix); fi
94 -@if [ ! -d $(includedir) ]; then mkdir -p $(includedir); fi
95 -@if [ ! -d $(libdir) ]; then mkdir -p $(libdir); fi
96 -@if [ ! -d $(man3dir) ]; then mkdir -p $(man3dir); fi
97 cp zlib.h zconf.h $(includedir)
98 chmod 644 $(includedir)/zlib.h $(includedir)/zconf.h
99 cp $(LIBS) $(libdir)
100 cd $(libdir); chmod 755 $(LIBS)
101 -@(cd $(libdir); $(RANLIB) libz.a || true) >/dev/null 2>&1
102 cd $(libdir); if test -f $(SHAREDLIBV); then \
103 rm -f $(SHAREDLIB) $(SHAREDLIBM); \
104 ln -s $(SHAREDLIBV) $(SHAREDLIB); \
105 ln -s $(SHAREDLIBV) $(SHAREDLIBM); \
106 (ldconfig || true) >/dev/null 2>&1; \
107 fi
108 cp zlib.3 $(man3dir)
109 chmod 644 $(man3dir)/zlib.3
110# The ranlib in install is needed on NeXTSTEP which checks file times
111# ldconfig is for Linux
112
113uninstall:
114 cd $(includedir); \
115 cd $(libdir); rm -f libz.a; \
116 if test -f $(SHAREDLIBV); then \
117 rm -f $(SHAREDLIBV) $(SHAREDLIB) $(SHAREDLIBM); \
118 fi
119 cd $(man3dir); rm -f zlib.3
120
121mostlyclean: clean
122clean:
123 rm -f *.o *~ example$(EXE) minigzip$(EXE) \
124 libz.* foo.gz so_locations \
125 _match.s maketree contrib/infback9/*.o
126
127maintainer-clean: distclean
128distclean: clean
129 cp -p Makefile.in Makefile
130 cp -p zconf.in.h zconf.h
131 rm -f .DS_Store
132
133tags:
134 etags *.[ch]
135
136depend:
137 makedepend -- $(CFLAGS) -- *.[ch]
138
139# DO NOT DELETE THIS LINE -- make depend depends on it.
140
141adler32.o: zlib.h zconf.h
142compress.o: zlib.h zconf.h
143crc32.o: crc32.h zlib.h zconf.h
144deflate.o: deflate.h zutil.h zlib.h zconf.h
145example.o: zlib.h zconf.h
146gzio.o: zutil.h zlib.h zconf.h
147inffast.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
148inflate.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
149infback.o: zutil.h zlib.h zconf.h inftrees.h inflate.h inffast.h
150inftrees.o: zutil.h zlib.h zconf.h inftrees.h
151minigzip.o: zlib.h zconf.h
152trees.o: deflate.h zutil.h zlib.h zconf.h trees.h
153uncompr.o: zlib.h zconf.h
154zutil.o: zutil.h zlib.h zconf.h
diff --git a/utils/zenutils/libraries/zlib123/zlib/README b/utils/zenutils/libraries/zlib123/zlib/README
new file mode 100755
index 0000000000..80f71ae856
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/README
@@ -0,0 +1,125 @@
1ZLIB DATA COMPRESSION LIBRARY
2
3zlib 1.2.3 is a general purpose data compression library. All the code is
4thread safe. The data format used by the zlib library is described by RFCs
5(Request for Comments) 1950 to 1952 in the files
6http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format)
7and rfc1952.txt (gzip format). These documents are also available in other
8formats from ftp://ftp.uu.net/graphics/png/documents/zlib/zdoc-index.html
9
10All functions of the compression library are documented in the file zlib.h
11(volunteer to write man pages welcome, contact zlib@gzip.org). A usage example
12of the library is given in the file example.c which also tests that the library
13is working correctly. Another example is given in the file minigzip.c. The
14compression library itself is composed of all source files except example.c and
15minigzip.c.
16
17To compile all files and run the test program, follow the instructions given at
18the top of Makefile. In short "make test; make install" should work for most
19machines. For Unix: "./configure; make test; make install". For MSDOS, use one
20of the special makefiles such as Makefile.msc. For VMS, use make_vms.com.
21
22Questions about zlib should be sent to <zlib@gzip.org>, or to Gilles Vollant
23<info@winimage.com> for the Windows DLL version. The zlib home page is
24http://www.zlib.org or http://www.gzip.org/zlib/ Before reporting a problem,
25please check this site to verify that you have the latest version of zlib;
26otherwise get the latest version and check whether the problem still exists or
27not.
28
29PLEASE read the zlib FAQ http://www.gzip.org/zlib/zlib_faq.html before asking
30for help.
31
32Mark Nelson <markn@ieee.org> wrote an article about zlib for the Jan. 1997
33issue of Dr. Dobb's Journal; a copy of the article is available in
34http://dogma.net/markn/articles/zlibtool/zlibtool.htm
35
36The changes made in version 1.2.3 are documented in the file ChangeLog.
37
38Unsupported third party contributions are provided in directory "contrib".
39
40A Java implementation of zlib is available in the Java Development Kit
41http://java.sun.com/j2se/1.4.2/docs/api/java/util/zip/package-summary.html
42See the zlib home page http://www.zlib.org for details.
43
44A Perl interface to zlib written by Paul Marquess <pmqs@cpan.org> is in the
45CPAN (Comprehensive Perl Archive Network) sites
46http://www.cpan.org/modules/by-module/Compress/
47
48A Python interface to zlib written by A.M. Kuchling <amk@amk.ca> is
49available in Python 1.5 and later versions, see
50http://www.python.org/doc/lib/module-zlib.html
51
52A zlib binding for TCL written by Andreas Kupries <a.kupries@westend.com> is
53availlable at http://www.oche.de/~akupries/soft/trf/trf_zip.html
54
55An experimental package to read and write files in .zip format, written on top
56of zlib by Gilles Vollant <info@winimage.com>, is available in the
57contrib/minizip directory of zlib.
58
59
60Notes for some targets:
61
62- For Windows DLL versions, please see win32/DLL_FAQ.txt
63
64- For 64-bit Irix, deflate.c must be compiled without any optimization. With
65 -O, one libpng test fails. The test works in 32 bit mode (with the -n32
66 compiler flag). The compiler bug has been reported to SGI.
67
68- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works
69 when compiled with cc.
70
71- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is
72 necessary to get gzprintf working correctly. This is done by configure.
73
74- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with
75 other compilers. Use "make test" to check your compiler.
76
77- gzdopen is not supported on RISCOS, BEOS and by some Mac compilers.
78
79- For PalmOs, see http://palmzlib.sourceforge.net/
80
81- When building a shared, i.e. dynamic library on Mac OS X, the library must be
82 installed before testing (do "make install" before "make test"), since the
83 library location is specified in the library.
84
85
86Acknowledgments:
87
88 The deflate format used by zlib was defined by Phil Katz. The deflate
89 and zlib specifications were written by L. Peter Deutsch. Thanks to all the
90 people who reported problems and suggested various improvements in zlib;
91 they are too numerous to cite here.
92
93Copyright notice:
94
95 (C) 1995-2004 Jean-loup Gailly and Mark Adler
96
97 This software is provided 'as-is', without any express or implied
98 warranty. In no event will the authors be held liable for any damages
99 arising from the use of this software.
100
101 Permission is granted to anyone to use this software for any purpose,
102 including commercial applications, and to alter it and redistribute it
103 freely, subject to the following restrictions:
104
105 1. The origin of this software must not be misrepresented; you must not
106 claim that you wrote the original software. If you use this software
107 in a product, an acknowledgment in the product documentation would be
108 appreciated but is not required.
109 2. Altered source versions must be plainly marked as such, and must not be
110 misrepresented as being the original software.
111 3. This notice may not be removed or altered from any source distribution.
112
113 Jean-loup Gailly Mark Adler
114 jloup@gzip.org madler@alumni.caltech.edu
115
116If you use the zlib library in a product, we would appreciate *not*
117receiving lengthy legal documents to sign. The sources are provided
118for free but without warranty of any kind. The library has been
119entirely written by Jean-loup Gailly and Mark Adler; it does not
120include third-party code.
121
122If you redistribute modified sources, we would appreciate that you include
123in the file ChangeLog history information documenting your changes. Please
124read the FAQ for more information on the distribution of modified source
125versions.
diff --git a/utils/zenutils/libraries/zlib123/zlib/adler32.c b/utils/zenutils/libraries/zlib123/zlib/adler32.c
new file mode 100755
index 0000000000..f201d6701e
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/adler32.c
@@ -0,0 +1,149 @@
1/* adler32.c -- compute the Adler-32 checksum of a data stream
2 * Copyright (C) 1995-2004 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/* @(#) $Id$ */
7
8#define ZLIB_INTERNAL
9#include "zlib.h"
10
11#define BASE 65521UL /* largest prime smaller than 65536 */
12#define NMAX 5552
13/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
14
15#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
16#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
17#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
18#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
19#define DO16(buf) DO8(buf,0); DO8(buf,8);
20
21/* use NO_DIVIDE if your processor does not do division in hardware */
22#ifdef NO_DIVIDE
23# define MOD(a) \
24 do { \
25 if (a >= (BASE << 16)) a -= (BASE << 16); \
26 if (a >= (BASE << 15)) a -= (BASE << 15); \
27 if (a >= (BASE << 14)) a -= (BASE << 14); \
28 if (a >= (BASE << 13)) a -= (BASE << 13); \
29 if (a >= (BASE << 12)) a -= (BASE << 12); \
30 if (a >= (BASE << 11)) a -= (BASE << 11); \
31 if (a >= (BASE << 10)) a -= (BASE << 10); \
32 if (a >= (BASE << 9)) a -= (BASE << 9); \
33 if (a >= (BASE << 8)) a -= (BASE << 8); \
34 if (a >= (BASE << 7)) a -= (BASE << 7); \
35 if (a >= (BASE << 6)) a -= (BASE << 6); \
36 if (a >= (BASE << 5)) a -= (BASE << 5); \
37 if (a >= (BASE << 4)) a -= (BASE << 4); \
38 if (a >= (BASE << 3)) a -= (BASE << 3); \
39 if (a >= (BASE << 2)) a -= (BASE << 2); \
40 if (a >= (BASE << 1)) a -= (BASE << 1); \
41 if (a >= BASE) a -= BASE; \
42 } while (0)
43# define MOD4(a) \
44 do { \
45 if (a >= (BASE << 4)) a -= (BASE << 4); \
46 if (a >= (BASE << 3)) a -= (BASE << 3); \
47 if (a >= (BASE << 2)) a -= (BASE << 2); \
48 if (a >= (BASE << 1)) a -= (BASE << 1); \
49 if (a >= BASE) a -= BASE; \
50 } while (0)
51#else
52# define MOD(a) a %= BASE
53# define MOD4(a) a %= BASE
54#endif
55
56/* ========================================================================= */
57uLong ZEXPORT adler32(adler, buf, len)
58 uLong adler;
59 const Bytef *buf;
60 uInt len;
61{
62 unsigned long sum2;
63 unsigned n;
64
65 /* split Adler-32 into component sums */
66 sum2 = (adler >> 16) & 0xffff;
67 adler &= 0xffff;
68
69 /* in case user likes doing a byte at a time, keep it fast */
70 if (len == 1) {
71 adler += buf[0];
72 if (adler >= BASE)
73 adler -= BASE;
74 sum2 += adler;
75 if (sum2 >= BASE)
76 sum2 -= BASE;
77 return adler | (sum2 << 16);
78 }
79
80 /* initial Adler-32 value (deferred check for len == 1 speed) */
81 if (buf == Z_NULL)
82 return 1L;
83
84 /* in case short lengths are provided, keep it somewhat fast */
85 if (len < 16) {
86 while (len--) {
87 adler += *buf++;
88 sum2 += adler;
89 }
90 if (adler >= BASE)
91 adler -= BASE;
92 MOD4(sum2); /* only added so many BASE's */
93 return adler | (sum2 << 16);
94 }
95
96 /* do length NMAX blocks -- requires just one modulo operation */
97 while (len >= NMAX) {
98 len -= NMAX;
99 n = NMAX / 16; /* NMAX is divisible by 16 */
100 do {
101 DO16(buf); /* 16 sums unrolled */
102 buf += 16;
103 } while (--n);
104 MOD(adler);
105 MOD(sum2);
106 }
107
108 /* do remaining bytes (less than NMAX, still just one modulo) */
109 if (len) { /* avoid modulos if none remaining */
110 while (len >= 16) {
111 len -= 16;
112 DO16(buf);
113 buf += 16;
114 }
115 while (len--) {
116 adler += *buf++;
117 sum2 += adler;
118 }
119 MOD(adler);
120 MOD(sum2);
121 }
122
123 /* return recombined sums */
124 return adler | (sum2 << 16);
125}
126
127/* ========================================================================= */
128uLong ZEXPORT adler32_combine(adler1, adler2, len2)
129 uLong adler1;
130 uLong adler2;
131 z_off_t len2;
132{
133 unsigned long sum1;
134 unsigned long sum2;
135 unsigned rem;
136
137 /* the derivation of this formula is left as an exercise for the reader */
138 rem = (unsigned)(len2 % BASE);
139 sum1 = adler1 & 0xffff;
140 sum2 = rem * sum1;
141 MOD(sum2);
142 sum1 += (adler2 & 0xffff) + BASE - 1;
143 sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
144 if (sum1 > BASE) sum1 -= BASE;
145 if (sum1 > BASE) sum1 -= BASE;
146 if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
147 if (sum2 > BASE) sum2 -= BASE;
148 return sum1 | (sum2 << 16);
149}
diff --git a/utils/zenutils/libraries/zlib123/zlib/algorithm.txt b/utils/zenutils/libraries/zlib123/zlib/algorithm.txt
new file mode 100755
index 0000000000..9f6b06808c
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/algorithm.txt
@@ -0,0 +1,209 @@
11. Compression algorithm (deflate)
2
3The deflation algorithm used by gzip (also zip and zlib) is a variation of
4LZ77 (Lempel-Ziv 1977, see reference below). It finds duplicated strings in
5the input data. The second occurrence of a string is replaced by a
6pointer to the previous string, in the form of a pair (distance,
7length). Distances are limited to 32K bytes, and lengths are limited
8to 258 bytes. When a string does not occur anywhere in the previous
932K bytes, it is emitted as a sequence of literal bytes. (In this
10description, `string' must be taken as an arbitrary sequence of bytes,
11and is not restricted to printable characters.)
12
13Literals or match lengths are compressed with one Huffman tree, and
14match distances are compressed with another tree. The trees are stored
15in a compact form at the start of each block. The blocks can have any
16size (except that the compressed data for one block must fit in
17available memory). A block is terminated when deflate() determines that
18it would be useful to start another block with fresh trees. (This is
19somewhat similar to the behavior of LZW-based _compress_.)
20
21Duplicated strings are found using a hash table. All input strings of
22length 3 are inserted in the hash table. A hash index is computed for
23the next 3 bytes. If the hash chain for this index is not empty, all
24strings in the chain are compared with the current input string, and
25the longest match is selected.
26
27The hash chains are searched starting with the most recent strings, to
28favor small distances and thus take advantage of the Huffman encoding.
29The hash chains are singly linked. There are no deletions from the
30hash chains, the algorithm simply discards matches that are too old.
31
32To avoid a worst-case situation, very long hash chains are arbitrarily
33truncated at a certain length, determined by a runtime option (level
34parameter of deflateInit). So deflate() does not always find the longest
35possible match but generally finds a match which is long enough.
36
37deflate() also defers the selection of matches with a lazy evaluation
38mechanism. After a match of length N has been found, deflate() searches for
39a longer match at the next input byte. If a longer match is found, the
40previous match is truncated to a length of one (thus producing a single
41literal byte) and the process of lazy evaluation begins again. Otherwise,
42the original match is kept, and the next match search is attempted only N
43steps later.
44
45The lazy match evaluation is also subject to a runtime parameter. If
46the current match is long enough, deflate() reduces the search for a longer
47match, thus speeding up the whole process. If compression ratio is more
48important than speed, deflate() attempts a complete second search even if
49the first match is already long enough.
50
51The lazy match evaluation is not performed for the fastest compression
52modes (level parameter 1 to 3). For these fast modes, new strings
53are inserted in the hash table only when no match was found, or
54when the match is not too long. This degrades the compression ratio
55but saves time since there are both fewer insertions and fewer searches.
56
57
582. Decompression algorithm (inflate)
59
602.1 Introduction
61
62The key question is how to represent a Huffman code (or any prefix code) so
63that you can decode fast. The most important characteristic is that shorter
64codes are much more common than longer codes, so pay attention to decoding the
65short codes fast, and let the long codes take longer to decode.
66
67inflate() sets up a first level table that covers some number of bits of
68input less than the length of longest code. It gets that many bits from the
69stream, and looks it up in the table. The table will tell if the next
70code is that many bits or less and how many, and if it is, it will tell
71the value, else it will point to the next level table for which inflate()
72grabs more bits and tries to decode a longer code.
73
74How many bits to make the first lookup is a tradeoff between the time it
75takes to decode and the time it takes to build the table. If building the
76table took no time (and if you had infinite memory), then there would only
77be a first level table to cover all the way to the longest code. However,
78building the table ends up taking a lot longer for more bits since short
79codes are replicated many times in such a table. What inflate() does is
80simply to make the number of bits in the first table a variable, and then
81to set that variable for the maximum speed.
82
83For inflate, which has 286 possible codes for the literal/length tree, the size
84of the first table is nine bits. Also the distance trees have 30 possible
85values, and the size of the first table is six bits. Note that for each of
86those cases, the table ended up one bit longer than the ``average'' code
87length, i.e. the code length of an approximately flat code which would be a
88little more than eight bits for 286 symbols and a little less than five bits
89for 30 symbols.
90
91
922.2 More details on the inflate table lookup
93
94Ok, you want to know what this cleverly obfuscated inflate tree actually
95looks like. You are correct that it's not a Huffman tree. It is simply a
96lookup table for the first, let's say, nine bits of a Huffman symbol. The
97symbol could be as short as one bit or as long as 15 bits. If a particular
98symbol is shorter than nine bits, then that symbol's translation is duplicated
99in all those entries that start with that symbol's bits. For example, if the
100symbol is four bits, then it's duplicated 32 times in a nine-bit table. If a
101symbol is nine bits long, it appears in the table once.
102
103If the symbol is longer than nine bits, then that entry in the table points
104to another similar table for the remaining bits. Again, there are duplicated
105entries as needed. The idea is that most of the time the symbol will be short
106and there will only be one table look up. (That's whole idea behind data
107compression in the first place.) For the less frequent long symbols, there
108will be two lookups. If you had a compression method with really long
109symbols, you could have as many levels of lookups as is efficient. For
110inflate, two is enough.
111
112So a table entry either points to another table (in which case nine bits in
113the above example are gobbled), or it contains the translation for the symbol
114and the number of bits to gobble. Then you start again with the next
115ungobbled bit.
116
117You may wonder: why not just have one lookup table for how ever many bits the
118longest symbol is? The reason is that if you do that, you end up spending
119more time filling in duplicate symbol entries than you do actually decoding.
120At least for deflate's output that generates new trees every several 10's of
121kbytes. You can imagine that filling in a 2^15 entry table for a 15-bit code
122would take too long if you're only decoding several thousand symbols. At the
123other extreme, you could make a new table for every bit in the code. In fact,
124that's essentially a Huffman tree. But then you spend two much time
125traversing the tree while decoding, even for short symbols.
126
127So the number of bits for the first lookup table is a trade of the time to
128fill out the table vs. the time spent looking at the second level and above of
129the table.
130
131Here is an example, scaled down:
132
133The code being decoded, with 10 symbols, from 1 to 6 bits long:
134
135A: 0
136B: 10
137C: 1100
138D: 11010
139E: 11011
140F: 11100
141G: 11101
142H: 11110
143I: 111110
144J: 111111
145
146Let's make the first table three bits long (eight entries):
147
148000: A,1
149001: A,1
150010: A,1
151011: A,1
152100: B,2
153101: B,2
154110: -> table X (gobble 3 bits)
155111: -> table Y (gobble 3 bits)
156
157Each entry is what the bits decode as and how many bits that is, i.e. how
158many bits to gobble. Or the entry points to another table, with the number of
159bits to gobble implicit in the size of the table.
160
161Table X is two bits long since the longest code starting with 110 is five bits
162long:
163
16400: C,1
16501: C,1
16610: D,2
16711: E,2
168
169Table Y is three bits long since the longest code starting with 111 is six
170bits long:
171
172000: F,2
173001: F,2
174010: G,2
175011: G,2
176100: H,2
177101: H,2
178110: I,3
179111: J,3
180
181So what we have here are three tables with a total of 20 entries that had to
182be constructed. That's compared to 64 entries for a single table. Or
183compared to 16 entries for a Huffman tree (six two entry tables and one four
184entry table). Assuming that the code ideally represents the probability of
185the symbols, it takes on the average 1.25 lookups per symbol. That's compared
186to one lookup for the single table, or 1.66 lookups per symbol for the
187Huffman tree.
188
189There, I think that gives you a picture of what's going on. For inflate, the
190meaning of a particular symbol is often more than just a letter. It can be a
191byte (a "literal"), or it can be either a length or a distance which
192indicates a base value and a number of bits to fetch after the code that is
193added to the base value. Or it might be the special end-of-block code. The
194data structures created in inftrees.c try to encode all that information
195compactly in the tables.
196
197
198Jean-loup Gailly Mark Adler
199jloup@gzip.org madler@alumni.caltech.edu
200
201
202References:
203
204[LZ77] Ziv J., Lempel A., ``A Universal Algorithm for Sequential Data
205Compression,'' IEEE Transactions on Information Theory, Vol. 23, No. 3,
206pp. 337-343.
207
208``DEFLATE Compressed Data Format Specification'' available in
209http://www.ietf.org/rfc/rfc1951.txt
diff --git a/utils/zenutils/libraries/zlib123/zlib/compress.c b/utils/zenutils/libraries/zlib123/zlib/compress.c
new file mode 100755
index 0000000000..d37e84f5e3
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/compress.c
@@ -0,0 +1,79 @@
1/* compress.c -- compress a memory buffer
2 * Copyright (C) 1995-2003 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/* @(#) $Id$ */
7
8#define ZLIB_INTERNAL
9#include "zlib.h"
10
11/* ===========================================================================
12 Compresses the source buffer into the destination buffer. The level
13 parameter has the same meaning as in deflateInit. sourceLen is the byte
14 length of the source buffer. Upon entry, destLen is the total size of the
15 destination buffer, which must be at least 0.1% larger than sourceLen plus
16 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
17
18 compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
19 memory, Z_BUF_ERROR if there was not enough room in the output buffer,
20 Z_STREAM_ERROR if the level parameter is invalid.
21*/
22int ZEXPORT compress2 (dest, destLen, source, sourceLen, level)
23 Bytef *dest;
24 uLongf *destLen;
25 const Bytef *source;
26 uLong sourceLen;
27 int level;
28{
29 z_stream stream;
30 int err;
31
32 stream.next_in = (Bytef*)source;
33 stream.avail_in = (uInt)sourceLen;
34#ifdef MAXSEG_64K
35 /* Check for source > 64K on 16-bit machine: */
36 if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
37#endif
38 stream.next_out = dest;
39 stream.avail_out = (uInt)*destLen;
40 if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
41
42 stream.zalloc = (alloc_func)0;
43 stream.zfree = (free_func)0;
44 stream.opaque = (voidpf)0;
45
46 err = deflateInit(&stream, level);
47 if (err != Z_OK) return err;
48
49 err = deflate(&stream, Z_FINISH);
50 if (err != Z_STREAM_END) {
51 deflateEnd(&stream);
52 return err == Z_OK ? Z_BUF_ERROR : err;
53 }
54 *destLen = stream.total_out;
55
56 err = deflateEnd(&stream);
57 return err;
58}
59
60/* ===========================================================================
61 */
62int ZEXPORT compress (dest, destLen, source, sourceLen)
63 Bytef *dest;
64 uLongf *destLen;
65 const Bytef *source;
66 uLong sourceLen;
67{
68 return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
69}
70
71/* ===========================================================================
72 If the default memLevel or windowBits for deflateInit() is changed, then
73 this function needs to be updated.
74 */
75uLong ZEXPORT compressBound (sourceLen)
76 uLong sourceLen;
77{
78 return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
79}
diff --git a/utils/zenutils/libraries/zlib123/zlib/configure b/utils/zenutils/libraries/zlib123/zlib/configure
new file mode 100755
index 0000000000..212e92ed27
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/configure
@@ -0,0 +1,459 @@
1#!/bin/sh
2# configure script for zlib. This script is needed only if
3# you wish to build a shared library and your system supports them,
4# of if you need special compiler, flags or install directory.
5# Otherwise, you can just use directly "make test; make install"
6#
7# To create a shared library, use "configure --shared"; by default a static
8# library is created. If the primitive shared library support provided here
9# does not work, use ftp://prep.ai.mit.edu/pub/gnu/libtool-*.tar.gz
10#
11# To impose specific compiler or flags or install directory, use for example:
12# prefix=$HOME CC=cc CFLAGS="-O4" ./configure
13# or for csh/tcsh users:
14# (setenv prefix $HOME; setenv CC cc; setenv CFLAGS "-O4"; ./configure)
15# LDSHARED is the command to be used to create a shared library
16
17# Incorrect settings of CC or CFLAGS may prevent creating a shared library.
18# If you have problems, try without defining CC and CFLAGS before reporting
19# an error.
20
21LIBS=libz.a
22LDFLAGS="-L. ${LIBS}"
23VER=`sed -n -e '/VERSION "/s/.*"\(.*\)".*/\1/p' < zlib.h`
24VER2=`sed -n -e '/VERSION "/s/.*"\([0-9]*\\.[0-9]*\)\\..*/\1/p' < zlib.h`
25VER1=`sed -n -e '/VERSION "/s/.*"\([0-9]*\)\\..*/\1/p' < zlib.h`
26AR=${AR-"ar rc"}
27RANLIB=${RANLIB-"ranlib"}
28prefix=${prefix-/usr/local}
29exec_prefix=${exec_prefix-'${prefix}'}
30libdir=${libdir-'${exec_prefix}/lib'}
31includedir=${includedir-'${prefix}/include'}
32mandir=${mandir-'${prefix}/share/man'}
33shared_ext='.so'
34shared=0
35gcc=0
36old_cc="$CC"
37old_cflags="$CFLAGS"
38
39while test $# -ge 1
40do
41case "$1" in
42 -h* | --h*)
43 echo 'usage:'
44 echo ' configure [--shared] [--prefix=PREFIX] [--exec_prefix=EXPREFIX]'
45 echo ' [--libdir=LIBDIR] [--includedir=INCLUDEDIR]'
46 exit 0;;
47 -p*=* | --p*=*) prefix=`echo $1 | sed 's/[-a-z_]*=//'`; shift;;
48 -e*=* | --e*=*) exec_prefix=`echo $1 | sed 's/[-a-z_]*=//'`; shift;;
49 -l*=* | --libdir=*) libdir=`echo $1 | sed 's/[-a-z_]*=//'`; shift;;
50 -i*=* | --includedir=*) includedir=`echo $1 | sed 's/[-a-z_]*=//'`;shift;;
51 -p* | --p*) prefix="$2"; shift; shift;;
52 -e* | --e*) exec_prefix="$2"; shift; shift;;
53 -l* | --l*) libdir="$2"; shift; shift;;
54 -i* | --i*) includedir="$2"; shift; shift;;
55 -s* | --s*) shared=1; shift;;
56 *) echo "unknown option: $1"; echo "$0 --help for help"; exit 1;;
57 esac
58done
59
60test=ztest$$
61cat > $test.c <<EOF
62extern int getchar();
63int hello() {return getchar();}
64EOF
65
66test -z "$CC" && echo Checking for gcc...
67cc=${CC-gcc}
68cflags=${CFLAGS-"-O3"}
69# to force the asm version use: CFLAGS="-O3 -DASMV" ./configure
70case "$cc" in
71 *gcc*) gcc=1;;
72esac
73
74if test "$gcc" -eq 1 && ($cc -c $cflags $test.c) 2>/dev/null; then
75 CC="$cc"
76 SFLAGS=${CFLAGS-"-fPIC -O3"}
77 CFLAGS="$cflags"
78 case `(uname -s || echo unknown) 2>/dev/null` in
79 Linux | linux | GNU | GNU/*) LDSHARED=${LDSHARED-"$cc -shared -Wl,-soname,libz.so.1"};;
80 CYGWIN* | Cygwin* | cygwin* | OS/2* )
81 EXE='.exe';;
82 QNX*) # This is for QNX6. I suppose that the QNX rule below is for QNX2,QNX4
83 # (alain.bonnefoy@icbt.com)
84 LDSHARED=${LDSHARED-"$cc -shared -Wl,-hlibz.so.1"};;
85 HP-UX*)
86 LDSHARED=${LDSHARED-"$cc -shared $SFLAGS"}
87 case `(uname -m || echo unknown) 2>/dev/null` in
88 ia64)
89 shared_ext='.so'
90 SHAREDLIB='libz.so';;
91 *)
92 shared_ext='.sl'
93 SHAREDLIB='libz.sl';;
94 esac;;
95 Darwin*) shared_ext='.dylib'
96 SHAREDLIB=libz$shared_ext
97 SHAREDLIBV=libz.$VER$shared_ext
98 SHAREDLIBM=libz.$VER1$shared_ext
99 LDSHARED=${LDSHARED-"$cc -dynamiclib -install_name $libdir/$SHAREDLIBM -compatibility_version $VER1 -current_version $VER"};;
100 *) LDSHARED=${LDSHARED-"$cc -shared"};;
101 esac
102else
103 # find system name and corresponding cc options
104 CC=${CC-cc}
105 case `(uname -sr || echo unknown) 2>/dev/null` in
106 HP-UX*) SFLAGS=${CFLAGS-"-O +z"}
107 CFLAGS=${CFLAGS-"-O"}
108# LDSHARED=${LDSHARED-"ld -b +vnocompatwarnings"}
109 LDSHARED=${LDSHARED-"ld -b"}
110 case `(uname -m || echo unknown) 2>/dev/null` in
111 ia64)
112 shared_ext='.so'
113 SHAREDLIB='libz.so';;
114 *)
115 shared_ext='.sl'
116 SHAREDLIB='libz.sl';;
117 esac;;
118 IRIX*) SFLAGS=${CFLAGS-"-ansi -O2 -rpath ."}
119 CFLAGS=${CFLAGS-"-ansi -O2"}
120 LDSHARED=${LDSHARED-"cc -shared"};;
121 OSF1\ V4*) SFLAGS=${CFLAGS-"-O -std1"}
122 CFLAGS=${CFLAGS-"-O -std1"}
123 LDSHARED=${LDSHARED-"cc -shared -Wl,-soname,libz.so -Wl,-msym -Wl,-rpath,$(libdir) -Wl,-set_version,${VER}:1.0"};;
124 OSF1*) SFLAGS=${CFLAGS-"-O -std1"}
125 CFLAGS=${CFLAGS-"-O -std1"}
126 LDSHARED=${LDSHARED-"cc -shared"};;
127 QNX*) SFLAGS=${CFLAGS-"-4 -O"}
128 CFLAGS=${CFLAGS-"-4 -O"}
129 LDSHARED=${LDSHARED-"cc"}
130 RANLIB=${RANLIB-"true"}
131 AR="cc -A";;
132 SCO_SV\ 3.2*) SFLAGS=${CFLAGS-"-O3 -dy -KPIC "}
133 CFLAGS=${CFLAGS-"-O3"}
134 LDSHARED=${LDSHARED-"cc -dy -KPIC -G"};;
135 SunOS\ 5*) SFLAGS=${CFLAGS-"-fast -xcg89 -KPIC -R."}
136 CFLAGS=${CFLAGS-"-fast -xcg89"}
137 LDSHARED=${LDSHARED-"cc -G"};;
138 SunOS\ 4*) SFLAGS=${CFLAGS-"-O2 -PIC"}
139 CFLAGS=${CFLAGS-"-O2"}
140 LDSHARED=${LDSHARED-"ld"};;
141 SunStudio\ 9*) SFLAGS=${CFLAGS-"-DUSE_MMAP -fast -xcode=pic32 -xtarget=ultra3 -xarch=v9b"}
142 CFLAGS=${CFLAGS-"-DUSE_MMAP -fast -xtarget=ultra3 -xarch=v9b"}
143 LDSHARED=${LDSHARED-"cc -xarch=v9b"};;
144 UNIX_System_V\ 4.2.0)
145 SFLAGS=${CFLAGS-"-KPIC -O"}
146 CFLAGS=${CFLAGS-"-O"}
147 LDSHARED=${LDSHARED-"cc -G"};;
148 UNIX_SV\ 4.2MP)
149 SFLAGS=${CFLAGS-"-Kconform_pic -O"}
150 CFLAGS=${CFLAGS-"-O"}
151 LDSHARED=${LDSHARED-"cc -G"};;
152 OpenUNIX\ 5)
153 SFLAGS=${CFLAGS-"-KPIC -O"}
154 CFLAGS=${CFLAGS-"-O"}
155 LDSHARED=${LDSHARED-"cc -G"};;
156 AIX*) # Courtesy of dbakker@arrayasolutions.com
157 SFLAGS=${CFLAGS-"-O -qmaxmem=8192"}
158 CFLAGS=${CFLAGS-"-O -qmaxmem=8192"}
159 LDSHARED=${LDSHARED-"xlc -G"};;
160 # send working options for other systems to support@gzip.org
161 *) SFLAGS=${CFLAGS-"-O"}
162 CFLAGS=${CFLAGS-"-O"}
163 LDSHARED=${LDSHARED-"cc -shared"};;
164 esac
165fi
166
167SHAREDLIB=${SHAREDLIB-"libz$shared_ext"}
168SHAREDLIBV=${SHAREDLIBV-"libz$shared_ext.$VER"}
169SHAREDLIBM=${SHAREDLIBM-"libz$shared_ext.$VER1"}
170
171if test $shared -eq 1; then
172 echo Checking for shared library support...
173 # we must test in two steps (cc then ld), required at least on SunOS 4.x
174 if test "`($CC -c $SFLAGS $test.c) 2>&1`" = "" &&
175 test "`($LDSHARED -o $test$shared_ext $test.o) 2>&1`" = ""; then
176 CFLAGS="$SFLAGS"
177 LIBS="$SHAREDLIBV"
178 echo Building shared library $SHAREDLIBV with $CC.
179 elif test -z "$old_cc" -a -z "$old_cflags"; then
180 echo No shared library support.
181 shared=0;
182 else
183 echo 'No shared library support; try without defining CC and CFLAGS'
184 shared=0;
185 fi
186fi
187if test $shared -eq 0; then
188 LDSHARED="$CC"
189 echo Building static library $LIBS version $VER with $CC.
190else
191 LDFLAGS="-L. ${SHAREDLIBV}"
192fi
193
194cat > $test.c <<EOF
195#include <unistd.h>
196int main() { return 0; }
197EOF
198if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
199 sed < zconf.in.h "/HAVE_UNISTD_H/s%0%1%" > zconf.h
200 echo "Checking for unistd.h... Yes."
201else
202 cp -p zconf.in.h zconf.h
203 echo "Checking for unistd.h... No."
204fi
205
206cat > $test.c <<EOF
207#include <stdio.h>
208#include <stdarg.h>
209#include "zconf.h"
210
211int main()
212{
213#ifndef STDC
214 choke me
215#endif
216
217 return 0;
218}
219EOF
220
221if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
222 echo "Checking whether to use vs[n]printf() or s[n]printf()... using vs[n]printf()"
223
224 cat > $test.c <<EOF
225#include <stdio.h>
226#include <stdarg.h>
227
228int mytest(char *fmt, ...)
229{
230 char buf[20];
231 va_list ap;
232
233 va_start(ap, fmt);
234 vsnprintf(buf, sizeof(buf), fmt, ap);
235 va_end(ap);
236 return 0;
237}
238
239int main()
240{
241 return (mytest("Hello%d\n", 1));
242}
243EOF
244
245 if test "`($CC $CFLAGS -o $test $test.c) 2>&1`" = ""; then
246 echo "Checking for vsnprintf() in stdio.h... Yes."
247
248 cat >$test.c <<EOF
249#include <stdio.h>
250#include <stdarg.h>
251
252int mytest(char *fmt, ...)
253{
254 int n;
255 char buf[20];
256 va_list ap;
257
258 va_start(ap, fmt);
259 n = vsnprintf(buf, sizeof(buf), fmt, ap);
260 va_end(ap);
261 return n;
262}
263
264int main()
265{
266 return (mytest("Hello%d\n", 1));
267}
268EOF
269
270 if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
271 echo "Checking for return value of vsnprintf()... Yes."
272 else
273 CFLAGS="$CFLAGS -DHAS_vsnprintf_void"
274 echo "Checking for return value of vsnprintf()... No."
275 echo " WARNING: apparently vsnprintf() does not return a value. zlib"
276 echo " can build but will be open to possible string-format security"
277 echo " vulnerabilities."
278 fi
279 else
280 CFLAGS="$CFLAGS -DNO_vsnprintf"
281 echo "Checking for vsnprintf() in stdio.h... No."
282 echo " WARNING: vsnprintf() not found, falling back to vsprintf(). zlib"
283 echo " can build but will be open to possible buffer-overflow security"
284 echo " vulnerabilities."
285
286 cat >$test.c <<EOF
287#include <stdio.h>
288#include <stdarg.h>
289
290int mytest(char *fmt, ...)
291{
292 int n;
293 char buf[20];
294 va_list ap;
295
296 va_start(ap, fmt);
297 n = vsprintf(buf, fmt, ap);
298 va_end(ap);
299 return n;
300}
301
302int main()
303{
304 return (mytest("Hello%d\n", 1));
305}
306EOF
307
308 if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
309 echo "Checking for return value of vsprintf()... Yes."
310 else
311 CFLAGS="$CFLAGS -DHAS_vsprintf_void"
312 echo "Checking for return value of vsprintf()... No."
313 echo " WARNING: apparently vsprintf() does not return a value. zlib"
314 echo " can build but will be open to possible string-format security"
315 echo " vulnerabilities."
316 fi
317 fi
318else
319 echo "Checking whether to use vs[n]printf() or s[n]printf()... using s[n]printf()"
320
321 cat >$test.c <<EOF
322#include <stdio.h>
323
324int mytest()
325{
326 char buf[20];
327
328 snprintf(buf, sizeof(buf), "%s", "foo");
329 return 0;
330}
331
332int main()
333{
334 return (mytest());
335}
336EOF
337
338 if test "`($CC $CFLAGS -o $test $test.c) 2>&1`" = ""; then
339 echo "Checking for snprintf() in stdio.h... Yes."
340
341 cat >$test.c <<EOF
342#include <stdio.h>
343
344int mytest()
345{
346 char buf[20];
347
348 return snprintf(buf, sizeof(buf), "%s", "foo");
349}
350
351int main()
352{
353 return (mytest());
354}
355EOF
356
357 if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
358 echo "Checking for return value of snprintf()... Yes."
359 else
360 CFLAGS="$CFLAGS -DHAS_snprintf_void"
361 echo "Checking for return value of snprintf()... No."
362 echo " WARNING: apparently snprintf() does not return a value. zlib"
363 echo " can build but will be open to possible string-format security"
364 echo " vulnerabilities."
365 fi
366 else
367 CFLAGS="$CFLAGS -DNO_snprintf"
368 echo "Checking for snprintf() in stdio.h... No."
369 echo " WARNING: snprintf() not found, falling back to sprintf(). zlib"
370 echo " can build but will be open to possible buffer-overflow security"
371 echo " vulnerabilities."
372
373 cat >$test.c <<EOF
374#include <stdio.h>
375
376int mytest()
377{
378 char buf[20];
379
380 return sprintf(buf, "%s", "foo");
381}
382
383int main()
384{
385 return (mytest());
386}
387EOF
388
389 if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
390 echo "Checking for return value of sprintf()... Yes."
391 else
392 CFLAGS="$CFLAGS -DHAS_sprintf_void"
393 echo "Checking for return value of sprintf()... No."
394 echo " WARNING: apparently sprintf() does not return a value. zlib"
395 echo " can build but will be open to possible string-format security"
396 echo " vulnerabilities."
397 fi
398 fi
399fi
400
401cat >$test.c <<EOF
402#include <errno.h>
403int main() { return 0; }
404EOF
405if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
406 echo "Checking for errno.h... Yes."
407else
408 echo "Checking for errno.h... No."
409 CFLAGS="$CFLAGS -DNO_ERRNO_H"
410fi
411
412cat > $test.c <<EOF
413#include <sys/types.h>
414#include <sys/mman.h>
415#include <sys/stat.h>
416caddr_t hello() {
417 return mmap((caddr_t)0, (off_t)0, PROT_READ, MAP_SHARED, 0, (off_t)0);
418}
419EOF
420if test "`($CC -c $CFLAGS $test.c) 2>&1`" = ""; then
421 CFLAGS="$CFLAGS -DUSE_MMAP"
422 echo Checking for mmap support... Yes.
423else
424 echo Checking for mmap support... No.
425fi
426
427CPP=${CPP-"$CC -E"}
428case $CFLAGS in
429 *ASMV*)
430 if test "`nm $test.o | grep _hello`" = ""; then
431 CPP="$CPP -DNO_UNDERLINE"
432 echo Checking for underline in external names... No.
433 else
434 echo Checking for underline in external names... Yes.
435 fi;;
436esac
437
438rm -f $test.[co] $test $test$shared_ext
439
440# udpate Makefile
441sed < Makefile.in "
442/^CC *=/s#=.*#=$CC#
443/^CFLAGS *=/s#=.*#=$CFLAGS#
444/^CPP *=/s#=.*#=$CPP#
445/^LDSHARED *=/s#=.*#=$LDSHARED#
446/^LIBS *=/s#=.*#=$LIBS#
447/^SHAREDLIB *=/s#=.*#=$SHAREDLIB#
448/^SHAREDLIBV *=/s#=.*#=$SHAREDLIBV#
449/^SHAREDLIBM *=/s#=.*#=$SHAREDLIBM#
450/^AR *=/s#=.*#=$AR#
451/^RANLIB *=/s#=.*#=$RANLIB#
452/^EXE *=/s#=.*#=$EXE#
453/^prefix *=/s#=.*#=$prefix#
454/^exec_prefix *=/s#=.*#=$exec_prefix#
455/^libdir *=/s#=.*#=$libdir#
456/^includedir *=/s#=.*#=$includedir#
457/^mandir *=/s#=.*#=$mandir#
458/^LDFLAGS *=/s#=.*#=$LDFLAGS#
459" > Makefile
diff --git a/utils/zenutils/libraries/zlib123/zlib/crc32.c b/utils/zenutils/libraries/zlib123/zlib/crc32.c
new file mode 100755
index 0000000000..32814c20c8
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/crc32.c
@@ -0,0 +1,423 @@
1/* crc32.c -- compute the CRC-32 of a data stream
2 * Copyright (C) 1995-2005 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 *
5 * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster
6 * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing
7 * tables for updating the shift register in one step with three exclusive-ors
8 * instead of four steps with four exclusive-ors. This results in about a
9 * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3.
10 */
11
12/* @(#) $Id$ */
13
14/*
15 Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
16 protection on the static variables used to control the first-use generation
17 of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
18 first call get_crc_table() to initialize the tables before allowing more than
19 one thread to use crc32().
20 */
21
22#ifdef MAKECRCH
23# include <stdio.h>
24# ifndef DYNAMIC_CRC_TABLE
25# define DYNAMIC_CRC_TABLE
26# endif /* !DYNAMIC_CRC_TABLE */
27#endif /* MAKECRCH */
28
29#include "zutil.h" /* for STDC and FAR definitions */
30
31#define local static
32
33/* Find a four-byte integer type for crc32_little() and crc32_big(). */
34#ifndef NOBYFOUR
35# ifdef STDC /* need ANSI C limits.h to determine sizes */
36# include <limits.h>
37# define BYFOUR
38# if (UINT_MAX == 0xffffffffUL)
39 typedef unsigned int u4;
40# else
41# if (ULONG_MAX == 0xffffffffUL)
42 typedef unsigned long u4;
43# else
44# if (USHRT_MAX == 0xffffffffUL)
45 typedef unsigned short u4;
46# else
47# undef BYFOUR /* can't find a four-byte integer type! */
48# endif
49# endif
50# endif
51# endif /* STDC */
52#endif /* !NOBYFOUR */
53
54/* Definitions for doing the crc four data bytes at a time. */
55#ifdef BYFOUR
56# define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
57 (((w)&0xff00)<<8)+(((w)&0xff)<<24))
58 local unsigned long crc32_little OF((unsigned long,
59 const unsigned char FAR *, unsigned));
60 local unsigned long crc32_big OF((unsigned long,
61 const unsigned char FAR *, unsigned));
62# define TBLS 8
63#else
64# define TBLS 1
65#endif /* BYFOUR */
66
67/* Local functions for crc concatenation */
68local unsigned long gf2_matrix_times OF((unsigned long *mat,
69 unsigned long vec));
70local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
71
72#ifdef DYNAMIC_CRC_TABLE
73
74local volatile int crc_table_empty = 1;
75local unsigned long FAR crc_table[TBLS][256];
76local void make_crc_table OF((void));
77#ifdef MAKECRCH
78 local void write_table OF((FILE *, const unsigned long FAR *));
79#endif /* MAKECRCH */
80/*
81 Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
82 x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
83
84 Polynomials over GF(2) are represented in binary, one bit per coefficient,
85 with the lowest powers in the most significant bit. Then adding polynomials
86 is just exclusive-or, and multiplying a polynomial by x is a right shift by
87 one. If we call the above polynomial p, and represent a byte as the
88 polynomial q, also with the lowest power in the most significant bit (so the
89 byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
90 where a mod b means the remainder after dividing a by b.
91
92 This calculation is done using the shift-register method of multiplying and
93 taking the remainder. The register is initialized to zero, and for each
94 incoming bit, x^32 is added mod p to the register if the bit is a one (where
95 x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
96 x (which is shifting right by one and adding x^32 mod p if the bit shifted
97 out is a one). We start with the highest power (least significant bit) of
98 q and repeat for all eight bits of q.
99
100 The first table is simply the CRC of all possible eight bit values. This is
101 all the information needed to generate CRCs on data a byte at a time for all
102 combinations of CRC register values and incoming bytes. The remaining tables
103 allow for word-at-a-time CRC calculation for both big-endian and little-
104 endian machines, where a word is four bytes.
105*/
106local void make_crc_table()
107{
108 unsigned long c;
109 int n, k;
110 unsigned long poly; /* polynomial exclusive-or pattern */
111 /* terms of polynomial defining this crc (except x^32): */
112 static volatile int first = 1; /* flag to limit concurrent making */
113 static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
114
115 /* See if another task is already doing this (not thread-safe, but better
116 than nothing -- significantly reduces duration of vulnerability in
117 case the advice about DYNAMIC_CRC_TABLE is ignored) */
118 if (first) {
119 first = 0;
120
121 /* make exclusive-or pattern from polynomial (0xedb88320UL) */
122 poly = 0UL;
123 for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
124 poly |= 1UL << (31 - p[n]);
125
126 /* generate a crc for every 8-bit value */
127 for (n = 0; n < 256; n++) {
128 c = (unsigned long)n;
129 for (k = 0; k < 8; k++)
130 c = c & 1 ? poly ^ (c >> 1) : c >> 1;
131 crc_table[0][n] = c;
132 }
133
134#ifdef BYFOUR
135 /* generate crc for each value followed by one, two, and three zeros,
136 and then the byte reversal of those as well as the first table */
137 for (n = 0; n < 256; n++) {
138 c = crc_table[0][n];
139 crc_table[4][n] = REV(c);
140 for (k = 1; k < 4; k++) {
141 c = crc_table[0][c & 0xff] ^ (c >> 8);
142 crc_table[k][n] = c;
143 crc_table[k + 4][n] = REV(c);
144 }
145 }
146#endif /* BYFOUR */
147
148 crc_table_empty = 0;
149 }
150 else { /* not first */
151 /* wait for the other guy to finish (not efficient, but rare) */
152 while (crc_table_empty)
153 ;
154 }
155
156#ifdef MAKECRCH
157 /* write out CRC tables to crc32.h */
158 {
159 FILE *out;
160
161 out = fopen("crc32.h", "w");
162 if (out == NULL) return;
163 fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
164 fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
165 fprintf(out, "local const unsigned long FAR ");
166 fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
167 write_table(out, crc_table[0]);
168# ifdef BYFOUR
169 fprintf(out, "#ifdef BYFOUR\n");
170 for (k = 1; k < 8; k++) {
171 fprintf(out, " },\n {\n");
172 write_table(out, crc_table[k]);
173 }
174 fprintf(out, "#endif\n");
175# endif /* BYFOUR */
176 fprintf(out, " }\n};\n");
177 fclose(out);
178 }
179#endif /* MAKECRCH */
180}
181
182#ifdef MAKECRCH
183local void write_table(out, table)
184 FILE *out;
185 const unsigned long FAR *table;
186{
187 int n;
188
189 for (n = 0; n < 256; n++)
190 fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
191 n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
192}
193#endif /* MAKECRCH */
194
195#else /* !DYNAMIC_CRC_TABLE */
196/* ========================================================================
197 * Tables of CRC-32s of all single-byte values, made by make_crc_table().
198 */
199#include "crc32.h"
200#endif /* DYNAMIC_CRC_TABLE */
201
202/* =========================================================================
203 * This function can be used by asm versions of crc32()
204 */
205const unsigned long FAR * ZEXPORT get_crc_table()
206{
207#ifdef DYNAMIC_CRC_TABLE
208 if (crc_table_empty)
209 make_crc_table();
210#endif /* DYNAMIC_CRC_TABLE */
211 return (const unsigned long FAR *)crc_table;
212}
213
214/* ========================================================================= */
215#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
216#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
217
218/* ========================================================================= */
219unsigned long ZEXPORT crc32(crc, buf, len)
220 unsigned long crc;
221 const unsigned char FAR *buf;
222 unsigned len;
223{
224 if (buf == Z_NULL) return 0UL;
225
226#ifdef DYNAMIC_CRC_TABLE
227 if (crc_table_empty)
228 make_crc_table();
229#endif /* DYNAMIC_CRC_TABLE */
230
231#ifdef BYFOUR
232 if (sizeof(void *) == sizeof(ptrdiff_t)) {
233 u4 endian;
234
235 endian = 1;
236 if (*((unsigned char *)(&endian)))
237 return crc32_little(crc, buf, len);
238 else
239 return crc32_big(crc, buf, len);
240 }
241#endif /* BYFOUR */
242 crc = crc ^ 0xffffffffUL;
243 while (len >= 8) {
244 DO8;
245 len -= 8;
246 }
247 if (len) do {
248 DO1;
249 } while (--len);
250 return crc ^ 0xffffffffUL;
251}
252
253#ifdef BYFOUR
254
255/* ========================================================================= */
256#define DOLIT4 c ^= *buf4++; \
257 c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
258 crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
259#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
260
261/* ========================================================================= */
262local unsigned long crc32_little(crc, buf, len)
263 unsigned long crc;
264 const unsigned char FAR *buf;
265 unsigned len;
266{
267 register u4 c;
268 register const u4 FAR *buf4;
269
270 c = (u4)crc;
271 c = ~c;
272 while (len && ((ptrdiff_t)buf & 3)) {
273 c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
274 len--;
275 }
276
277 buf4 = (const u4 FAR *)(const void FAR *)buf;
278 while (len >= 32) {
279 DOLIT32;
280 len -= 32;
281 }
282 while (len >= 4) {
283 DOLIT4;
284 len -= 4;
285 }
286 buf = (const unsigned char FAR *)buf4;
287
288 if (len) do {
289 c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
290 } while (--len);
291 c = ~c;
292 return (unsigned long)c;
293}
294
295/* ========================================================================= */
296#define DOBIG4 c ^= *++buf4; \
297 c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
298 crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
299#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
300
301/* ========================================================================= */
302local unsigned long crc32_big(crc, buf, len)
303 unsigned long crc;
304 const unsigned char FAR *buf;
305 unsigned len;
306{
307 register u4 c;
308 register const u4 FAR *buf4;
309
310 c = REV((u4)crc);
311 c = ~c;
312 while (len && ((ptrdiff_t)buf & 3)) {
313 c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
314 len--;
315 }
316
317 buf4 = (const u4 FAR *)(const void FAR *)buf;
318 buf4--;
319 while (len >= 32) {
320 DOBIG32;
321 len -= 32;
322 }
323 while (len >= 4) {
324 DOBIG4;
325 len -= 4;
326 }
327 buf4++;
328 buf = (const unsigned char FAR *)buf4;
329
330 if (len) do {
331 c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
332 } while (--len);
333 c = ~c;
334 return (unsigned long)(REV(c));
335}
336
337#endif /* BYFOUR */
338
339#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
340
341/* ========================================================================= */
342local unsigned long gf2_matrix_times(mat, vec)
343 unsigned long *mat;
344 unsigned long vec;
345{
346 unsigned long sum;
347
348 sum = 0;
349 while (vec) {
350 if (vec & 1)
351 sum ^= *mat;
352 vec >>= 1;
353 mat++;
354 }
355 return sum;
356}
357
358/* ========================================================================= */
359local void gf2_matrix_square(square, mat)
360 unsigned long *square;
361 unsigned long *mat;
362{
363 int n;
364
365 for (n = 0; n < GF2_DIM; n++)
366 square[n] = gf2_matrix_times(mat, mat[n]);
367}
368
369/* ========================================================================= */
370uLong ZEXPORT crc32_combine(crc1, crc2, len2)
371 uLong crc1;
372 uLong crc2;
373 z_off_t len2;
374{
375 int n;
376 unsigned long row;
377 unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
378 unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
379
380 /* degenerate case */
381 if (len2 == 0)
382 return crc1;
383
384 /* put operator for one zero bit in odd */
385 odd[0] = 0xedb88320L; /* CRC-32 polynomial */
386 row = 1;
387 for (n = 1; n < GF2_DIM; n++) {
388 odd[n] = row;
389 row <<= 1;
390 }
391
392 /* put operator for two zero bits in even */
393 gf2_matrix_square(even, odd);
394
395 /* put operator for four zero bits in odd */
396 gf2_matrix_square(odd, even);
397
398 /* apply len2 zeros to crc1 (first square will put the operator for one
399 zero byte, eight zero bits, in even) */
400 do {
401 /* apply zeros operator for this bit of len2 */
402 gf2_matrix_square(even, odd);
403 if (len2 & 1)
404 crc1 = gf2_matrix_times(even, crc1);
405 len2 >>= 1;
406
407 /* if no more bits set, then done */
408 if (len2 == 0)
409 break;
410
411 /* another iteration of the loop with odd and even swapped */
412 gf2_matrix_square(odd, even);
413 if (len2 & 1)
414 crc1 = gf2_matrix_times(odd, crc1);
415 len2 >>= 1;
416
417 /* if no more bits set, then done */
418 } while (len2 != 0);
419
420 /* return combined crc */
421 crc1 ^= crc2;
422 return crc1;
423}
diff --git a/utils/zenutils/libraries/zlib123/zlib/crc32.h b/utils/zenutils/libraries/zlib123/zlib/crc32.h
new file mode 100755
index 0000000000..5de49bc978
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/crc32.h
@@ -0,0 +1,441 @@
1/* crc32.h -- tables for rapid CRC calculation
2 * Generated automatically by crc32.c
3 */
4
5local const unsigned long FAR crc_table[TBLS][256] =
6{
7 {
8 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
9 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
10 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
11 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
12 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
13 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
14 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
15 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
16 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
17 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
18 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
19 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
20 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
21 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
22 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
23 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
24 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
25 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
26 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
27 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
28 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
29 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
30 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
31 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
32 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
33 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
34 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
35 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
36 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
37 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
38 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
39 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
40 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
41 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
42 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
43 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
44 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
45 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
46 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
47 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
48 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
49 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
50 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
51 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
52 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
53 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
54 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
55 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
56 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
57 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
58 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
59 0x2d02ef8dUL
60#ifdef BYFOUR
61 },
62 {
63 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
64 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
65 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
66 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
67 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
68 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
69 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
70 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
71 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
72 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
73 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
74 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
75 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
76 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
77 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
78 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
79 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
80 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
81 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
82 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
83 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
84 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
85 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
86 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
87 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
88 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
89 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
90 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
91 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
92 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
93 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
94 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
95 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
96 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
97 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
98 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
99 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
100 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
101 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
102 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
103 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
104 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
105 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
106 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
107 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
108 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
109 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
110 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
111 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
112 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
113 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
114 0x9324fd72UL
115 },
116 {
117 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
118 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
119 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
120 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
121 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
122 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
123 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
124 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
125 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
126 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
127 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
128 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
129 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
130 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
131 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
132 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
133 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
134 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
135 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
136 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
137 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
138 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
139 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
140 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
141 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
142 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
143 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
144 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
145 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
146 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
147 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
148 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
149 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
150 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
151 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
152 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
153 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
154 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
155 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
156 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
157 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
158 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
159 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
160 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
161 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
162 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
163 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
164 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
165 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
166 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
167 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
168 0xbe9834edUL
169 },
170 {
171 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
172 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
173 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
174 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
175 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
176 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
177 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
178 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
179 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
180 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
181 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
182 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
183 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
184 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
185 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
186 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
187 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
188 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
189 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
190 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
191 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
192 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
193 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
194 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
195 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
196 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
197 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
198 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
199 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
200 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
201 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
202 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
203 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
204 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
205 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
206 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
207 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
208 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
209 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
210 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
211 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
212 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
213 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
214 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
215 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
216 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
217 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
218 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
219 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
220 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
221 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
222 0xde0506f1UL
223 },
224 {
225 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
226 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
227 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
228 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
229 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
230 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
231 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
232 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
233 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
234 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
235 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
236 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
237 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
238 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
239 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
240 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
241 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
242 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
243 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
244 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
245 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
246 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
247 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
248 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
249 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
250 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
251 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
252 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
253 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
254 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
255 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
256 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
257 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
258 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
259 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
260 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
261 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
262 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
263 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
264 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
265 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
266 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
267 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
268 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
269 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
270 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
271 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
272 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
273 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
274 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
275 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
276 0x8def022dUL
277 },
278 {
279 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
280 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
281 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
282 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
283 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
284 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
285 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
286 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
287 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
288 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
289 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
290 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
291 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
292 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
293 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
294 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
295 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
296 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
297 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
298 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
299 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
300 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
301 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
302 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
303 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
304 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
305 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
306 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
307 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
308 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
309 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
310 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
311 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
312 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
313 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
314 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
315 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
316 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
317 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
318 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
319 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
320 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
321 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
322 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
323 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
324 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
325 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
326 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
327 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
328 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
329 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
330 0x72fd2493UL
331 },
332 {
333 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
334 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
335 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
336 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
337 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
338 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
339 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
340 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
341 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
342 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
343 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
344 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
345 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
346 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
347 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
348 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
349 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
350 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
351 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
352 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
353 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
354 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
355 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
356 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
357 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
358 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
359 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
360 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
361 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
362 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
363 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
364 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
365 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
366 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
367 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
368 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
369 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
370 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
371 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
372 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
373 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
374 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
375 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
376 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
377 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
378 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
379 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
380 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
381 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
382 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
383 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
384 0xed3498beUL
385 },
386 {
387 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
388 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
389 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
390 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
391 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
392 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
393 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
394 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
395 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
396 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
397 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
398 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
399 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
400 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
401 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
402 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
403 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
404 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
405 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
406 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
407 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
408 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
409 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
410 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
411 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
412 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
413 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
414 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
415 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
416 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
417 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
418 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
419 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
420 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
421 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
422 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
423 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
424 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
425 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
426 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
427 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
428 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
429 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
430 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
431 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
432 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
433 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
434 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
435 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
436 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
437 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
438 0xf10605deUL
439#endif
440 }
441};
diff --git a/utils/zenutils/libraries/zlib123/zlib/deflate.c b/utils/zenutils/libraries/zlib123/zlib/deflate.c
new file mode 100755
index 0000000000..529f716b7a
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/deflate.c
@@ -0,0 +1,1736 @@
1/* deflate.c -- compress data using the deflation algorithm
2 * Copyright (C) 1995-2005 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/*
7 * ALGORITHM
8 *
9 * The "deflation" process depends on being able to identify portions
10 * of the input text which are identical to earlier input (within a
11 * sliding window trailing behind the input currently being processed).
12 *
13 * The most straightforward technique turns out to be the fastest for
14 * most input files: try all possible matches and select the longest.
15 * The key feature of this algorithm is that insertions into the string
16 * dictionary are very simple and thus fast, and deletions are avoided
17 * completely. Insertions are performed at each input character, whereas
18 * string matches are performed only when the previous match ends. So it
19 * is preferable to spend more time in matches to allow very fast string
20 * insertions and avoid deletions. The matching algorithm for small
21 * strings is inspired from that of Rabin & Karp. A brute force approach
22 * is used to find longer strings when a small match has been found.
23 * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
24 * (by Leonid Broukhis).
25 * A previous version of this file used a more sophisticated algorithm
26 * (by Fiala and Greene) which is guaranteed to run in linear amortized
27 * time, but has a larger average cost, uses more memory and is patented.
28 * However the F&G algorithm may be faster for some highly redundant
29 * files if the parameter max_chain_length (described below) is too large.
30 *
31 * ACKNOWLEDGEMENTS
32 *
33 * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
34 * I found it in 'freeze' written by Leonid Broukhis.
35 * Thanks to many people for bug reports and testing.
36 *
37 * REFERENCES
38 *
39 * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
40 * Available in http://www.ietf.org/rfc/rfc1951.txt
41 *
42 * A description of the Rabin and Karp algorithm is given in the book
43 * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
44 *
45 * Fiala,E.R., and Greene,D.H.
46 * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
47 *
48 */
49
50/* @(#) $Id$ */
51
52#include "deflate.h"
53
54const char deflate_copyright[] =
55 " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
56/*
57 If you use the zlib library in a product, an acknowledgment is welcome
58 in the documentation of your product. If for some reason you cannot
59 include such an acknowledgment, I would appreciate that you keep this
60 copyright string in the executable of your product.
61 */
62
63/* ===========================================================================
64 * Function prototypes.
65 */
66typedef enum {
67 need_more, /* block not completed, need more input or more output */
68 block_done, /* block flush performed */
69 finish_started, /* finish started, need only more output at next deflate */
70 finish_done /* finish done, accept no more input or output */
71} block_state;
72
73typedef block_state (*compress_func) OF((deflate_state *s, int flush));
74/* Compression function. Returns the block state after the call. */
75
76local void fill_window OF((deflate_state *s));
77local block_state deflate_stored OF((deflate_state *s, int flush));
78local block_state deflate_fast OF((deflate_state *s, int flush));
79#ifndef FASTEST
80local block_state deflate_slow OF((deflate_state *s, int flush));
81#endif
82local void lm_init OF((deflate_state *s));
83local void putShortMSB OF((deflate_state *s, uInt b));
84local void flush_pending OF((z_streamp strm));
85local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
86#ifndef FASTEST
87#ifdef ASMV
88 void match_init OF((void)); /* asm code initialization */
89 uInt longest_match OF((deflate_state *s, IPos cur_match));
90#else
91local uInt longest_match OF((deflate_state *s, IPos cur_match));
92#endif
93#endif
94local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
95
96#ifdef DEBUG
97local void check_match OF((deflate_state *s, IPos start, IPos match,
98 int length));
99#endif
100
101/* ===========================================================================
102 * Local data
103 */
104
105#define NIL 0
106/* Tail of hash chains */
107
108#ifndef TOO_FAR
109# define TOO_FAR 4096
110#endif
111/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
112
113#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
114/* Minimum amount of lookahead, except at the end of the input file.
115 * See deflate.c for comments about the MIN_MATCH+1.
116 */
117
118/* Values for max_lazy_match, good_match and max_chain_length, depending on
119 * the desired pack level (0..9). The values given below have been tuned to
120 * exclude worst case performance for pathological files. Better values may be
121 * found for specific files.
122 */
123typedef struct config_s {
124 ush good_length; /* reduce lazy search above this match length */
125 ush max_lazy; /* do not perform lazy search above this match length */
126 ush nice_length; /* quit search above this match length */
127 ush max_chain;
128 compress_func func;
129} config;
130
131#ifdef FASTEST
132local const config configuration_table[2] = {
133/* good lazy nice chain */
134/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
135/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
136#else
137local const config configuration_table[10] = {
138/* good lazy nice chain */
139/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
140/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
141/* 2 */ {4, 5, 16, 8, deflate_fast},
142/* 3 */ {4, 6, 32, 32, deflate_fast},
143
144/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
145/* 5 */ {8, 16, 32, 32, deflate_slow},
146/* 6 */ {8, 16, 128, 128, deflate_slow},
147/* 7 */ {8, 32, 128, 256, deflate_slow},
148/* 8 */ {32, 128, 258, 1024, deflate_slow},
149/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
150#endif
151
152/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
153 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
154 * meaning.
155 */
156
157#define EQUAL 0
158/* result of memcmp for equal strings */
159
160#ifndef NO_DUMMY_DECL
161struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
162#endif
163
164/* ===========================================================================
165 * Update a hash value with the given input byte
166 * IN assertion: all calls to to UPDATE_HASH are made with consecutive
167 * input characters, so that a running hash key can be computed from the
168 * previous key instead of complete recalculation each time.
169 */
170#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
171
172
173/* ===========================================================================
174 * Insert string str in the dictionary and set match_head to the previous head
175 * of the hash chain (the most recent string with same hash key). Return
176 * the previous length of the hash chain.
177 * If this file is compiled with -DFASTEST, the compression level is forced
178 * to 1, and no hash chains are maintained.
179 * IN assertion: all calls to to INSERT_STRING are made with consecutive
180 * input characters and the first MIN_MATCH bytes of str are valid
181 * (except for the last MIN_MATCH-1 bytes of the input file).
182 */
183#ifdef FASTEST
184#define INSERT_STRING(s, str, match_head) \
185 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
186 match_head = s->head[s->ins_h], \
187 s->head[s->ins_h] = (Pos)(str))
188#else
189#define INSERT_STRING(s, str, match_head) \
190 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
191 match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
192 s->head[s->ins_h] = (Pos)(str))
193#endif
194
195/* ===========================================================================
196 * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
197 * prev[] will be initialized on the fly.
198 */
199#define CLEAR_HASH(s) \
200 s->head[s->hash_size-1] = NIL; \
201 zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
202
203/* ========================================================================= */
204int ZEXPORT deflateInit_(strm, level, version, stream_size)
205 z_streamp strm;
206 int level;
207 const char *version;
208 int stream_size;
209{
210 return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
211 Z_DEFAULT_STRATEGY, version, stream_size);
212 /* To do: ignore strm->next_in if we use it as window */
213}
214
215/* ========================================================================= */
216int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
217 version, stream_size)
218 z_streamp strm;
219 int level;
220 int method;
221 int windowBits;
222 int memLevel;
223 int strategy;
224 const char *version;
225 int stream_size;
226{
227 deflate_state *s;
228 int wrap = 1;
229 static const char my_version[] = ZLIB_VERSION;
230
231 ushf *overlay;
232 /* We overlay pending_buf and d_buf+l_buf. This works since the average
233 * output size for (length,distance) codes is <= 24 bits.
234 */
235
236 if (version == Z_NULL || version[0] != my_version[0] ||
237 stream_size != sizeof(z_stream)) {
238 return Z_VERSION_ERROR;
239 }
240 if (strm == Z_NULL) return Z_STREAM_ERROR;
241
242 strm->msg = Z_NULL;
243 if (strm->zalloc == (alloc_func)0) {
244 strm->zalloc = zcalloc;
245 strm->opaque = (voidpf)0;
246 }
247 if (strm->zfree == (free_func)0) strm->zfree = zcfree;
248
249#ifdef FASTEST
250 if (level != 0) level = 1;
251#else
252 if (level == Z_DEFAULT_COMPRESSION) level = 6;
253#endif
254
255 if (windowBits < 0) { /* suppress zlib wrapper */
256 wrap = 0;
257 windowBits = -windowBits;
258 }
259#ifdef GZIP
260 else if (windowBits > 15) {
261 wrap = 2; /* write gzip wrapper instead */
262 windowBits -= 16;
263 }
264#endif
265 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
266 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
267 strategy < 0 || strategy > Z_FIXED) {
268 return Z_STREAM_ERROR;
269 }
270 if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
271 s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
272 if (s == Z_NULL) return Z_MEM_ERROR;
273 strm->state = (struct internal_state FAR *)s;
274 s->strm = strm;
275
276 s->wrap = wrap;
277 s->gzhead = Z_NULL;
278 s->w_bits = windowBits;
279 s->w_size = 1 << s->w_bits;
280 s->w_mask = s->w_size - 1;
281
282 s->hash_bits = memLevel + 7;
283 s->hash_size = 1 << s->hash_bits;
284 s->hash_mask = s->hash_size - 1;
285 s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
286
287 s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
288 s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
289 s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
290
291 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
292
293 overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
294 s->pending_buf = (uchf *) overlay;
295 s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
296
297 if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
298 s->pending_buf == Z_NULL) {
299 s->status = FINISH_STATE;
300 strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
301 deflateEnd (strm);
302 return Z_MEM_ERROR;
303 }
304 s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
305 s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
306
307 s->level = level;
308 s->strategy = strategy;
309 s->method = (Byte)method;
310
311 return deflateReset(strm);
312}
313
314/* ========================================================================= */
315int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
316 z_streamp strm;
317 const Bytef *dictionary;
318 uInt dictLength;
319{
320 deflate_state *s;
321 uInt length = dictLength;
322 uInt n;
323 IPos hash_head = 0;
324
325 if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
326 strm->state->wrap == 2 ||
327 (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
328 return Z_STREAM_ERROR;
329
330 s = strm->state;
331 if (s->wrap)
332 strm->adler = adler32(strm->adler, dictionary, dictLength);
333
334 if (length < MIN_MATCH) return Z_OK;
335 if (length > MAX_DIST(s)) {
336 length = MAX_DIST(s);
337 dictionary += dictLength - length; /* use the tail of the dictionary */
338 }
339 zmemcpy(s->window, dictionary, length);
340 s->strstart = length;
341 s->block_start = (long)length;
342
343 /* Insert all strings in the hash table (except for the last two bytes).
344 * s->lookahead stays null, so s->ins_h will be recomputed at the next
345 * call of fill_window.
346 */
347 s->ins_h = s->window[0];
348 UPDATE_HASH(s, s->ins_h, s->window[1]);
349 for (n = 0; n <= length - MIN_MATCH; n++) {
350 INSERT_STRING(s, n, hash_head);
351 }
352 if (hash_head) hash_head = 0; /* to make compiler happy */
353 return Z_OK;
354}
355
356/* ========================================================================= */
357int ZEXPORT deflateReset (strm)
358 z_streamp strm;
359{
360 deflate_state *s;
361
362 if (strm == Z_NULL || strm->state == Z_NULL ||
363 strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
364 return Z_STREAM_ERROR;
365 }
366
367 strm->total_in = strm->total_out = 0;
368 strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
369 strm->data_type = Z_UNKNOWN;
370
371 s = (deflate_state *)strm->state;
372 s->pending = 0;
373 s->pending_out = s->pending_buf;
374
375 if (s->wrap < 0) {
376 s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
377 }
378 s->status = s->wrap ? INIT_STATE : BUSY_STATE;
379 strm->adler =
380#ifdef GZIP
381 s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
382#endif
383 adler32(0L, Z_NULL, 0);
384 s->last_flush = Z_NO_FLUSH;
385
386 _tr_init(s);
387 lm_init(s);
388
389 return Z_OK;
390}
391
392/* ========================================================================= */
393int ZEXPORT deflateSetHeader (strm, head)
394 z_streamp strm;
395 gz_headerp head;
396{
397 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
398 if (strm->state->wrap != 2) return Z_STREAM_ERROR;
399 strm->state->gzhead = head;
400 return Z_OK;
401}
402
403/* ========================================================================= */
404int ZEXPORT deflatePrime (strm, bits, value)
405 z_streamp strm;
406 int bits;
407 int value;
408{
409 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
410 strm->state->bi_valid = bits;
411 strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
412 return Z_OK;
413}
414
415/* ========================================================================= */
416int ZEXPORT deflateParams(strm, level, strategy)
417 z_streamp strm;
418 int level;
419 int strategy;
420{
421 deflate_state *s;
422 compress_func func;
423 int err = Z_OK;
424
425 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
426 s = strm->state;
427
428#ifdef FASTEST
429 if (level != 0) level = 1;
430#else
431 if (level == Z_DEFAULT_COMPRESSION) level = 6;
432#endif
433 if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
434 return Z_STREAM_ERROR;
435 }
436 func = configuration_table[s->level].func;
437
438 if (func != configuration_table[level].func && strm->total_in != 0) {
439 /* Flush the last buffer: */
440 err = deflate(strm, Z_PARTIAL_FLUSH);
441 }
442 if (s->level != level) {
443 s->level = level;
444 s->max_lazy_match = configuration_table[level].max_lazy;
445 s->good_match = configuration_table[level].good_length;
446 s->nice_match = configuration_table[level].nice_length;
447 s->max_chain_length = configuration_table[level].max_chain;
448 }
449 s->strategy = strategy;
450 return err;
451}
452
453/* ========================================================================= */
454int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
455 z_streamp strm;
456 int good_length;
457 int max_lazy;
458 int nice_length;
459 int max_chain;
460{
461 deflate_state *s;
462
463 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
464 s = strm->state;
465 s->good_match = good_length;
466 s->max_lazy_match = max_lazy;
467 s->nice_match = nice_length;
468 s->max_chain_length = max_chain;
469 return Z_OK;
470}
471
472/* =========================================================================
473 * For the default windowBits of 15 and memLevel of 8, this function returns
474 * a close to exact, as well as small, upper bound on the compressed size.
475 * They are coded as constants here for a reason--if the #define's are
476 * changed, then this function needs to be changed as well. The return
477 * value for 15 and 8 only works for those exact settings.
478 *
479 * For any setting other than those defaults for windowBits and memLevel,
480 * the value returned is a conservative worst case for the maximum expansion
481 * resulting from using fixed blocks instead of stored blocks, which deflate
482 * can emit on compressed data for some combinations of the parameters.
483 *
484 * This function could be more sophisticated to provide closer upper bounds
485 * for every combination of windowBits and memLevel, as well as wrap.
486 * But even the conservative upper bound of about 14% expansion does not
487 * seem onerous for output buffer allocation.
488 */
489uLong ZEXPORT deflateBound(strm, sourceLen)
490 z_streamp strm;
491 uLong sourceLen;
492{
493 deflate_state *s;
494 uLong destLen;
495
496 /* conservative upper bound */
497 destLen = sourceLen +
498 ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
499
500 /* if can't get parameters, return conservative bound */
501 if (strm == Z_NULL || strm->state == Z_NULL)
502 return destLen;
503
504 /* if not default parameters, return conservative bound */
505 s = strm->state;
506 if (s->w_bits != 15 || s->hash_bits != 8 + 7)
507 return destLen;
508
509 /* default settings: return tight bound for that case */
510 return compressBound(sourceLen);
511}
512
513/* =========================================================================
514 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
515 * IN assertion: the stream state is correct and there is enough room in
516 * pending_buf.
517 */
518local void putShortMSB (s, b)
519 deflate_state *s;
520 uInt b;
521{
522 put_byte(s, (Byte)(b >> 8));
523 put_byte(s, (Byte)(b & 0xff));
524}
525
526/* =========================================================================
527 * Flush as much pending output as possible. All deflate() output goes
528 * through this function so some applications may wish to modify it
529 * to avoid allocating a large strm->next_out buffer and copying into it.
530 * (See also read_buf()).
531 */
532local void flush_pending(strm)
533 z_streamp strm;
534{
535 unsigned len = strm->state->pending;
536
537 if (len > strm->avail_out) len = strm->avail_out;
538 if (len == 0) return;
539
540 zmemcpy(strm->next_out, strm->state->pending_out, len);
541 strm->next_out += len;
542 strm->state->pending_out += len;
543 strm->total_out += len;
544 strm->avail_out -= len;
545 strm->state->pending -= len;
546 if (strm->state->pending == 0) {
547 strm->state->pending_out = strm->state->pending_buf;
548 }
549}
550
551/* ========================================================================= */
552int ZEXPORT deflate (strm, flush)
553 z_streamp strm;
554 int flush;
555{
556 int old_flush; /* value of flush param for previous deflate call */
557 deflate_state *s;
558
559 if (strm == Z_NULL || strm->state == Z_NULL ||
560 flush > Z_FINISH || flush < 0) {
561 return Z_STREAM_ERROR;
562 }
563 s = strm->state;
564
565 if (strm->next_out == Z_NULL ||
566 (strm->next_in == Z_NULL && strm->avail_in != 0) ||
567 (s->status == FINISH_STATE && flush != Z_FINISH)) {
568 ERR_RETURN(strm, Z_STREAM_ERROR);
569 }
570 if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
571
572 s->strm = strm; /* just in case */
573 old_flush = s->last_flush;
574 s->last_flush = flush;
575
576 /* Write the header */
577 if (s->status == INIT_STATE) {
578#ifdef GZIP
579 if (s->wrap == 2) {
580 strm->adler = crc32(0L, Z_NULL, 0);
581 put_byte(s, 31);
582 put_byte(s, 139);
583 put_byte(s, 8);
584 if (s->gzhead == NULL) {
585 put_byte(s, 0);
586 put_byte(s, 0);
587 put_byte(s, 0);
588 put_byte(s, 0);
589 put_byte(s, 0);
590 put_byte(s, s->level == 9 ? 2 :
591 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
592 4 : 0));
593 put_byte(s, OS_CODE);
594 s->status = BUSY_STATE;
595 }
596 else {
597 put_byte(s, (s->gzhead->text ? 1 : 0) +
598 (s->gzhead->hcrc ? 2 : 0) +
599 (s->gzhead->extra == Z_NULL ? 0 : 4) +
600 (s->gzhead->name == Z_NULL ? 0 : 8) +
601 (s->gzhead->comment == Z_NULL ? 0 : 16)
602 );
603 put_byte(s, (Byte)(s->gzhead->time & 0xff));
604 put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
605 put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
606 put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
607 put_byte(s, s->level == 9 ? 2 :
608 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
609 4 : 0));
610 put_byte(s, s->gzhead->os & 0xff);
611 if (s->gzhead->extra != NULL) {
612 put_byte(s, s->gzhead->extra_len & 0xff);
613 put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
614 }
615 if (s->gzhead->hcrc)
616 strm->adler = crc32(strm->adler, s->pending_buf,
617 s->pending);
618 s->gzindex = 0;
619 s->status = EXTRA_STATE;
620 }
621 }
622 else
623#endif
624 {
625 uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
626 uInt level_flags;
627
628 if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
629 level_flags = 0;
630 else if (s->level < 6)
631 level_flags = 1;
632 else if (s->level == 6)
633 level_flags = 2;
634 else
635 level_flags = 3;
636 header |= (level_flags << 6);
637 if (s->strstart != 0) header |= PRESET_DICT;
638 header += 31 - (header % 31);
639
640 s->status = BUSY_STATE;
641 putShortMSB(s, header);
642
643 /* Save the adler32 of the preset dictionary: */
644 if (s->strstart != 0) {
645 putShortMSB(s, (uInt)(strm->adler >> 16));
646 putShortMSB(s, (uInt)(strm->adler & 0xffff));
647 }
648 strm->adler = adler32(0L, Z_NULL, 0);
649 }
650 }
651#ifdef GZIP
652 if (s->status == EXTRA_STATE) {
653 if (s->gzhead->extra != NULL) {
654 uInt beg = s->pending; /* start of bytes to update crc */
655
656 while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
657 if (s->pending == s->pending_buf_size) {
658 if (s->gzhead->hcrc && s->pending > beg)
659 strm->adler = crc32(strm->adler, s->pending_buf + beg,
660 s->pending - beg);
661 flush_pending(strm);
662 beg = s->pending;
663 if (s->pending == s->pending_buf_size)
664 break;
665 }
666 put_byte(s, s->gzhead->extra[s->gzindex]);
667 s->gzindex++;
668 }
669 if (s->gzhead->hcrc && s->pending > beg)
670 strm->adler = crc32(strm->adler, s->pending_buf + beg,
671 s->pending - beg);
672 if (s->gzindex == s->gzhead->extra_len) {
673 s->gzindex = 0;
674 s->status = NAME_STATE;
675 }
676 }
677 else
678 s->status = NAME_STATE;
679 }
680 if (s->status == NAME_STATE) {
681 if (s->gzhead->name != NULL) {
682 uInt beg = s->pending; /* start of bytes to update crc */
683 int val;
684
685 do {
686 if (s->pending == s->pending_buf_size) {
687 if (s->gzhead->hcrc && s->pending > beg)
688 strm->adler = crc32(strm->adler, s->pending_buf + beg,
689 s->pending - beg);
690 flush_pending(strm);
691 beg = s->pending;
692 if (s->pending == s->pending_buf_size) {
693 val = 1;
694 break;
695 }
696 }
697 val = s->gzhead->name[s->gzindex++];
698 put_byte(s, val);
699 } while (val != 0);
700 if (s->gzhead->hcrc && s->pending > beg)
701 strm->adler = crc32(strm->adler, s->pending_buf + beg,
702 s->pending - beg);
703 if (val == 0) {
704 s->gzindex = 0;
705 s->status = COMMENT_STATE;
706 }
707 }
708 else
709 s->status = COMMENT_STATE;
710 }
711 if (s->status == COMMENT_STATE) {
712 if (s->gzhead->comment != NULL) {
713 uInt beg = s->pending; /* start of bytes to update crc */
714 int val;
715
716 do {
717 if (s->pending == s->pending_buf_size) {
718 if (s->gzhead->hcrc && s->pending > beg)
719 strm->adler = crc32(strm->adler, s->pending_buf + beg,
720 s->pending - beg);
721 flush_pending(strm);
722 beg = s->pending;
723 if (s->pending == s->pending_buf_size) {
724 val = 1;
725 break;
726 }
727 }
728 val = s->gzhead->comment[s->gzindex++];
729 put_byte(s, val);
730 } while (val != 0);
731 if (s->gzhead->hcrc && s->pending > beg)
732 strm->adler = crc32(strm->adler, s->pending_buf + beg,
733 s->pending - beg);
734 if (val == 0)
735 s->status = HCRC_STATE;
736 }
737 else
738 s->status = HCRC_STATE;
739 }
740 if (s->status == HCRC_STATE) {
741 if (s->gzhead->hcrc) {
742 if (s->pending + 2 > s->pending_buf_size)
743 flush_pending(strm);
744 if (s->pending + 2 <= s->pending_buf_size) {
745 put_byte(s, (Byte)(strm->adler & 0xff));
746 put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
747 strm->adler = crc32(0L, Z_NULL, 0);
748 s->status = BUSY_STATE;
749 }
750 }
751 else
752 s->status = BUSY_STATE;
753 }
754#endif
755
756 /* Flush as much pending output as possible */
757 if (s->pending != 0) {
758 flush_pending(strm);
759 if (strm->avail_out == 0) {
760 /* Since avail_out is 0, deflate will be called again with
761 * more output space, but possibly with both pending and
762 * avail_in equal to zero. There won't be anything to do,
763 * but this is not an error situation so make sure we
764 * return OK instead of BUF_ERROR at next call of deflate:
765 */
766 s->last_flush = -1;
767 return Z_OK;
768 }
769
770 /* Make sure there is something to do and avoid duplicate consecutive
771 * flushes. For repeated and useless calls with Z_FINISH, we keep
772 * returning Z_STREAM_END instead of Z_BUF_ERROR.
773 */
774 } else if (strm->avail_in == 0 && flush <= old_flush &&
775 flush != Z_FINISH) {
776 ERR_RETURN(strm, Z_BUF_ERROR);
777 }
778
779 /* User must not provide more input after the first FINISH: */
780 if (s->status == FINISH_STATE && strm->avail_in != 0) {
781 ERR_RETURN(strm, Z_BUF_ERROR);
782 }
783
784 /* Start a new block or continue the current one.
785 */
786 if (strm->avail_in != 0 || s->lookahead != 0 ||
787 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
788 block_state bstate;
789
790 bstate = (*(configuration_table[s->level].func))(s, flush);
791
792 if (bstate == finish_started || bstate == finish_done) {
793 s->status = FINISH_STATE;
794 }
795 if (bstate == need_more || bstate == finish_started) {
796 if (strm->avail_out == 0) {
797 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
798 }
799 return Z_OK;
800 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
801 * of deflate should use the same flush parameter to make sure
802 * that the flush is complete. So we don't have to output an
803 * empty block here, this will be done at next call. This also
804 * ensures that for a very small output buffer, we emit at most
805 * one empty block.
806 */
807 }
808 if (bstate == block_done) {
809 if (flush == Z_PARTIAL_FLUSH) {
810 _tr_align(s);
811 } else { /* FULL_FLUSH or SYNC_FLUSH */
812 _tr_stored_block(s, (char*)0, 0L, 0);
813 /* For a full flush, this empty block will be recognized
814 * as a special marker by inflate_sync().
815 */
816 if (flush == Z_FULL_FLUSH) {
817 CLEAR_HASH(s); /* forget history */
818 }
819 }
820 flush_pending(strm);
821 if (strm->avail_out == 0) {
822 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
823 return Z_OK;
824 }
825 }
826 }
827 Assert(strm->avail_out > 0, "bug2");
828
829 if (flush != Z_FINISH) return Z_OK;
830 if (s->wrap <= 0) return Z_STREAM_END;
831
832 /* Write the trailer */
833#ifdef GZIP
834 if (s->wrap == 2) {
835 put_byte(s, (Byte)(strm->adler & 0xff));
836 put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
837 put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
838 put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
839 put_byte(s, (Byte)(strm->total_in & 0xff));
840 put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
841 put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
842 put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
843 }
844 else
845#endif
846 {
847 putShortMSB(s, (uInt)(strm->adler >> 16));
848 putShortMSB(s, (uInt)(strm->adler & 0xffff));
849 }
850 flush_pending(strm);
851 /* If avail_out is zero, the application will call deflate again
852 * to flush the rest.
853 */
854 if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
855 return s->pending != 0 ? Z_OK : Z_STREAM_END;
856}
857
858/* ========================================================================= */
859int ZEXPORT deflateEnd (strm)
860 z_streamp strm;
861{
862 int status;
863
864 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
865
866 status = strm->state->status;
867 if (status != INIT_STATE &&
868 status != EXTRA_STATE &&
869 status != NAME_STATE &&
870 status != COMMENT_STATE &&
871 status != HCRC_STATE &&
872 status != BUSY_STATE &&
873 status != FINISH_STATE) {
874 return Z_STREAM_ERROR;
875 }
876
877 /* Deallocate in reverse order of allocations: */
878 TRY_FREE(strm, strm->state->pending_buf);
879 TRY_FREE(strm, strm->state->head);
880 TRY_FREE(strm, strm->state->prev);
881 TRY_FREE(strm, strm->state->window);
882
883 ZFREE(strm, strm->state);
884 strm->state = Z_NULL;
885
886 return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
887}
888
889/* =========================================================================
890 * Copy the source state to the destination state.
891 * To simplify the source, this is not supported for 16-bit MSDOS (which
892 * doesn't have enough memory anyway to duplicate compression states).
893 */
894int ZEXPORT deflateCopy (dest, source)
895 z_streamp dest;
896 z_streamp source;
897{
898#ifdef MAXSEG_64K
899 return Z_STREAM_ERROR;
900#else
901 deflate_state *ds;
902 deflate_state *ss;
903 ushf *overlay;
904
905
906 if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
907 return Z_STREAM_ERROR;
908 }
909
910 ss = source->state;
911
912 zmemcpy(dest, source, sizeof(z_stream));
913
914 ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
915 if (ds == Z_NULL) return Z_MEM_ERROR;
916 dest->state = (struct internal_state FAR *) ds;
917 zmemcpy(ds, ss, sizeof(deflate_state));
918 ds->strm = dest;
919
920 ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
921 ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
922 ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
923 overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
924 ds->pending_buf = (uchf *) overlay;
925
926 if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
927 ds->pending_buf == Z_NULL) {
928 deflateEnd (dest);
929 return Z_MEM_ERROR;
930 }
931 /* following zmemcpy do not work for 16-bit MSDOS */
932 zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
933 zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
934 zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
935 zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
936
937 ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
938 ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
939 ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
940
941 ds->l_desc.dyn_tree = ds->dyn_ltree;
942 ds->d_desc.dyn_tree = ds->dyn_dtree;
943 ds->bl_desc.dyn_tree = ds->bl_tree;
944
945 return Z_OK;
946#endif /* MAXSEG_64K */
947}
948
949/* ===========================================================================
950 * Read a new buffer from the current input stream, update the adler32
951 * and total number of bytes read. All deflate() input goes through
952 * this function so some applications may wish to modify it to avoid
953 * allocating a large strm->next_in buffer and copying from it.
954 * (See also flush_pending()).
955 */
956local int read_buf(strm, buf, size)
957 z_streamp strm;
958 Bytef *buf;
959 unsigned size;
960{
961 unsigned len = strm->avail_in;
962
963 if (len > size) len = size;
964 if (len == 0) return 0;
965
966 strm->avail_in -= len;
967
968 if (strm->state->wrap == 1) {
969 strm->adler = adler32(strm->adler, strm->next_in, len);
970 }
971#ifdef GZIP
972 else if (strm->state->wrap == 2) {
973 strm->adler = crc32(strm->adler, strm->next_in, len);
974 }
975#endif
976 zmemcpy(buf, strm->next_in, len);
977 strm->next_in += len;
978 strm->total_in += len;
979
980 return (int)len;
981}
982
983/* ===========================================================================
984 * Initialize the "longest match" routines for a new zlib stream
985 */
986local void lm_init (s)
987 deflate_state *s;
988{
989 s->window_size = (ulg)2L*s->w_size;
990
991 CLEAR_HASH(s);
992
993 /* Set the default configuration parameters:
994 */
995 s->max_lazy_match = configuration_table[s->level].max_lazy;
996 s->good_match = configuration_table[s->level].good_length;
997 s->nice_match = configuration_table[s->level].nice_length;
998 s->max_chain_length = configuration_table[s->level].max_chain;
999
1000 s->strstart = 0;
1001 s->block_start = 0L;
1002 s->lookahead = 0;
1003 s->match_length = s->prev_length = MIN_MATCH-1;
1004 s->match_available = 0;
1005 s->ins_h = 0;
1006#ifndef FASTEST
1007#ifdef ASMV
1008 match_init(); /* initialize the asm code */
1009#endif
1010#endif
1011}
1012
1013#ifndef FASTEST
1014/* ===========================================================================
1015 * Set match_start to the longest match starting at the given string and
1016 * return its length. Matches shorter or equal to prev_length are discarded,
1017 * in which case the result is equal to prev_length and match_start is
1018 * garbage.
1019 * IN assertions: cur_match is the head of the hash chain for the current
1020 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1021 * OUT assertion: the match length is not greater than s->lookahead.
1022 */
1023#ifndef ASMV
1024/* For 80x86 and 680x0, an optimized version will be provided in match.asm or
1025 * match.S. The code will be functionally equivalent.
1026 */
1027local uInt longest_match(s, cur_match)
1028 deflate_state *s;
1029 IPos cur_match; /* current match */
1030{
1031 unsigned chain_length = s->max_chain_length;/* max hash chain length */
1032 register Bytef *scan = s->window + s->strstart; /* current string */
1033 register Bytef *match; /* matched string */
1034 register int len; /* length of current match */
1035 int best_len = s->prev_length; /* best match length so far */
1036 int nice_match = s->nice_match; /* stop if match long enough */
1037 IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
1038 s->strstart - (IPos)MAX_DIST(s) : NIL;
1039 /* Stop when cur_match becomes <= limit. To simplify the code,
1040 * we prevent matches with the string of window index 0.
1041 */
1042 Posf *prev = s->prev;
1043 uInt wmask = s->w_mask;
1044
1045#ifdef UNALIGNED_OK
1046 /* Compare two bytes at a time. Note: this is not always beneficial.
1047 * Try with and without -DUNALIGNED_OK to check.
1048 */
1049 register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
1050 register ush scan_start = *(ushf*)scan;
1051 register ush scan_end = *(ushf*)(scan+best_len-1);
1052#else
1053 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1054 register Byte scan_end1 = scan[best_len-1];
1055 register Byte scan_end = scan[best_len];
1056#endif
1057
1058 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1059 * It is easy to get rid of this optimization if necessary.
1060 */
1061 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1062
1063 /* Do not waste too much time if we already have a good match: */
1064 if (s->prev_length >= s->good_match) {
1065 chain_length >>= 2;
1066 }
1067 /* Do not look for matches beyond the end of the input. This is necessary
1068 * to make deflate deterministic.
1069 */
1070 if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
1071
1072 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1073
1074 do {
1075 Assert(cur_match < s->strstart, "no future");
1076 match = s->window + cur_match;
1077
1078 /* Skip to next match if the match length cannot increase
1079 * or if the match length is less than 2. Note that the checks below
1080 * for insufficient lookahead only occur occasionally for performance
1081 * reasons. Therefore uninitialized memory will be accessed, and
1082 * conditional jumps will be made that depend on those values.
1083 * However the length of the match is limited to the lookahead, so
1084 * the output of deflate is not affected by the uninitialized values.
1085 */
1086#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
1087 /* This code assumes sizeof(unsigned short) == 2. Do not use
1088 * UNALIGNED_OK if your compiler uses a different size.
1089 */
1090 if (*(ushf*)(match+best_len-1) != scan_end ||
1091 *(ushf*)match != scan_start) continue;
1092
1093 /* It is not necessary to compare scan[2] and match[2] since they are
1094 * always equal when the other bytes match, given that the hash keys
1095 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1096 * strstart+3, +5, ... up to strstart+257. We check for insufficient
1097 * lookahead only every 4th comparison; the 128th check will be made
1098 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
1099 * necessary to put more guard bytes at the end of the window, or
1100 * to check more often for insufficient lookahead.
1101 */
1102 Assert(scan[2] == match[2], "scan[2]?");
1103 scan++, match++;
1104 do {
1105 } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1106 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1107 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1108 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1109 scan < strend);
1110 /* The funny "do {}" generates better code on most compilers */
1111
1112 /* Here, scan <= window+strstart+257 */
1113 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1114 if (*scan == *match) scan++;
1115
1116 len = (MAX_MATCH - 1) - (int)(strend-scan);
1117 scan = strend - (MAX_MATCH-1);
1118
1119#else /* UNALIGNED_OK */
1120
1121 if (match[best_len] != scan_end ||
1122 match[best_len-1] != scan_end1 ||
1123 *match != *scan ||
1124 *++match != scan[1]) continue;
1125
1126 /* The check at best_len-1 can be removed because it will be made
1127 * again later. (This heuristic is not always a win.)
1128 * It is not necessary to compare scan[2] and match[2] since they
1129 * are always equal when the other bytes match, given that
1130 * the hash keys are equal and that HASH_BITS >= 8.
1131 */
1132 scan += 2, match++;
1133 Assert(*scan == *match, "match[2]?");
1134
1135 /* We check for insufficient lookahead only every 8th comparison;
1136 * the 256th check will be made at strstart+258.
1137 */
1138 do {
1139 } while (*++scan == *++match && *++scan == *++match &&
1140 *++scan == *++match && *++scan == *++match &&
1141 *++scan == *++match && *++scan == *++match &&
1142 *++scan == *++match && *++scan == *++match &&
1143 scan < strend);
1144
1145 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1146
1147 len = MAX_MATCH - (int)(strend - scan);
1148 scan = strend - MAX_MATCH;
1149
1150#endif /* UNALIGNED_OK */
1151
1152 if (len > best_len) {
1153 s->match_start = cur_match;
1154 best_len = len;
1155 if (len >= nice_match) break;
1156#ifdef UNALIGNED_OK
1157 scan_end = *(ushf*)(scan+best_len-1);
1158#else
1159 scan_end1 = scan[best_len-1];
1160 scan_end = scan[best_len];
1161#endif
1162 }
1163 } while ((cur_match = prev[cur_match & wmask]) > limit
1164 && --chain_length != 0);
1165
1166 if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
1167 return s->lookahead;
1168}
1169#endif /* ASMV */
1170#endif /* FASTEST */
1171
1172/* ---------------------------------------------------------------------------
1173 * Optimized version for level == 1 or strategy == Z_RLE only
1174 */
1175local uInt longest_match_fast(s, cur_match)
1176 deflate_state *s;
1177 IPos cur_match; /* current match */
1178{
1179 register Bytef *scan = s->window + s->strstart; /* current string */
1180 register Bytef *match; /* matched string */
1181 register int len; /* length of current match */
1182 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1183
1184 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1185 * It is easy to get rid of this optimization if necessary.
1186 */
1187 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1188
1189 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1190
1191 Assert(cur_match < s->strstart, "no future");
1192
1193 match = s->window + cur_match;
1194
1195 /* Return failure if the match length is less than 2:
1196 */
1197 if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
1198
1199 /* The check at best_len-1 can be removed because it will be made
1200 * again later. (This heuristic is not always a win.)
1201 * It is not necessary to compare scan[2] and match[2] since they
1202 * are always equal when the other bytes match, given that
1203 * the hash keys are equal and that HASH_BITS >= 8.
1204 */
1205 scan += 2, match += 2;
1206 Assert(*scan == *match, "match[2]?");
1207
1208 /* We check for insufficient lookahead only every 8th comparison;
1209 * the 256th check will be made at strstart+258.
1210 */
1211 do {
1212 } while (*++scan == *++match && *++scan == *++match &&
1213 *++scan == *++match && *++scan == *++match &&
1214 *++scan == *++match && *++scan == *++match &&
1215 *++scan == *++match && *++scan == *++match &&
1216 scan < strend);
1217
1218 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1219
1220 len = MAX_MATCH - (int)(strend - scan);
1221
1222 if (len < MIN_MATCH) return MIN_MATCH - 1;
1223
1224 s->match_start = cur_match;
1225 return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
1226}
1227
1228#ifdef DEBUG
1229/* ===========================================================================
1230 * Check that the match at match_start is indeed a match.
1231 */
1232local void check_match(s, start, match, length)
1233 deflate_state *s;
1234 IPos start, match;
1235 int length;
1236{
1237 /* check that the match is indeed a match */
1238 if (zmemcmp(s->window + match,
1239 s->window + start, length) != EQUAL) {
1240 fprintf(stderr, " start %u, match %u, length %d\n",
1241 start, match, length);
1242 do {
1243 fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
1244 } while (--length != 0);
1245 z_error("invalid match");
1246 }
1247 if (z_verbose > 1) {
1248 fprintf(stderr,"\\[%d,%d]", start-match, length);
1249 do { putc(s->window[start++], stderr); } while (--length != 0);
1250 }
1251}
1252#else
1253# define check_match(s, start, match, length)
1254#endif /* DEBUG */
1255
1256/* ===========================================================================
1257 * Fill the window when the lookahead becomes insufficient.
1258 * Updates strstart and lookahead.
1259 *
1260 * IN assertion: lookahead < MIN_LOOKAHEAD
1261 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1262 * At least one byte has been read, or avail_in == 0; reads are
1263 * performed for at least two bytes (required for the zip translate_eol
1264 * option -- not supported here).
1265 */
1266local void fill_window(s)
1267 deflate_state *s;
1268{
1269 register unsigned n, m;
1270 register Posf *p;
1271 unsigned more; /* Amount of free space at the end of the window. */
1272 uInt wsize = s->w_size;
1273
1274 do {
1275 more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
1276
1277 /* Deal with !@#$% 64K limit: */
1278 if (sizeof(int) <= 2) {
1279 if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1280 more = wsize;
1281
1282 } else if (more == (unsigned)(-1)) {
1283 /* Very unlikely, but possible on 16 bit machine if
1284 * strstart == 0 && lookahead == 1 (input done a byte at time)
1285 */
1286 more--;
1287 }
1288 }
1289
1290 /* If the window is almost full and there is insufficient lookahead,
1291 * move the upper half to the lower one to make room in the upper half.
1292 */
1293 if (s->strstart >= wsize+MAX_DIST(s)) {
1294
1295 zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
1296 s->match_start -= wsize;
1297 s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
1298 s->block_start -= (long) wsize;
1299
1300 /* Slide the hash table (could be avoided with 32 bit values
1301 at the expense of memory usage). We slide even when level == 0
1302 to keep the hash table consistent if we switch back to level > 0
1303 later. (Using level 0 permanently is not an optimal usage of
1304 zlib, so we don't care about this pathological case.)
1305 */
1306 /* %%% avoid this when Z_RLE */
1307 n = s->hash_size;
1308 p = &s->head[n];
1309 do {
1310 m = *--p;
1311 *p = (Pos)(m >= wsize ? m-wsize : NIL);
1312 } while (--n);
1313
1314 n = wsize;
1315#ifndef FASTEST
1316 p = &s->prev[n];
1317 do {
1318 m = *--p;
1319 *p = (Pos)(m >= wsize ? m-wsize : NIL);
1320 /* If n is not on any hash chain, prev[n] is garbage but
1321 * its value will never be used.
1322 */
1323 } while (--n);
1324#endif
1325 more += wsize;
1326 }
1327 if (s->strm->avail_in == 0) return;
1328
1329 /* If there was no sliding:
1330 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1331 * more == window_size - lookahead - strstart
1332 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1333 * => more >= window_size - 2*WSIZE + 2
1334 * In the BIG_MEM or MMAP case (not yet supported),
1335 * window_size == input_size + MIN_LOOKAHEAD &&
1336 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1337 * Otherwise, window_size == 2*WSIZE so more >= 2.
1338 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1339 */
1340 Assert(more >= 2, "more < 2");
1341
1342 n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1343 s->lookahead += n;
1344
1345 /* Initialize the hash value now that we have some input: */
1346 if (s->lookahead >= MIN_MATCH) {
1347 s->ins_h = s->window[s->strstart];
1348 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1349#if MIN_MATCH != 3
1350 Call UPDATE_HASH() MIN_MATCH-3 more times
1351#endif
1352 }
1353 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1354 * but this is not important since only literal bytes will be emitted.
1355 */
1356
1357 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1358}
1359
1360/* ===========================================================================
1361 * Flush the current block, with given end-of-file flag.
1362 * IN assertion: strstart is set to the end of the current match.
1363 */
1364#define FLUSH_BLOCK_ONLY(s, eof) { \
1365 _tr_flush_block(s, (s->block_start >= 0L ? \
1366 (charf *)&s->window[(unsigned)s->block_start] : \
1367 (charf *)Z_NULL), \
1368 (ulg)((long)s->strstart - s->block_start), \
1369 (eof)); \
1370 s->block_start = s->strstart; \
1371 flush_pending(s->strm); \
1372 Tracev((stderr,"[FLUSH]")); \
1373}
1374
1375/* Same but force premature exit if necessary. */
1376#define FLUSH_BLOCK(s, eof) { \
1377 FLUSH_BLOCK_ONLY(s, eof); \
1378 if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
1379}
1380
1381/* ===========================================================================
1382 * Copy without compression as much as possible from the input stream, return
1383 * the current block state.
1384 * This function does not insert new strings in the dictionary since
1385 * uncompressible data is probably not useful. This function is used
1386 * only for the level=0 compression option.
1387 * NOTE: this function should be optimized to avoid extra copying from
1388 * window to pending_buf.
1389 */
1390local block_state deflate_stored(s, flush)
1391 deflate_state *s;
1392 int flush;
1393{
1394 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
1395 * to pending_buf_size, and each stored block has a 5 byte header:
1396 */
1397 ulg max_block_size = 0xffff;
1398 ulg max_start;
1399
1400 if (max_block_size > s->pending_buf_size - 5) {
1401 max_block_size = s->pending_buf_size - 5;
1402 }
1403
1404 /* Copy as much as possible from input to output: */
1405 for (;;) {
1406 /* Fill the window as much as possible: */
1407 if (s->lookahead <= 1) {
1408
1409 Assert(s->strstart < s->w_size+MAX_DIST(s) ||
1410 s->block_start >= (long)s->w_size, "slide too late");
1411
1412 fill_window(s);
1413 if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
1414
1415 if (s->lookahead == 0) break; /* flush the current block */
1416 }
1417 Assert(s->block_start >= 0L, "block gone");
1418
1419 s->strstart += s->lookahead;
1420 s->lookahead = 0;
1421
1422 /* Emit a stored block if pending_buf will be full: */
1423 max_start = s->block_start + max_block_size;
1424 if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
1425 /* strstart == 0 is possible when wraparound on 16-bit machine */
1426 s->lookahead = (uInt)(s->strstart - max_start);
1427 s->strstart = (uInt)max_start;
1428 FLUSH_BLOCK(s, 0);
1429 }
1430 /* Flush if we may have to slide, otherwise block_start may become
1431 * negative and the data will be gone:
1432 */
1433 if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
1434 FLUSH_BLOCK(s, 0);
1435 }
1436 }
1437 FLUSH_BLOCK(s, flush == Z_FINISH);
1438 return flush == Z_FINISH ? finish_done : block_done;
1439}
1440
1441/* ===========================================================================
1442 * Compress as much as possible from the input stream, return the current
1443 * block state.
1444 * This function does not perform lazy evaluation of matches and inserts
1445 * new strings in the dictionary only for unmatched strings or for short
1446 * matches. It is used only for the fast compression options.
1447 */
1448local block_state deflate_fast(s, flush)
1449 deflate_state *s;
1450 int flush;
1451{
1452 IPos hash_head = NIL; /* head of the hash chain */
1453 int bflush; /* set if current block must be flushed */
1454
1455 for (;;) {
1456 /* Make sure that we always have enough lookahead, except
1457 * at the end of the input file. We need MAX_MATCH bytes
1458 * for the next match, plus MIN_MATCH bytes to insert the
1459 * string following the next match.
1460 */
1461 if (s->lookahead < MIN_LOOKAHEAD) {
1462 fill_window(s);
1463 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1464 return need_more;
1465 }
1466 if (s->lookahead == 0) break; /* flush the current block */
1467 }
1468
1469 /* Insert the string window[strstart .. strstart+2] in the
1470 * dictionary, and set hash_head to the head of the hash chain:
1471 */
1472 if (s->lookahead >= MIN_MATCH) {
1473 INSERT_STRING(s, s->strstart, hash_head);
1474 }
1475
1476 /* Find the longest match, discarding those <= prev_length.
1477 * At this point we have always match_length < MIN_MATCH
1478 */
1479 if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1480 /* To simplify the code, we prevent matches with the string
1481 * of window index 0 (in particular we have to avoid a match
1482 * of the string with itself at the start of the input file).
1483 */
1484#ifdef FASTEST
1485 if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
1486 (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
1487 s->match_length = longest_match_fast (s, hash_head);
1488 }
1489#else
1490 if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
1491 s->match_length = longest_match (s, hash_head);
1492 } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
1493 s->match_length = longest_match_fast (s, hash_head);
1494 }
1495#endif
1496 /* longest_match() or longest_match_fast() sets match_start */
1497 }
1498 if (s->match_length >= MIN_MATCH) {
1499 check_match(s, s->strstart, s->match_start, s->match_length);
1500
1501 _tr_tally_dist(s, s->strstart - s->match_start,
1502 s->match_length - MIN_MATCH, bflush);
1503
1504 s->lookahead -= s->match_length;
1505
1506 /* Insert new strings in the hash table only if the match length
1507 * is not too large. This saves time but degrades compression.
1508 */
1509#ifndef FASTEST
1510 if (s->match_length <= s->max_insert_length &&
1511 s->lookahead >= MIN_MATCH) {
1512 s->match_length--; /* string at strstart already in table */
1513 do {
1514 s->strstart++;
1515 INSERT_STRING(s, s->strstart, hash_head);
1516 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1517 * always MIN_MATCH bytes ahead.
1518 */
1519 } while (--s->match_length != 0);
1520 s->strstart++;
1521 } else
1522#endif
1523 {
1524 s->strstart += s->match_length;
1525 s->match_length = 0;
1526 s->ins_h = s->window[s->strstart];
1527 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1528#if MIN_MATCH != 3
1529 Call UPDATE_HASH() MIN_MATCH-3 more times
1530#endif
1531 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1532 * matter since it will be recomputed at next deflate call.
1533 */
1534 }
1535 } else {
1536 /* No match, output a literal byte */
1537 Tracevv((stderr,"%c", s->window[s->strstart]));
1538 _tr_tally_lit (s, s->window[s->strstart], bflush);
1539 s->lookahead--;
1540 s->strstart++;
1541 }
1542 if (bflush) FLUSH_BLOCK(s, 0);
1543 }
1544 FLUSH_BLOCK(s, flush == Z_FINISH);
1545 return flush == Z_FINISH ? finish_done : block_done;
1546}
1547
1548#ifndef FASTEST
1549/* ===========================================================================
1550 * Same as above, but achieves better compression. We use a lazy
1551 * evaluation for matches: a match is finally adopted only if there is
1552 * no better match at the next window position.
1553 */
1554local block_state deflate_slow(s, flush)
1555 deflate_state *s;
1556 int flush;
1557{
1558 IPos hash_head = NIL; /* head of hash chain */
1559 int bflush; /* set if current block must be flushed */
1560
1561 /* Process the input block. */
1562 for (;;) {
1563 /* Make sure that we always have enough lookahead, except
1564 * at the end of the input file. We need MAX_MATCH bytes
1565 * for the next match, plus MIN_MATCH bytes to insert the
1566 * string following the next match.
1567 */
1568 if (s->lookahead < MIN_LOOKAHEAD) {
1569 fill_window(s);
1570 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1571 return need_more;
1572 }
1573 if (s->lookahead == 0) break; /* flush the current block */
1574 }
1575
1576 /* Insert the string window[strstart .. strstart+2] in the
1577 * dictionary, and set hash_head to the head of the hash chain:
1578 */
1579 if (s->lookahead >= MIN_MATCH) {
1580 INSERT_STRING(s, s->strstart, hash_head);
1581 }
1582
1583 /* Find the longest match, discarding those <= prev_length.
1584 */
1585 s->prev_length = s->match_length, s->prev_match = s->match_start;
1586 s->match_length = MIN_MATCH-1;
1587
1588 if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
1589 s->strstart - hash_head <= MAX_DIST(s)) {
1590 /* To simplify the code, we prevent matches with the string
1591 * of window index 0 (in particular we have to avoid a match
1592 * of the string with itself at the start of the input file).
1593 */
1594 if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
1595 s->match_length = longest_match (s, hash_head);
1596 } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
1597 s->match_length = longest_match_fast (s, hash_head);
1598 }
1599 /* longest_match() or longest_match_fast() sets match_start */
1600
1601 if (s->match_length <= 5 && (s->strategy == Z_FILTERED
1602#if TOO_FAR <= 32767
1603 || (s->match_length == MIN_MATCH &&
1604 s->strstart - s->match_start > TOO_FAR)
1605#endif
1606 )) {
1607
1608 /* If prev_match is also MIN_MATCH, match_start is garbage
1609 * but we will ignore the current match anyway.
1610 */
1611 s->match_length = MIN_MATCH-1;
1612 }
1613 }
1614 /* If there was a match at the previous step and the current
1615 * match is not better, output the previous match:
1616 */
1617 if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
1618 uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
1619 /* Do not insert strings in hash table beyond this. */
1620
1621 check_match(s, s->strstart-1, s->prev_match, s->prev_length);
1622
1623 _tr_tally_dist(s, s->strstart -1 - s->prev_match,
1624 s->prev_length - MIN_MATCH, bflush);
1625
1626 /* Insert in hash table all strings up to the end of the match.
1627 * strstart-1 and strstart are already inserted. If there is not
1628 * enough lookahead, the last two strings are not inserted in
1629 * the hash table.
1630 */
1631 s->lookahead -= s->prev_length-1;
1632 s->prev_length -= 2;
1633 do {
1634 if (++s->strstart <= max_insert) {
1635 INSERT_STRING(s, s->strstart, hash_head);
1636 }
1637 } while (--s->prev_length != 0);
1638 s->match_available = 0;
1639 s->match_length = MIN_MATCH-1;
1640 s->strstart++;
1641
1642 if (bflush) FLUSH_BLOCK(s, 0);
1643
1644 } else if (s->match_available) {
1645 /* If there was no match at the previous position, output a
1646 * single literal. If there was a match but the current match
1647 * is longer, truncate the previous match to a single literal.
1648 */
1649 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1650 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1651 if (bflush) {
1652 FLUSH_BLOCK_ONLY(s, 0);
1653 }
1654 s->strstart++;
1655 s->lookahead--;
1656 if (s->strm->avail_out == 0) return need_more;
1657 } else {
1658 /* There is no previous match to compare with, wait for
1659 * the next step to decide.
1660 */
1661 s->match_available = 1;
1662 s->strstart++;
1663 s->lookahead--;
1664 }
1665 }
1666 Assert (flush != Z_NO_FLUSH, "no flush?");
1667 if (s->match_available) {
1668 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1669 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1670 s->match_available = 0;
1671 }
1672 FLUSH_BLOCK(s, flush == Z_FINISH);
1673 return flush == Z_FINISH ? finish_done : block_done;
1674}
1675#endif /* FASTEST */
1676
1677#if 0
1678/* ===========================================================================
1679 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
1680 * one. Do not maintain a hash table. (It will be regenerated if this run of
1681 * deflate switches away from Z_RLE.)
1682 */
1683local block_state deflate_rle(s, flush)
1684 deflate_state *s;
1685 int flush;
1686{
1687 int bflush; /* set if current block must be flushed */
1688 uInt run; /* length of run */
1689 uInt max; /* maximum length of run */
1690 uInt prev; /* byte at distance one to match */
1691 Bytef *scan; /* scan for end of run */
1692
1693 for (;;) {
1694 /* Make sure that we always have enough lookahead, except
1695 * at the end of the input file. We need MAX_MATCH bytes
1696 * for the longest encodable run.
1697 */
1698 if (s->lookahead < MAX_MATCH) {
1699 fill_window(s);
1700 if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
1701 return need_more;
1702 }
1703 if (s->lookahead == 0) break; /* flush the current block */
1704 }
1705
1706 /* See how many times the previous byte repeats */
1707 run = 0;
1708 if (s->strstart > 0) { /* if there is a previous byte, that is */
1709 max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
1710 scan = s->window + s->strstart - 1;
1711 prev = *scan++;
1712 do {
1713 if (*scan++ != prev)
1714 break;
1715 } while (++run < max);
1716 }
1717
1718 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
1719 if (run >= MIN_MATCH) {
1720 check_match(s, s->strstart, s->strstart - 1, run);
1721 _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
1722 s->lookahead -= run;
1723 s->strstart += run;
1724 } else {
1725 /* No match, output a literal byte */
1726 Tracevv((stderr,"%c", s->window[s->strstart]));
1727 _tr_tally_lit (s, s->window[s->strstart], bflush);
1728 s->lookahead--;
1729 s->strstart++;
1730 }
1731 if (bflush) FLUSH_BLOCK(s, 0);
1732 }
1733 FLUSH_BLOCK(s, flush == Z_FINISH);
1734 return flush == Z_FINISH ? finish_done : block_done;
1735}
1736#endif
diff --git a/utils/zenutils/libraries/zlib123/zlib/deflate.h b/utils/zenutils/libraries/zlib123/zlib/deflate.h
new file mode 100755
index 0000000000..222c53e043
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/deflate.h
@@ -0,0 +1,331 @@
1/* deflate.h -- internal compression state
2 * Copyright (C) 1995-2004 Jean-loup Gailly
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/* WARNING: this file should *not* be used by applications. It is
7 part of the implementation of the compression library and is
8 subject to change. Applications should only use zlib.h.
9 */
10
11/* @(#) $Id$ */
12
13#ifndef DEFLATE_H
14#define DEFLATE_H
15
16#include "zutil.h"
17
18/* define NO_GZIP when compiling if you want to disable gzip header and
19 trailer creation by deflate(). NO_GZIP would be used to avoid linking in
20 the crc code when it is not needed. For shared libraries, gzip encoding
21 should be left enabled. */
22#ifndef NO_GZIP
23# define GZIP
24#endif
25
26/* ===========================================================================
27 * Internal compression state.
28 */
29
30#define LENGTH_CODES 29
31/* number of length codes, not counting the special END_BLOCK code */
32
33#define LITERALS 256
34/* number of literal bytes 0..255 */
35
36#define L_CODES (LITERALS+1+LENGTH_CODES)
37/* number of Literal or Length codes, including the END_BLOCK code */
38
39#define D_CODES 30
40/* number of distance codes */
41
42#define BL_CODES 19
43/* number of codes used to transfer the bit lengths */
44
45#define HEAP_SIZE (2*L_CODES+1)
46/* maximum heap size */
47
48#define MAX_BITS 15
49/* All codes must not exceed MAX_BITS bits */
50
51#define INIT_STATE 42
52#define EXTRA_STATE 69
53#define NAME_STATE 73
54#define COMMENT_STATE 91
55#define HCRC_STATE 103
56#define BUSY_STATE 113
57#define FINISH_STATE 666
58/* Stream status */
59
60
61/* Data structure describing a single value and its code string. */
62typedef struct ct_data_s {
63 union {
64 ush freq; /* frequency count */
65 ush code; /* bit string */
66 } fc;
67 union {
68 ush dad; /* father node in Huffman tree */
69 ush len; /* length of bit string */
70 } dl;
71} FAR ct_data;
72
73#define Freq fc.freq
74#define Code fc.code
75#define Dad dl.dad
76#define Len dl.len
77
78typedef struct static_tree_desc_s static_tree_desc;
79
80typedef struct tree_desc_s {
81 ct_data *dyn_tree; /* the dynamic tree */
82 int max_code; /* largest code with non zero frequency */
83 static_tree_desc *stat_desc; /* the corresponding static tree */
84} FAR tree_desc;
85
86typedef ush Pos;
87typedef Pos FAR Posf;
88typedef unsigned IPos;
89
90/* A Pos is an index in the character window. We use short instead of int to
91 * save space in the various tables. IPos is used only for parameter passing.
92 */
93
94typedef struct internal_state {
95 z_streamp strm; /* pointer back to this zlib stream */
96 int status; /* as the name implies */
97 Bytef *pending_buf; /* output still pending */
98 ulg pending_buf_size; /* size of pending_buf */
99 Bytef *pending_out; /* next pending byte to output to the stream */
100 uInt pending; /* nb of bytes in the pending buffer */
101 int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
102 gz_headerp gzhead; /* gzip header information to write */
103 uInt gzindex; /* where in extra, name, or comment */
104 Byte method; /* STORED (for zip only) or DEFLATED */
105 int last_flush; /* value of flush param for previous deflate call */
106
107 /* used by deflate.c: */
108
109 uInt w_size; /* LZ77 window size (32K by default) */
110 uInt w_bits; /* log2(w_size) (8..16) */
111 uInt w_mask; /* w_size - 1 */
112
113 Bytef *window;
114 /* Sliding window. Input bytes are read into the second half of the window,
115 * and move to the first half later to keep a dictionary of at least wSize
116 * bytes. With this organization, matches are limited to a distance of
117 * wSize-MAX_MATCH bytes, but this ensures that IO is always
118 * performed with a length multiple of the block size. Also, it limits
119 * the window size to 64K, which is quite useful on MSDOS.
120 * To do: use the user input buffer as sliding window.
121 */
122
123 ulg window_size;
124 /* Actual size of window: 2*wSize, except when the user input buffer
125 * is directly used as sliding window.
126 */
127
128 Posf *prev;
129 /* Link to older string with same hash index. To limit the size of this
130 * array to 64K, this link is maintained only for the last 32K strings.
131 * An index in this array is thus a window index modulo 32K.
132 */
133
134 Posf *head; /* Heads of the hash chains or NIL. */
135
136 uInt ins_h; /* hash index of string to be inserted */
137 uInt hash_size; /* number of elements in hash table */
138 uInt hash_bits; /* log2(hash_size) */
139 uInt hash_mask; /* hash_size-1 */
140
141 uInt hash_shift;
142 /* Number of bits by which ins_h must be shifted at each input
143 * step. It must be such that after MIN_MATCH steps, the oldest
144 * byte no longer takes part in the hash key, that is:
145 * hash_shift * MIN_MATCH >= hash_bits
146 */
147
148 long block_start;
149 /* Window position at the beginning of the current output block. Gets
150 * negative when the window is moved backwards.
151 */
152
153 uInt match_length; /* length of best match */
154 IPos prev_match; /* previous match */
155 int match_available; /* set if previous match exists */
156 uInt strstart; /* start of string to insert */
157 uInt match_start; /* start of matching string */
158 uInt lookahead; /* number of valid bytes ahead in window */
159
160 uInt prev_length;
161 /* Length of the best match at previous step. Matches not greater than this
162 * are discarded. This is used in the lazy match evaluation.
163 */
164
165 uInt max_chain_length;
166 /* To speed up deflation, hash chains are never searched beyond this
167 * length. A higher limit improves compression ratio but degrades the
168 * speed.
169 */
170
171 uInt max_lazy_match;
172 /* Attempt to find a better match only when the current match is strictly
173 * smaller than this value. This mechanism is used only for compression
174 * levels >= 4.
175 */
176# define max_insert_length max_lazy_match
177 /* Insert new strings in the hash table only if the match length is not
178 * greater than this length. This saves time but degrades compression.
179 * max_insert_length is used only for compression levels <= 3.
180 */
181
182 int level; /* compression level (1..9) */
183 int strategy; /* favor or force Huffman coding*/
184
185 uInt good_match;
186 /* Use a faster search when the previous match is longer than this */
187
188 int nice_match; /* Stop searching when current match exceeds this */
189
190 /* used by trees.c: */
191 /* Didn't use ct_data typedef below to supress compiler warning */
192 struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
193 struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
194 struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
195
196 struct tree_desc_s l_desc; /* desc. for literal tree */
197 struct tree_desc_s d_desc; /* desc. for distance tree */
198 struct tree_desc_s bl_desc; /* desc. for bit length tree */
199
200 ush bl_count[MAX_BITS+1];
201 /* number of codes at each bit length for an optimal tree */
202
203 int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
204 int heap_len; /* number of elements in the heap */
205 int heap_max; /* element of largest frequency */
206 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
207 * The same heap array is used to build all trees.
208 */
209
210 uch depth[2*L_CODES+1];
211 /* Depth of each subtree used as tie breaker for trees of equal frequency
212 */
213
214 uchf *l_buf; /* buffer for literals or lengths */
215
216 uInt lit_bufsize;
217 /* Size of match buffer for literals/lengths. There are 4 reasons for
218 * limiting lit_bufsize to 64K:
219 * - frequencies can be kept in 16 bit counters
220 * - if compression is not successful for the first block, all input
221 * data is still in the window so we can still emit a stored block even
222 * when input comes from standard input. (This can also be done for
223 * all blocks if lit_bufsize is not greater than 32K.)
224 * - if compression is not successful for a file smaller than 64K, we can
225 * even emit a stored file instead of a stored block (saving 5 bytes).
226 * This is applicable only for zip (not gzip or zlib).
227 * - creating new Huffman trees less frequently may not provide fast
228 * adaptation to changes in the input data statistics. (Take for
229 * example a binary file with poorly compressible code followed by
230 * a highly compressible string table.) Smaller buffer sizes give
231 * fast adaptation but have of course the overhead of transmitting
232 * trees more frequently.
233 * - I can't count above 4
234 */
235
236 uInt last_lit; /* running index in l_buf */
237
238 ushf *d_buf;
239 /* Buffer for distances. To simplify the code, d_buf and l_buf have
240 * the same number of elements. To use different lengths, an extra flag
241 * array would be necessary.
242 */
243
244 ulg opt_len; /* bit length of current block with optimal trees */
245 ulg static_len; /* bit length of current block with static trees */
246 uInt matches; /* number of string matches in current block */
247 int last_eob_len; /* bit length of EOB code for last block */
248
249#ifdef DEBUG
250 ulg compressed_len; /* total bit length of compressed file mod 2^32 */
251 ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
252#endif
253
254 ush bi_buf;
255 /* Output buffer. bits are inserted starting at the bottom (least
256 * significant bits).
257 */
258 int bi_valid;
259 /* Number of valid bits in bi_buf. All bits above the last valid bit
260 * are always zero.
261 */
262
263} FAR deflate_state;
264
265/* Output a byte on the stream.
266 * IN assertion: there is enough room in pending_buf.
267 */
268#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
269
270
271#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
272/* Minimum amount of lookahead, except at the end of the input file.
273 * See deflate.c for comments about the MIN_MATCH+1.
274 */
275
276#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
277/* In order to simplify the code, particularly on 16 bit machines, match
278 * distances are limited to MAX_DIST instead of WSIZE.
279 */
280
281 /* in trees.c */
282void _tr_init OF((deflate_state *s));
283int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
284void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
285 int eof));
286void _tr_align OF((deflate_state *s));
287void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
288 int eof));
289
290#define d_code(dist) \
291 ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
292/* Mapping from a distance to a distance code. dist is the distance - 1 and
293 * must not have side effects. _dist_code[256] and _dist_code[257] are never
294 * used.
295 */
296
297#ifndef DEBUG
298/* Inline versions of _tr_tally for speed: */
299
300#if defined(GEN_TREES_H) || !defined(STDC)
301 extern uch _length_code[];
302 extern uch _dist_code[];
303#else
304 extern const uch _length_code[];
305 extern const uch _dist_code[];
306#endif
307
308# define _tr_tally_lit(s, c, flush) \
309 { uch cc = (c); \
310 s->d_buf[s->last_lit] = 0; \
311 s->l_buf[s->last_lit++] = cc; \
312 s->dyn_ltree[cc].Freq++; \
313 flush = (s->last_lit == s->lit_bufsize-1); \
314 }
315# define _tr_tally_dist(s, distance, length, flush) \
316 { uch len = (length); \
317 ush dist = (distance); \
318 s->d_buf[s->last_lit] = dist; \
319 s->l_buf[s->last_lit++] = len; \
320 dist--; \
321 s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
322 s->dyn_dtree[d_code(dist)].Freq++; \
323 flush = (s->last_lit == s->lit_bufsize-1); \
324 }
325#else
326# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
327# define _tr_tally_dist(s, distance, length, flush) \
328 flush = _tr_tally(s, distance, length)
329#endif
330
331#endif /* DEFLATE_H */
diff --git a/utils/zenutils/libraries/zlib123/zlib/example.c b/utils/zenutils/libraries/zlib123/zlib/example.c
new file mode 100755
index 0000000000..455a1d062a
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/example.c
@@ -0,0 +1,565 @@
1/* example.c -- usage example of the zlib compression library
2 * Copyright (C) 1995-2004 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/* @(#) $Id$ */
7
8#include <stdio.h>
9#include "zlib.h"
10
11#ifdef STDC
12# include <string.h>
13# include <stdlib.h>
14#endif
15
16#if defined(VMS) || defined(RISCOS)
17# define TESTFILE "foo-gz"
18#else
19# define TESTFILE "foo.gz"
20#endif
21
22#define CHECK_ERR(err, msg) { \
23 if (err != Z_OK) { \
24 fprintf(stderr, "%s error: %d\n", msg, err); \
25 exit(1); \
26 } \
27}
28
29const char hello[] = "hello, hello!";
30/* "hello world" would be more standard, but the repeated "hello"
31 * stresses the compression code better, sorry...
32 */
33
34const char dictionary[] = "hello";
35uLong dictId; /* Adler32 value of the dictionary */
36
37void test_compress OF((Byte *compr, uLong comprLen,
38 Byte *uncompr, uLong uncomprLen));
39void test_gzio OF((const char *fname,
40 Byte *uncompr, uLong uncomprLen));
41void test_deflate OF((Byte *compr, uLong comprLen));
42void test_inflate OF((Byte *compr, uLong comprLen,
43 Byte *uncompr, uLong uncomprLen));
44void test_large_deflate OF((Byte *compr, uLong comprLen,
45 Byte *uncompr, uLong uncomprLen));
46void test_large_inflate OF((Byte *compr, uLong comprLen,
47 Byte *uncompr, uLong uncomprLen));
48void test_flush OF((Byte *compr, uLong *comprLen));
49void test_sync OF((Byte *compr, uLong comprLen,
50 Byte *uncompr, uLong uncomprLen));
51void test_dict_deflate OF((Byte *compr, uLong comprLen));
52void test_dict_inflate OF((Byte *compr, uLong comprLen,
53 Byte *uncompr, uLong uncomprLen));
54int main OF((int argc, char *argv[]));
55
56/* ===========================================================================
57 * Test compress() and uncompress()
58 */
59void test_compress(compr, comprLen, uncompr, uncomprLen)
60 Byte *compr, *uncompr;
61 uLong comprLen, uncomprLen;
62{
63 int err;
64 uLong len = (uLong)strlen(hello)+1;
65
66 err = compress(compr, &comprLen, (const Bytef*)hello, len);
67 CHECK_ERR(err, "compress");
68
69 strcpy((char*)uncompr, "garbage");
70
71 err = uncompress(uncompr, &uncomprLen, compr, comprLen);
72 CHECK_ERR(err, "uncompress");
73
74 if (strcmp((char*)uncompr, hello)) {
75 fprintf(stderr, "bad uncompress\n");
76 exit(1);
77 } else {
78 printf("uncompress(): %s\n", (char *)uncompr);
79 }
80}
81
82/* ===========================================================================
83 * Test read/write of .gz files
84 */
85void test_gzio(fname, uncompr, uncomprLen)
86 const char *fname; /* compressed file name */
87 Byte *uncompr;
88 uLong uncomprLen;
89{
90#ifdef NO_GZCOMPRESS
91 fprintf(stderr, "NO_GZCOMPRESS -- gz* functions cannot compress\n");
92#else
93 int err;
94 int len = (int)strlen(hello)+1;
95 gzFile file;
96 z_off_t pos;
97
98 file = gzopen(fname, "wb");
99 if (file == NULL) {
100 fprintf(stderr, "gzopen error\n");
101 exit(1);
102 }
103 gzputc(file, 'h');
104 if (gzputs(file, "ello") != 4) {
105 fprintf(stderr, "gzputs err: %s\n", gzerror(file, &err));
106 exit(1);
107 }
108 if (gzprintf(file, ", %s!", "hello") != 8) {
109 fprintf(stderr, "gzprintf err: %s\n", gzerror(file, &err));
110 exit(1);
111 }
112 gzseek(file, 1L, SEEK_CUR); /* add one zero byte */
113 gzclose(file);
114
115 file = gzopen(fname, "rb");
116 if (file == NULL) {
117 fprintf(stderr, "gzopen error\n");
118 exit(1);
119 }
120 strcpy((char*)uncompr, "garbage");
121
122 if (gzread(file, uncompr, (unsigned)uncomprLen) != len) {
123 fprintf(stderr, "gzread err: %s\n", gzerror(file, &err));
124 exit(1);
125 }
126 if (strcmp((char*)uncompr, hello)) {
127 fprintf(stderr, "bad gzread: %s\n", (char*)uncompr);
128 exit(1);
129 } else {
130 printf("gzread(): %s\n", (char*)uncompr);
131 }
132
133 pos = gzseek(file, -8L, SEEK_CUR);
134 if (pos != 6 || gztell(file) != pos) {
135 fprintf(stderr, "gzseek error, pos=%ld, gztell=%ld\n",
136 (long)pos, (long)gztell(file));
137 exit(1);
138 }
139
140 if (gzgetc(file) != ' ') {
141 fprintf(stderr, "gzgetc error\n");
142 exit(1);
143 }
144
145 if (gzungetc(' ', file) != ' ') {
146 fprintf(stderr, "gzungetc error\n");
147 exit(1);
148 }
149
150 gzgets(file, (char*)uncompr, (int)uncomprLen);
151 if (strlen((char*)uncompr) != 7) { /* " hello!" */
152 fprintf(stderr, "gzgets err after gzseek: %s\n", gzerror(file, &err));
153 exit(1);
154 }
155 if (strcmp((char*)uncompr, hello + 6)) {
156 fprintf(stderr, "bad gzgets after gzseek\n");
157 exit(1);
158 } else {
159 printf("gzgets() after gzseek: %s\n", (char*)uncompr);
160 }
161
162 gzclose(file);
163#endif
164}
165
166/* ===========================================================================
167 * Test deflate() with small buffers
168 */
169void test_deflate(compr, comprLen)
170 Byte *compr;
171 uLong comprLen;
172{
173 z_stream c_stream; /* compression stream */
174 int err;
175 uLong len = (uLong)strlen(hello)+1;
176
177 c_stream.zalloc = (alloc_func)0;
178 c_stream.zfree = (free_func)0;
179 c_stream.opaque = (voidpf)0;
180
181 err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);
182 CHECK_ERR(err, "deflateInit");
183
184 c_stream.next_in = (Bytef*)hello;
185 c_stream.next_out = compr;
186
187 while (c_stream.total_in != len && c_stream.total_out < comprLen) {
188 c_stream.avail_in = c_stream.avail_out = 1; /* force small buffers */
189 err = deflate(&c_stream, Z_NO_FLUSH);
190 CHECK_ERR(err, "deflate");
191 }
192 /* Finish the stream, still forcing small buffers: */
193 for (;;) {
194 c_stream.avail_out = 1;
195 err = deflate(&c_stream, Z_FINISH);
196 if (err == Z_STREAM_END) break;
197 CHECK_ERR(err, "deflate");
198 }
199
200 err = deflateEnd(&c_stream);
201 CHECK_ERR(err, "deflateEnd");
202}
203
204/* ===========================================================================
205 * Test inflate() with small buffers
206 */
207void test_inflate(compr, comprLen, uncompr, uncomprLen)
208 Byte *compr, *uncompr;
209 uLong comprLen, uncomprLen;
210{
211 int err;
212 z_stream d_stream; /* decompression stream */
213
214 strcpy((char*)uncompr, "garbage");
215
216 d_stream.zalloc = (alloc_func)0;
217 d_stream.zfree = (free_func)0;
218 d_stream.opaque = (voidpf)0;
219
220 d_stream.next_in = compr;
221 d_stream.avail_in = 0;
222 d_stream.next_out = uncompr;
223
224 err = inflateInit(&d_stream);
225 CHECK_ERR(err, "inflateInit");
226
227 while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen) {
228 d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */
229 err = inflate(&d_stream, Z_NO_FLUSH);
230 if (err == Z_STREAM_END) break;
231 CHECK_ERR(err, "inflate");
232 }
233
234 err = inflateEnd(&d_stream);
235 CHECK_ERR(err, "inflateEnd");
236
237 if (strcmp((char*)uncompr, hello)) {
238 fprintf(stderr, "bad inflate\n");
239 exit(1);
240 } else {
241 printf("inflate(): %s\n", (char *)uncompr);
242 }
243}
244
245/* ===========================================================================
246 * Test deflate() with large buffers and dynamic change of compression level
247 */
248void test_large_deflate(compr, comprLen, uncompr, uncomprLen)
249 Byte *compr, *uncompr;
250 uLong comprLen, uncomprLen;
251{
252 z_stream c_stream; /* compression stream */
253 int err;
254
255 c_stream.zalloc = (alloc_func)0;
256 c_stream.zfree = (free_func)0;
257 c_stream.opaque = (voidpf)0;
258
259 err = deflateInit(&c_stream, Z_BEST_SPEED);
260 CHECK_ERR(err, "deflateInit");
261
262 c_stream.next_out = compr;
263 c_stream.avail_out = (uInt)comprLen;
264
265 /* At this point, uncompr is still mostly zeroes, so it should compress
266 * very well:
267 */
268 c_stream.next_in = uncompr;
269 c_stream.avail_in = (uInt)uncomprLen;
270 err = deflate(&c_stream, Z_NO_FLUSH);
271 CHECK_ERR(err, "deflate");
272 if (c_stream.avail_in != 0) {
273 fprintf(stderr, "deflate not greedy\n");
274 exit(1);
275 }
276
277 /* Feed in already compressed data and switch to no compression: */
278 deflateParams(&c_stream, Z_NO_COMPRESSION, Z_DEFAULT_STRATEGY);
279 c_stream.next_in = compr;
280 c_stream.avail_in = (uInt)comprLen/2;
281 err = deflate(&c_stream, Z_NO_FLUSH);
282 CHECK_ERR(err, "deflate");
283
284 /* Switch back to compressing mode: */
285 deflateParams(&c_stream, Z_BEST_COMPRESSION, Z_FILTERED);
286 c_stream.next_in = uncompr;
287 c_stream.avail_in = (uInt)uncomprLen;
288 err = deflate(&c_stream, Z_NO_FLUSH);
289 CHECK_ERR(err, "deflate");
290
291 err = deflate(&c_stream, Z_FINISH);
292 if (err != Z_STREAM_END) {
293 fprintf(stderr, "deflate should report Z_STREAM_END\n");
294 exit(1);
295 }
296 err = deflateEnd(&c_stream);
297 CHECK_ERR(err, "deflateEnd");
298}
299
300/* ===========================================================================
301 * Test inflate() with large buffers
302 */
303void test_large_inflate(compr, comprLen, uncompr, uncomprLen)
304 Byte *compr, *uncompr;
305 uLong comprLen, uncomprLen;
306{
307 int err;
308 z_stream d_stream; /* decompression stream */
309
310 strcpy((char*)uncompr, "garbage");
311
312 d_stream.zalloc = (alloc_func)0;
313 d_stream.zfree = (free_func)0;
314 d_stream.opaque = (voidpf)0;
315
316 d_stream.next_in = compr;
317 d_stream.avail_in = (uInt)comprLen;
318
319 err = inflateInit(&d_stream);
320 CHECK_ERR(err, "inflateInit");
321
322 for (;;) {
323 d_stream.next_out = uncompr; /* discard the output */
324 d_stream.avail_out = (uInt)uncomprLen;
325 err = inflate(&d_stream, Z_NO_FLUSH);
326 if (err == Z_STREAM_END) break;
327 CHECK_ERR(err, "large inflate");
328 }
329
330 err = inflateEnd(&d_stream);
331 CHECK_ERR(err, "inflateEnd");
332
333 if (d_stream.total_out != 2*uncomprLen + comprLen/2) {
334 fprintf(stderr, "bad large inflate: %ld\n", d_stream.total_out);
335 exit(1);
336 } else {
337 printf("large_inflate(): OK\n");
338 }
339}
340
341/* ===========================================================================
342 * Test deflate() with full flush
343 */
344void test_flush(compr, comprLen)
345 Byte *compr;
346 uLong *comprLen;
347{
348 z_stream c_stream; /* compression stream */
349 int err;
350 uInt len = (uInt)strlen(hello)+1;
351
352 c_stream.zalloc = (alloc_func)0;
353 c_stream.zfree = (free_func)0;
354 c_stream.opaque = (voidpf)0;
355
356 err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);
357 CHECK_ERR(err, "deflateInit");
358
359 c_stream.next_in = (Bytef*)hello;
360 c_stream.next_out = compr;
361 c_stream.avail_in = 3;
362 c_stream.avail_out = (uInt)*comprLen;
363 err = deflate(&c_stream, Z_FULL_FLUSH);
364 CHECK_ERR(err, "deflate");
365
366 compr[3]++; /* force an error in first compressed block */
367 c_stream.avail_in = len - 3;
368
369 err = deflate(&c_stream, Z_FINISH);
370 if (err != Z_STREAM_END) {
371 CHECK_ERR(err, "deflate");
372 }
373 err = deflateEnd(&c_stream);
374 CHECK_ERR(err, "deflateEnd");
375
376 *comprLen = c_stream.total_out;
377}
378
379/* ===========================================================================
380 * Test inflateSync()
381 */
382void test_sync(compr, comprLen, uncompr, uncomprLen)
383 Byte *compr, *uncompr;
384 uLong comprLen, uncomprLen;
385{
386 int err;
387 z_stream d_stream; /* decompression stream */
388
389 strcpy((char*)uncompr, "garbage");
390
391 d_stream.zalloc = (alloc_func)0;
392 d_stream.zfree = (free_func)0;
393 d_stream.opaque = (voidpf)0;
394
395 d_stream.next_in = compr;
396 d_stream.avail_in = 2; /* just read the zlib header */
397
398 err = inflateInit(&d_stream);
399 CHECK_ERR(err, "inflateInit");
400
401 d_stream.next_out = uncompr;
402 d_stream.avail_out = (uInt)uncomprLen;
403
404 inflate(&d_stream, Z_NO_FLUSH);
405 CHECK_ERR(err, "inflate");
406
407 d_stream.avail_in = (uInt)comprLen-2; /* read all compressed data */
408 err = inflateSync(&d_stream); /* but skip the damaged part */
409 CHECK_ERR(err, "inflateSync");
410
411 err = inflate(&d_stream, Z_FINISH);
412 if (err != Z_DATA_ERROR) {
413 fprintf(stderr, "inflate should report DATA_ERROR\n");
414 /* Because of incorrect adler32 */
415 exit(1);
416 }
417 err = inflateEnd(&d_stream);
418 CHECK_ERR(err, "inflateEnd");
419
420 printf("after inflateSync(): hel%s\n", (char *)uncompr);
421}
422
423/* ===========================================================================
424 * Test deflate() with preset dictionary
425 */
426void test_dict_deflate(compr, comprLen)
427 Byte *compr;
428 uLong comprLen;
429{
430 z_stream c_stream; /* compression stream */
431 int err;
432
433 c_stream.zalloc = (alloc_func)0;
434 c_stream.zfree = (free_func)0;
435 c_stream.opaque = (voidpf)0;
436
437 err = deflateInit(&c_stream, Z_BEST_COMPRESSION);
438 CHECK_ERR(err, "deflateInit");
439
440 err = deflateSetDictionary(&c_stream,
441 (const Bytef*)dictionary, sizeof(dictionary));
442 CHECK_ERR(err, "deflateSetDictionary");
443
444 dictId = c_stream.adler;
445 c_stream.next_out = compr;
446 c_stream.avail_out = (uInt)comprLen;
447
448 c_stream.next_in = (Bytef*)hello;
449 c_stream.avail_in = (uInt)strlen(hello)+1;
450
451 err = deflate(&c_stream, Z_FINISH);
452 if (err != Z_STREAM_END) {
453 fprintf(stderr, "deflate should report Z_STREAM_END\n");
454 exit(1);
455 }
456 err = deflateEnd(&c_stream);
457 CHECK_ERR(err, "deflateEnd");
458}
459
460/* ===========================================================================
461 * Test inflate() with a preset dictionary
462 */
463void test_dict_inflate(compr, comprLen, uncompr, uncomprLen)
464 Byte *compr, *uncompr;
465 uLong comprLen, uncomprLen;
466{
467 int err;
468 z_stream d_stream; /* decompression stream */
469
470 strcpy((char*)uncompr, "garbage");
471
472 d_stream.zalloc = (alloc_func)0;
473 d_stream.zfree = (free_func)0;
474 d_stream.opaque = (voidpf)0;
475
476 d_stream.next_in = compr;
477 d_stream.avail_in = (uInt)comprLen;
478
479 err = inflateInit(&d_stream);
480 CHECK_ERR(err, "inflateInit");
481
482 d_stream.next_out = uncompr;
483 d_stream.avail_out = (uInt)uncomprLen;
484
485 for (;;) {
486 err = inflate(&d_stream, Z_NO_FLUSH);
487 if (err == Z_STREAM_END) break;
488 if (err == Z_NEED_DICT) {
489 if (d_stream.adler != dictId) {
490 fprintf(stderr, "unexpected dictionary");
491 exit(1);
492 }
493 err = inflateSetDictionary(&d_stream, (const Bytef*)dictionary,
494 sizeof(dictionary));
495 }
496 CHECK_ERR(err, "inflate with dict");
497 }
498
499 err = inflateEnd(&d_stream);
500 CHECK_ERR(err, "inflateEnd");
501
502 if (strcmp((char*)uncompr, hello)) {
503 fprintf(stderr, "bad inflate with dict\n");
504 exit(1);
505 } else {
506 printf("inflate with dictionary: %s\n", (char *)uncompr);
507 }
508}
509
510/* ===========================================================================
511 * Usage: example [output.gz [input.gz]]
512 */
513
514int main(argc, argv)
515 int argc;
516 char *argv[];
517{
518 Byte *compr, *uncompr;
519 uLong comprLen = 10000*sizeof(int); /* don't overflow on MSDOS */
520 uLong uncomprLen = comprLen;
521 static const char* myVersion = ZLIB_VERSION;
522
523 if (zlibVersion()[0] != myVersion[0]) {
524 fprintf(stderr, "incompatible zlib version\n");
525 exit(1);
526
527 } else if (strcmp(zlibVersion(), ZLIB_VERSION) != 0) {
528 fprintf(stderr, "warning: different zlib version\n");
529 }
530
531 printf("zlib version %s = 0x%04x, compile flags = 0x%lx\n",
532 ZLIB_VERSION, ZLIB_VERNUM, zlibCompileFlags());
533
534 compr = (Byte*)calloc((uInt)comprLen, 1);
535 uncompr = (Byte*)calloc((uInt)uncomprLen, 1);
536 /* compr and uncompr are cleared to avoid reading uninitialized
537 * data and to ensure that uncompr compresses well.
538 */
539 if (compr == Z_NULL || uncompr == Z_NULL) {
540 printf("out of memory\n");
541 exit(1);
542 }
543 test_compress(compr, comprLen, uncompr, uncomprLen);
544
545 test_gzio((argc > 1 ? argv[1] : TESTFILE),
546 uncompr, uncomprLen);
547
548 test_deflate(compr, comprLen);
549 test_inflate(compr, comprLen, uncompr, uncomprLen);
550
551 test_large_deflate(compr, comprLen, uncompr, uncomprLen);
552 test_large_inflate(compr, comprLen, uncompr, uncomprLen);
553
554 test_flush(compr, &comprLen);
555 test_sync(compr, comprLen, uncompr, uncomprLen);
556 comprLen = uncomprLen;
557
558 test_dict_deflate(compr, comprLen);
559 test_dict_inflate(compr, comprLen, uncompr, uncomprLen);
560
561 free(compr);
562 free(uncompr);
563
564 return 0;
565}
diff --git a/utils/zenutils/libraries/zlib123/zlib/gzio.c b/utils/zenutils/libraries/zlib123/zlib/gzio.c
new file mode 100755
index 0000000000..5e20a4aa0d
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/gzio.c
@@ -0,0 +1,1026 @@
1/* gzio.c -- IO on .gz files
2 * Copyright (C) 1995-2005 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 *
5 * Compile this file with -DNO_GZCOMPRESS to avoid the compression code.
6 */
7
8/* @(#) $Id$ */
9
10#include <stdio.h>
11
12#include "zutil.h"
13
14#ifdef NO_DEFLATE /* for compatibility with old definition */
15# define NO_GZCOMPRESS
16#endif
17
18#ifndef NO_DUMMY_DECL
19struct internal_state {int dummy;}; /* for buggy compilers */
20#endif
21
22#ifndef Z_BUFSIZE
23# ifdef MAXSEG_64K
24# define Z_BUFSIZE 4096 /* minimize memory usage for 16-bit DOS */
25# else
26# define Z_BUFSIZE 16384
27# endif
28#endif
29#ifndef Z_PRINTF_BUFSIZE
30# define Z_PRINTF_BUFSIZE 4096
31#endif
32
33#ifdef __MVS__
34# pragma map (fdopen , "\174\174FDOPEN")
35 FILE *fdopen(int, const char *);
36#endif
37
38#ifndef STDC
39extern voidp malloc OF((uInt size));
40extern void free OF((voidpf ptr));
41#endif
42
43#define ALLOC(size) malloc(size)
44#define TRYFREE(p) {if (p) free(p);}
45
46static int const gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
47
48/* gzip flag byte */
49#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
50#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */
51#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
52#define ORIG_NAME 0x08 /* bit 3 set: original file name present */
53#define COMMENT 0x10 /* bit 4 set: file comment present */
54#define RESERVED 0xE0 /* bits 5..7: reserved */
55
56typedef struct gz_stream {
57 z_stream stream;
58 int z_err; /* error code for last stream operation */
59 int z_eof; /* set if end of input file */
60 FILE *file; /* .gz file */
61 Byte *inbuf; /* input buffer */
62 Byte *outbuf; /* output buffer */
63 uLong crc; /* crc32 of uncompressed data */
64 char *msg; /* error message */
65 char *path; /* path name for debugging only */
66 int transparent; /* 1 if input file is not a .gz file */
67 char mode; /* 'w' or 'r' */
68 z_off_t start; /* start of compressed data in file (header skipped) */
69 z_off_t in; /* bytes into deflate or inflate */
70 z_off_t out; /* bytes out of deflate or inflate */
71 int back; /* one character push-back */
72 int last; /* true if push-back is last character */
73} gz_stream;
74
75
76local gzFile gz_open OF((const char *path, const char *mode, int fd));
77local int do_flush OF((gzFile file, int flush));
78local int get_byte OF((gz_stream *s));
79local void check_header OF((gz_stream *s));
80local int destroy OF((gz_stream *s));
81local void putLong OF((FILE *file, uLong x));
82local uLong getLong OF((gz_stream *s));
83
84/* ===========================================================================
85 Opens a gzip (.gz) file for reading or writing. The mode parameter
86 is as in fopen ("rb" or "wb"). The file is given either by file descriptor
87 or path name (if fd == -1).
88 gz_open returns NULL if the file could not be opened or if there was
89 insufficient memory to allocate the (de)compression state; errno
90 can be checked to distinguish the two cases (if errno is zero, the
91 zlib error is Z_MEM_ERROR).
92*/
93local gzFile gz_open (path, mode, fd)
94 const char *path;
95 const char *mode;
96 int fd;
97{
98 int err;
99 int level = Z_DEFAULT_COMPRESSION; /* compression level */
100 int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */
101 char *p = (char*)mode;
102 gz_stream *s;
103 char fmode[80]; /* copy of mode, without the compression level */
104 char *m = fmode;
105
106 if (!path || !mode) return Z_NULL;
107
108 s = (gz_stream *)ALLOC(sizeof(gz_stream));
109 if (!s) return Z_NULL;
110
111 s->stream.zalloc = (alloc_func)0;
112 s->stream.zfree = (free_func)0;
113 s->stream.opaque = (voidpf)0;
114 s->stream.next_in = s->inbuf = Z_NULL;
115 s->stream.next_out = s->outbuf = Z_NULL;
116 s->stream.avail_in = s->stream.avail_out = 0;
117 s->file = NULL;
118 s->z_err = Z_OK;
119 s->z_eof = 0;
120 s->in = 0;
121 s->out = 0;
122 s->back = EOF;
123 s->crc = crc32(0L, Z_NULL, 0);
124 s->msg = NULL;
125 s->transparent = 0;
126
127 s->path = (char*)ALLOC(strlen(path)+1);
128 if (s->path == NULL) {
129 return destroy(s), (gzFile)Z_NULL;
130 }
131 strcpy(s->path, path); /* do this early for debugging */
132
133 s->mode = '\0';
134 do {
135 if (*p == 'r') s->mode = 'r';
136 if (*p == 'w' || *p == 'a') s->mode = 'w';
137 if (*p >= '0' && *p <= '9') {
138 level = *p - '0';
139 } else if (*p == 'f') {
140 strategy = Z_FILTERED;
141 } else if (*p == 'h') {
142 strategy = Z_HUFFMAN_ONLY;
143 } else if (*p == 'R') {
144 strategy = Z_RLE;
145 } else {
146 *m++ = *p; /* copy the mode */
147 }
148 } while (*p++ && m != fmode + sizeof(fmode));
149 if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL;
150
151 if (s->mode == 'w') {
152#ifdef NO_GZCOMPRESS
153 err = Z_STREAM_ERROR;
154#else
155 err = deflateInit2(&(s->stream), level,
156 Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy);
157 /* windowBits is passed < 0 to suppress zlib header */
158
159 s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
160#endif
161 if (err != Z_OK || s->outbuf == Z_NULL) {
162 return destroy(s), (gzFile)Z_NULL;
163 }
164 } else {
165 s->stream.next_in = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE);
166
167 err = inflateInit2(&(s->stream), -MAX_WBITS);
168 /* windowBits is passed < 0 to tell that there is no zlib header.
169 * Note that in this case inflate *requires* an extra "dummy" byte
170 * after the compressed stream in order to complete decompression and
171 * return Z_STREAM_END. Here the gzip CRC32 ensures that 4 bytes are
172 * present after the compressed stream.
173 */
174 if (err != Z_OK || s->inbuf == Z_NULL) {
175 return destroy(s), (gzFile)Z_NULL;
176 }
177 }
178 s->stream.avail_out = Z_BUFSIZE;
179
180 errno = 0;
181 s->file = fd < 0 ? F_OPEN(path, fmode) : (FILE*)fdopen(fd, fmode);
182
183 if (s->file == NULL) {
184 return destroy(s), (gzFile)Z_NULL;
185 }
186 if (s->mode == 'w') {
187 /* Write a very simple .gz header:
188 */
189 fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1],
190 Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE);
191 s->start = 10L;
192 /* We use 10L instead of ftell(s->file) to because ftell causes an
193 * fflush on some systems. This version of the library doesn't use
194 * start anyway in write mode, so this initialization is not
195 * necessary.
196 */
197 } else {
198 check_header(s); /* skip the .gz header */
199 s->start = ftell(s->file) - s->stream.avail_in;
200 }
201
202 return (gzFile)s;
203}
204
205/* ===========================================================================
206 Opens a gzip (.gz) file for reading or writing.
207*/
208gzFile ZEXPORT gzopen (path, mode)
209 const char *path;
210 const char *mode;
211{
212 return gz_open (path, mode, -1);
213}
214
215/* ===========================================================================
216 Associate a gzFile with the file descriptor fd. fd is not dup'ed here
217 to mimic the behavio(u)r of fdopen.
218*/
219gzFile ZEXPORT gzdopen (fd, mode)
220 int fd;
221 const char *mode;
222{
223 char name[46]; /* allow for up to 128-bit integers */
224
225 if (fd < 0) return (gzFile)Z_NULL;
226 sprintf(name, "<fd:%d>", fd); /* for debugging */
227
228 return gz_open (name, mode, fd);
229}
230
231/* ===========================================================================
232 * Update the compression level and strategy
233 */
234int ZEXPORT gzsetparams (file, level, strategy)
235 gzFile file;
236 int level;
237 int strategy;
238{
239 gz_stream *s = (gz_stream*)file;
240
241 if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
242
243 /* Make room to allow flushing */
244 if (s->stream.avail_out == 0) {
245
246 s->stream.next_out = s->outbuf;
247 if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
248 s->z_err = Z_ERRNO;
249 }
250 s->stream.avail_out = Z_BUFSIZE;
251 }
252
253 return deflateParams (&(s->stream), level, strategy);
254}
255
256/* ===========================================================================
257 Read a byte from a gz_stream; update next_in and avail_in. Return EOF
258 for end of file.
259 IN assertion: the stream s has been sucessfully opened for reading.
260*/
261local int get_byte(s)
262 gz_stream *s;
263{
264 if (s->z_eof) return EOF;
265 if (s->stream.avail_in == 0) {
266 errno = 0;
267 s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file);
268 if (s->stream.avail_in == 0) {
269 s->z_eof = 1;
270 if (ferror(s->file)) s->z_err = Z_ERRNO;
271 return EOF;
272 }
273 s->stream.next_in = s->inbuf;
274 }
275 s->stream.avail_in--;
276 return *(s->stream.next_in)++;
277}
278
279/* ===========================================================================
280 Check the gzip header of a gz_stream opened for reading. Set the stream
281 mode to transparent if the gzip magic header is not present; set s->err
282 to Z_DATA_ERROR if the magic header is present but the rest of the header
283 is incorrect.
284 IN assertion: the stream s has already been created sucessfully;
285 s->stream.avail_in is zero for the first time, but may be non-zero
286 for concatenated .gz files.
287*/
288local void check_header(s)
289 gz_stream *s;
290{
291 int method; /* method byte */
292 int flags; /* flags byte */
293 uInt len;
294 int c;
295
296 /* Assure two bytes in the buffer so we can peek ahead -- handle case
297 where first byte of header is at the end of the buffer after the last
298 gzip segment */
299 len = s->stream.avail_in;
300 if (len < 2) {
301 if (len) s->inbuf[0] = s->stream.next_in[0];
302 errno = 0;
303 len = (uInt)fread(s->inbuf + len, 1, Z_BUFSIZE >> len, s->file);
304 if (len == 0 && ferror(s->file)) s->z_err = Z_ERRNO;
305 s->stream.avail_in += len;
306 s->stream.next_in = s->inbuf;
307 if (s->stream.avail_in < 2) {
308 s->transparent = s->stream.avail_in;
309 return;
310 }
311 }
312
313 /* Peek ahead to check the gzip magic header */
314 if (s->stream.next_in[0] != gz_magic[0] ||
315 s->stream.next_in[1] != gz_magic[1]) {
316 s->transparent = 1;
317 return;
318 }
319 s->stream.avail_in -= 2;
320 s->stream.next_in += 2;
321
322 /* Check the rest of the gzip header */
323 method = get_byte(s);
324 flags = get_byte(s);
325 if (method != Z_DEFLATED || (flags & RESERVED) != 0) {
326 s->z_err = Z_DATA_ERROR;
327 return;
328 }
329
330 /* Discard time, xflags and OS code: */
331 for (len = 0; len < 6; len++) (void)get_byte(s);
332
333 if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */
334 len = (uInt)get_byte(s);
335 len += ((uInt)get_byte(s))<<8;
336 /* len is garbage if EOF but the loop below will quit anyway */
337 while (len-- != 0 && get_byte(s) != EOF) ;
338 }
339 if ((flags & ORIG_NAME) != 0) { /* skip the original file name */
340 while ((c = get_byte(s)) != 0 && c != EOF) ;
341 }
342 if ((flags & COMMENT) != 0) { /* skip the .gz file comment */
343 while ((c = get_byte(s)) != 0 && c != EOF) ;
344 }
345 if ((flags & HEAD_CRC) != 0) { /* skip the header crc */
346 for (len = 0; len < 2; len++) (void)get_byte(s);
347 }
348 s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK;
349}
350
351 /* ===========================================================================
352 * Cleanup then free the given gz_stream. Return a zlib error code.
353 Try freeing in the reverse order of allocations.
354 */
355local int destroy (s)
356 gz_stream *s;
357{
358 int err = Z_OK;
359
360 if (!s) return Z_STREAM_ERROR;
361
362 TRYFREE(s->msg);
363
364 if (s->stream.state != NULL) {
365 if (s->mode == 'w') {
366#ifdef NO_GZCOMPRESS
367 err = Z_STREAM_ERROR;
368#else
369 err = deflateEnd(&(s->stream));
370#endif
371 } else if (s->mode == 'r') {
372 err = inflateEnd(&(s->stream));
373 }
374 }
375 if (s->file != NULL && fclose(s->file)) {
376#ifdef ESPIPE
377 if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */
378#endif
379 err = Z_ERRNO;
380 }
381 if (s->z_err < 0) err = s->z_err;
382
383 TRYFREE(s->inbuf);
384 TRYFREE(s->outbuf);
385 TRYFREE(s->path);
386 TRYFREE(s);
387 return err;
388}
389
390/* ===========================================================================
391 Reads the given number of uncompressed bytes from the compressed file.
392 gzread returns the number of bytes actually read (0 for end of file).
393*/
394int ZEXPORT gzread (file, buf, len)
395 gzFile file;
396 voidp buf;
397 unsigned len;
398{
399 gz_stream *s = (gz_stream*)file;
400 Bytef *start = (Bytef*)buf; /* starting point for crc computation */
401 Byte *next_out; /* == stream.next_out but not forced far (for MSDOS) */
402
403 if (s == NULL || s->mode != 'r') return Z_STREAM_ERROR;
404
405 if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1;
406 if (s->z_err == Z_STREAM_END) return 0; /* EOF */
407
408 next_out = (Byte*)buf;
409 s->stream.next_out = (Bytef*)buf;
410 s->stream.avail_out = len;
411
412 if (s->stream.avail_out && s->back != EOF) {
413 *next_out++ = s->back;
414 s->stream.next_out++;
415 s->stream.avail_out--;
416 s->back = EOF;
417 s->out++;
418 start++;
419 if (s->last) {
420 s->z_err = Z_STREAM_END;
421 return 1;
422 }
423 }
424
425 while (s->stream.avail_out != 0) {
426
427 if (s->transparent) {
428 /* Copy first the lookahead bytes: */
429 uInt n = s->stream.avail_in;
430 if (n > s->stream.avail_out) n = s->stream.avail_out;
431 if (n > 0) {
432 zmemcpy(s->stream.next_out, s->stream.next_in, n);
433 next_out += n;
434 s->stream.next_out = next_out;
435 s->stream.next_in += n;
436 s->stream.avail_out -= n;
437 s->stream.avail_in -= n;
438 }
439 if (s->stream.avail_out > 0) {
440 s->stream.avail_out -=
441 (uInt)fread(next_out, 1, s->stream.avail_out, s->file);
442 }
443 len -= s->stream.avail_out;
444 s->in += len;
445 s->out += len;
446 if (len == 0) s->z_eof = 1;
447 return (int)len;
448 }
449 if (s->stream.avail_in == 0 && !s->z_eof) {
450
451 errno = 0;
452 s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file);
453 if (s->stream.avail_in == 0) {
454 s->z_eof = 1;
455 if (ferror(s->file)) {
456 s->z_err = Z_ERRNO;
457 break;
458 }
459 }
460 s->stream.next_in = s->inbuf;
461 }
462 s->in += s->stream.avail_in;
463 s->out += s->stream.avail_out;
464 s->z_err = inflate(&(s->stream), Z_NO_FLUSH);
465 s->in -= s->stream.avail_in;
466 s->out -= s->stream.avail_out;
467
468 if (s->z_err == Z_STREAM_END) {
469 /* Check CRC and original size */
470 s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
471 start = s->stream.next_out;
472
473 if (getLong(s) != s->crc) {
474 s->z_err = Z_DATA_ERROR;
475 } else {
476 (void)getLong(s);
477 /* The uncompressed length returned by above getlong() may be
478 * different from s->out in case of concatenated .gz files.
479 * Check for such files:
480 */
481 check_header(s);
482 if (s->z_err == Z_OK) {
483 inflateReset(&(s->stream));
484 s->crc = crc32(0L, Z_NULL, 0);
485 }
486 }
487 }
488 if (s->z_err != Z_OK || s->z_eof) break;
489 }
490 s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
491
492 if (len == s->stream.avail_out &&
493 (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO))
494 return -1;
495 return (int)(len - s->stream.avail_out);
496}
497
498
499/* ===========================================================================
500 Reads one byte from the compressed file. gzgetc returns this byte
501 or -1 in case of end of file or error.
502*/
503int ZEXPORT gzgetc(file)
504 gzFile file;
505{
506 unsigned char c;
507
508 return gzread(file, &c, 1) == 1 ? c : -1;
509}
510
511
512/* ===========================================================================
513 Push one byte back onto the stream.
514*/
515int ZEXPORT gzungetc(c, file)
516 int c;
517 gzFile file;
518{
519 gz_stream *s = (gz_stream*)file;
520
521 if (s == NULL || s->mode != 'r' || c == EOF || s->back != EOF) return EOF;
522 s->back = c;
523 s->out--;
524 s->last = (s->z_err == Z_STREAM_END);
525 if (s->last) s->z_err = Z_OK;
526 s->z_eof = 0;
527 return c;
528}
529
530
531/* ===========================================================================
532 Reads bytes from the compressed file until len-1 characters are
533 read, or a newline character is read and transferred to buf, or an
534 end-of-file condition is encountered. The string is then terminated
535 with a null character.
536 gzgets returns buf, or Z_NULL in case of error.
537
538 The current implementation is not optimized at all.
539*/
540char * ZEXPORT gzgets(file, buf, len)
541 gzFile file;
542 char *buf;
543 int len;
544{
545 char *b = buf;
546 if (buf == Z_NULL || len <= 0) return Z_NULL;
547
548 while (--len > 0 && gzread(file, buf, 1) == 1 && *buf++ != '\n') ;
549 *buf = '\0';
550 return b == buf && len > 0 ? Z_NULL : b;
551}
552
553
554#ifndef NO_GZCOMPRESS
555/* ===========================================================================
556 Writes the given number of uncompressed bytes into the compressed file.
557 gzwrite returns the number of bytes actually written (0 in case of error).
558*/
559int ZEXPORT gzwrite (file, buf, len)
560 gzFile file;
561 voidpc buf;
562 unsigned len;
563{
564 gz_stream *s = (gz_stream*)file;
565
566 if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
567
568 s->stream.next_in = (Bytef*)buf;
569 s->stream.avail_in = len;
570
571 while (s->stream.avail_in != 0) {
572
573 if (s->stream.avail_out == 0) {
574
575 s->stream.next_out = s->outbuf;
576 if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
577 s->z_err = Z_ERRNO;
578 break;
579 }
580 s->stream.avail_out = Z_BUFSIZE;
581 }
582 s->in += s->stream.avail_in;
583 s->out += s->stream.avail_out;
584 s->z_err = deflate(&(s->stream), Z_NO_FLUSH);
585 s->in -= s->stream.avail_in;
586 s->out -= s->stream.avail_out;
587 if (s->z_err != Z_OK) break;
588 }
589 s->crc = crc32(s->crc, (const Bytef *)buf, len);
590
591 return (int)(len - s->stream.avail_in);
592}
593
594
595/* ===========================================================================
596 Converts, formats, and writes the args to the compressed file under
597 control of the format string, as in fprintf. gzprintf returns the number of
598 uncompressed bytes actually written (0 in case of error).
599*/
600#ifdef STDC
601#include <stdarg.h>
602
603int ZEXPORTVA gzprintf (gzFile file, const char *format, /* args */ ...)
604{
605 char buf[Z_PRINTF_BUFSIZE];
606 va_list va;
607 int len;
608
609 buf[sizeof(buf) - 1] = 0;
610 va_start(va, format);
611#ifdef NO_vsnprintf
612# ifdef HAS_vsprintf_void
613 (void)vsprintf(buf, format, va);
614 va_end(va);
615 for (len = 0; len < sizeof(buf); len++)
616 if (buf[len] == 0) break;
617# else
618 len = vsprintf(buf, format, va);
619 va_end(va);
620# endif
621#else
622# ifdef HAS_vsnprintf_void
623 (void)vsnprintf(buf, sizeof(buf), format, va);
624 va_end(va);
625 len = strlen(buf);
626# else
627 len = vsnprintf(buf, sizeof(buf), format, va);
628 va_end(va);
629# endif
630#endif
631 if (len <= 0 || len >= (int)sizeof(buf) || buf[sizeof(buf) - 1] != 0)
632 return 0;
633 return gzwrite(file, buf, (unsigned)len);
634}
635#else /* not ANSI C */
636
637int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
638 a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)
639 gzFile file;
640 const char *format;
641 int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
642 a11, a12, a13, a14, a15, a16, a17, a18, a19, a20;
643{
644 char buf[Z_PRINTF_BUFSIZE];
645 int len;
646
647 buf[sizeof(buf) - 1] = 0;
648#ifdef NO_snprintf
649# ifdef HAS_sprintf_void
650 sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8,
651 a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
652 for (len = 0; len < sizeof(buf); len++)
653 if (buf[len] == 0) break;
654# else
655 len = sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8,
656 a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
657# endif
658#else
659# ifdef HAS_snprintf_void
660 snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8,
661 a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
662 len = strlen(buf);
663# else
664 len = snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8,
665 a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
666# endif
667#endif
668 if (len <= 0 || len >= sizeof(buf) || buf[sizeof(buf) - 1] != 0)
669 return 0;
670 return gzwrite(file, buf, len);
671}
672#endif
673
674/* ===========================================================================
675 Writes c, converted to an unsigned char, into the compressed file.
676 gzputc returns the value that was written, or -1 in case of error.
677*/
678int ZEXPORT gzputc(file, c)
679 gzFile file;
680 int c;
681{
682 unsigned char cc = (unsigned char) c; /* required for big endian systems */
683
684 return gzwrite(file, &cc, 1) == 1 ? (int)cc : -1;
685}
686
687
688/* ===========================================================================
689 Writes the given null-terminated string to the compressed file, excluding
690 the terminating null character.
691 gzputs returns the number of characters written, or -1 in case of error.
692*/
693int ZEXPORT gzputs(file, s)
694 gzFile file;
695 const char *s;
696{
697 return gzwrite(file, (char*)s, (unsigned)strlen(s));
698}
699
700
701/* ===========================================================================
702 Flushes all pending output into the compressed file. The parameter
703 flush is as in the deflate() function.
704*/
705local int do_flush (file, flush)
706 gzFile file;
707 int flush;
708{
709 uInt len;
710 int done = 0;
711 gz_stream *s = (gz_stream*)file;
712
713 if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
714
715 s->stream.avail_in = 0; /* should be zero already anyway */
716
717 for (;;) {
718 len = Z_BUFSIZE - s->stream.avail_out;
719
720 if (len != 0) {
721 if ((uInt)fwrite(s->outbuf, 1, len, s->file) != len) {
722 s->z_err = Z_ERRNO;
723 return Z_ERRNO;
724 }
725 s->stream.next_out = s->outbuf;
726 s->stream.avail_out = Z_BUFSIZE;
727 }
728 if (done) break;
729 s->out += s->stream.avail_out;
730 s->z_err = deflate(&(s->stream), flush);
731 s->out -= s->stream.avail_out;
732
733 /* Ignore the second of two consecutive flushes: */
734 if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK;
735
736 /* deflate has finished flushing only when it hasn't used up
737 * all the available space in the output buffer:
738 */
739 done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END);
740
741 if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break;
742 }
743 return s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
744}
745
746int ZEXPORT gzflush (file, flush)
747 gzFile file;
748 int flush;
749{
750 gz_stream *s = (gz_stream*)file;
751 int err = do_flush (file, flush);
752
753 if (err) return err;
754 fflush(s->file);
755 return s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
756}
757#endif /* NO_GZCOMPRESS */
758
759/* ===========================================================================
760 Sets the starting position for the next gzread or gzwrite on the given
761 compressed file. The offset represents a number of bytes in the
762 gzseek returns the resulting offset location as measured in bytes from
763 the beginning of the uncompressed stream, or -1 in case of error.
764 SEEK_END is not implemented, returns error.
765 In this version of the library, gzseek can be extremely slow.
766*/
767z_off_t ZEXPORT gzseek (file, offset, whence)
768 gzFile file;
769 z_off_t offset;
770 int whence;
771{
772 gz_stream *s = (gz_stream*)file;
773
774 if (s == NULL || whence == SEEK_END ||
775 s->z_err == Z_ERRNO || s->z_err == Z_DATA_ERROR) {
776 return -1L;
777 }
778
779 if (s->mode == 'w') {
780#ifdef NO_GZCOMPRESS
781 return -1L;
782#else
783 if (whence == SEEK_SET) {
784 offset -= s->in;
785 }
786 if (offset < 0) return -1L;
787
788 /* At this point, offset is the number of zero bytes to write. */
789 if (s->inbuf == Z_NULL) {
790 s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); /* for seeking */
791 if (s->inbuf == Z_NULL) return -1L;
792 zmemzero(s->inbuf, Z_BUFSIZE);
793 }
794 while (offset > 0) {
795 uInt size = Z_BUFSIZE;
796 if (offset < Z_BUFSIZE) size = (uInt)offset;
797
798 size = gzwrite(file, s->inbuf, size);
799 if (size == 0) return -1L;
800
801 offset -= size;
802 }
803 return s->in;
804#endif
805 }
806 /* Rest of function is for reading only */
807
808 /* compute absolute position */
809 if (whence == SEEK_CUR) {
810 offset += s->out;
811 }
812 if (offset < 0) return -1L;
813
814 if (s->transparent) {
815 /* map to fseek */
816 s->back = EOF;
817 s->stream.avail_in = 0;
818 s->stream.next_in = s->inbuf;
819 if (fseek(s->file, offset, SEEK_SET) < 0) return -1L;
820
821 s->in = s->out = offset;
822 return offset;
823 }
824
825 /* For a negative seek, rewind and use positive seek */
826 if (offset >= s->out) {
827 offset -= s->out;
828 } else if (gzrewind(file) < 0) {
829 return -1L;
830 }
831 /* offset is now the number of bytes to skip. */
832
833 if (offset != 0 && s->outbuf == Z_NULL) {
834 s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
835 if (s->outbuf == Z_NULL) return -1L;
836 }
837 if (offset && s->back != EOF) {
838 s->back = EOF;
839 s->out++;
840 offset--;
841 if (s->last) s->z_err = Z_STREAM_END;
842 }
843 while (offset > 0) {
844 int size = Z_BUFSIZE;
845 if (offset < Z_BUFSIZE) size = (int)offset;
846
847 size = gzread(file, s->outbuf, (uInt)size);
848 if (size <= 0) return -1L;
849 offset -= size;
850 }
851 return s->out;
852}
853
854/* ===========================================================================
855 Rewinds input file.
856*/
857int ZEXPORT gzrewind (file)
858 gzFile file;
859{
860 gz_stream *s = (gz_stream*)file;
861
862 if (s == NULL || s->mode != 'r') return -1;
863
864 s->z_err = Z_OK;
865 s->z_eof = 0;
866 s->back = EOF;
867 s->stream.avail_in = 0;
868 s->stream.next_in = s->inbuf;
869 s->crc = crc32(0L, Z_NULL, 0);
870 if (!s->transparent) (void)inflateReset(&s->stream);
871 s->in = 0;
872 s->out = 0;
873 return fseek(s->file, s->start, SEEK_SET);
874}
875
876/* ===========================================================================
877 Returns the starting position for the next gzread or gzwrite on the
878 given compressed file. This position represents a number of bytes in the
879 uncompressed data stream.
880*/
881z_off_t ZEXPORT gztell (file)
882 gzFile file;
883{
884 return gzseek(file, 0L, SEEK_CUR);
885}
886
887/* ===========================================================================
888 Returns 1 when EOF has previously been detected reading the given
889 input stream, otherwise zero.
890*/
891int ZEXPORT gzeof (file)
892 gzFile file;
893{
894 gz_stream *s = (gz_stream*)file;
895
896 /* With concatenated compressed files that can have embedded
897 * crc trailers, z_eof is no longer the only/best indicator of EOF
898 * on a gz_stream. Handle end-of-stream error explicitly here.
899 */
900 if (s == NULL || s->mode != 'r') return 0;
901 if (s->z_eof) return 1;
902 return s->z_err == Z_STREAM_END;
903}
904
905/* ===========================================================================
906 Returns 1 if reading and doing so transparently, otherwise zero.
907*/
908int ZEXPORT gzdirect (file)
909 gzFile file;
910{
911 gz_stream *s = (gz_stream*)file;
912
913 if (s == NULL || s->mode != 'r') return 0;
914 return s->transparent;
915}
916
917/* ===========================================================================
918 Outputs a long in LSB order to the given file
919*/
920local void putLong (file, x)
921 FILE *file;
922 uLong x;
923{
924 int n;
925 for (n = 0; n < 4; n++) {
926 fputc((int)(x & 0xff), file);
927 x >>= 8;
928 }
929}
930
931/* ===========================================================================
932 Reads a long in LSB order from the given gz_stream. Sets z_err in case
933 of error.
934*/
935local uLong getLong (s)
936 gz_stream *s;
937{
938 uLong x = (uLong)get_byte(s);
939 int c;
940
941 x += ((uLong)get_byte(s))<<8;
942 x += ((uLong)get_byte(s))<<16;
943 c = get_byte(s);
944 if (c == EOF) s->z_err = Z_DATA_ERROR;
945 x += ((uLong)c)<<24;
946 return x;
947}
948
949/* ===========================================================================
950 Flushes all pending output if necessary, closes the compressed file
951 and deallocates all the (de)compression state.
952*/
953int ZEXPORT gzclose (file)
954 gzFile file;
955{
956 gz_stream *s = (gz_stream*)file;
957
958 if (s == NULL) return Z_STREAM_ERROR;
959
960 if (s->mode == 'w') {
961#ifdef NO_GZCOMPRESS
962 return Z_STREAM_ERROR;
963#else
964 if (do_flush (file, Z_FINISH) != Z_OK)
965 return destroy((gz_stream*)file);
966
967 putLong (s->file, s->crc);
968 putLong (s->file, (uLong)(s->in & 0xffffffff));
969#endif
970 }
971 return destroy((gz_stream*)file);
972}
973
974#ifdef STDC
975# define zstrerror(errnum) strerror(errnum)
976#else
977# define zstrerror(errnum) ""
978#endif
979
980/* ===========================================================================
981 Returns the error message for the last error which occurred on the
982 given compressed file. errnum is set to zlib error number. If an
983 error occurred in the file system and not in the compression library,
984 errnum is set to Z_ERRNO and the application may consult errno
985 to get the exact error code.
986*/
987const char * ZEXPORT gzerror (file, errnum)
988 gzFile file;
989 int *errnum;
990{
991 char *m;
992 gz_stream *s = (gz_stream*)file;
993
994 if (s == NULL) {
995 *errnum = Z_STREAM_ERROR;
996 return (const char*)ERR_MSG(Z_STREAM_ERROR);
997 }
998 *errnum = s->z_err;
999 if (*errnum == Z_OK) return (const char*)"";
1000
1001 m = (char*)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg);
1002
1003 if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err);
1004
1005 TRYFREE(s->msg);
1006 s->msg = (char*)ALLOC(strlen(s->path) + strlen(m) + 3);
1007 if (s->msg == Z_NULL) return (const char*)ERR_MSG(Z_MEM_ERROR);
1008 strcpy(s->msg, s->path);
1009 strcat(s->msg, ": ");
1010 strcat(s->msg, m);
1011 return (const char*)s->msg;
1012}
1013
1014/* ===========================================================================
1015 Clear the error and end-of-file flags, and do the same for the real file.
1016*/
1017void ZEXPORT gzclearerr (file)
1018 gzFile file;
1019{
1020 gz_stream *s = (gz_stream*)file;
1021
1022 if (s == NULL) return;
1023 if (s->z_err != Z_STREAM_END) s->z_err = Z_OK;
1024 s->z_eof = 0;
1025 clearerr(s->file);
1026}
diff --git a/utils/zenutils/libraries/zlib123/zlib/infback.c b/utils/zenutils/libraries/zlib123/zlib/infback.c
new file mode 100755
index 0000000000..1e03e1bab0
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/infback.c
@@ -0,0 +1,623 @@
1/* infback.c -- inflate using a call-back interface
2 * Copyright (C) 1995-2005 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/*
7 This code is largely copied from inflate.c. Normally either infback.o or
8 inflate.o would be linked into an application--not both. The interface
9 with inffast.c is retained so that optimized assembler-coded versions of
10 inflate_fast() can be used with either inflate.c or infback.c.
11 */
12
13#include "zutil.h"
14#include "inftrees.h"
15#include "inflate.h"
16#include "inffast.h"
17
18/* function prototypes */
19local void fixedtables OF((struct inflate_state FAR *state));
20
21/*
22 strm provides memory allocation functions in zalloc and zfree, or
23 Z_NULL to use the library memory allocation functions.
24
25 windowBits is in the range 8..15, and window is a user-supplied
26 window and output buffer that is 2**windowBits bytes.
27 */
28int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size)
29z_streamp strm;
30int windowBits;
31unsigned char FAR *window;
32const char *version;
33int stream_size;
34{
35 struct inflate_state FAR *state;
36
37 if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
38 stream_size != (int)(sizeof(z_stream)))
39 return Z_VERSION_ERROR;
40 if (strm == Z_NULL || window == Z_NULL ||
41 windowBits < 8 || windowBits > 15)
42 return Z_STREAM_ERROR;
43 strm->msg = Z_NULL; /* in case we return an error */
44 if (strm->zalloc == (alloc_func)0) {
45 strm->zalloc = zcalloc;
46 strm->opaque = (voidpf)0;
47 }
48 if (strm->zfree == (free_func)0) strm->zfree = zcfree;
49 state = (struct inflate_state FAR *)ZALLOC(strm, 1,
50 sizeof(struct inflate_state));
51 if (state == Z_NULL) return Z_MEM_ERROR;
52 Tracev((stderr, "inflate: allocated\n"));
53 strm->state = (struct internal_state FAR *)state;
54 state->dmax = 32768U;
55 state->wbits = windowBits;
56 state->wsize = 1U << windowBits;
57 state->window = window;
58 state->write = 0;
59 state->whave = 0;
60 return Z_OK;
61}
62
63/*
64 Return state with length and distance decoding tables and index sizes set to
65 fixed code decoding. Normally this returns fixed tables from inffixed.h.
66 If BUILDFIXED is defined, then instead this routine builds the tables the
67 first time it's called, and returns those tables the first time and
68 thereafter. This reduces the size of the code by about 2K bytes, in
69 exchange for a little execution time. However, BUILDFIXED should not be
70 used for threaded applications, since the rewriting of the tables and virgin
71 may not be thread-safe.
72 */
73local void fixedtables(state)
74struct inflate_state FAR *state;
75{
76#ifdef BUILDFIXED
77 static int virgin = 1;
78 static code *lenfix, *distfix;
79 static code fixed[544];
80
81 /* build fixed huffman tables if first call (may not be thread safe) */
82 if (virgin) {
83 unsigned sym, bits;
84 static code *next;
85
86 /* literal/length table */
87 sym = 0;
88 while (sym < 144) state->lens[sym++] = 8;
89 while (sym < 256) state->lens[sym++] = 9;
90 while (sym < 280) state->lens[sym++] = 7;
91 while (sym < 288) state->lens[sym++] = 8;
92 next = fixed;
93 lenfix = next;
94 bits = 9;
95 inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
96
97 /* distance table */
98 sym = 0;
99 while (sym < 32) state->lens[sym++] = 5;
100 distfix = next;
101 bits = 5;
102 inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
103
104 /* do this just once */
105 virgin = 0;
106 }
107#else /* !BUILDFIXED */
108# include "inffixed.h"
109#endif /* BUILDFIXED */
110 state->lencode = lenfix;
111 state->lenbits = 9;
112 state->distcode = distfix;
113 state->distbits = 5;
114}
115
116/* Macros for inflateBack(): */
117
118/* Load returned state from inflate_fast() */
119#define LOAD() \
120 do { \
121 put = strm->next_out; \
122 left = strm->avail_out; \
123 next = strm->next_in; \
124 have = strm->avail_in; \
125 hold = state->hold; \
126 bits = state->bits; \
127 } while (0)
128
129/* Set state from registers for inflate_fast() */
130#define RESTORE() \
131 do { \
132 strm->next_out = put; \
133 strm->avail_out = left; \
134 strm->next_in = next; \
135 strm->avail_in = have; \
136 state->hold = hold; \
137 state->bits = bits; \
138 } while (0)
139
140/* Clear the input bit accumulator */
141#define INITBITS() \
142 do { \
143 hold = 0; \
144 bits = 0; \
145 } while (0)
146
147/* Assure that some input is available. If input is requested, but denied,
148 then return a Z_BUF_ERROR from inflateBack(). */
149#define PULL() \
150 do { \
151 if (have == 0) { \
152 have = in(in_desc, &next); \
153 if (have == 0) { \
154 next = Z_NULL; \
155 ret = Z_BUF_ERROR; \
156 goto inf_leave; \
157 } \
158 } \
159 } while (0)
160
161/* Get a byte of input into the bit accumulator, or return from inflateBack()
162 with an error if there is no input available. */
163#define PULLBYTE() \
164 do { \
165 PULL(); \
166 have--; \
167 hold += (unsigned long)(*next++) << bits; \
168 bits += 8; \
169 } while (0)
170
171/* Assure that there are at least n bits in the bit accumulator. If there is
172 not enough available input to do that, then return from inflateBack() with
173 an error. */
174#define NEEDBITS(n) \
175 do { \
176 while (bits < (unsigned)(n)) \
177 PULLBYTE(); \
178 } while (0)
179
180/* Return the low n bits of the bit accumulator (n < 16) */
181#define BITS(n) \
182 ((unsigned)hold & ((1U << (n)) - 1))
183
184/* Remove n bits from the bit accumulator */
185#define DROPBITS(n) \
186 do { \
187 hold >>= (n); \
188 bits -= (unsigned)(n); \
189 } while (0)
190
191/* Remove zero to seven bits as needed to go to a byte boundary */
192#define BYTEBITS() \
193 do { \
194 hold >>= bits & 7; \
195 bits -= bits & 7; \
196 } while (0)
197
198/* Assure that some output space is available, by writing out the window
199 if it's full. If the write fails, return from inflateBack() with a
200 Z_BUF_ERROR. */
201#define ROOM() \
202 do { \
203 if (left == 0) { \
204 put = state->window; \
205 left = state->wsize; \
206 state->whave = left; \
207 if (out(out_desc, put, left)) { \
208 ret = Z_BUF_ERROR; \
209 goto inf_leave; \
210 } \
211 } \
212 } while (0)
213
214/*
215 strm provides the memory allocation functions and window buffer on input,
216 and provides information on the unused input on return. For Z_DATA_ERROR
217 returns, strm will also provide an error message.
218
219 in() and out() are the call-back input and output functions. When
220 inflateBack() needs more input, it calls in(). When inflateBack() has
221 filled the window with output, or when it completes with data in the
222 window, it calls out() to write out the data. The application must not
223 change the provided input until in() is called again or inflateBack()
224 returns. The application must not change the window/output buffer until
225 inflateBack() returns.
226
227 in() and out() are called with a descriptor parameter provided in the
228 inflateBack() call. This parameter can be a structure that provides the
229 information required to do the read or write, as well as accumulated
230 information on the input and output such as totals and check values.
231
232 in() should return zero on failure. out() should return non-zero on
233 failure. If either in() or out() fails, than inflateBack() returns a
234 Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it
235 was in() or out() that caused in the error. Otherwise, inflateBack()
236 returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format
237 error, or Z_MEM_ERROR if it could not allocate memory for the state.
238 inflateBack() can also return Z_STREAM_ERROR if the input parameters
239 are not correct, i.e. strm is Z_NULL or the state was not initialized.
240 */
241int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc)
242z_streamp strm;
243in_func in;
244void FAR *in_desc;
245out_func out;
246void FAR *out_desc;
247{
248 struct inflate_state FAR *state;
249 unsigned char FAR *next; /* next input */
250 unsigned char FAR *put; /* next output */
251 unsigned have, left; /* available input and output */
252 unsigned long hold; /* bit buffer */
253 unsigned bits; /* bits in bit buffer */
254 unsigned copy; /* number of stored or match bytes to copy */
255 unsigned char FAR *from; /* where to copy match bytes from */
256 code this; /* current decoding table entry */
257 code last; /* parent table entry */
258 unsigned len; /* length to copy for repeats, bits to drop */
259 int ret; /* return code */
260 static const unsigned short order[19] = /* permutation of code lengths */
261 {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
262
263 /* Check that the strm exists and that the state was initialized */
264 if (strm == Z_NULL || strm->state == Z_NULL)
265 return Z_STREAM_ERROR;
266 state = (struct inflate_state FAR *)strm->state;
267
268 /* Reset the state */
269 strm->msg = Z_NULL;
270 state->mode = TYPE;
271 state->last = 0;
272 state->whave = 0;
273 next = strm->next_in;
274 have = next != Z_NULL ? strm->avail_in : 0;
275 hold = 0;
276 bits = 0;
277 put = state->window;
278 left = state->wsize;
279
280 /* Inflate until end of block marked as last */
281 for (;;)
282 switch (state->mode) {
283 case TYPE:
284 /* determine and dispatch block type */
285 if (state->last) {
286 BYTEBITS();
287 state->mode = DONE;
288 break;
289 }
290 NEEDBITS(3);
291 state->last = BITS(1);
292 DROPBITS(1);
293 switch (BITS(2)) {
294 case 0: /* stored block */
295 Tracev((stderr, "inflate: stored block%s\n",
296 state->last ? " (last)" : ""));
297 state->mode = STORED;
298 break;
299 case 1: /* fixed block */
300 fixedtables(state);
301 Tracev((stderr, "inflate: fixed codes block%s\n",
302 state->last ? " (last)" : ""));
303 state->mode = LEN; /* decode codes */
304 break;
305 case 2: /* dynamic block */
306 Tracev((stderr, "inflate: dynamic codes block%s\n",
307 state->last ? " (last)" : ""));
308 state->mode = TABLE;
309 break;
310 case 3:
311 strm->msg = (char *)"invalid block type";
312 state->mode = BAD;
313 }
314 DROPBITS(2);
315 break;
316
317 case STORED:
318 /* get and verify stored block length */
319 BYTEBITS(); /* go to byte boundary */
320 NEEDBITS(32);
321 if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
322 strm->msg = (char *)"invalid stored block lengths";
323 state->mode = BAD;
324 break;
325 }
326 state->length = (unsigned)hold & 0xffff;
327 Tracev((stderr, "inflate: stored length %u\n",
328 state->length));
329 INITBITS();
330
331 /* copy stored block from input to output */
332 while (state->length != 0) {
333 copy = state->length;
334 PULL();
335 ROOM();
336 if (copy > have) copy = have;
337 if (copy > left) copy = left;
338 zmemcpy(put, next, copy);
339 have -= copy;
340 next += copy;
341 left -= copy;
342 put += copy;
343 state->length -= copy;
344 }
345 Tracev((stderr, "inflate: stored end\n"));
346 state->mode = TYPE;
347 break;
348
349 case TABLE:
350 /* get dynamic table entries descriptor */
351 NEEDBITS(14);
352 state->nlen = BITS(5) + 257;
353 DROPBITS(5);
354 state->ndist = BITS(5) + 1;
355 DROPBITS(5);
356 state->ncode = BITS(4) + 4;
357 DROPBITS(4);
358#ifndef PKZIP_BUG_WORKAROUND
359 if (state->nlen > 286 || state->ndist > 30) {
360 strm->msg = (char *)"too many length or distance symbols";
361 state->mode = BAD;
362 break;
363 }
364#endif
365 Tracev((stderr, "inflate: table sizes ok\n"));
366
367 /* get code length code lengths (not a typo) */
368 state->have = 0;
369 while (state->have < state->ncode) {
370 NEEDBITS(3);
371 state->lens[order[state->have++]] = (unsigned short)BITS(3);
372 DROPBITS(3);
373 }
374 while (state->have < 19)
375 state->lens[order[state->have++]] = 0;
376 state->next = state->codes;
377 state->lencode = (code const FAR *)(state->next);
378 state->lenbits = 7;
379 ret = inflate_table(CODES, state->lens, 19, &(state->next),
380 &(state->lenbits), state->work);
381 if (ret) {
382 strm->msg = (char *)"invalid code lengths set";
383 state->mode = BAD;
384 break;
385 }
386 Tracev((stderr, "inflate: code lengths ok\n"));
387
388 /* get length and distance code code lengths */
389 state->have = 0;
390 while (state->have < state->nlen + state->ndist) {
391 for (;;) {
392 this = state->lencode[BITS(state->lenbits)];
393 if ((unsigned)(this.bits) <= bits) break;
394 PULLBYTE();
395 }
396 if (this.val < 16) {
397 NEEDBITS(this.bits);
398 DROPBITS(this.bits);
399 state->lens[state->have++] = this.val;
400 }
401 else {
402 if (this.val == 16) {
403 NEEDBITS(this.bits + 2);
404 DROPBITS(this.bits);
405 if (state->have == 0) {
406 strm->msg = (char *)"invalid bit length repeat";
407 state->mode = BAD;
408 break;
409 }
410 len = (unsigned)(state->lens[state->have - 1]);
411 copy = 3 + BITS(2);
412 DROPBITS(2);
413 }
414 else if (this.val == 17) {
415 NEEDBITS(this.bits + 3);
416 DROPBITS(this.bits);
417 len = 0;
418 copy = 3 + BITS(3);
419 DROPBITS(3);
420 }
421 else {
422 NEEDBITS(this.bits + 7);
423 DROPBITS(this.bits);
424 len = 0;
425 copy = 11 + BITS(7);
426 DROPBITS(7);
427 }
428 if (state->have + copy > state->nlen + state->ndist) {
429 strm->msg = (char *)"invalid bit length repeat";
430 state->mode = BAD;
431 break;
432 }
433 while (copy--)
434 state->lens[state->have++] = (unsigned short)len;
435 }
436 }
437
438 /* handle error breaks in while */
439 if (state->mode == BAD) break;
440
441 /* build code tables */
442 state->next = state->codes;
443 state->lencode = (code const FAR *)(state->next);
444 state->lenbits = 9;
445 ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
446 &(state->lenbits), state->work);
447 if (ret) {
448 strm->msg = (char *)"invalid literal/lengths set";
449 state->mode = BAD;
450 break;
451 }
452 state->distcode = (code const FAR *)(state->next);
453 state->distbits = 6;
454 ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
455 &(state->next), &(state->distbits), state->work);
456 if (ret) {
457 strm->msg = (char *)"invalid distances set";
458 state->mode = BAD;
459 break;
460 }
461 Tracev((stderr, "inflate: codes ok\n"));
462 state->mode = LEN;
463
464 case LEN:
465 /* use inflate_fast() if we have enough input and output */
466 if (have >= 6 && left >= 258) {
467 RESTORE();
468 if (state->whave < state->wsize)
469 state->whave = state->wsize - left;
470 inflate_fast(strm, state->wsize);
471 LOAD();
472 break;
473 }
474
475 /* get a literal, length, or end-of-block code */
476 for (;;) {
477 this = state->lencode[BITS(state->lenbits)];
478 if ((unsigned)(this.bits) <= bits) break;
479 PULLBYTE();
480 }
481 if (this.op && (this.op & 0xf0) == 0) {
482 last = this;
483 for (;;) {
484 this = state->lencode[last.val +
485 (BITS(last.bits + last.op) >> last.bits)];
486 if ((unsigned)(last.bits + this.bits) <= bits) break;
487 PULLBYTE();
488 }
489 DROPBITS(last.bits);
490 }
491 DROPBITS(this.bits);
492 state->length = (unsigned)this.val;
493
494 /* process literal */
495 if (this.op == 0) {
496 Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
497 "inflate: literal '%c'\n" :
498 "inflate: literal 0x%02x\n", this.val));
499 ROOM();
500 *put++ = (unsigned char)(state->length);
501 left--;
502 state->mode = LEN;
503 break;
504 }
505
506 /* process end of block */
507 if (this.op & 32) {
508 Tracevv((stderr, "inflate: end of block\n"));
509 state->mode = TYPE;
510 break;
511 }
512
513 /* invalid code */
514 if (this.op & 64) {
515 strm->msg = (char *)"invalid literal/length code";
516 state->mode = BAD;
517 break;
518 }
519
520 /* length code -- get extra bits, if any */
521 state->extra = (unsigned)(this.op) & 15;
522 if (state->extra != 0) {
523 NEEDBITS(state->extra);
524 state->length += BITS(state->extra);
525 DROPBITS(state->extra);
526 }
527 Tracevv((stderr, "inflate: length %u\n", state->length));
528
529 /* get distance code */
530 for (;;) {
531 this = state->distcode[BITS(state->distbits)];
532 if ((unsigned)(this.bits) <= bits) break;
533 PULLBYTE();
534 }
535 if ((this.op & 0xf0) == 0) {
536 last = this;
537 for (;;) {
538 this = state->distcode[last.val +
539 (BITS(last.bits + last.op) >> last.bits)];
540 if ((unsigned)(last.bits + this.bits) <= bits) break;
541 PULLBYTE();
542 }
543 DROPBITS(last.bits);
544 }
545 DROPBITS(this.bits);
546 if (this.op & 64) {
547 strm->msg = (char *)"invalid distance code";
548 state->mode = BAD;
549 break;
550 }
551 state->offset = (unsigned)this.val;
552
553 /* get distance extra bits, if any */
554 state->extra = (unsigned)(this.op) & 15;
555 if (state->extra != 0) {
556 NEEDBITS(state->extra);
557 state->offset += BITS(state->extra);
558 DROPBITS(state->extra);
559 }
560 if (state->offset > state->wsize - (state->whave < state->wsize ?
561 left : 0)) {
562 strm->msg = (char *)"invalid distance too far back";
563 state->mode = BAD;
564 break;
565 }
566 Tracevv((stderr, "inflate: distance %u\n", state->offset));
567
568 /* copy match from window to output */
569 do {
570 ROOM();
571 copy = state->wsize - state->offset;
572 if (copy < left) {
573 from = put + copy;
574 copy = left - copy;
575 }
576 else {
577 from = put - state->offset;
578 copy = left;
579 }
580 if (copy > state->length) copy = state->length;
581 state->length -= copy;
582 left -= copy;
583 do {
584 *put++ = *from++;
585 } while (--copy);
586 } while (state->length != 0);
587 break;
588
589 case DONE:
590 /* inflate stream terminated properly -- write leftover output */
591 ret = Z_STREAM_END;
592 if (left < state->wsize) {
593 if (out(out_desc, state->window, state->wsize - left))
594 ret = Z_BUF_ERROR;
595 }
596 goto inf_leave;
597
598 case BAD:
599 ret = Z_DATA_ERROR;
600 goto inf_leave;
601
602 default: /* can't happen, but makes compilers happy */
603 ret = Z_STREAM_ERROR;
604 goto inf_leave;
605 }
606
607 /* Return unused input */
608 inf_leave:
609 strm->next_in = next;
610 strm->avail_in = have;
611 return ret;
612}
613
614int ZEXPORT inflateBackEnd(strm)
615z_streamp strm;
616{
617 if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
618 return Z_STREAM_ERROR;
619 ZFREE(strm, strm->state);
620 strm->state = Z_NULL;
621 Tracev((stderr, "inflate: end\n"));
622 return Z_OK;
623}
diff --git a/utils/zenutils/libraries/zlib123/zlib/inffast.c b/utils/zenutils/libraries/zlib123/zlib/inffast.c
new file mode 100755
index 0000000000..fa31cad905
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/inffast.c
@@ -0,0 +1,318 @@
1/* inffast.c -- fast decoding
2 * Copyright (C) 1995-2004 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6#include "zutil.h"
7#include "inftrees.h"
8#include "inflate.h"
9#include "inffast.h"
10
11#ifndef ASMINF
12
13/* Allow machine dependent optimization for post-increment or pre-increment.
14 Based on testing to date,
15 Pre-increment preferred for:
16 - PowerPC G3 (Adler)
17 - MIPS R5000 (Randers-Pehrson)
18 Post-increment preferred for:
19 - none
20 No measurable difference:
21 - Pentium III (Anderson)
22 - M68060 (Nikl)
23 */
24#ifdef POSTINC
25# define OFF 0
26# define PUP(a) *(a)++
27#else
28# define OFF 1
29# define PUP(a) *++(a)
30#endif
31
32/*
33 Decode literal, length, and distance codes and write out the resulting
34 literal and match bytes until either not enough input or output is
35 available, an end-of-block is encountered, or a data error is encountered.
36 When large enough input and output buffers are supplied to inflate(), for
37 example, a 16K input buffer and a 64K output buffer, more than 95% of the
38 inflate execution time is spent in this routine.
39
40 Entry assumptions:
41
42 state->mode == LEN
43 strm->avail_in >= 6
44 strm->avail_out >= 258
45 start >= strm->avail_out
46 state->bits < 8
47
48 On return, state->mode is one of:
49
50 LEN -- ran out of enough output space or enough available input
51 TYPE -- reached end of block code, inflate() to interpret next block
52 BAD -- error in block data
53
54 Notes:
55
56 - The maximum input bits used by a length/distance pair is 15 bits for the
57 length code, 5 bits for the length extra, 15 bits for the distance code,
58 and 13 bits for the distance extra. This totals 48 bits, or six bytes.
59 Therefore if strm->avail_in >= 6, then there is enough input to avoid
60 checking for available input while decoding.
61
62 - The maximum bytes that a single length/distance pair can output is 258
63 bytes, which is the maximum length that can be coded. inflate_fast()
64 requires strm->avail_out >= 258 for each loop to avoid checking for
65 output space.
66 */
67void inflate_fast(strm, start)
68z_streamp strm;
69unsigned start; /* inflate()'s starting value for strm->avail_out */
70{
71 struct inflate_state FAR *state;
72 unsigned char FAR *in; /* local strm->next_in */
73 unsigned char FAR *last; /* while in < last, enough input available */
74 unsigned char FAR *out; /* local strm->next_out */
75 unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
76 unsigned char FAR *end; /* while out < end, enough space available */
77#ifdef INFLATE_STRICT
78 unsigned dmax; /* maximum distance from zlib header */
79#endif
80 unsigned wsize; /* window size or zero if not using window */
81 unsigned whave; /* valid bytes in the window */
82 unsigned write; /* window write index */
83 unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
84 unsigned long hold; /* local strm->hold */
85 unsigned bits; /* local strm->bits */
86 code const FAR *lcode; /* local strm->lencode */
87 code const FAR *dcode; /* local strm->distcode */
88 unsigned lmask; /* mask for first level of length codes */
89 unsigned dmask; /* mask for first level of distance codes */
90 code this; /* retrieved table entry */
91 unsigned op; /* code bits, operation, extra bits, or */
92 /* window position, window bytes to copy */
93 unsigned len; /* match length, unused bytes */
94 unsigned dist; /* match distance */
95 unsigned char FAR *from; /* where to copy match from */
96
97 /* copy state to local variables */
98 state = (struct inflate_state FAR *)strm->state;
99 in = strm->next_in - OFF;
100 last = in + (strm->avail_in - 5);
101 out = strm->next_out - OFF;
102 beg = out - (start - strm->avail_out);
103 end = out + (strm->avail_out - 257);
104#ifdef INFLATE_STRICT
105 dmax = state->dmax;
106#endif
107 wsize = state->wsize;
108 whave = state->whave;
109 write = state->write;
110 window = state->window;
111 hold = state->hold;
112 bits = state->bits;
113 lcode = state->lencode;
114 dcode = state->distcode;
115 lmask = (1U << state->lenbits) - 1;
116 dmask = (1U << state->distbits) - 1;
117
118 /* decode literals and length/distances until end-of-block or not enough
119 input data or output space */
120 do {
121 if (bits < 15) {
122 hold += (unsigned long)(PUP(in)) << bits;
123 bits += 8;
124 hold += (unsigned long)(PUP(in)) << bits;
125 bits += 8;
126 }
127 this = lcode[hold & lmask];
128 dolen:
129 op = (unsigned)(this.bits);
130 hold >>= op;
131 bits -= op;
132 op = (unsigned)(this.op);
133 if (op == 0) { /* literal */
134 Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
135 "inflate: literal '%c'\n" :
136 "inflate: literal 0x%02x\n", this.val));
137 PUP(out) = (unsigned char)(this.val);
138 }
139 else if (op & 16) { /* length base */
140 len = (unsigned)(this.val);
141 op &= 15; /* number of extra bits */
142 if (op) {
143 if (bits < op) {
144 hold += (unsigned long)(PUP(in)) << bits;
145 bits += 8;
146 }
147 len += (unsigned)hold & ((1U << op) - 1);
148 hold >>= op;
149 bits -= op;
150 }
151 Tracevv((stderr, "inflate: length %u\n", len));
152 if (bits < 15) {
153 hold += (unsigned long)(PUP(in)) << bits;
154 bits += 8;
155 hold += (unsigned long)(PUP(in)) << bits;
156 bits += 8;
157 }
158 this = dcode[hold & dmask];
159 dodist:
160 op = (unsigned)(this.bits);
161 hold >>= op;
162 bits -= op;
163 op = (unsigned)(this.op);
164 if (op & 16) { /* distance base */
165 dist = (unsigned)(this.val);
166 op &= 15; /* number of extra bits */
167 if (bits < op) {
168 hold += (unsigned long)(PUP(in)) << bits;
169 bits += 8;
170 if (bits < op) {
171 hold += (unsigned long)(PUP(in)) << bits;
172 bits += 8;
173 }
174 }
175 dist += (unsigned)hold & ((1U << op) - 1);
176#ifdef INFLATE_STRICT
177 if (dist > dmax) {
178 strm->msg = (char *)"invalid distance too far back";
179 state->mode = BAD;
180 break;
181 }
182#endif
183 hold >>= op;
184 bits -= op;
185 Tracevv((stderr, "inflate: distance %u\n", dist));
186 op = (unsigned)(out - beg); /* max distance in output */
187 if (dist > op) { /* see if copy from window */
188 op = dist - op; /* distance back in window */
189 if (op > whave) {
190 strm->msg = (char *)"invalid distance too far back";
191 state->mode = BAD;
192 break;
193 }
194 from = window - OFF;
195 if (write == 0) { /* very common case */
196 from += wsize - op;
197 if (op < len) { /* some from window */
198 len -= op;
199 do {
200 PUP(out) = PUP(from);
201 } while (--op);
202 from = out - dist; /* rest from output */
203 }
204 }
205 else if (write < op) { /* wrap around window */
206 from += wsize + write - op;
207 op -= write;
208 if (op < len) { /* some from end of window */
209 len -= op;
210 do {
211 PUP(out) = PUP(from);
212 } while (--op);
213 from = window - OFF;
214 if (write < len) { /* some from start of window */
215 op = write;
216 len -= op;
217 do {
218 PUP(out) = PUP(from);
219 } while (--op);
220 from = out - dist; /* rest from output */
221 }
222 }
223 }
224 else { /* contiguous in window */
225 from += write - op;
226 if (op < len) { /* some from window */
227 len -= op;
228 do {
229 PUP(out) = PUP(from);
230 } while (--op);
231 from = out - dist; /* rest from output */
232 }
233 }
234 while (len > 2) {
235 PUP(out) = PUP(from);
236 PUP(out) = PUP(from);
237 PUP(out) = PUP(from);
238 len -= 3;
239 }
240 if (len) {
241 PUP(out) = PUP(from);
242 if (len > 1)
243 PUP(out) = PUP(from);
244 }
245 }
246 else {
247 from = out - dist; /* copy direct from output */
248 do { /* minimum length is three */
249 PUP(out) = PUP(from);
250 PUP(out) = PUP(from);
251 PUP(out) = PUP(from);
252 len -= 3;
253 } while (len > 2);
254 if (len) {
255 PUP(out) = PUP(from);
256 if (len > 1)
257 PUP(out) = PUP(from);
258 }
259 }
260 }
261 else if ((op & 64) == 0) { /* 2nd level distance code */
262 this = dcode[this.val + (hold & ((1U << op) - 1))];
263 goto dodist;
264 }
265 else {
266 strm->msg = (char *)"invalid distance code";
267 state->mode = BAD;
268 break;
269 }
270 }
271 else if ((op & 64) == 0) { /* 2nd level length code */
272 this = lcode[this.val + (hold & ((1U << op) - 1))];
273 goto dolen;
274 }
275 else if (op & 32) { /* end-of-block */
276 Tracevv((stderr, "inflate: end of block\n"));
277 state->mode = TYPE;
278 break;
279 }
280 else {
281 strm->msg = (char *)"invalid literal/length code";
282 state->mode = BAD;
283 break;
284 }
285 } while (in < last && out < end);
286
287 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
288 len = bits >> 3;
289 in -= len;
290 bits -= len << 3;
291 hold &= (1U << bits) - 1;
292
293 /* update state and return */
294 strm->next_in = in + OFF;
295 strm->next_out = out + OFF;
296 strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
297 strm->avail_out = (unsigned)(out < end ?
298 257 + (end - out) : 257 - (out - end));
299 state->hold = hold;
300 state->bits = bits;
301 return;
302}
303
304/*
305 inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
306 - Using bit fields for code structure
307 - Different op definition to avoid & for extra bits (do & for table bits)
308 - Three separate decoding do-loops for direct, window, and write == 0
309 - Special case for distance > 1 copies to do overlapped load and store copy
310 - Explicit branch predictions (based on measured branch probabilities)
311 - Deferring match copy and interspersed it with decoding subsequent codes
312 - Swapping literal/length else
313 - Swapping window/direct else
314 - Larger unrolled copy loops (three is about right)
315 - Moving len -= 3 statement into middle of loop
316 */
317
318#endif /* !ASMINF */
diff --git a/utils/zenutils/libraries/zlib123/zlib/inffast.h b/utils/zenutils/libraries/zlib123/zlib/inffast.h
new file mode 100755
index 0000000000..614fa7877d
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/inffast.h
@@ -0,0 +1,11 @@
1/* inffast.h -- header to use inffast.c
2 * Copyright (C) 1995-2003 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/* WARNING: this file should *not* be used by applications. It is
7 part of the implementation of the compression library and is
8 subject to change. Applications should only use zlib.h.
9 */
10
11void inflate_fast OF((z_streamp strm, unsigned start));
diff --git a/utils/zenutils/libraries/zlib123/zlib/inffixed.h b/utils/zenutils/libraries/zlib123/zlib/inffixed.h
new file mode 100755
index 0000000000..423d5c5b50
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/inffixed.h
@@ -0,0 +1,94 @@
1 /* inffixed.h -- table for decoding fixed codes
2 * Generated automatically by makefixed().
3 */
4
5 /* WARNING: this file should *not* be used by applications. It
6 is part of the implementation of the compression library and
7 is subject to change. Applications should only use zlib.h.
8 */
9
10 static const code lenfix[512] = {
11 {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
12 {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
13 {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
14 {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
15 {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
16 {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
17 {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
18 {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
19 {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
20 {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
21 {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
22 {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
23 {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
24 {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
25 {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
26 {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
27 {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
28 {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
29 {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
30 {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
31 {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
32 {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
33 {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
34 {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
35 {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
36 {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
37 {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
38 {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
39 {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
40 {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
41 {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
42 {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
43 {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
44 {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
45 {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
46 {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
47 {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
48 {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
49 {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
50 {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
51 {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
52 {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
53 {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
54 {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
55 {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
56 {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
57 {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
58 {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
59 {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
60 {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
61 {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
62 {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
63 {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
64 {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
65 {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
66 {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
67 {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
68 {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
69 {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
70 {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
71 {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
72 {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
73 {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
74 {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
75 {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
76 {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
77 {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
78 {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
79 {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
80 {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
81 {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
82 {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
83 {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
84 {0,9,255}
85 };
86
87 static const code distfix[32] = {
88 {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
89 {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
90 {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
91 {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
92 {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
93 {22,5,193},{64,5,0}
94 };
diff --git a/utils/zenutils/libraries/zlib123/zlib/inflate.c b/utils/zenutils/libraries/zlib123/zlib/inflate.c
new file mode 100755
index 0000000000..33ea902928
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/inflate.c
@@ -0,0 +1,1368 @@
1/* inflate.c -- zlib decompression
2 * Copyright (C) 1995-2005 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/*
7 * Change history:
8 *
9 * 1.2.beta0 24 Nov 2002
10 * - First version -- complete rewrite of inflate to simplify code, avoid
11 * creation of window when not needed, minimize use of window when it is
12 * needed, make inffast.c even faster, implement gzip decoding, and to
13 * improve code readability and style over the previous zlib inflate code
14 *
15 * 1.2.beta1 25 Nov 2002
16 * - Use pointers for available input and output checking in inffast.c
17 * - Remove input and output counters in inffast.c
18 * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
19 * - Remove unnecessary second byte pull from length extra in inffast.c
20 * - Unroll direct copy to three copies per loop in inffast.c
21 *
22 * 1.2.beta2 4 Dec 2002
23 * - Change external routine names to reduce potential conflicts
24 * - Correct filename to inffixed.h for fixed tables in inflate.c
25 * - Make hbuf[] unsigned char to match parameter type in inflate.c
26 * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
27 * to avoid negation problem on Alphas (64 bit) in inflate.c
28 *
29 * 1.2.beta3 22 Dec 2002
30 * - Add comments on state->bits assertion in inffast.c
31 * - Add comments on op field in inftrees.h
32 * - Fix bug in reuse of allocated window after inflateReset()
33 * - Remove bit fields--back to byte structure for speed
34 * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
35 * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
36 * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
37 * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
38 * - Use local copies of stream next and avail values, as well as local bit
39 * buffer and bit count in inflate()--for speed when inflate_fast() not used
40 *
41 * 1.2.beta4 1 Jan 2003
42 * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
43 * - Move a comment on output buffer sizes from inffast.c to inflate.c
44 * - Add comments in inffast.c to introduce the inflate_fast() routine
45 * - Rearrange window copies in inflate_fast() for speed and simplification
46 * - Unroll last copy for window match in inflate_fast()
47 * - Use local copies of window variables in inflate_fast() for speed
48 * - Pull out common write == 0 case for speed in inflate_fast()
49 * - Make op and len in inflate_fast() unsigned for consistency
50 * - Add FAR to lcode and dcode declarations in inflate_fast()
51 * - Simplified bad distance check in inflate_fast()
52 * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
53 * source file infback.c to provide a call-back interface to inflate for
54 * programs like gzip and unzip -- uses window as output buffer to avoid
55 * window copying
56 *
57 * 1.2.beta5 1 Jan 2003
58 * - Improved inflateBack() interface to allow the caller to provide initial
59 * input in strm.
60 * - Fixed stored blocks bug in inflateBack()
61 *
62 * 1.2.beta6 4 Jan 2003
63 * - Added comments in inffast.c on effectiveness of POSTINC
64 * - Typecasting all around to reduce compiler warnings
65 * - Changed loops from while (1) or do {} while (1) to for (;;), again to
66 * make compilers happy
67 * - Changed type of window in inflateBackInit() to unsigned char *
68 *
69 * 1.2.beta7 27 Jan 2003
70 * - Changed many types to unsigned or unsigned short to avoid warnings
71 * - Added inflateCopy() function
72 *
73 * 1.2.0 9 Mar 2003
74 * - Changed inflateBack() interface to provide separate opaque descriptors
75 * for the in() and out() functions
76 * - Changed inflateBack() argument and in_func typedef to swap the length
77 * and buffer address return values for the input function
78 * - Check next_in and next_out for Z_NULL on entry to inflate()
79 *
80 * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
81 */
82
83#include "zutil.h"
84#include "inftrees.h"
85#include "inflate.h"
86#include "inffast.h"
87
88#ifdef MAKEFIXED
89# ifndef BUILDFIXED
90# define BUILDFIXED
91# endif
92#endif
93
94/* function prototypes */
95local void fixedtables OF((struct inflate_state FAR *state));
96local int updatewindow OF((z_streamp strm, unsigned out));
97#ifdef BUILDFIXED
98 void makefixed OF((void));
99#endif
100local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
101 unsigned len));
102
103int ZEXPORT inflateReset(strm)
104z_streamp strm;
105{
106 struct inflate_state FAR *state;
107
108 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
109 state = (struct inflate_state FAR *)strm->state;
110 strm->total_in = strm->total_out = state->total = 0;
111 strm->msg = Z_NULL;
112 strm->adler = 1; /* to support ill-conceived Java test suite */
113 state->mode = HEAD;
114 state->last = 0;
115 state->havedict = 0;
116 state->dmax = 32768U;
117 state->head = Z_NULL;
118 state->wsize = 0;
119 state->whave = 0;
120 state->write = 0;
121 state->hold = 0;
122 state->bits = 0;
123 state->lencode = state->distcode = state->next = state->codes;
124 Tracev((stderr, "inflate: reset\n"));
125 return Z_OK;
126}
127
128int ZEXPORT inflatePrime(strm, bits, value)
129z_streamp strm;
130int bits;
131int value;
132{
133 struct inflate_state FAR *state;
134
135 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
136 state = (struct inflate_state FAR *)strm->state;
137 if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
138 value &= (1L << bits) - 1;
139 state->hold += value << state->bits;
140 state->bits += bits;
141 return Z_OK;
142}
143
144int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)
145z_streamp strm;
146int windowBits;
147const char *version;
148int stream_size;
149{
150 struct inflate_state FAR *state;
151
152 if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
153 stream_size != (int)(sizeof(z_stream)))
154 return Z_VERSION_ERROR;
155 if (strm == Z_NULL) return Z_STREAM_ERROR;
156 strm->msg = Z_NULL; /* in case we return an error */
157 if (strm->zalloc == (alloc_func)0) {
158 strm->zalloc = zcalloc;
159 strm->opaque = (voidpf)0;
160 }
161 if (strm->zfree == (free_func)0) strm->zfree = zcfree;
162 state = (struct inflate_state FAR *)
163 ZALLOC(strm, 1, sizeof(struct inflate_state));
164 if (state == Z_NULL) return Z_MEM_ERROR;
165 Tracev((stderr, "inflate: allocated\n"));
166 strm->state = (struct internal_state FAR *)state;
167 if (windowBits < 0) {
168 state->wrap = 0;
169 windowBits = -windowBits;
170 }
171 else {
172 state->wrap = (windowBits >> 4) + 1;
173#ifdef GUNZIP
174 if (windowBits < 48) windowBits &= 15;
175#endif
176 }
177 if (windowBits < 8 || windowBits > 15) {
178 ZFREE(strm, state);
179 strm->state = Z_NULL;
180 return Z_STREAM_ERROR;
181 }
182 state->wbits = (unsigned)windowBits;
183 state->window = Z_NULL;
184 return inflateReset(strm);
185}
186
187int ZEXPORT inflateInit_(strm, version, stream_size)
188z_streamp strm;
189const char *version;
190int stream_size;
191{
192 return inflateInit2_(strm, DEF_WBITS, version, stream_size);
193}
194
195/*
196 Return state with length and distance decoding tables and index sizes set to
197 fixed code decoding. Normally this returns fixed tables from inffixed.h.
198 If BUILDFIXED is defined, then instead this routine builds the tables the
199 first time it's called, and returns those tables the first time and
200 thereafter. This reduces the size of the code by about 2K bytes, in
201 exchange for a little execution time. However, BUILDFIXED should not be
202 used for threaded applications, since the rewriting of the tables and virgin
203 may not be thread-safe.
204 */
205local void fixedtables(state)
206struct inflate_state FAR *state;
207{
208#ifdef BUILDFIXED
209 static int virgin = 1;
210 static code *lenfix, *distfix;
211 static code fixed[544];
212
213 /* build fixed huffman tables if first call (may not be thread safe) */
214 if (virgin) {
215 unsigned sym, bits;
216 static code *next;
217
218 /* literal/length table */
219 sym = 0;
220 while (sym < 144) state->lens[sym++] = 8;
221 while (sym < 256) state->lens[sym++] = 9;
222 while (sym < 280) state->lens[sym++] = 7;
223 while (sym < 288) state->lens[sym++] = 8;
224 next = fixed;
225 lenfix = next;
226 bits = 9;
227 inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
228
229 /* distance table */
230 sym = 0;
231 while (sym < 32) state->lens[sym++] = 5;
232 distfix = next;
233 bits = 5;
234 inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
235
236 /* do this just once */
237 virgin = 0;
238 }
239#else /* !BUILDFIXED */
240# include "inffixed.h"
241#endif /* BUILDFIXED */
242 state->lencode = lenfix;
243 state->lenbits = 9;
244 state->distcode = distfix;
245 state->distbits = 5;
246}
247
248#ifdef MAKEFIXED
249#include <stdio.h>
250
251/*
252 Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
253 defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
254 those tables to stdout, which would be piped to inffixed.h. A small program
255 can simply call makefixed to do this:
256
257 void makefixed(void);
258
259 int main(void)
260 {
261 makefixed();
262 return 0;
263 }
264
265 Then that can be linked with zlib built with MAKEFIXED defined and run:
266
267 a.out > inffixed.h
268 */
269void makefixed()
270{
271 unsigned low, size;
272 struct inflate_state state;
273
274 fixedtables(&state);
275 puts(" /* inffixed.h -- table for decoding fixed codes");
276 puts(" * Generated automatically by makefixed().");
277 puts(" */");
278 puts("");
279 puts(" /* WARNING: this file should *not* be used by applications.");
280 puts(" It is part of the implementation of this library and is");
281 puts(" subject to change. Applications should only use zlib.h.");
282 puts(" */");
283 puts("");
284 size = 1U << 9;
285 printf(" static const code lenfix[%u] = {", size);
286 low = 0;
287 for (;;) {
288 if ((low % 7) == 0) printf("\n ");
289 printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
290 state.lencode[low].val);
291 if (++low == size) break;
292 putchar(',');
293 }
294 puts("\n };");
295 size = 1U << 5;
296 printf("\n static const code distfix[%u] = {", size);
297 low = 0;
298 for (;;) {
299 if ((low % 6) == 0) printf("\n ");
300 printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
301 state.distcode[low].val);
302 if (++low == size) break;
303 putchar(',');
304 }
305 puts("\n };");
306}
307#endif /* MAKEFIXED */
308
309/*
310 Update the window with the last wsize (normally 32K) bytes written before
311 returning. If window does not exist yet, create it. This is only called
312 when a window is already in use, or when output has been written during this
313 inflate call, but the end of the deflate stream has not been reached yet.
314 It is also called to create a window for dictionary data when a dictionary
315 is loaded.
316
317 Providing output buffers larger than 32K to inflate() should provide a speed
318 advantage, since only the last 32K of output is copied to the sliding window
319 upon return from inflate(), and since all distances after the first 32K of
320 output will fall in the output data, making match copies simpler and faster.
321 The advantage may be dependent on the size of the processor's data caches.
322 */
323local int updatewindow(strm, out)
324z_streamp strm;
325unsigned out;
326{
327 struct inflate_state FAR *state;
328 unsigned copy, dist;
329
330 state = (struct inflate_state FAR *)strm->state;
331
332 /* if it hasn't been done already, allocate space for the window */
333 if (state->window == Z_NULL) {
334 state->window = (unsigned char FAR *)
335 ZALLOC(strm, 1U << state->wbits,
336 sizeof(unsigned char));
337 if (state->window == Z_NULL) return 1;
338 }
339
340 /* if window not in use yet, initialize */
341 if (state->wsize == 0) {
342 state->wsize = 1U << state->wbits;
343 state->write = 0;
344 state->whave = 0;
345 }
346
347 /* copy state->wsize or less output bytes into the circular window */
348 copy = out - strm->avail_out;
349 if (copy >= state->wsize) {
350 zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
351 state->write = 0;
352 state->whave = state->wsize;
353 }
354 else {
355 dist = state->wsize - state->write;
356 if (dist > copy) dist = copy;
357 zmemcpy(state->window + state->write, strm->next_out - copy, dist);
358 copy -= dist;
359 if (copy) {
360 zmemcpy(state->window, strm->next_out - copy, copy);
361 state->write = copy;
362 state->whave = state->wsize;
363 }
364 else {
365 state->write += dist;
366 if (state->write == state->wsize) state->write = 0;
367 if (state->whave < state->wsize) state->whave += dist;
368 }
369 }
370 return 0;
371}
372
373/* Macros for inflate(): */
374
375/* check function to use adler32() for zlib or crc32() for gzip */
376#ifdef GUNZIP
377# define UPDATE(check, buf, len) \
378 (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
379#else
380# define UPDATE(check, buf, len) adler32(check, buf, len)
381#endif
382
383/* check macros for header crc */
384#ifdef GUNZIP
385# define CRC2(check, word) \
386 do { \
387 hbuf[0] = (unsigned char)(word); \
388 hbuf[1] = (unsigned char)((word) >> 8); \
389 check = crc32(check, hbuf, 2); \
390 } while (0)
391
392# define CRC4(check, word) \
393 do { \
394 hbuf[0] = (unsigned char)(word); \
395 hbuf[1] = (unsigned char)((word) >> 8); \
396 hbuf[2] = (unsigned char)((word) >> 16); \
397 hbuf[3] = (unsigned char)((word) >> 24); \
398 check = crc32(check, hbuf, 4); \
399 } while (0)
400#endif
401
402/* Load registers with state in inflate() for speed */
403#define LOAD() \
404 do { \
405 put = strm->next_out; \
406 left = strm->avail_out; \
407 next = strm->next_in; \
408 have = strm->avail_in; \
409 hold = state->hold; \
410 bits = state->bits; \
411 } while (0)
412
413/* Restore state from registers in inflate() */
414#define RESTORE() \
415 do { \
416 strm->next_out = put; \
417 strm->avail_out = left; \
418 strm->next_in = next; \
419 strm->avail_in = have; \
420 state->hold = hold; \
421 state->bits = bits; \
422 } while (0)
423
424/* Clear the input bit accumulator */
425#define INITBITS() \
426 do { \
427 hold = 0; \
428 bits = 0; \
429 } while (0)
430
431/* Get a byte of input into the bit accumulator, or return from inflate()
432 if there is no input available. */
433#define PULLBYTE() \
434 do { \
435 if (have == 0) goto inf_leave; \
436 have--; \
437 hold += (unsigned long)(*next++) << bits; \
438 bits += 8; \
439 } while (0)
440
441/* Assure that there are at least n bits in the bit accumulator. If there is
442 not enough available input to do that, then return from inflate(). */
443#define NEEDBITS(n) \
444 do { \
445 while (bits < (unsigned)(n)) \
446 PULLBYTE(); \
447 } while (0)
448
449/* Return the low n bits of the bit accumulator (n < 16) */
450#define BITS(n) \
451 ((unsigned)hold & ((1U << (n)) - 1))
452
453/* Remove n bits from the bit accumulator */
454#define DROPBITS(n) \
455 do { \
456 hold >>= (n); \
457 bits -= (unsigned)(n); \
458 } while (0)
459
460/* Remove zero to seven bits as needed to go to a byte boundary */
461#define BYTEBITS() \
462 do { \
463 hold >>= bits & 7; \
464 bits -= bits & 7; \
465 } while (0)
466
467/* Reverse the bytes in a 32-bit value */
468#define REVERSE(q) \
469 ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
470 (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
471
472/*
473 inflate() uses a state machine to process as much input data and generate as
474 much output data as possible before returning. The state machine is
475 structured roughly as follows:
476
477 for (;;) switch (state) {
478 ...
479 case STATEn:
480 if (not enough input data or output space to make progress)
481 return;
482 ... make progress ...
483 state = STATEm;
484 break;
485 ...
486 }
487
488 so when inflate() is called again, the same case is attempted again, and
489 if the appropriate resources are provided, the machine proceeds to the
490 next state. The NEEDBITS() macro is usually the way the state evaluates
491 whether it can proceed or should return. NEEDBITS() does the return if
492 the requested bits are not available. The typical use of the BITS macros
493 is:
494
495 NEEDBITS(n);
496 ... do something with BITS(n) ...
497 DROPBITS(n);
498
499 where NEEDBITS(n) either returns from inflate() if there isn't enough
500 input left to load n bits into the accumulator, or it continues. BITS(n)
501 gives the low n bits in the accumulator. When done, DROPBITS(n) drops
502 the low n bits off the accumulator. INITBITS() clears the accumulator
503 and sets the number of available bits to zero. BYTEBITS() discards just
504 enough bits to put the accumulator on a byte boundary. After BYTEBITS()
505 and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
506
507 NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
508 if there is no input available. The decoding of variable length codes uses
509 PULLBYTE() directly in order to pull just enough bytes to decode the next
510 code, and no more.
511
512 Some states loop until they get enough input, making sure that enough
513 state information is maintained to continue the loop where it left off
514 if NEEDBITS() returns in the loop. For example, want, need, and keep
515 would all have to actually be part of the saved state in case NEEDBITS()
516 returns:
517
518 case STATEw:
519 while (want < need) {
520 NEEDBITS(n);
521 keep[want++] = BITS(n);
522 DROPBITS(n);
523 }
524 state = STATEx;
525 case STATEx:
526
527 As shown above, if the next state is also the next case, then the break
528 is omitted.
529
530 A state may also return if there is not enough output space available to
531 complete that state. Those states are copying stored data, writing a
532 literal byte, and copying a matching string.
533
534 When returning, a "goto inf_leave" is used to update the total counters,
535 update the check value, and determine whether any progress has been made
536 during that inflate() call in order to return the proper return code.
537 Progress is defined as a change in either strm->avail_in or strm->avail_out.
538 When there is a window, goto inf_leave will update the window with the last
539 output written. If a goto inf_leave occurs in the middle of decompression
540 and there is no window currently, goto inf_leave will create one and copy
541 output to the window for the next call of inflate().
542
543 In this implementation, the flush parameter of inflate() only affects the
544 return code (per zlib.h). inflate() always writes as much as possible to
545 strm->next_out, given the space available and the provided input--the effect
546 documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
547 the allocation of and copying into a sliding window until necessary, which
548 provides the effect documented in zlib.h for Z_FINISH when the entire input
549 stream available. So the only thing the flush parameter actually does is:
550 when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
551 will return Z_BUF_ERROR if it has not reached the end of the stream.
552 */
553
554int ZEXPORT inflate(strm, flush)
555z_streamp strm;
556int flush;
557{
558 struct inflate_state FAR *state;
559 unsigned char FAR *next; /* next input */
560 unsigned char FAR *put; /* next output */
561 unsigned have, left; /* available input and output */
562 unsigned long hold; /* bit buffer */
563 unsigned bits; /* bits in bit buffer */
564 unsigned in, out; /* save starting available input and output */
565 unsigned copy; /* number of stored or match bytes to copy */
566 unsigned char FAR *from; /* where to copy match bytes from */
567 code this; /* current decoding table entry */
568 code last; /* parent table entry */
569 unsigned len; /* length to copy for repeats, bits to drop */
570 int ret; /* return code */
571#ifdef GUNZIP
572 unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
573#endif
574 static const unsigned short order[19] = /* permutation of code lengths */
575 {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
576
577 if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
578 (strm->next_in == Z_NULL && strm->avail_in != 0))
579 return Z_STREAM_ERROR;
580
581 state = (struct inflate_state FAR *)strm->state;
582 if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
583 LOAD();
584 in = have;
585 out = left;
586 ret = Z_OK;
587 for (;;)
588 switch (state->mode) {
589 case HEAD:
590 if (state->wrap == 0) {
591 state->mode = TYPEDO;
592 break;
593 }
594 NEEDBITS(16);
595#ifdef GUNZIP
596 if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
597 state->check = crc32(0L, Z_NULL, 0);
598 CRC2(state->check, hold);
599 INITBITS();
600 state->mode = FLAGS;
601 break;
602 }
603 state->flags = 0; /* expect zlib header */
604 if (state->head != Z_NULL)
605 state->head->done = -1;
606 if (!(state->wrap & 1) || /* check if zlib header allowed */
607#else
608 if (
609#endif
610 ((BITS(8) << 8) + (hold >> 8)) % 31) {
611 strm->msg = (char *)"incorrect header check";
612 state->mode = BAD;
613 break;
614 }
615 if (BITS(4) != Z_DEFLATED) {
616 strm->msg = (char *)"unknown compression method";
617 state->mode = BAD;
618 break;
619 }
620 DROPBITS(4);
621 len = BITS(4) + 8;
622 if (len > state->wbits) {
623 strm->msg = (char *)"invalid window size";
624 state->mode = BAD;
625 break;
626 }
627 state->dmax = 1U << len;
628 Tracev((stderr, "inflate: zlib header ok\n"));
629 strm->adler = state->check = adler32(0L, Z_NULL, 0);
630 state->mode = hold & 0x200 ? DICTID : TYPE;
631 INITBITS();
632 break;
633#ifdef GUNZIP
634 case FLAGS:
635 NEEDBITS(16);
636 state->flags = (int)(hold);
637 if ((state->flags & 0xff) != Z_DEFLATED) {
638 strm->msg = (char *)"unknown compression method";
639 state->mode = BAD;
640 break;
641 }
642 if (state->flags & 0xe000) {
643 strm->msg = (char *)"unknown header flags set";
644 state->mode = BAD;
645 break;
646 }
647 if (state->head != Z_NULL)
648 state->head->text = (int)((hold >> 8) & 1);
649 if (state->flags & 0x0200) CRC2(state->check, hold);
650 INITBITS();
651 state->mode = TIME;
652 case TIME:
653 NEEDBITS(32);
654 if (state->head != Z_NULL)
655 state->head->time = hold;
656 if (state->flags & 0x0200) CRC4(state->check, hold);
657 INITBITS();
658 state->mode = OS;
659 case OS:
660 NEEDBITS(16);
661 if (state->head != Z_NULL) {
662 state->head->xflags = (int)(hold & 0xff);
663 state->head->os = (int)(hold >> 8);
664 }
665 if (state->flags & 0x0200) CRC2(state->check, hold);
666 INITBITS();
667 state->mode = EXLEN;
668 case EXLEN:
669 if (state->flags & 0x0400) {
670 NEEDBITS(16);
671 state->length = (unsigned)(hold);
672 if (state->head != Z_NULL)
673 state->head->extra_len = (unsigned)hold;
674 if (state->flags & 0x0200) CRC2(state->check, hold);
675 INITBITS();
676 }
677 else if (state->head != Z_NULL)
678 state->head->extra = Z_NULL;
679 state->mode = EXTRA;
680 case EXTRA:
681 if (state->flags & 0x0400) {
682 copy = state->length;
683 if (copy > have) copy = have;
684 if (copy) {
685 if (state->head != Z_NULL &&
686 state->head->extra != Z_NULL) {
687 len = state->head->extra_len - state->length;
688 zmemcpy(state->head->extra + len, next,
689 len + copy > state->head->extra_max ?
690 state->head->extra_max - len : copy);
691 }
692 if (state->flags & 0x0200)
693 state->check = crc32(state->check, next, copy);
694 have -= copy;
695 next += copy;
696 state->length -= copy;
697 }
698 if (state->length) goto inf_leave;
699 }
700 state->length = 0;
701 state->mode = NAME;
702 case NAME:
703 if (state->flags & 0x0800) {
704 if (have == 0) goto inf_leave;
705 copy = 0;
706 do {
707 len = (unsigned)(next[copy++]);
708 if (state->head != Z_NULL &&
709 state->head->name != Z_NULL &&
710 state->length < state->head->name_max)
711 state->head->name[state->length++] = len;
712 } while (len && copy < have);
713 if (state->flags & 0x0200)
714 state->check = crc32(state->check, next, copy);
715 have -= copy;
716 next += copy;
717 if (len) goto inf_leave;
718 }
719 else if (state->head != Z_NULL)
720 state->head->name = Z_NULL;
721 state->length = 0;
722 state->mode = COMMENT;
723 case COMMENT:
724 if (state->flags & 0x1000) {
725 if (have == 0) goto inf_leave;
726 copy = 0;
727 do {
728 len = (unsigned)(next[copy++]);
729 if (state->head != Z_NULL &&
730 state->head->comment != Z_NULL &&
731 state->length < state->head->comm_max)
732 state->head->comment[state->length++] = len;
733 } while (len && copy < have);
734 if (state->flags & 0x0200)
735 state->check = crc32(state->check, next, copy);
736 have -= copy;
737 next += copy;
738 if (len) goto inf_leave;
739 }
740 else if (state->head != Z_NULL)
741 state->head->comment = Z_NULL;
742 state->mode = HCRC;
743 case HCRC:
744 if (state->flags & 0x0200) {
745 NEEDBITS(16);
746 if (hold != (state->check & 0xffff)) {
747 strm->msg = (char *)"header crc mismatch";
748 state->mode = BAD;
749 break;
750 }
751 INITBITS();
752 }
753 if (state->head != Z_NULL) {
754 state->head->hcrc = (int)((state->flags >> 9) & 1);
755 state->head->done = 1;
756 }
757 strm->adler = state->check = crc32(0L, Z_NULL, 0);
758 state->mode = TYPE;
759 break;
760#endif
761 case DICTID:
762 NEEDBITS(32);
763 strm->adler = state->check = REVERSE(hold);
764 INITBITS();
765 state->mode = DICT;
766 case DICT:
767 if (state->havedict == 0) {
768 RESTORE();
769 return Z_NEED_DICT;
770 }
771 strm->adler = state->check = adler32(0L, Z_NULL, 0);
772 state->mode = TYPE;
773 case TYPE:
774 if (flush == Z_BLOCK) goto inf_leave;
775 case TYPEDO:
776 if (state->last) {
777 BYTEBITS();
778 state->mode = CHECK;
779 break;
780 }
781 NEEDBITS(3);
782 state->last = BITS(1);
783 DROPBITS(1);
784 switch (BITS(2)) {
785 case 0: /* stored block */
786 Tracev((stderr, "inflate: stored block%s\n",
787 state->last ? " (last)" : ""));
788 state->mode = STORED;
789 break;
790 case 1: /* fixed block */
791 fixedtables(state);
792 Tracev((stderr, "inflate: fixed codes block%s\n",
793 state->last ? " (last)" : ""));
794 state->mode = LEN; /* decode codes */
795 break;
796 case 2: /* dynamic block */
797 Tracev((stderr, "inflate: dynamic codes block%s\n",
798 state->last ? " (last)" : ""));
799 state->mode = TABLE;
800 break;
801 case 3:
802 strm->msg = (char *)"invalid block type";
803 state->mode = BAD;
804 }
805 DROPBITS(2);
806 break;
807 case STORED:
808 BYTEBITS(); /* go to byte boundary */
809 NEEDBITS(32);
810 if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
811 strm->msg = (char *)"invalid stored block lengths";
812 state->mode = BAD;
813 break;
814 }
815 state->length = (unsigned)hold & 0xffff;
816 Tracev((stderr, "inflate: stored length %u\n",
817 state->length));
818 INITBITS();
819 state->mode = COPY;
820 case COPY:
821 copy = state->length;
822 if (copy) {
823 if (copy > have) copy = have;
824 if (copy > left) copy = left;
825 if (copy == 0) goto inf_leave;
826 zmemcpy(put, next, copy);
827 have -= copy;
828 next += copy;
829 left -= copy;
830 put += copy;
831 state->length -= copy;
832 break;
833 }
834 Tracev((stderr, "inflate: stored end\n"));
835 state->mode = TYPE;
836 break;
837 case TABLE:
838 NEEDBITS(14);
839 state->nlen = BITS(5) + 257;
840 DROPBITS(5);
841 state->ndist = BITS(5) + 1;
842 DROPBITS(5);
843 state->ncode = BITS(4) + 4;
844 DROPBITS(4);
845#ifndef PKZIP_BUG_WORKAROUND
846 if (state->nlen > 286 || state->ndist > 30) {
847 strm->msg = (char *)"too many length or distance symbols";
848 state->mode = BAD;
849 break;
850 }
851#endif
852 Tracev((stderr, "inflate: table sizes ok\n"));
853 state->have = 0;
854 state->mode = LENLENS;
855 case LENLENS:
856 while (state->have < state->ncode) {
857 NEEDBITS(3);
858 state->lens[order[state->have++]] = (unsigned short)BITS(3);
859 DROPBITS(3);
860 }
861 while (state->have < 19)
862 state->lens[order[state->have++]] = 0;
863 state->next = state->codes;
864 state->lencode = (code const FAR *)(state->next);
865 state->lenbits = 7;
866 ret = inflate_table(CODES, state->lens, 19, &(state->next),
867 &(state->lenbits), state->work);
868 if (ret) {
869 strm->msg = (char *)"invalid code lengths set";
870 state->mode = BAD;
871 break;
872 }
873 Tracev((stderr, "inflate: code lengths ok\n"));
874 state->have = 0;
875 state->mode = CODELENS;
876 case CODELENS:
877 while (state->have < state->nlen + state->ndist) {
878 for (;;) {
879 this = state->lencode[BITS(state->lenbits)];
880 if ((unsigned)(this.bits) <= bits) break;
881 PULLBYTE();
882 }
883 if (this.val < 16) {
884 NEEDBITS(this.bits);
885 DROPBITS(this.bits);
886 state->lens[state->have++] = this.val;
887 }
888 else {
889 if (this.val == 16) {
890 NEEDBITS(this.bits + 2);
891 DROPBITS(this.bits);
892 if (state->have == 0) {
893 strm->msg = (char *)"invalid bit length repeat";
894 state->mode = BAD;
895 break;
896 }
897 len = state->lens[state->have - 1];
898 copy = 3 + BITS(2);
899 DROPBITS(2);
900 }
901 else if (this.val == 17) {
902 NEEDBITS(this.bits + 3);
903 DROPBITS(this.bits);
904 len = 0;
905 copy = 3 + BITS(3);
906 DROPBITS(3);
907 }
908 else {
909 NEEDBITS(this.bits + 7);
910 DROPBITS(this.bits);
911 len = 0;
912 copy = 11 + BITS(7);
913 DROPBITS(7);
914 }
915 if (state->have + copy > state->nlen + state->ndist) {
916 strm->msg = (char *)"invalid bit length repeat";
917 state->mode = BAD;
918 break;
919 }
920 while (copy--)
921 state->lens[state->have++] = (unsigned short)len;
922 }
923 }
924
925 /* handle error breaks in while */
926 if (state->mode == BAD) break;
927
928 /* build code tables */
929 state->next = state->codes;
930 state->lencode = (code const FAR *)(state->next);
931 state->lenbits = 9;
932 ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
933 &(state->lenbits), state->work);
934 if (ret) {
935 strm->msg = (char *)"invalid literal/lengths set";
936 state->mode = BAD;
937 break;
938 }
939 state->distcode = (code const FAR *)(state->next);
940 state->distbits = 6;
941 ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
942 &(state->next), &(state->distbits), state->work);
943 if (ret) {
944 strm->msg = (char *)"invalid distances set";
945 state->mode = BAD;
946 break;
947 }
948 Tracev((stderr, "inflate: codes ok\n"));
949 state->mode = LEN;
950 case LEN:
951 if (have >= 6 && left >= 258) {
952 RESTORE();
953 inflate_fast(strm, out);
954 LOAD();
955 break;
956 }
957 for (;;) {
958 this = state->lencode[BITS(state->lenbits)];
959 if ((unsigned)(this.bits) <= bits) break;
960 PULLBYTE();
961 }
962 if (this.op && (this.op & 0xf0) == 0) {
963 last = this;
964 for (;;) {
965 this = state->lencode[last.val +
966 (BITS(last.bits + last.op) >> last.bits)];
967 if ((unsigned)(last.bits + this.bits) <= bits) break;
968 PULLBYTE();
969 }
970 DROPBITS(last.bits);
971 }
972 DROPBITS(this.bits);
973 state->length = (unsigned)this.val;
974 if ((int)(this.op) == 0) {
975 Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
976 "inflate: literal '%c'\n" :
977 "inflate: literal 0x%02x\n", this.val));
978 state->mode = LIT;
979 break;
980 }
981 if (this.op & 32) {
982 Tracevv((stderr, "inflate: end of block\n"));
983 state->mode = TYPE;
984 break;
985 }
986 if (this.op & 64) {
987 strm->msg = (char *)"invalid literal/length code";
988 state->mode = BAD;
989 break;
990 }
991 state->extra = (unsigned)(this.op) & 15;
992 state->mode = LENEXT;
993 case LENEXT:
994 if (state->extra) {
995 NEEDBITS(state->extra);
996 state->length += BITS(state->extra);
997 DROPBITS(state->extra);
998 }
999 Tracevv((stderr, "inflate: length %u\n", state->length));
1000 state->mode = DIST;
1001 case DIST:
1002 for (;;) {
1003 this = state->distcode[BITS(state->distbits)];
1004 if ((unsigned)(this.bits) <= bits) break;
1005 PULLBYTE();
1006 }
1007 if ((this.op & 0xf0) == 0) {
1008 last = this;
1009 for (;;) {
1010 this = state->distcode[last.val +
1011 (BITS(last.bits + last.op) >> last.bits)];
1012 if ((unsigned)(last.bits + this.bits) <= bits) break;
1013 PULLBYTE();
1014 }
1015 DROPBITS(last.bits);
1016 }
1017 DROPBITS(this.bits);
1018 if (this.op & 64) {
1019 strm->msg = (char *)"invalid distance code";
1020 state->mode = BAD;
1021 break;
1022 }
1023 state->offset = (unsigned)this.val;
1024 state->extra = (unsigned)(this.op) & 15;
1025 state->mode = DISTEXT;
1026 case DISTEXT:
1027 if (state->extra) {
1028 NEEDBITS(state->extra);
1029 state->offset += BITS(state->extra);
1030 DROPBITS(state->extra);
1031 }
1032#ifdef INFLATE_STRICT
1033 if (state->offset > state->dmax) {
1034 strm->msg = (char *)"invalid distance too far back";
1035 state->mode = BAD;
1036 break;
1037 }
1038#endif
1039 if (state->offset > state->whave + out - left) {
1040 strm->msg = (char *)"invalid distance too far back";
1041 state->mode = BAD;
1042 break;
1043 }
1044 Tracevv((stderr, "inflate: distance %u\n", state->offset));
1045 state->mode = MATCH;
1046 case MATCH:
1047 if (left == 0) goto inf_leave;
1048 copy = out - left;
1049 if (state->offset > copy) { /* copy from window */
1050 copy = state->offset - copy;
1051 if (copy > state->write) {
1052 copy -= state->write;
1053 from = state->window + (state->wsize - copy);
1054 }
1055 else
1056 from = state->window + (state->write - copy);
1057 if (copy > state->length) copy = state->length;
1058 }
1059 else { /* copy from output */
1060 from = put - state->offset;
1061 copy = state->length;
1062 }
1063 if (copy > left) copy = left;
1064 left -= copy;
1065 state->length -= copy;
1066 do {
1067 *put++ = *from++;
1068 } while (--copy);
1069 if (state->length == 0) state->mode = LEN;
1070 break;
1071 case LIT:
1072 if (left == 0) goto inf_leave;
1073 *put++ = (unsigned char)(state->length);
1074 left--;
1075 state->mode = LEN;
1076 break;
1077 case CHECK:
1078 if (state->wrap) {
1079 NEEDBITS(32);
1080 out -= left;
1081 strm->total_out += out;
1082 state->total += out;
1083 if (out)
1084 strm->adler = state->check =
1085 UPDATE(state->check, put - out, out);
1086 out = left;
1087 if ((
1088#ifdef GUNZIP
1089 state->flags ? hold :
1090#endif
1091 REVERSE(hold)) != state->check) {
1092 strm->msg = (char *)"incorrect data check";
1093 state->mode = BAD;
1094 break;
1095 }
1096 INITBITS();
1097 Tracev((stderr, "inflate: check matches trailer\n"));
1098 }
1099#ifdef GUNZIP
1100 state->mode = LENGTH;
1101 case LENGTH:
1102 if (state->wrap && state->flags) {
1103 NEEDBITS(32);
1104 if (hold != (state->total & 0xffffffffUL)) {
1105 strm->msg = (char *)"incorrect length check";
1106 state->mode = BAD;
1107 break;
1108 }
1109 INITBITS();
1110 Tracev((stderr, "inflate: length matches trailer\n"));
1111 }
1112#endif
1113 state->mode = DONE;
1114 case DONE:
1115 ret = Z_STREAM_END;
1116 goto inf_leave;
1117 case BAD:
1118 ret = Z_DATA_ERROR;
1119 goto inf_leave;
1120 case MEM:
1121 return Z_MEM_ERROR;
1122 case SYNC:
1123 default:
1124 return Z_STREAM_ERROR;
1125 }
1126
1127 /*
1128 Return from inflate(), updating the total counts and the check value.
1129 If there was no progress during the inflate() call, return a buffer
1130 error. Call updatewindow() to create and/or update the window state.
1131 Note: a memory error from inflate() is non-recoverable.
1132 */
1133 inf_leave:
1134 RESTORE();
1135 if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
1136 if (updatewindow(strm, out)) {
1137 state->mode = MEM;
1138 return Z_MEM_ERROR;
1139 }
1140 in -= strm->avail_in;
1141 out -= strm->avail_out;
1142 strm->total_in += in;
1143 strm->total_out += out;
1144 state->total += out;
1145 if (state->wrap && out)
1146 strm->adler = state->check =
1147 UPDATE(state->check, strm->next_out - out, out);
1148 strm->data_type = state->bits + (state->last ? 64 : 0) +
1149 (state->mode == TYPE ? 128 : 0);
1150 if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
1151 ret = Z_BUF_ERROR;
1152 return ret;
1153}
1154
1155int ZEXPORT inflateEnd(strm)
1156z_streamp strm;
1157{
1158 struct inflate_state FAR *state;
1159 if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
1160 return Z_STREAM_ERROR;
1161 state = (struct inflate_state FAR *)strm->state;
1162 if (state->window != Z_NULL) ZFREE(strm, state->window);
1163 ZFREE(strm, strm->state);
1164 strm->state = Z_NULL;
1165 Tracev((stderr, "inflate: end\n"));
1166 return Z_OK;
1167}
1168
1169int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength)
1170z_streamp strm;
1171const Bytef *dictionary;
1172uInt dictLength;
1173{
1174 struct inflate_state FAR *state;
1175 unsigned long id;
1176
1177 /* check state */
1178 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
1179 state = (struct inflate_state FAR *)strm->state;
1180 if (state->wrap != 0 && state->mode != DICT)
1181 return Z_STREAM_ERROR;
1182
1183 /* check for correct dictionary id */
1184 if (state->mode == DICT) {
1185 id = adler32(0L, Z_NULL, 0);
1186 id = adler32(id, dictionary, dictLength);
1187 if (id != state->check)
1188 return Z_DATA_ERROR;
1189 }
1190
1191 /* copy dictionary to window */
1192 if (updatewindow(strm, strm->avail_out)) {
1193 state->mode = MEM;
1194 return Z_MEM_ERROR;
1195 }
1196 if (dictLength > state->wsize) {
1197 zmemcpy(state->window, dictionary + dictLength - state->wsize,
1198 state->wsize);
1199 state->whave = state->wsize;
1200 }
1201 else {
1202 zmemcpy(state->window + state->wsize - dictLength, dictionary,
1203 dictLength);
1204 state->whave = dictLength;
1205 }
1206 state->havedict = 1;
1207 Tracev((stderr, "inflate: dictionary set\n"));
1208 return Z_OK;
1209}
1210
1211int ZEXPORT inflateGetHeader(strm, head)
1212z_streamp strm;
1213gz_headerp head;
1214{
1215 struct inflate_state FAR *state;
1216
1217 /* check state */
1218 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
1219 state = (struct inflate_state FAR *)strm->state;
1220 if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
1221
1222 /* save header structure */
1223 state->head = head;
1224 head->done = 0;
1225 return Z_OK;
1226}
1227
1228/*
1229 Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
1230 or when out of input. When called, *have is the number of pattern bytes
1231 found in order so far, in 0..3. On return *have is updated to the new
1232 state. If on return *have equals four, then the pattern was found and the
1233 return value is how many bytes were read including the last byte of the
1234 pattern. If *have is less than four, then the pattern has not been found
1235 yet and the return value is len. In the latter case, syncsearch() can be
1236 called again with more data and the *have state. *have is initialized to
1237 zero for the first call.
1238 */
1239local unsigned syncsearch(have, buf, len)
1240unsigned FAR *have;
1241unsigned char FAR *buf;
1242unsigned len;
1243{
1244 unsigned got;
1245 unsigned next;
1246
1247 got = *have;
1248 next = 0;
1249 while (next < len && got < 4) {
1250 if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
1251 got++;
1252 else if (buf[next])
1253 got = 0;
1254 else
1255 got = 4 - got;
1256 next++;
1257 }
1258 *have = got;
1259 return next;
1260}
1261
1262int ZEXPORT inflateSync(strm)
1263z_streamp strm;
1264{
1265 unsigned len; /* number of bytes to look at or looked at */
1266 unsigned long in, out; /* temporary to save total_in and total_out */
1267 unsigned char buf[4]; /* to restore bit buffer to byte string */
1268 struct inflate_state FAR *state;
1269
1270 /* check parameters */
1271 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
1272 state = (struct inflate_state FAR *)strm->state;
1273 if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
1274
1275 /* if first time, start search in bit buffer */
1276 if (state->mode != SYNC) {
1277 state->mode = SYNC;
1278 state->hold <<= state->bits & 7;
1279 state->bits -= state->bits & 7;
1280 len = 0;
1281 while (state->bits >= 8) {
1282 buf[len++] = (unsigned char)(state->hold);
1283 state->hold >>= 8;
1284 state->bits -= 8;
1285 }
1286 state->have = 0;
1287 syncsearch(&(state->have), buf, len);
1288 }
1289
1290 /* search available input */
1291 len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
1292 strm->avail_in -= len;
1293 strm->next_in += len;
1294 strm->total_in += len;
1295
1296 /* return no joy or set up to restart inflate() on a new block */
1297 if (state->have != 4) return Z_DATA_ERROR;
1298 in = strm->total_in; out = strm->total_out;
1299 inflateReset(strm);
1300 strm->total_in = in; strm->total_out = out;
1301 state->mode = TYPE;
1302 return Z_OK;
1303}
1304
1305/*
1306 Returns true if inflate is currently at the end of a block generated by
1307 Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
1308 implementation to provide an additional safety check. PPP uses
1309 Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
1310 block. When decompressing, PPP checks that at the end of input packet,
1311 inflate is waiting for these length bytes.
1312 */
1313int ZEXPORT inflateSyncPoint(strm)
1314z_streamp strm;
1315{
1316 struct inflate_state FAR *state;
1317
1318 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
1319 state = (struct inflate_state FAR *)strm->state;
1320 return state->mode == STORED && state->bits == 0;
1321}
1322
1323int ZEXPORT inflateCopy(dest, source)
1324z_streamp dest;
1325z_streamp source;
1326{
1327 struct inflate_state FAR *state;
1328 struct inflate_state FAR *copy;
1329 unsigned char FAR *window;
1330 unsigned wsize;
1331
1332 /* check input */
1333 if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
1334 source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
1335 return Z_STREAM_ERROR;
1336 state = (struct inflate_state FAR *)source->state;
1337
1338 /* allocate space */
1339 copy = (struct inflate_state FAR *)
1340 ZALLOC(source, 1, sizeof(struct inflate_state));
1341 if (copy == Z_NULL) return Z_MEM_ERROR;
1342 window = Z_NULL;
1343 if (state->window != Z_NULL) {
1344 window = (unsigned char FAR *)
1345 ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
1346 if (window == Z_NULL) {
1347 ZFREE(source, copy);
1348 return Z_MEM_ERROR;
1349 }
1350 }
1351
1352 /* copy state */
1353 zmemcpy(dest, source, sizeof(z_stream));
1354 zmemcpy(copy, state, sizeof(struct inflate_state));
1355 if (state->lencode >= state->codes &&
1356 state->lencode <= state->codes + ENOUGH - 1) {
1357 copy->lencode = copy->codes + (state->lencode - state->codes);
1358 copy->distcode = copy->codes + (state->distcode - state->codes);
1359 }
1360 copy->next = copy->codes + (state->next - state->codes);
1361 if (window != Z_NULL) {
1362 wsize = 1U << state->wbits;
1363 zmemcpy(window, state->window, wsize);
1364 }
1365 copy->window = window;
1366 dest->state = (struct internal_state FAR *)copy;
1367 return Z_OK;
1368}
diff --git a/utils/zenutils/libraries/zlib123/zlib/inflate.h b/utils/zenutils/libraries/zlib123/zlib/inflate.h
new file mode 100755
index 0000000000..fbbc871432
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/inflate.h
@@ -0,0 +1,115 @@
1/* inflate.h -- internal inflate state definition
2 * Copyright (C) 1995-2004 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/* WARNING: this file should *not* be used by applications. It is
7 part of the implementation of the compression library and is
8 subject to change. Applications should only use zlib.h.
9 */
10
11/* define NO_GZIP when compiling if you want to disable gzip header and
12 trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
13 the crc code when it is not needed. For shared libraries, gzip decoding
14 should be left enabled. */
15#ifndef NO_GZIP
16# define GUNZIP
17#endif
18
19/* Possible inflate modes between inflate() calls */
20typedef enum {
21 HEAD, /* i: waiting for magic header */
22 FLAGS, /* i: waiting for method and flags (gzip) */
23 TIME, /* i: waiting for modification time (gzip) */
24 OS, /* i: waiting for extra flags and operating system (gzip) */
25 EXLEN, /* i: waiting for extra length (gzip) */
26 EXTRA, /* i: waiting for extra bytes (gzip) */
27 NAME, /* i: waiting for end of file name (gzip) */
28 COMMENT, /* i: waiting for end of comment (gzip) */
29 HCRC, /* i: waiting for header crc (gzip) */
30 DICTID, /* i: waiting for dictionary check value */
31 DICT, /* waiting for inflateSetDictionary() call */
32 TYPE, /* i: waiting for type bits, including last-flag bit */
33 TYPEDO, /* i: same, but skip check to exit inflate on new block */
34 STORED, /* i: waiting for stored size (length and complement) */
35 COPY, /* i/o: waiting for input or output to copy stored block */
36 TABLE, /* i: waiting for dynamic block table lengths */
37 LENLENS, /* i: waiting for code length code lengths */
38 CODELENS, /* i: waiting for length/lit and distance code lengths */
39 LEN, /* i: waiting for length/lit code */
40 LENEXT, /* i: waiting for length extra bits */
41 DIST, /* i: waiting for distance code */
42 DISTEXT, /* i: waiting for distance extra bits */
43 MATCH, /* o: waiting for output space to copy string */
44 LIT, /* o: waiting for output space to write literal */
45 CHECK, /* i: waiting for 32-bit check value */
46 LENGTH, /* i: waiting for 32-bit length (gzip) */
47 DONE, /* finished check, done -- remain here until reset */
48 BAD, /* got a data error -- remain here until reset */
49 MEM, /* got an inflate() memory error -- remain here until reset */
50 SYNC /* looking for synchronization bytes to restart inflate() */
51} inflate_mode;
52
53/*
54 State transitions between above modes -
55
56 (most modes can go to the BAD or MEM mode -- not shown for clarity)
57
58 Process header:
59 HEAD -> (gzip) or (zlib)
60 (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
61 NAME -> COMMENT -> HCRC -> TYPE
62 (zlib) -> DICTID or TYPE
63 DICTID -> DICT -> TYPE
64 Read deflate blocks:
65 TYPE -> STORED or TABLE or LEN or CHECK
66 STORED -> COPY -> TYPE
67 TABLE -> LENLENS -> CODELENS -> LEN
68 Read deflate codes:
69 LEN -> LENEXT or LIT or TYPE
70 LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
71 LIT -> LEN
72 Process trailer:
73 CHECK -> LENGTH -> DONE
74 */
75
76/* state maintained between inflate() calls. Approximately 7K bytes. */
77struct inflate_state {
78 inflate_mode mode; /* current inflate mode */
79 int last; /* true if processing last block */
80 int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
81 int havedict; /* true if dictionary provided */
82 int flags; /* gzip header method and flags (0 if zlib) */
83 unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
84 unsigned long check; /* protected copy of check value */
85 unsigned long total; /* protected copy of output count */
86 gz_headerp head; /* where to save gzip header information */
87 /* sliding window */
88 unsigned wbits; /* log base 2 of requested window size */
89 unsigned wsize; /* window size or zero if not using window */
90 unsigned whave; /* valid bytes in the window */
91 unsigned write; /* window write index */
92 unsigned char FAR *window; /* allocated sliding window, if needed */
93 /* bit accumulator */
94 unsigned long hold; /* input bit accumulator */
95 unsigned bits; /* number of bits in "in" */
96 /* for string and stored block copying */
97 unsigned length; /* literal or length of data to copy */
98 unsigned offset; /* distance back to copy string from */
99 /* for table and code decoding */
100 unsigned extra; /* extra bits needed */
101 /* fixed and dynamic code tables */
102 code const FAR *lencode; /* starting table for length/literal codes */
103 code const FAR *distcode; /* starting table for distance codes */
104 unsigned lenbits; /* index bits for lencode */
105 unsigned distbits; /* index bits for distcode */
106 /* dynamic table building */
107 unsigned ncode; /* number of code length code lengths */
108 unsigned nlen; /* number of length code lengths */
109 unsigned ndist; /* number of distance code lengths */
110 unsigned have; /* number of code lengths in lens[] */
111 code FAR *next; /* next available space in codes[] */
112 unsigned short lens[320]; /* temporary storage for code lengths */
113 unsigned short work[288]; /* work area for code table building */
114 code codes[ENOUGH]; /* space for code tables */
115};
diff --git a/utils/zenutils/libraries/zlib123/zlib/inftrees.c b/utils/zenutils/libraries/zlib123/zlib/inftrees.c
new file mode 100755
index 0000000000..38ded81c36
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/inftrees.c
@@ -0,0 +1,329 @@
1/* inftrees.c -- generate Huffman trees for efficient decoding
2 * Copyright (C) 1995-2005 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6#include "zutil.h"
7#include "inftrees.h"
8
9#define MAXBITS 15
10
11const char inflate_copyright[] =
12 " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
13/*
14 If you use the zlib library in a product, an acknowledgment is welcome
15 in the documentation of your product. If for some reason you cannot
16 include such an acknowledgment, I would appreciate that you keep this
17 copyright string in the executable of your product.
18 */
19
20/*
21 Build a set of tables to decode the provided canonical Huffman code.
22 The code lengths are lens[0..codes-1]. The result starts at *table,
23 whose indices are 0..2^bits-1. work is a writable array of at least
24 lens shorts, which is used as a work area. type is the type of code
25 to be generated, CODES, LENS, or DISTS. On return, zero is success,
26 -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
27 on return points to the next available entry's address. bits is the
28 requested root table index bits, and on return it is the actual root
29 table index bits. It will differ if the request is greater than the
30 longest code or if it is less than the shortest code.
31 */
32int inflate_table(type, lens, codes, table, bits, work)
33codetype type;
34unsigned short FAR *lens;
35unsigned codes;
36code FAR * FAR *table;
37unsigned FAR *bits;
38unsigned short FAR *work;
39{
40 unsigned len; /* a code's length in bits */
41 unsigned sym; /* index of code symbols */
42 unsigned min, max; /* minimum and maximum code lengths */
43 unsigned root; /* number of index bits for root table */
44 unsigned curr; /* number of index bits for current table */
45 unsigned drop; /* code bits to drop for sub-table */
46 int left; /* number of prefix codes available */
47 unsigned used; /* code entries in table used */
48 unsigned huff; /* Huffman code */
49 unsigned incr; /* for incrementing code, index */
50 unsigned fill; /* index for replicating entries */
51 unsigned low; /* low bits for current root entry */
52 unsigned mask; /* mask for low root bits */
53 code this; /* table entry for duplication */
54 code FAR *next; /* next available space in table */
55 const unsigned short FAR *base; /* base value table to use */
56 const unsigned short FAR *extra; /* extra bits table to use */
57 int end; /* use base and extra for symbol > end */
58 unsigned short count[MAXBITS+1]; /* number of codes of each length */
59 unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
60 static const unsigned short lbase[31] = { /* Length codes 257..285 base */
61 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
62 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
63 static const unsigned short lext[31] = { /* Length codes 257..285 extra */
64 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
65 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
66 static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
67 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
68 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
69 8193, 12289, 16385, 24577, 0, 0};
70 static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
71 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
72 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
73 28, 28, 29, 29, 64, 64};
74
75 /*
76 Process a set of code lengths to create a canonical Huffman code. The
77 code lengths are lens[0..codes-1]. Each length corresponds to the
78 symbols 0..codes-1. The Huffman code is generated by first sorting the
79 symbols by length from short to long, and retaining the symbol order
80 for codes with equal lengths. Then the code starts with all zero bits
81 for the first code of the shortest length, and the codes are integer
82 increments for the same length, and zeros are appended as the length
83 increases. For the deflate format, these bits are stored backwards
84 from their more natural integer increment ordering, and so when the
85 decoding tables are built in the large loop below, the integer codes
86 are incremented backwards.
87
88 This routine assumes, but does not check, that all of the entries in
89 lens[] are in the range 0..MAXBITS. The caller must assure this.
90 1..MAXBITS is interpreted as that code length. zero means that that
91 symbol does not occur in this code.
92
93 The codes are sorted by computing a count of codes for each length,
94 creating from that a table of starting indices for each length in the
95 sorted table, and then entering the symbols in order in the sorted
96 table. The sorted table is work[], with that space being provided by
97 the caller.
98
99 The length counts are used for other purposes as well, i.e. finding
100 the minimum and maximum length codes, determining if there are any
101 codes at all, checking for a valid set of lengths, and looking ahead
102 at length counts to determine sub-table sizes when building the
103 decoding tables.
104 */
105
106 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
107 for (len = 0; len <= MAXBITS; len++)
108 count[len] = 0;
109 for (sym = 0; sym < codes; sym++)
110 count[lens[sym]]++;
111
112 /* bound code lengths, force root to be within code lengths */
113 root = *bits;
114 for (max = MAXBITS; max >= 1; max--)
115 if (count[max] != 0) break;
116 if (root > max) root = max;
117 if (max == 0) { /* no symbols to code at all */
118 this.op = (unsigned char)64; /* invalid code marker */
119 this.bits = (unsigned char)1;
120 this.val = (unsigned short)0;
121 *(*table)++ = this; /* make a table to force an error */
122 *(*table)++ = this;
123 *bits = 1;
124 return 0; /* no symbols, but wait for decoding to report error */
125 }
126 for (min = 1; min <= MAXBITS; min++)
127 if (count[min] != 0) break;
128 if (root < min) root = min;
129
130 /* check for an over-subscribed or incomplete set of lengths */
131 left = 1;
132 for (len = 1; len <= MAXBITS; len++) {
133 left <<= 1;
134 left -= count[len];
135 if (left < 0) return -1; /* over-subscribed */
136 }
137 if (left > 0 && (type == CODES || max != 1))
138 return -1; /* incomplete set */
139
140 /* generate offsets into symbol table for each length for sorting */
141 offs[1] = 0;
142 for (len = 1; len < MAXBITS; len++)
143 offs[len + 1] = offs[len] + count[len];
144
145 /* sort symbols by length, by symbol order within each length */
146 for (sym = 0; sym < codes; sym++)
147 if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
148
149 /*
150 Create and fill in decoding tables. In this loop, the table being
151 filled is at next and has curr index bits. The code being used is huff
152 with length len. That code is converted to an index by dropping drop
153 bits off of the bottom. For codes where len is less than drop + curr,
154 those top drop + curr - len bits are incremented through all values to
155 fill the table with replicated entries.
156
157 root is the number of index bits for the root table. When len exceeds
158 root, sub-tables are created pointed to by the root entry with an index
159 of the low root bits of huff. This is saved in low to check for when a
160 new sub-table should be started. drop is zero when the root table is
161 being filled, and drop is root when sub-tables are being filled.
162
163 When a new sub-table is needed, it is necessary to look ahead in the
164 code lengths to determine what size sub-table is needed. The length
165 counts are used for this, and so count[] is decremented as codes are
166 entered in the tables.
167
168 used keeps track of how many table entries have been allocated from the
169 provided *table space. It is checked when a LENS table is being made
170 against the space in *table, ENOUGH, minus the maximum space needed by
171 the worst case distance code, MAXD. This should never happen, but the
172 sufficiency of ENOUGH has not been proven exhaustively, hence the check.
173 This assumes that when type == LENS, bits == 9.
174
175 sym increments through all symbols, and the loop terminates when
176 all codes of length max, i.e. all codes, have been processed. This
177 routine permits incomplete codes, so another loop after this one fills
178 in the rest of the decoding tables with invalid code markers.
179 */
180
181 /* set up for code type */
182 switch (type) {
183 case CODES:
184 base = extra = work; /* dummy value--not used */
185 end = 19;
186 break;
187 case LENS:
188 base = lbase;
189 base -= 257;
190 extra = lext;
191 extra -= 257;
192 end = 256;
193 break;
194 default: /* DISTS */
195 base = dbase;
196 extra = dext;
197 end = -1;
198 }
199
200 /* initialize state for loop */
201 huff = 0; /* starting code */
202 sym = 0; /* starting code symbol */
203 len = min; /* starting code length */
204 next = *table; /* current table to fill in */
205 curr = root; /* current table index bits */
206 drop = 0; /* current bits to drop from code for index */
207 low = (unsigned)(-1); /* trigger new sub-table when len > root */
208 used = 1U << root; /* use root table entries */
209 mask = used - 1; /* mask for comparing low */
210
211 /* check available table space */
212 if (type == LENS && used >= ENOUGH - MAXD)
213 return 1;
214
215 /* process all codes and make table entries */
216 for (;;) {
217 /* create table entry */
218 this.bits = (unsigned char)(len - drop);
219 if ((int)(work[sym]) < end) {
220 this.op = (unsigned char)0;
221 this.val = work[sym];
222 }
223 else if ((int)(work[sym]) > end) {
224 this.op = (unsigned char)(extra[work[sym]]);
225 this.val = base[work[sym]];
226 }
227 else {
228 this.op = (unsigned char)(32 + 64); /* end of block */
229 this.val = 0;
230 }
231
232 /* replicate for those indices with low len bits equal to huff */
233 incr = 1U << (len - drop);
234 fill = 1U << curr;
235 min = fill; /* save offset to next table */
236 do {
237 fill -= incr;
238 next[(huff >> drop) + fill] = this;
239 } while (fill != 0);
240
241 /* backwards increment the len-bit code huff */
242 incr = 1U << (len - 1);
243 while (huff & incr)
244 incr >>= 1;
245 if (incr != 0) {
246 huff &= incr - 1;
247 huff += incr;
248 }
249 else
250 huff = 0;
251
252 /* go to next symbol, update count, len */
253 sym++;
254 if (--(count[len]) == 0) {
255 if (len == max) break;
256 len = lens[work[sym]];
257 }
258
259 /* create new sub-table if needed */
260 if (len > root && (huff & mask) != low) {
261 /* if first time, transition to sub-tables */
262 if (drop == 0)
263 drop = root;
264
265 /* increment past last table */
266 next += min; /* here min is 1 << curr */
267
268 /* determine length of next table */
269 curr = len - drop;
270 left = (int)(1 << curr);
271 while (curr + drop < max) {
272 left -= count[curr + drop];
273 if (left <= 0) break;
274 curr++;
275 left <<= 1;
276 }
277
278 /* check for enough space */
279 used += 1U << curr;
280 if (type == LENS && used >= ENOUGH - MAXD)
281 return 1;
282
283 /* point entry in root table to sub-table */
284 low = huff & mask;
285 (*table)[low].op = (unsigned char)curr;
286 (*table)[low].bits = (unsigned char)root;
287 (*table)[low].val = (unsigned short)(next - *table);
288 }
289 }
290
291 /*
292 Fill in rest of table for incomplete codes. This loop is similar to the
293 loop above in incrementing huff for table indices. It is assumed that
294 len is equal to curr + drop, so there is no loop needed to increment
295 through high index bits. When the current sub-table is filled, the loop
296 drops back to the root table to fill in any remaining entries there.
297 */
298 this.op = (unsigned char)64; /* invalid code marker */
299 this.bits = (unsigned char)(len - drop);
300 this.val = (unsigned short)0;
301 while (huff != 0) {
302 /* when done with sub-table, drop back to root table */
303 if (drop != 0 && (huff & mask) != low) {
304 drop = 0;
305 len = root;
306 next = *table;
307 this.bits = (unsigned char)len;
308 }
309
310 /* put invalid code marker in table */
311 next[huff >> drop] = this;
312
313 /* backwards increment the len-bit code huff */
314 incr = 1U << (len - 1);
315 while (huff & incr)
316 incr >>= 1;
317 if (incr != 0) {
318 huff &= incr - 1;
319 huff += incr;
320 }
321 else
322 huff = 0;
323 }
324
325 /* set return parameters */
326 *table += used;
327 *bits = root;
328 return 0;
329}
diff --git a/utils/zenutils/libraries/zlib123/zlib/inftrees.h b/utils/zenutils/libraries/zlib123/zlib/inftrees.h
new file mode 100755
index 0000000000..dc0fd567ea
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/inftrees.h
@@ -0,0 +1,55 @@
1/* inftrees.h -- header to use inftrees.c
2 * Copyright (C) 1995-2005 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/* WARNING: this file should *not* be used by applications. It is
7 part of the implementation of the compression library and is
8 subject to change. Applications should only use zlib.h.
9 */
10
11/* Structure for decoding tables. Each entry provides either the
12 information needed to do the operation requested by the code that
13 indexed that table entry, or it provides a pointer to another
14 table that indexes more bits of the code. op indicates whether
15 the entry is a pointer to another table, a literal, a length or
16 distance, an end-of-block, or an invalid code. For a table
17 pointer, the low four bits of op is the number of index bits of
18 that table. For a length or distance, the low four bits of op
19 is the number of extra bits to get after the code. bits is
20 the number of bits in this code or part of the code to drop off
21 of the bit buffer. val is the actual byte to output in the case
22 of a literal, the base length or distance, or the offset from
23 the current table to the next table. Each entry is four bytes. */
24typedef struct {
25 unsigned char op; /* operation, extra bits, table bits */
26 unsigned char bits; /* bits in this part of the code */
27 unsigned short val; /* offset in table or code value */
28} code;
29
30/* op values as set by inflate_table():
31 00000000 - literal
32 0000tttt - table link, tttt != 0 is the number of table index bits
33 0001eeee - length or distance, eeee is the number of extra bits
34 01100000 - end of block
35 01000000 - invalid code
36 */
37
38/* Maximum size of dynamic tree. The maximum found in a long but non-
39 exhaustive search was 1444 code structures (852 for length/literals
40 and 592 for distances, the latter actually the result of an
41 exhaustive search). The true maximum is not known, but the value
42 below is more than safe. */
43#define ENOUGH 2048
44#define MAXD 592
45
46/* Type of code to build for inftable() */
47typedef enum {
48 CODES,
49 LENS,
50 DISTS
51} codetype;
52
53extern int inflate_table OF((codetype type, unsigned short FAR *lens,
54 unsigned codes, code FAR * FAR *table,
55 unsigned FAR *bits, unsigned short FAR *work));
diff --git a/utils/zenutils/libraries/zlib123/zlib/make_vms.com b/utils/zenutils/libraries/zlib123/zlib/make_vms.com
new file mode 100755
index 0000000000..93174bbc8a
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/make_vms.com
@@ -0,0 +1,461 @@
1$! make libz under VMS written by
2$! Martin P.J. Zinser
3$! <zinser@zinser.no-ip.info or zinser@sysdev.deutsche-boerse.com>
4$!
5$ on error then goto err_exit
6$!
7$!
8$! Just some general constants...
9$!
10$ true = 1
11$ false = 0
12$ tmpnam = "temp_" + f$getjpi("","pid")
13$ SAY = "WRITE SYS$OUTPUT"
14$!
15$! Setup variables holding "config" information
16$!
17$ Make = ""
18$ name = "Zlib"
19$ version = "?.?.?"
20$ v_string = "ZLIB_VERSION"
21$ v_file = "zlib.h"
22$ ccopt = ""
23$ lopts = ""
24$ linkonly = false
25$ optfile = name + ".opt"
26$ its_decc = false
27$ its_vaxc = false
28$ its_gnuc = false
29$ axp = f$getsyi("HW_MODEL").ge.1024
30$ s_case = false
31$! Check for MMK/MMS
32$!
33$ If F$Search ("Sys$System:MMS.EXE") .nes. "" Then Make = "MMS"
34$ If F$Type (MMK) .eqs. "STRING" Then Make = "MMK"
35$!
36$!
37$ gosub find_version
38$!
39$ gosub check_opts
40$!
41$! Look for the compiler used
42$!
43$ gosub check_compiler
44$ if its_decc
45$ then
46$ ccopt = "/prefix=all" + ccopt
47$ if f$trnlnm("SYS") .eqs. ""
48$ then
49$ if axp
50$ then
51$ define sys sys$library:
52$ else
53$ ccopt = "/decc" + ccopt
54$ define sys decc$library_include:
55$ endif
56$ endif
57$ endif
58$ if its_vaxc .or. its_gnuc
59$ then
60$ if f$trnlnm("SYS").eqs."" then define sys sys$library:
61$ endif
62$!
63$! Build the thing plain or with mms
64$!
65$ write sys$output "Compiling Zlib sources ..."
66$ if make.eqs.""
67$ then
68$ dele example.obj;*,minigzip.obj;*
69$ CALL MAKE adler32.OBJ "CC ''CCOPT' adler32" -
70 adler32.c zlib.h zconf.h
71$ CALL MAKE compress.OBJ "CC ''CCOPT' compress" -
72 compress.c zlib.h zconf.h
73$ CALL MAKE crc32.OBJ "CC ''CCOPT' crc32" -
74 crc32.c zlib.h zconf.h
75$ CALL MAKE deflate.OBJ "CC ''CCOPT' deflate" -
76 deflate.c deflate.h zutil.h zlib.h zconf.h
77$ CALL MAKE gzio.OBJ "CC ''CCOPT' gzio" -
78 gzio.c zutil.h zlib.h zconf.h
79$ CALL MAKE infback.OBJ "CC ''CCOPT' infback" -
80 infback.c zutil.h inftrees.h inflate.h inffast.h inffixed.h
81$ CALL MAKE inffast.OBJ "CC ''CCOPT' inffast" -
82 inffast.c zutil.h zlib.h zconf.h inffast.h
83$ CALL MAKE inflate.OBJ "CC ''CCOPT' inflate" -
84 inflate.c zutil.h zlib.h zconf.h infblock.h
85$ CALL MAKE inftrees.OBJ "CC ''CCOPT' inftrees" -
86 inftrees.c zutil.h zlib.h zconf.h inftrees.h
87$ CALL MAKE trees.OBJ "CC ''CCOPT' trees" -
88 trees.c deflate.h zutil.h zlib.h zconf.h
89$ CALL MAKE uncompr.OBJ "CC ''CCOPT' uncompr" -
90 uncompr.c zlib.h zconf.h
91$ CALL MAKE zutil.OBJ "CC ''CCOPT' zutil" -
92 zutil.c zutil.h zlib.h zconf.h
93$ write sys$output "Building Zlib ..."
94$ CALL MAKE libz.OLB "lib/crea libz.olb *.obj" *.OBJ
95$ write sys$output "Building example..."
96$ CALL MAKE example.OBJ "CC ''CCOPT' example" -
97 example.c zlib.h zconf.h
98$ call make example.exe "LINK example,libz.olb/lib" example.obj libz.olb
99$ if f$search("x11vms:xvmsutils.olb") .nes. ""
100$ then
101$ write sys$output "Building minigzip..."
102$ CALL MAKE minigzip.OBJ "CC ''CCOPT' minigzip" -
103 minigzip.c zlib.h zconf.h
104$ call make minigzip.exe -
105 "LINK minigzip,libz.olb/lib,x11vms:xvmsutils.olb/lib" -
106 minigzip.obj libz.olb
107$ endif
108$ else
109$ gosub crea_mms
110$ SAY "Make ''name' ''version' with ''Make' "
111$ 'make'
112$ endif
113$!
114$! Alpha gets a shareable image
115$!
116$ If axp
117$ Then
118$ gosub crea_olist
119$ write sys$output "Creating libzshr.exe"
120$ call anal_obj_axp modules.opt _link.opt
121$ if s_case
122$ then
123$ open/append optf modules.opt
124$ write optf "case_sensitive=YES"
125$ close optf
126$ endif
127$ LINK_'lopts'/SHARE=libzshr.exe modules.opt/opt,_link.opt/opt
128$ endif
129$ write sys$output "Zlib build completed"
130$ exit
131$CC_ERR:
132$ write sys$output "C compiler required to build ''name'"
133$ goto err_exit
134$ERR_EXIT:
135$ set message/facil/ident/sever/text
136$ write sys$output "Exiting..."
137$ exit 2
138$!
139$!
140$MAKE: SUBROUTINE !SUBROUTINE TO CHECK DEPENDENCIES
141$ V = 'F$Verify(0)
142$! P1 = What we are trying to make
143$! P2 = Command to make it
144$! P3 - P8 What it depends on
145$
146$ If F$Search(P1) .Eqs. "" Then Goto Makeit
147$ Time = F$CvTime(F$File(P1,"RDT"))
148$arg=3
149$Loop:
150$ Argument = P'arg
151$ If Argument .Eqs. "" Then Goto Exit
152$ El=0
153$Loop2:
154$ File = F$Element(El," ",Argument)
155$ If File .Eqs. " " Then Goto Endl
156$ AFile = ""
157$Loop3:
158$ OFile = AFile
159$ AFile = F$Search(File)
160$ If AFile .Eqs. "" .Or. AFile .Eqs. OFile Then Goto NextEl
161$ If F$CvTime(F$File(AFile,"RDT")) .Ges. Time Then Goto Makeit
162$ Goto Loop3
163$NextEL:
164$ El = El + 1
165$ Goto Loop2
166$EndL:
167$ arg=arg+1
168$ If arg .Le. 8 Then Goto Loop
169$ Goto Exit
170$
171$Makeit:
172$ VV=F$VERIFY(0)
173$ write sys$output P2
174$ 'P2
175$ VV='F$Verify(VV)
176$Exit:
177$ If V Then Set Verify
178$ENDSUBROUTINE
179$!------------------------------------------------------------------------------
180$!
181$! Check command line options and set symbols accordingly
182$!
183$ CHECK_OPTS:
184$ i = 1
185$ OPT_LOOP:
186$ if i .lt. 9
187$ then
188$ cparm = f$edit(p'i',"upcase")
189$ if cparm .eqs. "DEBUG"
190$ then
191$ ccopt = ccopt + "/noopt/deb"
192$ lopts = lopts + "/deb"
193$ endif
194$ if f$locate("CCOPT=",cparm) .lt. f$length(cparm)
195$ then
196$ start = f$locate("=",cparm) + 1
197$ len = f$length(cparm) - start
198$ ccopt = ccopt + f$extract(start,len,cparm)
199$ if f$locate("AS_IS",f$edit(ccopt,"UPCASE")) .lt. f$length(ccopt) -
200 then s_case = true
201$ endif
202$ if cparm .eqs. "LINK" then linkonly = true
203$ if f$locate("LOPTS=",cparm) .lt. f$length(cparm)
204$ then
205$ start = f$locate("=",cparm) + 1
206$ len = f$length(cparm) - start
207$ lopts = lopts + f$extract(start,len,cparm)
208$ endif
209$ if f$locate("CC=",cparm) .lt. f$length(cparm)
210$ then
211$ start = f$locate("=",cparm) + 1
212$ len = f$length(cparm) - start
213$ cc_com = f$extract(start,len,cparm)
214 if (cc_com .nes. "DECC") .and. -
215 (cc_com .nes. "VAXC") .and. -
216 (cc_com .nes. "GNUC")
217$ then
218$ write sys$output "Unsupported compiler choice ''cc_com' ignored"
219$ write sys$output "Use DECC, VAXC, or GNUC instead"
220$ else
221$ if cc_com .eqs. "DECC" then its_decc = true
222$ if cc_com .eqs. "VAXC" then its_vaxc = true
223$ if cc_com .eqs. "GNUC" then its_gnuc = true
224$ endif
225$ endif
226$ if f$locate("MAKE=",cparm) .lt. f$length(cparm)
227$ then
228$ start = f$locate("=",cparm) + 1
229$ len = f$length(cparm) - start
230$ mmks = f$extract(start,len,cparm)
231$ if (mmks .eqs. "MMK") .or. (mmks .eqs. "MMS")
232$ then
233$ make = mmks
234$ else
235$ write sys$output "Unsupported make choice ''mmks' ignored"
236$ write sys$output "Use MMK or MMS instead"
237$ endif
238$ endif
239$ i = i + 1
240$ goto opt_loop
241$ endif
242$ return
243$!------------------------------------------------------------------------------
244$!
245$! Look for the compiler used
246$!
247$CHECK_COMPILER:
248$ if (.not. (its_decc .or. its_vaxc .or. its_gnuc))
249$ then
250$ its_decc = (f$search("SYS$SYSTEM:DECC$COMPILER.EXE") .nes. "")
251$ its_vaxc = .not. its_decc .and. (F$Search("SYS$System:VAXC.Exe") .nes. "")
252$ its_gnuc = .not. (its_decc .or. its_vaxc) .and. (f$trnlnm("gnu_cc") .nes. "")
253$ endif
254$!
255$! Exit if no compiler available
256$!
257$ if (.not. (its_decc .or. its_vaxc .or. its_gnuc))
258$ then goto CC_ERR
259$ else
260$ if its_decc then write sys$output "CC compiler check ... Compaq C"
261$ if its_vaxc then write sys$output "CC compiler check ... VAX C"
262$ if its_gnuc then write sys$output "CC compiler check ... GNU C"
263$ endif
264$ return
265$!------------------------------------------------------------------------------
266$!
267$! If MMS/MMK are available dump out the descrip.mms if required
268$!
269$CREA_MMS:
270$ write sys$output "Creating descrip.mms..."
271$ create descrip.mms
272$ open/append out descrip.mms
273$ copy sys$input: out
274$ deck
275# descrip.mms: MMS description file for building zlib on VMS
276# written by Martin P.J. Zinser
277# <zinser@zinser.no-ip.info or zinser@sysdev.deutsche-boerse.com>
278
279OBJS = adler32.obj, compress.obj, crc32.obj, gzio.obj, uncompr.obj, infback.obj\
280 deflate.obj, trees.obj, zutil.obj, inflate.obj, \
281 inftrees.obj, inffast.obj
282
283$ eod
284$ write out "CFLAGS=", ccopt
285$ write out "LOPTS=", lopts
286$ copy sys$input: out
287$ deck
288
289all : example.exe minigzip.exe libz.olb
290 @ write sys$output " Example applications available"
291
292libz.olb : libz.olb($(OBJS))
293 @ write sys$output " libz available"
294
295example.exe : example.obj libz.olb
296 link $(LOPTS) example,libz.olb/lib
297
298minigzip.exe : minigzip.obj libz.olb
299 link $(LOPTS) minigzip,libz.olb/lib,x11vms:xvmsutils.olb/lib
300
301clean :
302 delete *.obj;*,libz.olb;*,*.opt;*,*.exe;*
303
304
305# Other dependencies.
306adler32.obj : adler32.c zutil.h zlib.h zconf.h
307compress.obj : compress.c zlib.h zconf.h
308crc32.obj : crc32.c zutil.h zlib.h zconf.h
309deflate.obj : deflate.c deflate.h zutil.h zlib.h zconf.h
310example.obj : example.c zlib.h zconf.h
311gzio.obj : gzio.c zutil.h zlib.h zconf.h
312inffast.obj : inffast.c zutil.h zlib.h zconf.h inftrees.h inffast.h
313inflate.obj : inflate.c zutil.h zlib.h zconf.h
314inftrees.obj : inftrees.c zutil.h zlib.h zconf.h inftrees.h
315minigzip.obj : minigzip.c zlib.h zconf.h
316trees.obj : trees.c deflate.h zutil.h zlib.h zconf.h
317uncompr.obj : uncompr.c zlib.h zconf.h
318zutil.obj : zutil.c zutil.h zlib.h zconf.h
319infback.obj : infback.c zutil.h inftrees.h inflate.h inffast.h inffixed.h
320$ eod
321$ close out
322$ return
323$!------------------------------------------------------------------------------
324$!
325$! Read list of core library sources from makefile.in and create options
326$! needed to build shareable image
327$!
328$CREA_OLIST:
329$ open/read min makefile.in
330$ open/write mod modules.opt
331$ src_check = "OBJS ="
332$MRLOOP:
333$ read/end=mrdone min rec
334$ if (f$extract(0,6,rec) .nes. src_check) then goto mrloop
335$ rec = rec - src_check
336$ gosub extra_filnam
337$ if (f$element(1,"\",rec) .eqs. "\") then goto mrdone
338$MRSLOOP:
339$ read/end=mrdone min rec
340$ gosub extra_filnam
341$ if (f$element(1,"\",rec) .nes. "\") then goto mrsloop
342$MRDONE:
343$ close min
344$ close mod
345$ return
346$!------------------------------------------------------------------------------
347$!
348$! Take record extracted in crea_olist and split it into single filenames
349$!
350$EXTRA_FILNAM:
351$ myrec = f$edit(rec - "\", "trim,compress")
352$ i = 0
353$FELOOP:
354$ srcfil = f$element(i," ", myrec)
355$ if (srcfil .nes. " ")
356$ then
357$ write mod f$parse(srcfil,,,"NAME"), ".obj"
358$ i = i + 1
359$ goto feloop
360$ endif
361$ return
362$!------------------------------------------------------------------------------
363$!
364$! Find current Zlib version number
365$!
366$FIND_VERSION:
367$ open/read h_in 'v_file'
368$hloop:
369$ read/end=hdone h_in rec
370$ rec = f$edit(rec,"TRIM")
371$ if (f$extract(0,1,rec) .nes. "#") then goto hloop
372$ rec = f$edit(rec - "#", "TRIM")
373$ if f$element(0," ",rec) .nes. "define" then goto hloop
374$ if f$element(1," ",rec) .eqs. v_string
375$ then
376$ version = 'f$element(2," ",rec)'
377$ goto hdone
378$ endif
379$ goto hloop
380$hdone:
381$ close h_in
382$ return
383$!------------------------------------------------------------------------------
384$!
385$! Analyze Object files for OpenVMS AXP to extract Procedure and Data
386$! information to build a symbol vector for a shareable image
387$! All the "brains" of this logic was suggested by Hartmut Becker
388$! (Hartmut.Becker@compaq.com). All the bugs were introduced by me
389$! (zinser@decus.de), so if you do have problem reports please do not
390$! bother Hartmut/HP, but get in touch with me
391$!
392$ ANAL_OBJ_AXP: Subroutine
393$ V = 'F$Verify(0)
394$ SAY := "WRITE_ SYS$OUTPUT"
395$
396$ IF F$SEARCH("''P1'") .EQS. ""
397$ THEN
398$ SAY "ANAL_OBJ_AXP-E-NOSUCHFILE: Error, inputfile ''p1' not available"
399$ goto exit_aa
400$ ENDIF
401$ IF "''P2'" .EQS. ""
402$ THEN
403$ SAY "ANAL_OBJ_AXP: Error, no output file provided"
404$ goto exit_aa
405$ ENDIF
406$
407$ open/read in 'p1
408$ create a.tmp
409$ open/append atmp a.tmp
410$ loop:
411$ read/end=end_loop in line
412$ f= f$search(line)
413$ if f .eqs. ""
414$ then
415$ write sys$output "ANAL_OBJ_AXP-w-nosuchfile, ''line'"
416$ goto loop
417$ endif
418$ define/user sys$output nl:
419$ define/user sys$error nl:
420$ anal/obj/gsd 'f /out=x.tmp
421$ open/read xtmp x.tmp
422$ XLOOP:
423$ read/end=end_xloop xtmp xline
424$ xline = f$edit(xline,"compress")
425$ write atmp xline
426$ goto xloop
427$ END_XLOOP:
428$ close xtmp
429$ goto loop
430$ end_loop:
431$ close in
432$ close atmp
433$ if f$search("a.tmp") .eqs. "" -
434 then $ exit
435$ ! all global definitions
436$ search a.tmp "symbol:","EGSY$V_DEF 1","EGSY$V_NORM 1"/out=b.tmp
437$ ! all procedures
438$ search b.tmp "EGSY$V_NORM 1"/wind=(0,1) /out=c.tmp
439$ search c.tmp "symbol:"/out=d.tmp
440$ define/user sys$output nl:
441$ edito/edt/command=sys$input d.tmp
442sub/symbol: "/symbol_vector=(/whole
443sub/"/=PROCEDURE)/whole
444exit
445$ ! all data
446$ search b.tmp "EGSY$V_DEF 1"/wind=(0,1) /out=e.tmp
447$ search e.tmp "symbol:"/out=f.tmp
448$ define/user sys$output nl:
449$ edito/edt/command=sys$input f.tmp
450sub/symbol: "/symbol_vector=(/whole
451sub/"/=DATA)/whole
452exit
453$ sort/nodupl d.tmp,f.tmp 'p2'
454$ delete a.tmp;*,b.tmp;*,c.tmp;*,d.tmp;*,e.tmp;*,f.tmp;*
455$ if f$search("x.tmp") .nes. "" -
456 then $ delete x.tmp;*
457$!
458$ EXIT_AA:
459$ if V then set verify
460$ endsubroutine
461$!------------------------------------------------------------------------------
diff --git a/utils/zenutils/libraries/zlib123/zlib/minigzip.c b/utils/zenutils/libraries/zlib123/zlib/minigzip.c
new file mode 100755
index 0000000000..41996dbc9a
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/minigzip.c
@@ -0,0 +1,322 @@
1/* minigzip.c -- simulate gzip using the zlib compression library
2 * Copyright (C) 1995-2005 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/*
7 * minigzip is a minimal implementation of the gzip utility. This is
8 * only an example of using zlib and isn't meant to replace the
9 * full-featured gzip. No attempt is made to deal with file systems
10 * limiting names to 14 or 8+3 characters, etc... Error checking is
11 * very limited. So use minigzip only for testing; use gzip for the
12 * real thing. On MSDOS, use only on file names without extension
13 * or in pipe mode.
14 */
15
16/* @(#) $Id$ */
17
18#include <stdio.h>
19#include "zlib.h"
20
21#ifdef STDC
22# include <string.h>
23# include <stdlib.h>
24#endif
25
26#ifdef USE_MMAP
27# include <sys/types.h>
28# include <sys/mman.h>
29# include <sys/stat.h>
30#endif
31
32#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
33# include <fcntl.h>
34# include <io.h>
35# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
36#else
37# define SET_BINARY_MODE(file)
38#endif
39
40#ifdef VMS
41# define unlink delete
42# define GZ_SUFFIX "-gz"
43#endif
44#ifdef RISCOS
45# define unlink remove
46# define GZ_SUFFIX "-gz"
47# define fileno(file) file->__file
48#endif
49#if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
50# include <unix.h> /* for fileno */
51#endif
52
53#ifndef WIN32 /* unlink already in stdio.h for WIN32 */
54 extern int unlink OF((const char *));
55#endif
56
57#ifndef GZ_SUFFIX
58# define GZ_SUFFIX ".gz"
59#endif
60#define SUFFIX_LEN (sizeof(GZ_SUFFIX)-1)
61
62#define BUFLEN 16384
63#define MAX_NAME_LEN 1024
64
65#ifdef MAXSEG_64K
66# define local static
67 /* Needed for systems with limitation on stack size. */
68#else
69# define local
70#endif
71
72char *prog;
73
74void error OF((const char *msg));
75void gz_compress OF((FILE *in, gzFile out));
76#ifdef USE_MMAP
77int gz_compress_mmap OF((FILE *in, gzFile out));
78#endif
79void gz_uncompress OF((gzFile in, FILE *out));
80void file_compress OF((char *file, char *mode));
81void file_uncompress OF((char *file));
82int main OF((int argc, char *argv[]));
83
84/* ===========================================================================
85 * Display error message and exit
86 */
87void error(msg)
88 const char *msg;
89{
90 fprintf(stderr, "%s: %s\n", prog, msg);
91 exit(1);
92}
93
94/* ===========================================================================
95 * Compress input to output then close both files.
96 */
97
98void gz_compress(in, out)
99 FILE *in;
100 gzFile out;
101{
102 local char buf[BUFLEN];
103 int len;
104 int err;
105
106#ifdef USE_MMAP
107 /* Try first compressing with mmap. If mmap fails (minigzip used in a
108 * pipe), use the normal fread loop.
109 */
110 if (gz_compress_mmap(in, out) == Z_OK) return;
111#endif
112 for (;;) {
113 len = (int)fread(buf, 1, sizeof(buf), in);
114 if (ferror(in)) {
115 perror("fread");
116 exit(1);
117 }
118 if (len == 0) break;
119
120 if (gzwrite(out, buf, (unsigned)len) != len) error(gzerror(out, &err));
121 }
122 fclose(in);
123 if (gzclose(out) != Z_OK) error("failed gzclose");
124}
125
126#ifdef USE_MMAP /* MMAP version, Miguel Albrecht <malbrech@eso.org> */
127
128/* Try compressing the input file at once using mmap. Return Z_OK if
129 * if success, Z_ERRNO otherwise.
130 */
131int gz_compress_mmap(in, out)
132 FILE *in;
133 gzFile out;
134{
135 int len;
136 int err;
137 int ifd = fileno(in);
138 caddr_t buf; /* mmap'ed buffer for the entire input file */
139 off_t buf_len; /* length of the input file */
140 struct stat sb;
141
142 /* Determine the size of the file, needed for mmap: */
143 if (fstat(ifd, &sb) < 0) return Z_ERRNO;
144 buf_len = sb.st_size;
145 if (buf_len <= 0) return Z_ERRNO;
146
147 /* Now do the actual mmap: */
148 buf = mmap((caddr_t) 0, buf_len, PROT_READ, MAP_SHARED, ifd, (off_t)0);
149 if (buf == (caddr_t)(-1)) return Z_ERRNO;
150
151 /* Compress the whole file at once: */
152 len = gzwrite(out, (char *)buf, (unsigned)buf_len);
153
154 if (len != (int)buf_len) error(gzerror(out, &err));
155
156 munmap(buf, buf_len);
157 fclose(in);
158 if (gzclose(out) != Z_OK) error("failed gzclose");
159 return Z_OK;
160}
161#endif /* USE_MMAP */
162
163/* ===========================================================================
164 * Uncompress input to output then close both files.
165 */
166void gz_uncompress(in, out)
167 gzFile in;
168 FILE *out;
169{
170 local char buf[BUFLEN];
171 int len;
172 int err;
173
174 for (;;) {
175 len = gzread(in, buf, sizeof(buf));
176 if (len < 0) error (gzerror(in, &err));
177 if (len == 0) break;
178
179 if ((int)fwrite(buf, 1, (unsigned)len, out) != len) {
180 error("failed fwrite");
181 }
182 }
183 if (fclose(out)) error("failed fclose");
184
185 if (gzclose(in) != Z_OK) error("failed gzclose");
186}
187
188
189/* ===========================================================================
190 * Compress the given file: create a corresponding .gz file and remove the
191 * original.
192 */
193void file_compress(file, mode)
194 char *file;
195 char *mode;
196{
197 local char outfile[MAX_NAME_LEN];
198 FILE *in;
199 gzFile out;
200
201 strcpy(outfile, file);
202 strcat(outfile, GZ_SUFFIX);
203
204 in = fopen(file, "rb");
205 if (in == NULL) {
206 perror(file);
207 exit(1);
208 }
209 out = gzopen(outfile, mode);
210 if (out == NULL) {
211 fprintf(stderr, "%s: can't gzopen %s\n", prog, outfile);
212 exit(1);
213 }
214 gz_compress(in, out);
215
216 unlink(file);
217}
218
219
220/* ===========================================================================
221 * Uncompress the given file and remove the original.
222 */
223void file_uncompress(file)
224 char *file;
225{
226 local char buf[MAX_NAME_LEN];
227 char *infile, *outfile;
228 FILE *out;
229 gzFile in;
230 uInt len = (uInt)strlen(file);
231
232 strcpy(buf, file);
233
234 if (len > SUFFIX_LEN && strcmp(file+len-SUFFIX_LEN, GZ_SUFFIX) == 0) {
235 infile = file;
236 outfile = buf;
237 outfile[len-3] = '\0';
238 } else {
239 outfile = file;
240 infile = buf;
241 strcat(infile, GZ_SUFFIX);
242 }
243 in = gzopen(infile, "rb");
244 if (in == NULL) {
245 fprintf(stderr, "%s: can't gzopen %s\n", prog, infile);
246 exit(1);
247 }
248 out = fopen(outfile, "wb");
249 if (out == NULL) {
250 perror(file);
251 exit(1);
252 }
253
254 gz_uncompress(in, out);
255
256 unlink(infile);
257}
258
259
260/* ===========================================================================
261 * Usage: minigzip [-d] [-f] [-h] [-r] [-1 to -9] [files...]
262 * -d : decompress
263 * -f : compress with Z_FILTERED
264 * -h : compress with Z_HUFFMAN_ONLY
265 * -r : compress with Z_RLE
266 * -1 to -9 : compression level
267 */
268
269int main(argc, argv)
270 int argc;
271 char *argv[];
272{
273 int uncompr = 0;
274 gzFile file;
275 char outmode[20];
276
277 strcpy(outmode, "wb6 ");
278
279 prog = argv[0];
280 argc--, argv++;
281
282 while (argc > 0) {
283 if (strcmp(*argv, "-d") == 0)
284 uncompr = 1;
285 else if (strcmp(*argv, "-f") == 0)
286 outmode[3] = 'f';
287 else if (strcmp(*argv, "-h") == 0)
288 outmode[3] = 'h';
289 else if (strcmp(*argv, "-r") == 0)
290 outmode[3] = 'R';
291 else if ((*argv)[0] == '-' && (*argv)[1] >= '1' && (*argv)[1] <= '9' &&
292 (*argv)[2] == 0)
293 outmode[2] = (*argv)[1];
294 else
295 break;
296 argc--, argv++;
297 }
298 if (outmode[3] == ' ')
299 outmode[3] = 0;
300 if (argc == 0) {
301 SET_BINARY_MODE(stdin);
302 SET_BINARY_MODE(stdout);
303 if (uncompr) {
304 file = gzdopen(fileno(stdin), "rb");
305 if (file == NULL) error("can't gzdopen stdin");
306 gz_uncompress(file, stdout);
307 } else {
308 file = gzdopen(fileno(stdout), outmode);
309 if (file == NULL) error("can't gzdopen stdout");
310 gz_compress(stdin, file);
311 }
312 } else {
313 do {
314 if (uncompr) {
315 file_uncompress(*argv);
316 } else {
317 file_compress(*argv, outmode);
318 }
319 } while (argv++, --argc);
320 }
321 return 0;
322}
diff --git a/utils/zenutils/libraries/zlib123/zlib/trees.c b/utils/zenutils/libraries/zlib123/zlib/trees.c
new file mode 100755
index 0000000000..7a04802862
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/trees.c
@@ -0,0 +1,1219 @@
1/* trees.c -- output deflated data using Huffman coding
2 * Copyright (C) 1995-2005 Jean-loup Gailly
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/*
7 * ALGORITHM
8 *
9 * The "deflation" process uses several Huffman trees. The more
10 * common source values are represented by shorter bit sequences.
11 *
12 * Each code tree is stored in a compressed form which is itself
13 * a Huffman encoding of the lengths of all the code strings (in
14 * ascending order by source values). The actual code strings are
15 * reconstructed from the lengths in the inflate process, as described
16 * in the deflate specification.
17 *
18 * REFERENCES
19 *
20 * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
21 * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
22 *
23 * Storer, James A.
24 * Data Compression: Methods and Theory, pp. 49-50.
25 * Computer Science Press, 1988. ISBN 0-7167-8156-5.
26 *
27 * Sedgewick, R.
28 * Algorithms, p290.
29 * Addison-Wesley, 1983. ISBN 0-201-06672-6.
30 */
31
32/* @(#) $Id$ */
33
34/* #define GEN_TREES_H */
35
36#include "deflate.h"
37
38#ifdef DEBUG
39# include <ctype.h>
40#endif
41
42/* ===========================================================================
43 * Constants
44 */
45
46#define MAX_BL_BITS 7
47/* Bit length codes must not exceed MAX_BL_BITS bits */
48
49#define END_BLOCK 256
50/* end of block literal code */
51
52#define REP_3_6 16
53/* repeat previous bit length 3-6 times (2 bits of repeat count) */
54
55#define REPZ_3_10 17
56/* repeat a zero length 3-10 times (3 bits of repeat count) */
57
58#define REPZ_11_138 18
59/* repeat a zero length 11-138 times (7 bits of repeat count) */
60
61local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
62 = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
63
64local const int extra_dbits[D_CODES] /* extra bits for each distance code */
65 = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
66
67local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
68 = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
69
70local const uch bl_order[BL_CODES]
71 = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
72/* The lengths of the bit length codes are sent in order of decreasing
73 * probability, to avoid transmitting the lengths for unused bit length codes.
74 */
75
76#define Buf_size (8 * 2*sizeof(char))
77/* Number of bits used within bi_buf. (bi_buf might be implemented on
78 * more than 16 bits on some systems.)
79 */
80
81/* ===========================================================================
82 * Local data. These are initialized only once.
83 */
84
85#define DIST_CODE_LEN 512 /* see definition of array dist_code below */
86
87#if defined(GEN_TREES_H) || !defined(STDC)
88/* non ANSI compilers may not accept trees.h */
89
90local ct_data static_ltree[L_CODES+2];
91/* The static literal tree. Since the bit lengths are imposed, there is no
92 * need for the L_CODES extra codes used during heap construction. However
93 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
94 * below).
95 */
96
97local ct_data static_dtree[D_CODES];
98/* The static distance tree. (Actually a trivial tree since all codes use
99 * 5 bits.)
100 */
101
102uch _dist_code[DIST_CODE_LEN];
103/* Distance codes. The first 256 values correspond to the distances
104 * 3 .. 258, the last 256 values correspond to the top 8 bits of
105 * the 15 bit distances.
106 */
107
108uch _length_code[MAX_MATCH-MIN_MATCH+1];
109/* length code for each normalized match length (0 == MIN_MATCH) */
110
111local int base_length[LENGTH_CODES];
112/* First normalized length for each code (0 = MIN_MATCH) */
113
114local int base_dist[D_CODES];
115/* First normalized distance for each code (0 = distance of 1) */
116
117#else
118# include "trees.h"
119#endif /* GEN_TREES_H */
120
121struct static_tree_desc_s {
122 const ct_data *static_tree; /* static tree or NULL */
123 const intf *extra_bits; /* extra bits for each code or NULL */
124 int extra_base; /* base index for extra_bits */
125 int elems; /* max number of elements in the tree */
126 int max_length; /* max bit length for the codes */
127};
128
129local static_tree_desc static_l_desc =
130{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
131
132local static_tree_desc static_d_desc =
133{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
134
135local static_tree_desc static_bl_desc =
136{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
137
138/* ===========================================================================
139 * Local (static) routines in this file.
140 */
141
142local void tr_static_init OF((void));
143local void init_block OF((deflate_state *s));
144local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
145local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
146local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
147local void build_tree OF((deflate_state *s, tree_desc *desc));
148local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
149local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
150local int build_bl_tree OF((deflate_state *s));
151local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
152 int blcodes));
153local void compress_block OF((deflate_state *s, ct_data *ltree,
154 ct_data *dtree));
155local void set_data_type OF((deflate_state *s));
156local unsigned bi_reverse OF((unsigned value, int length));
157local void bi_windup OF((deflate_state *s));
158local void bi_flush OF((deflate_state *s));
159local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
160 int header));
161
162#ifdef GEN_TREES_H
163local void gen_trees_header OF((void));
164#endif
165
166#ifndef DEBUG
167# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
168 /* Send a code of the given tree. c and tree must not have side effects */
169
170#else /* DEBUG */
171# define send_code(s, c, tree) \
172 { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
173 send_bits(s, tree[c].Code, tree[c].Len); }
174#endif
175
176/* ===========================================================================
177 * Output a short LSB first on the stream.
178 * IN assertion: there is enough room in pendingBuf.
179 */
180#define put_short(s, w) { \
181 put_byte(s, (uch)((w) & 0xff)); \
182 put_byte(s, (uch)((ush)(w) >> 8)); \
183}
184
185/* ===========================================================================
186 * Send a value on a given number of bits.
187 * IN assertion: length <= 16 and value fits in length bits.
188 */
189#ifdef DEBUG
190local void send_bits OF((deflate_state *s, int value, int length));
191
192local void send_bits(s, value, length)
193 deflate_state *s;
194 int value; /* value to send */
195 int length; /* number of bits */
196{
197 Tracevv((stderr," l %2d v %4x ", length, value));
198 Assert(length > 0 && length <= 15, "invalid length");
199 s->bits_sent += (ulg)length;
200
201 /* If not enough room in bi_buf, use (valid) bits from bi_buf and
202 * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
203 * unused bits in value.
204 */
205 if (s->bi_valid > (int)Buf_size - length) {
206 s->bi_buf |= (value << s->bi_valid);
207 put_short(s, s->bi_buf);
208 s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
209 s->bi_valid += length - Buf_size;
210 } else {
211 s->bi_buf |= value << s->bi_valid;
212 s->bi_valid += length;
213 }
214}
215#else /* !DEBUG */
216
217#define send_bits(s, value, length) \
218{ int len = length;\
219 if (s->bi_valid > (int)Buf_size - len) {\
220 int val = value;\
221 s->bi_buf |= (val << s->bi_valid);\
222 put_short(s, s->bi_buf);\
223 s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
224 s->bi_valid += len - Buf_size;\
225 } else {\
226 s->bi_buf |= (value) << s->bi_valid;\
227 s->bi_valid += len;\
228 }\
229}
230#endif /* DEBUG */
231
232
233/* the arguments must not have side effects */
234
235/* ===========================================================================
236 * Initialize the various 'constant' tables.
237 */
238local void tr_static_init()
239{
240#if defined(GEN_TREES_H) || !defined(STDC)
241 static int static_init_done = 0;
242 int n; /* iterates over tree elements */
243 int bits; /* bit counter */
244 int length; /* length value */
245 int code; /* code value */
246 int dist; /* distance index */
247 ush bl_count[MAX_BITS+1];
248 /* number of codes at each bit length for an optimal tree */
249
250 if (static_init_done) return;
251
252 /* For some embedded targets, global variables are not initialized: */
253 static_l_desc.static_tree = static_ltree;
254 static_l_desc.extra_bits = extra_lbits;
255 static_d_desc.static_tree = static_dtree;
256 static_d_desc.extra_bits = extra_dbits;
257 static_bl_desc.extra_bits = extra_blbits;
258
259 /* Initialize the mapping length (0..255) -> length code (0..28) */
260 length = 0;
261 for (code = 0; code < LENGTH_CODES-1; code++) {
262 base_length[code] = length;
263 for (n = 0; n < (1<<extra_lbits[code]); n++) {
264 _length_code[length++] = (uch)code;
265 }
266 }
267 Assert (length == 256, "tr_static_init: length != 256");
268 /* Note that the length 255 (match length 258) can be represented
269 * in two different ways: code 284 + 5 bits or code 285, so we
270 * overwrite length_code[255] to use the best encoding:
271 */
272 _length_code[length-1] = (uch)code;
273
274 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
275 dist = 0;
276 for (code = 0 ; code < 16; code++) {
277 base_dist[code] = dist;
278 for (n = 0; n < (1<<extra_dbits[code]); n++) {
279 _dist_code[dist++] = (uch)code;
280 }
281 }
282 Assert (dist == 256, "tr_static_init: dist != 256");
283 dist >>= 7; /* from now on, all distances are divided by 128 */
284 for ( ; code < D_CODES; code++) {
285 base_dist[code] = dist << 7;
286 for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
287 _dist_code[256 + dist++] = (uch)code;
288 }
289 }
290 Assert (dist == 256, "tr_static_init: 256+dist != 512");
291
292 /* Construct the codes of the static literal tree */
293 for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
294 n = 0;
295 while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
296 while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
297 while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
298 while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
299 /* Codes 286 and 287 do not exist, but we must include them in the
300 * tree construction to get a canonical Huffman tree (longest code
301 * all ones)
302 */
303 gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
304
305 /* The static distance tree is trivial: */
306 for (n = 0; n < D_CODES; n++) {
307 static_dtree[n].Len = 5;
308 static_dtree[n].Code = bi_reverse((unsigned)n, 5);
309 }
310 static_init_done = 1;
311
312# ifdef GEN_TREES_H
313 gen_trees_header();
314# endif
315#endif /* defined(GEN_TREES_H) || !defined(STDC) */
316}
317
318/* ===========================================================================
319 * Genererate the file trees.h describing the static trees.
320 */
321#ifdef GEN_TREES_H
322# ifndef DEBUG
323# include <stdio.h>
324# endif
325
326# define SEPARATOR(i, last, width) \
327 ((i) == (last)? "\n};\n\n" : \
328 ((i) % (width) == (width)-1 ? ",\n" : ", "))
329
330void gen_trees_header()
331{
332 FILE *header = fopen("trees.h", "w");
333 int i;
334
335 Assert (header != NULL, "Can't open trees.h");
336 fprintf(header,
337 "/* header created automatically with -DGEN_TREES_H */\n\n");
338
339 fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
340 for (i = 0; i < L_CODES+2; i++) {
341 fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
342 static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
343 }
344
345 fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
346 for (i = 0; i < D_CODES; i++) {
347 fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
348 static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
349 }
350
351 fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
352 for (i = 0; i < DIST_CODE_LEN; i++) {
353 fprintf(header, "%2u%s", _dist_code[i],
354 SEPARATOR(i, DIST_CODE_LEN-1, 20));
355 }
356
357 fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
358 for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
359 fprintf(header, "%2u%s", _length_code[i],
360 SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
361 }
362
363 fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
364 for (i = 0; i < LENGTH_CODES; i++) {
365 fprintf(header, "%1u%s", base_length[i],
366 SEPARATOR(i, LENGTH_CODES-1, 20));
367 }
368
369 fprintf(header, "local const int base_dist[D_CODES] = {\n");
370 for (i = 0; i < D_CODES; i++) {
371 fprintf(header, "%5u%s", base_dist[i],
372 SEPARATOR(i, D_CODES-1, 10));
373 }
374
375 fclose(header);
376}
377#endif /* GEN_TREES_H */
378
379/* ===========================================================================
380 * Initialize the tree data structures for a new zlib stream.
381 */
382void _tr_init(s)
383 deflate_state *s;
384{
385 tr_static_init();
386
387 s->l_desc.dyn_tree = s->dyn_ltree;
388 s->l_desc.stat_desc = &static_l_desc;
389
390 s->d_desc.dyn_tree = s->dyn_dtree;
391 s->d_desc.stat_desc = &static_d_desc;
392
393 s->bl_desc.dyn_tree = s->bl_tree;
394 s->bl_desc.stat_desc = &static_bl_desc;
395
396 s->bi_buf = 0;
397 s->bi_valid = 0;
398 s->last_eob_len = 8; /* enough lookahead for inflate */
399#ifdef DEBUG
400 s->compressed_len = 0L;
401 s->bits_sent = 0L;
402#endif
403
404 /* Initialize the first block of the first file: */
405 init_block(s);
406}
407
408/* ===========================================================================
409 * Initialize a new block.
410 */
411local void init_block(s)
412 deflate_state *s;
413{
414 int n; /* iterates over tree elements */
415
416 /* Initialize the trees. */
417 for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
418 for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
419 for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
420
421 s->dyn_ltree[END_BLOCK].Freq = 1;
422 s->opt_len = s->static_len = 0L;
423 s->last_lit = s->matches = 0;
424}
425
426#define SMALLEST 1
427/* Index within the heap array of least frequent node in the Huffman tree */
428
429
430/* ===========================================================================
431 * Remove the smallest element from the heap and recreate the heap with
432 * one less element. Updates heap and heap_len.
433 */
434#define pqremove(s, tree, top) \
435{\
436 top = s->heap[SMALLEST]; \
437 s->heap[SMALLEST] = s->heap[s->heap_len--]; \
438 pqdownheap(s, tree, SMALLEST); \
439}
440
441/* ===========================================================================
442 * Compares to subtrees, using the tree depth as tie breaker when
443 * the subtrees have equal frequency. This minimizes the worst case length.
444 */
445#define smaller(tree, n, m, depth) \
446 (tree[n].Freq < tree[m].Freq || \
447 (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
448
449/* ===========================================================================
450 * Restore the heap property by moving down the tree starting at node k,
451 * exchanging a node with the smallest of its two sons if necessary, stopping
452 * when the heap property is re-established (each father smaller than its
453 * two sons).
454 */
455local void pqdownheap(s, tree, k)
456 deflate_state *s;
457 ct_data *tree; /* the tree to restore */
458 int k; /* node to move down */
459{
460 int v = s->heap[k];
461 int j = k << 1; /* left son of k */
462 while (j <= s->heap_len) {
463 /* Set j to the smallest of the two sons: */
464 if (j < s->heap_len &&
465 smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
466 j++;
467 }
468 /* Exit if v is smaller than both sons */
469 if (smaller(tree, v, s->heap[j], s->depth)) break;
470
471 /* Exchange v with the smallest son */
472 s->heap[k] = s->heap[j]; k = j;
473
474 /* And continue down the tree, setting j to the left son of k */
475 j <<= 1;
476 }
477 s->heap[k] = v;
478}
479
480/* ===========================================================================
481 * Compute the optimal bit lengths for a tree and update the total bit length
482 * for the current block.
483 * IN assertion: the fields freq and dad are set, heap[heap_max] and
484 * above are the tree nodes sorted by increasing frequency.
485 * OUT assertions: the field len is set to the optimal bit length, the
486 * array bl_count contains the frequencies for each bit length.
487 * The length opt_len is updated; static_len is also updated if stree is
488 * not null.
489 */
490local void gen_bitlen(s, desc)
491 deflate_state *s;
492 tree_desc *desc; /* the tree descriptor */
493{
494 ct_data *tree = desc->dyn_tree;
495 int max_code = desc->max_code;
496 const ct_data *stree = desc->stat_desc->static_tree;
497 const intf *extra = desc->stat_desc->extra_bits;
498 int base = desc->stat_desc->extra_base;
499 int max_length = desc->stat_desc->max_length;
500 int h; /* heap index */
501 int n, m; /* iterate over the tree elements */
502 int bits; /* bit length */
503 int xbits; /* extra bits */
504 ush f; /* frequency */
505 int overflow = 0; /* number of elements with bit length too large */
506
507 for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
508
509 /* In a first pass, compute the optimal bit lengths (which may
510 * overflow in the case of the bit length tree).
511 */
512 tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
513
514 for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
515 n = s->heap[h];
516 bits = tree[tree[n].Dad].Len + 1;
517 if (bits > max_length) bits = max_length, overflow++;
518 tree[n].Len = (ush)bits;
519 /* We overwrite tree[n].Dad which is no longer needed */
520
521 if (n > max_code) continue; /* not a leaf node */
522
523 s->bl_count[bits]++;
524 xbits = 0;
525 if (n >= base) xbits = extra[n-base];
526 f = tree[n].Freq;
527 s->opt_len += (ulg)f * (bits + xbits);
528 if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
529 }
530 if (overflow == 0) return;
531
532 Trace((stderr,"\nbit length overflow\n"));
533 /* This happens for example on obj2 and pic of the Calgary corpus */
534
535 /* Find the first bit length which could increase: */
536 do {
537 bits = max_length-1;
538 while (s->bl_count[bits] == 0) bits--;
539 s->bl_count[bits]--; /* move one leaf down the tree */
540 s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
541 s->bl_count[max_length]--;
542 /* The brother of the overflow item also moves one step up,
543 * but this does not affect bl_count[max_length]
544 */
545 overflow -= 2;
546 } while (overflow > 0);
547
548 /* Now recompute all bit lengths, scanning in increasing frequency.
549 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
550 * lengths instead of fixing only the wrong ones. This idea is taken
551 * from 'ar' written by Haruhiko Okumura.)
552 */
553 for (bits = max_length; bits != 0; bits--) {
554 n = s->bl_count[bits];
555 while (n != 0) {
556 m = s->heap[--h];
557 if (m > max_code) continue;
558 if ((unsigned) tree[m].Len != (unsigned) bits) {
559 Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
560 s->opt_len += ((long)bits - (long)tree[m].Len)
561 *(long)tree[m].Freq;
562 tree[m].Len = (ush)bits;
563 }
564 n--;
565 }
566 }
567}
568
569/* ===========================================================================
570 * Generate the codes for a given tree and bit counts (which need not be
571 * optimal).
572 * IN assertion: the array bl_count contains the bit length statistics for
573 * the given tree and the field len is set for all tree elements.
574 * OUT assertion: the field code is set for all tree elements of non
575 * zero code length.
576 */
577local void gen_codes (tree, max_code, bl_count)
578 ct_data *tree; /* the tree to decorate */
579 int max_code; /* largest code with non zero frequency */
580 ushf *bl_count; /* number of codes at each bit length */
581{
582 ush next_code[MAX_BITS+1]; /* next code value for each bit length */
583 ush code = 0; /* running code value */
584 int bits; /* bit index */
585 int n; /* code index */
586
587 /* The distribution counts are first used to generate the code values
588 * without bit reversal.
589 */
590 for (bits = 1; bits <= MAX_BITS; bits++) {
591 next_code[bits] = code = (code + bl_count[bits-1]) << 1;
592 }
593 /* Check that the bit counts in bl_count are consistent. The last code
594 * must be all ones.
595 */
596 Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
597 "inconsistent bit counts");
598 Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
599
600 for (n = 0; n <= max_code; n++) {
601 int len = tree[n].Len;
602 if (len == 0) continue;
603 /* Now reverse the bits */
604 tree[n].Code = bi_reverse(next_code[len]++, len);
605
606 Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
607 n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
608 }
609}
610
611/* ===========================================================================
612 * Construct one Huffman tree and assigns the code bit strings and lengths.
613 * Update the total bit length for the current block.
614 * IN assertion: the field freq is set for all tree elements.
615 * OUT assertions: the fields len and code are set to the optimal bit length
616 * and corresponding code. The length opt_len is updated; static_len is
617 * also updated if stree is not null. The field max_code is set.
618 */
619local void build_tree(s, desc)
620 deflate_state *s;
621 tree_desc *desc; /* the tree descriptor */
622{
623 ct_data *tree = desc->dyn_tree;
624 const ct_data *stree = desc->stat_desc->static_tree;
625 int elems = desc->stat_desc->elems;
626 int n, m; /* iterate over heap elements */
627 int max_code = -1; /* largest code with non zero frequency */
628 int node; /* new node being created */
629
630 /* Construct the initial heap, with least frequent element in
631 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
632 * heap[0] is not used.
633 */
634 s->heap_len = 0, s->heap_max = HEAP_SIZE;
635
636 for (n = 0; n < elems; n++) {
637 if (tree[n].Freq != 0) {
638 s->heap[++(s->heap_len)] = max_code = n;
639 s->depth[n] = 0;
640 } else {
641 tree[n].Len = 0;
642 }
643 }
644
645 /* The pkzip format requires that at least one distance code exists,
646 * and that at least one bit should be sent even if there is only one
647 * possible code. So to avoid special checks later on we force at least
648 * two codes of non zero frequency.
649 */
650 while (s->heap_len < 2) {
651 node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
652 tree[node].Freq = 1;
653 s->depth[node] = 0;
654 s->opt_len--; if (stree) s->static_len -= stree[node].Len;
655 /* node is 0 or 1 so it does not have extra bits */
656 }
657 desc->max_code = max_code;
658
659 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
660 * establish sub-heaps of increasing lengths:
661 */
662 for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
663
664 /* Construct the Huffman tree by repeatedly combining the least two
665 * frequent nodes.
666 */
667 node = elems; /* next internal node of the tree */
668 do {
669 pqremove(s, tree, n); /* n = node of least frequency */
670 m = s->heap[SMALLEST]; /* m = node of next least frequency */
671
672 s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
673 s->heap[--(s->heap_max)] = m;
674
675 /* Create a new node father of n and m */
676 tree[node].Freq = tree[n].Freq + tree[m].Freq;
677 s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
678 s->depth[n] : s->depth[m]) + 1);
679 tree[n].Dad = tree[m].Dad = (ush)node;
680#ifdef DUMP_BL_TREE
681 if (tree == s->bl_tree) {
682 fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
683 node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
684 }
685#endif
686 /* and insert the new node in the heap */
687 s->heap[SMALLEST] = node++;
688 pqdownheap(s, tree, SMALLEST);
689
690 } while (s->heap_len >= 2);
691
692 s->heap[--(s->heap_max)] = s->heap[SMALLEST];
693
694 /* At this point, the fields freq and dad are set. We can now
695 * generate the bit lengths.
696 */
697 gen_bitlen(s, (tree_desc *)desc);
698
699 /* The field len is now set, we can generate the bit codes */
700 gen_codes ((ct_data *)tree, max_code, s->bl_count);
701}
702
703/* ===========================================================================
704 * Scan a literal or distance tree to determine the frequencies of the codes
705 * in the bit length tree.
706 */
707local void scan_tree (s, tree, max_code)
708 deflate_state *s;
709 ct_data *tree; /* the tree to be scanned */
710 int max_code; /* and its largest code of non zero frequency */
711{
712 int n; /* iterates over all tree elements */
713 int prevlen = -1; /* last emitted length */
714 int curlen; /* length of current code */
715 int nextlen = tree[0].Len; /* length of next code */
716 int count = 0; /* repeat count of the current code */
717 int max_count = 7; /* max repeat count */
718 int min_count = 4; /* min repeat count */
719
720 if (nextlen == 0) max_count = 138, min_count = 3;
721 tree[max_code+1].Len = (ush)0xffff; /* guard */
722
723 for (n = 0; n <= max_code; n++) {
724 curlen = nextlen; nextlen = tree[n+1].Len;
725 if (++count < max_count && curlen == nextlen) {
726 continue;
727 } else if (count < min_count) {
728 s->bl_tree[curlen].Freq += count;
729 } else if (curlen != 0) {
730 if (curlen != prevlen) s->bl_tree[curlen].Freq++;
731 s->bl_tree[REP_3_6].Freq++;
732 } else if (count <= 10) {
733 s->bl_tree[REPZ_3_10].Freq++;
734 } else {
735 s->bl_tree[REPZ_11_138].Freq++;
736 }
737 count = 0; prevlen = curlen;
738 if (nextlen == 0) {
739 max_count = 138, min_count = 3;
740 } else if (curlen == nextlen) {
741 max_count = 6, min_count = 3;
742 } else {
743 max_count = 7, min_count = 4;
744 }
745 }
746}
747
748/* ===========================================================================
749 * Send a literal or distance tree in compressed form, using the codes in
750 * bl_tree.
751 */
752local void send_tree (s, tree, max_code)
753 deflate_state *s;
754 ct_data *tree; /* the tree to be scanned */
755 int max_code; /* and its largest code of non zero frequency */
756{
757 int n; /* iterates over all tree elements */
758 int prevlen = -1; /* last emitted length */
759 int curlen; /* length of current code */
760 int nextlen = tree[0].Len; /* length of next code */
761 int count = 0; /* repeat count of the current code */
762 int max_count = 7; /* max repeat count */
763 int min_count = 4; /* min repeat count */
764
765 /* tree[max_code+1].Len = -1; */ /* guard already set */
766 if (nextlen == 0) max_count = 138, min_count = 3;
767
768 for (n = 0; n <= max_code; n++) {
769 curlen = nextlen; nextlen = tree[n+1].Len;
770 if (++count < max_count && curlen == nextlen) {
771 continue;
772 } else if (count < min_count) {
773 do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
774
775 } else if (curlen != 0) {
776 if (curlen != prevlen) {
777 send_code(s, curlen, s->bl_tree); count--;
778 }
779 Assert(count >= 3 && count <= 6, " 3_6?");
780 send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
781
782 } else if (count <= 10) {
783 send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
784
785 } else {
786 send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
787 }
788 count = 0; prevlen = curlen;
789 if (nextlen == 0) {
790 max_count = 138, min_count = 3;
791 } else if (curlen == nextlen) {
792 max_count = 6, min_count = 3;
793 } else {
794 max_count = 7, min_count = 4;
795 }
796 }
797}
798
799/* ===========================================================================
800 * Construct the Huffman tree for the bit lengths and return the index in
801 * bl_order of the last bit length code to send.
802 */
803local int build_bl_tree(s)
804 deflate_state *s;
805{
806 int max_blindex; /* index of last bit length code of non zero freq */
807
808 /* Determine the bit length frequencies for literal and distance trees */
809 scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
810 scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
811
812 /* Build the bit length tree: */
813 build_tree(s, (tree_desc *)(&(s->bl_desc)));
814 /* opt_len now includes the length of the tree representations, except
815 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
816 */
817
818 /* Determine the number of bit length codes to send. The pkzip format
819 * requires that at least 4 bit length codes be sent. (appnote.txt says
820 * 3 but the actual value used is 4.)
821 */
822 for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
823 if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
824 }
825 /* Update opt_len to include the bit length tree and counts */
826 s->opt_len += 3*(max_blindex+1) + 5+5+4;
827 Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
828 s->opt_len, s->static_len));
829
830 return max_blindex;
831}
832
833/* ===========================================================================
834 * Send the header for a block using dynamic Huffman trees: the counts, the
835 * lengths of the bit length codes, the literal tree and the distance tree.
836 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
837 */
838local void send_all_trees(s, lcodes, dcodes, blcodes)
839 deflate_state *s;
840 int lcodes, dcodes, blcodes; /* number of codes for each tree */
841{
842 int rank; /* index in bl_order */
843
844 Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
845 Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
846 "too many codes");
847 Tracev((stderr, "\nbl counts: "));
848 send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
849 send_bits(s, dcodes-1, 5);
850 send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
851 for (rank = 0; rank < blcodes; rank++) {
852 Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
853 send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
854 }
855 Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
856
857 send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
858 Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
859
860 send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
861 Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
862}
863
864/* ===========================================================================
865 * Send a stored block
866 */
867void _tr_stored_block(s, buf, stored_len, eof)
868 deflate_state *s;
869 charf *buf; /* input block */
870 ulg stored_len; /* length of input block */
871 int eof; /* true if this is the last block for a file */
872{
873 send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
874#ifdef DEBUG
875 s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
876 s->compressed_len += (stored_len + 4) << 3;
877#endif
878 copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
879}
880
881/* ===========================================================================
882 * Send one empty static block to give enough lookahead for inflate.
883 * This takes 10 bits, of which 7 may remain in the bit buffer.
884 * The current inflate code requires 9 bits of lookahead. If the
885 * last two codes for the previous block (real code plus EOB) were coded
886 * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
887 * the last real code. In this case we send two empty static blocks instead
888 * of one. (There are no problems if the previous block is stored or fixed.)
889 * To simplify the code, we assume the worst case of last real code encoded
890 * on one bit only.
891 */
892void _tr_align(s)
893 deflate_state *s;
894{
895 send_bits(s, STATIC_TREES<<1, 3);
896 send_code(s, END_BLOCK, static_ltree);
897#ifdef DEBUG
898 s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
899#endif
900 bi_flush(s);
901 /* Of the 10 bits for the empty block, we have already sent
902 * (10 - bi_valid) bits. The lookahead for the last real code (before
903 * the EOB of the previous block) was thus at least one plus the length
904 * of the EOB plus what we have just sent of the empty static block.
905 */
906 if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
907 send_bits(s, STATIC_TREES<<1, 3);
908 send_code(s, END_BLOCK, static_ltree);
909#ifdef DEBUG
910 s->compressed_len += 10L;
911#endif
912 bi_flush(s);
913 }
914 s->last_eob_len = 7;
915}
916
917/* ===========================================================================
918 * Determine the best encoding for the current block: dynamic trees, static
919 * trees or store, and output the encoded block to the zip file.
920 */
921void _tr_flush_block(s, buf, stored_len, eof)
922 deflate_state *s;
923 charf *buf; /* input block, or NULL if too old */
924 ulg stored_len; /* length of input block */
925 int eof; /* true if this is the last block for a file */
926{
927 ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
928 int max_blindex = 0; /* index of last bit length code of non zero freq */
929
930 /* Build the Huffman trees unless a stored block is forced */
931 if (s->level > 0) {
932
933 /* Check if the file is binary or text */
934 if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
935 set_data_type(s);
936
937 /* Construct the literal and distance trees */
938 build_tree(s, (tree_desc *)(&(s->l_desc)));
939 Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
940 s->static_len));
941
942 build_tree(s, (tree_desc *)(&(s->d_desc)));
943 Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
944 s->static_len));
945 /* At this point, opt_len and static_len are the total bit lengths of
946 * the compressed block data, excluding the tree representations.
947 */
948
949 /* Build the bit length tree for the above two trees, and get the index
950 * in bl_order of the last bit length code to send.
951 */
952 max_blindex = build_bl_tree(s);
953
954 /* Determine the best encoding. Compute the block lengths in bytes. */
955 opt_lenb = (s->opt_len+3+7)>>3;
956 static_lenb = (s->static_len+3+7)>>3;
957
958 Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
959 opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
960 s->last_lit));
961
962 if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
963
964 } else {
965 Assert(buf != (char*)0, "lost buf");
966 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
967 }
968
969#ifdef FORCE_STORED
970 if (buf != (char*)0) { /* force stored block */
971#else
972 if (stored_len+4 <= opt_lenb && buf != (char*)0) {
973 /* 4: two words for the lengths */
974#endif
975 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
976 * Otherwise we can't have processed more than WSIZE input bytes since
977 * the last block flush, because compression would have been
978 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
979 * transform a block into a stored block.
980 */
981 _tr_stored_block(s, buf, stored_len, eof);
982
983#ifdef FORCE_STATIC
984 } else if (static_lenb >= 0) { /* force static trees */
985#else
986 } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
987#endif
988 send_bits(s, (STATIC_TREES<<1)+eof, 3);
989 compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
990#ifdef DEBUG
991 s->compressed_len += 3 + s->static_len;
992#endif
993 } else {
994 send_bits(s, (DYN_TREES<<1)+eof, 3);
995 send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
996 max_blindex+1);
997 compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
998#ifdef DEBUG
999 s->compressed_len += 3 + s->opt_len;
1000#endif
1001 }
1002 Assert (s->compressed_len == s->bits_sent, "bad compressed size");
1003 /* The above check is made mod 2^32, for files larger than 512 MB
1004 * and uLong implemented on 32 bits.
1005 */
1006 init_block(s);
1007
1008 if (eof) {
1009 bi_windup(s);
1010#ifdef DEBUG
1011 s->compressed_len += 7; /* align on byte boundary */
1012#endif
1013 }
1014 Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
1015 s->compressed_len-7*eof));
1016}
1017
1018/* ===========================================================================
1019 * Save the match info and tally the frequency counts. Return true if
1020 * the current block must be flushed.
1021 */
1022int _tr_tally (s, dist, lc)
1023 deflate_state *s;
1024 unsigned dist; /* distance of matched string */
1025 unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
1026{
1027 s->d_buf[s->last_lit] = (ush)dist;
1028 s->l_buf[s->last_lit++] = (uch)lc;
1029 if (dist == 0) {
1030 /* lc is the unmatched char */
1031 s->dyn_ltree[lc].Freq++;
1032 } else {
1033 s->matches++;
1034 /* Here, lc is the match length - MIN_MATCH */
1035 dist--; /* dist = match distance - 1 */
1036 Assert((ush)dist < (ush)MAX_DIST(s) &&
1037 (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
1038 (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
1039
1040 s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
1041 s->dyn_dtree[d_code(dist)].Freq++;
1042 }
1043
1044#ifdef TRUNCATE_BLOCK
1045 /* Try to guess if it is profitable to stop the current block here */
1046 if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
1047 /* Compute an upper bound for the compressed length */
1048 ulg out_length = (ulg)s->last_lit*8L;
1049 ulg in_length = (ulg)((long)s->strstart - s->block_start);
1050 int dcode;
1051 for (dcode = 0; dcode < D_CODES; dcode++) {
1052 out_length += (ulg)s->dyn_dtree[dcode].Freq *
1053 (5L+extra_dbits[dcode]);
1054 }
1055 out_length >>= 3;
1056 Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
1057 s->last_lit, in_length, out_length,
1058 100L - out_length*100L/in_length));
1059 if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
1060 }
1061#endif
1062 return (s->last_lit == s->lit_bufsize-1);
1063 /* We avoid equality with lit_bufsize because of wraparound at 64K
1064 * on 16 bit machines and because stored blocks are restricted to
1065 * 64K-1 bytes.
1066 */
1067}
1068
1069/* ===========================================================================
1070 * Send the block data compressed using the given Huffman trees
1071 */
1072local void compress_block(s, ltree, dtree)
1073 deflate_state *s;
1074 ct_data *ltree; /* literal tree */
1075 ct_data *dtree; /* distance tree */
1076{
1077 unsigned dist; /* distance of matched string */
1078 int lc; /* match length or unmatched char (if dist == 0) */
1079 unsigned lx = 0; /* running index in l_buf */
1080 unsigned code; /* the code to send */
1081 int extra; /* number of extra bits to send */
1082
1083 if (s->last_lit != 0) do {
1084 dist = s->d_buf[lx];
1085 lc = s->l_buf[lx++];
1086 if (dist == 0) {
1087 send_code(s, lc, ltree); /* send a literal byte */
1088 Tracecv(isgraph(lc), (stderr," '%c' ", lc));
1089 } else {
1090 /* Here, lc is the match length - MIN_MATCH */
1091 code = _length_code[lc];
1092 send_code(s, code+LITERALS+1, ltree); /* send the length code */
1093 extra = extra_lbits[code];
1094 if (extra != 0) {
1095 lc -= base_length[code];
1096 send_bits(s, lc, extra); /* send the extra length bits */
1097 }
1098 dist--; /* dist is now the match distance - 1 */
1099 code = d_code(dist);
1100 Assert (code < D_CODES, "bad d_code");
1101
1102 send_code(s, code, dtree); /* send the distance code */
1103 extra = extra_dbits[code];
1104 if (extra != 0) {
1105 dist -= base_dist[code];
1106 send_bits(s, dist, extra); /* send the extra distance bits */
1107 }
1108 } /* literal or match pair ? */
1109
1110 /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
1111 Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
1112 "pendingBuf overflow");
1113
1114 } while (lx < s->last_lit);
1115
1116 send_code(s, END_BLOCK, ltree);
1117 s->last_eob_len = ltree[END_BLOCK].Len;
1118}
1119
1120/* ===========================================================================
1121 * Set the data type to BINARY or TEXT, using a crude approximation:
1122 * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
1123 * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
1124 * IN assertion: the fields Freq of dyn_ltree are set.
1125 */
1126local void set_data_type(s)
1127 deflate_state *s;
1128{
1129 int n;
1130
1131 for (n = 0; n < 9; n++)
1132 if (s->dyn_ltree[n].Freq != 0)
1133 break;
1134 if (n == 9)
1135 for (n = 14; n < 32; n++)
1136 if (s->dyn_ltree[n].Freq != 0)
1137 break;
1138 s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
1139}
1140
1141/* ===========================================================================
1142 * Reverse the first len bits of a code, using straightforward code (a faster
1143 * method would use a table)
1144 * IN assertion: 1 <= len <= 15
1145 */
1146local unsigned bi_reverse(code, len)
1147 unsigned code; /* the value to invert */
1148 int len; /* its bit length */
1149{
1150 register unsigned res = 0;
1151 do {
1152 res |= code & 1;
1153 code >>= 1, res <<= 1;
1154 } while (--len > 0);
1155 return res >> 1;
1156}
1157
1158/* ===========================================================================
1159 * Flush the bit buffer, keeping at most 7 bits in it.
1160 */
1161local void bi_flush(s)
1162 deflate_state *s;
1163{
1164 if (s->bi_valid == 16) {
1165 put_short(s, s->bi_buf);
1166 s->bi_buf = 0;
1167 s->bi_valid = 0;
1168 } else if (s->bi_valid >= 8) {
1169 put_byte(s, (Byte)s->bi_buf);
1170 s->bi_buf >>= 8;
1171 s->bi_valid -= 8;
1172 }
1173}
1174
1175/* ===========================================================================
1176 * Flush the bit buffer and align the output on a byte boundary
1177 */
1178local void bi_windup(s)
1179 deflate_state *s;
1180{
1181 if (s->bi_valid > 8) {
1182 put_short(s, s->bi_buf);
1183 } else if (s->bi_valid > 0) {
1184 put_byte(s, (Byte)s->bi_buf);
1185 }
1186 s->bi_buf = 0;
1187 s->bi_valid = 0;
1188#ifdef DEBUG
1189 s->bits_sent = (s->bits_sent+7) & ~7;
1190#endif
1191}
1192
1193/* ===========================================================================
1194 * Copy a stored block, storing first the length and its
1195 * one's complement if requested.
1196 */
1197local void copy_block(s, buf, len, header)
1198 deflate_state *s;
1199 charf *buf; /* the input data */
1200 unsigned len; /* its length */
1201 int header; /* true if block header must be written */
1202{
1203 bi_windup(s); /* align on byte boundary */
1204 s->last_eob_len = 8; /* enough lookahead for inflate */
1205
1206 if (header) {
1207 put_short(s, (ush)len);
1208 put_short(s, (ush)~len);
1209#ifdef DEBUG
1210 s->bits_sent += 2*16;
1211#endif
1212 }
1213#ifdef DEBUG
1214 s->bits_sent += (ulg)len<<3;
1215#endif
1216 while (len--) {
1217 put_byte(s, *buf++);
1218 }
1219}
diff --git a/utils/zenutils/libraries/zlib123/zlib/trees.h b/utils/zenutils/libraries/zlib123/zlib/trees.h
new file mode 100755
index 0000000000..1ca868b848
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/trees.h
@@ -0,0 +1,128 @@
1/* header created automatically with -DGEN_TREES_H */
2
3local const ct_data static_ltree[L_CODES+2] = {
4{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
5{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
6{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
7{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
8{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
9{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
10{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
11{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
12{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
13{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
14{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
15{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
16{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
17{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
18{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
19{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
20{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
21{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
22{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
23{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
24{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
25{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
26{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
27{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
28{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
29{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
30{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
31{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
32{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
33{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
34{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
35{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
36{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
37{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
38{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
39{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
40{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
41{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
42{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
43{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
44{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
45{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
46{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
47{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
48{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
49{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
50{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
51{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
52{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
53{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
54{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
55{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
56{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
57{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
58{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
59{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
60{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
61{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
62};
63
64local const ct_data static_dtree[D_CODES] = {
65{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
66{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
67{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
68{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
69{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
70{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
71};
72
73const uch _dist_code[DIST_CODE_LEN] = {
74 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
75 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
7610, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
7711, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
7812, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
7913, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
8013, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
8114, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
8214, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
8314, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
8415, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
8515, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
8615, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
8718, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
8823, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
8924, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
9026, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
9126, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
9227, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
9327, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
9428, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
9528, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
9628, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
9729, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
9829, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
9929, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
100};
101
102const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
103 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
10413, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
10517, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
10619, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
10721, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
10822, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
10923, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
11024, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
11125, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
11225, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
11326, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
11426, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
11527, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
116};
117
118local const int base_length[LENGTH_CODES] = {
1190, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
12064, 80, 96, 112, 128, 160, 192, 224, 0
121};
122
123local const int base_dist[D_CODES] = {
124 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
125 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
126 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
127};
128
diff --git a/utils/zenutils/libraries/zlib123/zlib/uncompr.c b/utils/zenutils/libraries/zlib123/zlib/uncompr.c
new file mode 100755
index 0000000000..ad6db0a67c
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/uncompr.c
@@ -0,0 +1,61 @@
1/* uncompr.c -- decompress a memory buffer
2 * Copyright (C) 1995-2003 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/* @(#) $Id$ */
7
8#define ZLIB_INTERNAL
9#include "zlib.h"
10
11/* ===========================================================================
12 Decompresses the source buffer into the destination buffer. sourceLen is
13 the byte length of the source buffer. Upon entry, destLen is the total
14 size of the destination buffer, which must be large enough to hold the
15 entire uncompressed data. (The size of the uncompressed data must have
16 been saved previously by the compressor and transmitted to the decompressor
17 by some mechanism outside the scope of this compression library.)
18 Upon exit, destLen is the actual size of the compressed buffer.
19 This function can be used to decompress a whole file at once if the
20 input file is mmap'ed.
21
22 uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
23 enough memory, Z_BUF_ERROR if there was not enough room in the output
24 buffer, or Z_DATA_ERROR if the input data was corrupted.
25*/
26int ZEXPORT uncompress (dest, destLen, source, sourceLen)
27 Bytef *dest;
28 uLongf *destLen;
29 const Bytef *source;
30 uLong sourceLen;
31{
32 z_stream stream;
33 int err;
34
35 stream.next_in = (Bytef*)source;
36 stream.avail_in = (uInt)sourceLen;
37 /* Check for source > 64K on 16-bit machine: */
38 if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
39
40 stream.next_out = dest;
41 stream.avail_out = (uInt)*destLen;
42 if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
43
44 stream.zalloc = (alloc_func)0;
45 stream.zfree = (free_func)0;
46
47 err = inflateInit(&stream);
48 if (err != Z_OK) return err;
49
50 err = inflate(&stream, Z_FINISH);
51 if (err != Z_STREAM_END) {
52 inflateEnd(&stream);
53 if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0))
54 return Z_DATA_ERROR;
55 return err;
56 }
57 *destLen = stream.total_out;
58
59 err = inflateEnd(&stream);
60 return err;
61}
diff --git a/utils/zenutils/libraries/zlib123/zlib/zconf.h b/utils/zenutils/libraries/zlib123/zlib/zconf.h
new file mode 100755
index 0000000000..e3b0c962e3
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/zconf.h
@@ -0,0 +1,332 @@
1/* zconf.h -- configuration of the zlib compression library
2 * Copyright (C) 1995-2005 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/* @(#) $Id$ */
7
8#ifndef ZCONF_H
9#define ZCONF_H
10
11/*
12 * If you *really* need a unique prefix for all types and library functions,
13 * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
14 */
15#ifdef Z_PREFIX
16# define deflateInit_ z_deflateInit_
17# define deflate z_deflate
18# define deflateEnd z_deflateEnd
19# define inflateInit_ z_inflateInit_
20# define inflate z_inflate
21# define inflateEnd z_inflateEnd
22# define deflateInit2_ z_deflateInit2_
23# define deflateSetDictionary z_deflateSetDictionary
24# define deflateCopy z_deflateCopy
25# define deflateReset z_deflateReset
26# define deflateParams z_deflateParams
27# define deflateBound z_deflateBound
28# define deflatePrime z_deflatePrime
29# define inflateInit2_ z_inflateInit2_
30# define inflateSetDictionary z_inflateSetDictionary
31# define inflateSync z_inflateSync
32# define inflateSyncPoint z_inflateSyncPoint
33# define inflateCopy z_inflateCopy
34# define inflateReset z_inflateReset
35# define inflateBack z_inflateBack
36# define inflateBackEnd z_inflateBackEnd
37# define compress z_compress
38# define compress2 z_compress2
39# define compressBound z_compressBound
40# define uncompress z_uncompress
41# define adler32 z_adler32
42# define crc32 z_crc32
43# define get_crc_table z_get_crc_table
44# define zError z_zError
45
46# define alloc_func z_alloc_func
47# define free_func z_free_func
48# define in_func z_in_func
49# define out_func z_out_func
50# define Byte z_Byte
51# define uInt z_uInt
52# define uLong z_uLong
53# define Bytef z_Bytef
54# define charf z_charf
55# define intf z_intf
56# define uIntf z_uIntf
57# define uLongf z_uLongf
58# define voidpf z_voidpf
59# define voidp z_voidp
60#endif
61
62#if defined(__MSDOS__) && !defined(MSDOS)
63# define MSDOS
64#endif
65#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
66# define OS2
67#endif
68#if defined(_WINDOWS) && !defined(WINDOWS)
69# define WINDOWS
70#endif
71#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
72# ifndef WIN32
73# define WIN32
74# endif
75#endif
76#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
77# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
78# ifndef SYS16BIT
79# define SYS16BIT
80# endif
81# endif
82#endif
83
84/*
85 * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
86 * than 64k bytes at a time (needed on systems with 16-bit int).
87 */
88#ifdef SYS16BIT
89# define MAXSEG_64K
90#endif
91#ifdef MSDOS
92# define UNALIGNED_OK
93#endif
94
95#ifdef __STDC_VERSION__
96# ifndef STDC
97# define STDC
98# endif
99# if __STDC_VERSION__ >= 199901L
100# ifndef STDC99
101# define STDC99
102# endif
103# endif
104#endif
105#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
106# define STDC
107#endif
108#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
109# define STDC
110#endif
111#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
112# define STDC
113#endif
114#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
115# define STDC
116#endif
117
118#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
119# define STDC
120#endif
121
122#ifndef STDC
123# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
124# define const /* note: need a more gentle solution here */
125# endif
126#endif
127
128/* Some Mac compilers merge all .h files incorrectly: */
129#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
130# define NO_DUMMY_DECL
131#endif
132
133/* Maximum value for memLevel in deflateInit2 */
134#ifndef MAX_MEM_LEVEL
135# ifdef MAXSEG_64K
136# define MAX_MEM_LEVEL 8
137# else
138# define MAX_MEM_LEVEL 9
139# endif
140#endif
141
142/* Maximum value for windowBits in deflateInit2 and inflateInit2.
143 * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
144 * created by gzip. (Files created by minigzip can still be extracted by
145 * gzip.)
146 */
147#ifndef MAX_WBITS
148# define MAX_WBITS 15 /* 32K LZ77 window */
149#endif
150
151/* The memory requirements for deflate are (in bytes):
152 (1 << (windowBits+2)) + (1 << (memLevel+9))
153 that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
154 plus a few kilobytes for small objects. For example, if you want to reduce
155 the default memory requirements from 256K to 128K, compile with
156 make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
157 Of course this will generally degrade compression (there's no free lunch).
158
159 The memory requirements for inflate are (in bytes) 1 << windowBits
160 that is, 32K for windowBits=15 (default value) plus a few kilobytes
161 for small objects.
162*/
163
164 /* Type declarations */
165
166#ifndef OF /* function prototypes */
167# ifdef STDC
168# define OF(args) args
169# else
170# define OF(args) ()
171# endif
172#endif
173
174/* The following definitions for FAR are needed only for MSDOS mixed
175 * model programming (small or medium model with some far allocations).
176 * This was tested only with MSC; for other MSDOS compilers you may have
177 * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
178 * just define FAR to be empty.
179 */
180#ifdef SYS16BIT
181# if defined(M_I86SM) || defined(M_I86MM)
182 /* MSC small or medium model */
183# define SMALL_MEDIUM
184# ifdef _MSC_VER
185# define FAR _far
186# else
187# define FAR far
188# endif
189# endif
190# if (defined(__SMALL__) || defined(__MEDIUM__))
191 /* Turbo C small or medium model */
192# define SMALL_MEDIUM
193# ifdef __BORLANDC__
194# define FAR _far
195# else
196# define FAR far
197# endif
198# endif
199#endif
200
201#if defined(WINDOWS) || defined(WIN32)
202 /* If building or using zlib as a DLL, define ZLIB_DLL.
203 * This is not mandatory, but it offers a little performance increase.
204 */
205# ifdef ZLIB_DLL
206# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
207# ifdef ZLIB_INTERNAL
208# define ZEXTERN extern __declspec(dllexport)
209# else
210# define ZEXTERN extern __declspec(dllimport)
211# endif
212# endif
213# endif /* ZLIB_DLL */
214 /* If building or using zlib with the WINAPI/WINAPIV calling convention,
215 * define ZLIB_WINAPI.
216 * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
217 */
218# ifdef ZLIB_WINAPI
219# ifdef FAR
220# undef FAR
221# endif
222# include <windows.h>
223 /* No need for _export, use ZLIB.DEF instead. */
224 /* For complete Windows compatibility, use WINAPI, not __stdcall. */
225# define ZEXPORT WINAPI
226# ifdef WIN32
227# define ZEXPORTVA WINAPIV
228# else
229# define ZEXPORTVA FAR CDECL
230# endif
231# endif
232#endif
233
234#if defined (__BEOS__)
235# ifdef ZLIB_DLL
236# ifdef ZLIB_INTERNAL
237# define ZEXPORT __declspec(dllexport)
238# define ZEXPORTVA __declspec(dllexport)
239# else
240# define ZEXPORT __declspec(dllimport)
241# define ZEXPORTVA __declspec(dllimport)
242# endif
243# endif
244#endif
245
246#ifndef ZEXTERN
247# define ZEXTERN extern
248#endif
249#ifndef ZEXPORT
250# define ZEXPORT
251#endif
252#ifndef ZEXPORTVA
253# define ZEXPORTVA
254#endif
255
256#ifndef FAR
257# define FAR
258#endif
259
260#if !defined(__MACTYPES__)
261typedef unsigned char Byte; /* 8 bits */
262#endif
263typedef unsigned int uInt; /* 16 bits or more */
264typedef unsigned long uLong; /* 32 bits or more */
265
266#ifdef SMALL_MEDIUM
267 /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
268# define Bytef Byte FAR
269#else
270 typedef Byte FAR Bytef;
271#endif
272typedef char FAR charf;
273typedef int FAR intf;
274typedef uInt FAR uIntf;
275typedef uLong FAR uLongf;
276
277#ifdef STDC
278 typedef void const *voidpc;
279 typedef void FAR *voidpf;
280 typedef void *voidp;
281#else
282 typedef Byte const *voidpc;
283 typedef Byte FAR *voidpf;
284 typedef Byte *voidp;
285#endif
286
287#if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
288# include <sys/types.h> /* for off_t */
289# include <unistd.h> /* for SEEK_* and off_t */
290# ifdef VMS
291# include <unixio.h> /* for off_t */
292# endif
293# define z_off_t off_t
294#endif
295#ifndef SEEK_SET
296# define SEEK_SET 0 /* Seek from beginning of file. */
297# define SEEK_CUR 1 /* Seek from current position. */
298# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
299#endif
300#ifndef z_off_t
301# define z_off_t long
302#endif
303
304#if defined(__OS400__)
305# define NO_vsnprintf
306#endif
307
308#if defined(__MVS__)
309# define NO_vsnprintf
310# ifdef FAR
311# undef FAR
312# endif
313#endif
314
315/* MVS linker does not support external names larger than 8 bytes */
316#if defined(__MVS__)
317# pragma map(deflateInit_,"DEIN")
318# pragma map(deflateInit2_,"DEIN2")
319# pragma map(deflateEnd,"DEEND")
320# pragma map(deflateBound,"DEBND")
321# pragma map(inflateInit_,"ININ")
322# pragma map(inflateInit2_,"ININ2")
323# pragma map(inflateEnd,"INEND")
324# pragma map(inflateSync,"INSY")
325# pragma map(inflateSetDictionary,"INSEDI")
326# pragma map(compressBound,"CMBND")
327# pragma map(inflate_table,"INTABL")
328# pragma map(inflate_fast,"INFA")
329# pragma map(inflate_copyright,"INCOPY")
330#endif
331
332#endif /* ZCONF_H */
diff --git a/utils/zenutils/libraries/zlib123/zlib/zconf.in.h b/utils/zenutils/libraries/zlib123/zlib/zconf.in.h
new file mode 100755
index 0000000000..e3b0c962e3
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/zconf.in.h
@@ -0,0 +1,332 @@
1/* zconf.h -- configuration of the zlib compression library
2 * Copyright (C) 1995-2005 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/* @(#) $Id$ */
7
8#ifndef ZCONF_H
9#define ZCONF_H
10
11/*
12 * If you *really* need a unique prefix for all types and library functions,
13 * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
14 */
15#ifdef Z_PREFIX
16# define deflateInit_ z_deflateInit_
17# define deflate z_deflate
18# define deflateEnd z_deflateEnd
19# define inflateInit_ z_inflateInit_
20# define inflate z_inflate
21# define inflateEnd z_inflateEnd
22# define deflateInit2_ z_deflateInit2_
23# define deflateSetDictionary z_deflateSetDictionary
24# define deflateCopy z_deflateCopy
25# define deflateReset z_deflateReset
26# define deflateParams z_deflateParams
27# define deflateBound z_deflateBound
28# define deflatePrime z_deflatePrime
29# define inflateInit2_ z_inflateInit2_
30# define inflateSetDictionary z_inflateSetDictionary
31# define inflateSync z_inflateSync
32# define inflateSyncPoint z_inflateSyncPoint
33# define inflateCopy z_inflateCopy
34# define inflateReset z_inflateReset
35# define inflateBack z_inflateBack
36# define inflateBackEnd z_inflateBackEnd
37# define compress z_compress
38# define compress2 z_compress2
39# define compressBound z_compressBound
40# define uncompress z_uncompress
41# define adler32 z_adler32
42# define crc32 z_crc32
43# define get_crc_table z_get_crc_table
44# define zError z_zError
45
46# define alloc_func z_alloc_func
47# define free_func z_free_func
48# define in_func z_in_func
49# define out_func z_out_func
50# define Byte z_Byte
51# define uInt z_uInt
52# define uLong z_uLong
53# define Bytef z_Bytef
54# define charf z_charf
55# define intf z_intf
56# define uIntf z_uIntf
57# define uLongf z_uLongf
58# define voidpf z_voidpf
59# define voidp z_voidp
60#endif
61
62#if defined(__MSDOS__) && !defined(MSDOS)
63# define MSDOS
64#endif
65#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
66# define OS2
67#endif
68#if defined(_WINDOWS) && !defined(WINDOWS)
69# define WINDOWS
70#endif
71#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
72# ifndef WIN32
73# define WIN32
74# endif
75#endif
76#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
77# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
78# ifndef SYS16BIT
79# define SYS16BIT
80# endif
81# endif
82#endif
83
84/*
85 * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
86 * than 64k bytes at a time (needed on systems with 16-bit int).
87 */
88#ifdef SYS16BIT
89# define MAXSEG_64K
90#endif
91#ifdef MSDOS
92# define UNALIGNED_OK
93#endif
94
95#ifdef __STDC_VERSION__
96# ifndef STDC
97# define STDC
98# endif
99# if __STDC_VERSION__ >= 199901L
100# ifndef STDC99
101# define STDC99
102# endif
103# endif
104#endif
105#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
106# define STDC
107#endif
108#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
109# define STDC
110#endif
111#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
112# define STDC
113#endif
114#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
115# define STDC
116#endif
117
118#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
119# define STDC
120#endif
121
122#ifndef STDC
123# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
124# define const /* note: need a more gentle solution here */
125# endif
126#endif
127
128/* Some Mac compilers merge all .h files incorrectly: */
129#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
130# define NO_DUMMY_DECL
131#endif
132
133/* Maximum value for memLevel in deflateInit2 */
134#ifndef MAX_MEM_LEVEL
135# ifdef MAXSEG_64K
136# define MAX_MEM_LEVEL 8
137# else
138# define MAX_MEM_LEVEL 9
139# endif
140#endif
141
142/* Maximum value for windowBits in deflateInit2 and inflateInit2.
143 * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
144 * created by gzip. (Files created by minigzip can still be extracted by
145 * gzip.)
146 */
147#ifndef MAX_WBITS
148# define MAX_WBITS 15 /* 32K LZ77 window */
149#endif
150
151/* The memory requirements for deflate are (in bytes):
152 (1 << (windowBits+2)) + (1 << (memLevel+9))
153 that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
154 plus a few kilobytes for small objects. For example, if you want to reduce
155 the default memory requirements from 256K to 128K, compile with
156 make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
157 Of course this will generally degrade compression (there's no free lunch).
158
159 The memory requirements for inflate are (in bytes) 1 << windowBits
160 that is, 32K for windowBits=15 (default value) plus a few kilobytes
161 for small objects.
162*/
163
164 /* Type declarations */
165
166#ifndef OF /* function prototypes */
167# ifdef STDC
168# define OF(args) args
169# else
170# define OF(args) ()
171# endif
172#endif
173
174/* The following definitions for FAR are needed only for MSDOS mixed
175 * model programming (small or medium model with some far allocations).
176 * This was tested only with MSC; for other MSDOS compilers you may have
177 * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
178 * just define FAR to be empty.
179 */
180#ifdef SYS16BIT
181# if defined(M_I86SM) || defined(M_I86MM)
182 /* MSC small or medium model */
183# define SMALL_MEDIUM
184# ifdef _MSC_VER
185# define FAR _far
186# else
187# define FAR far
188# endif
189# endif
190# if (defined(__SMALL__) || defined(__MEDIUM__))
191 /* Turbo C small or medium model */
192# define SMALL_MEDIUM
193# ifdef __BORLANDC__
194# define FAR _far
195# else
196# define FAR far
197# endif
198# endif
199#endif
200
201#if defined(WINDOWS) || defined(WIN32)
202 /* If building or using zlib as a DLL, define ZLIB_DLL.
203 * This is not mandatory, but it offers a little performance increase.
204 */
205# ifdef ZLIB_DLL
206# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
207# ifdef ZLIB_INTERNAL
208# define ZEXTERN extern __declspec(dllexport)
209# else
210# define ZEXTERN extern __declspec(dllimport)
211# endif
212# endif
213# endif /* ZLIB_DLL */
214 /* If building or using zlib with the WINAPI/WINAPIV calling convention,
215 * define ZLIB_WINAPI.
216 * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
217 */
218# ifdef ZLIB_WINAPI
219# ifdef FAR
220# undef FAR
221# endif
222# include <windows.h>
223 /* No need for _export, use ZLIB.DEF instead. */
224 /* For complete Windows compatibility, use WINAPI, not __stdcall. */
225# define ZEXPORT WINAPI
226# ifdef WIN32
227# define ZEXPORTVA WINAPIV
228# else
229# define ZEXPORTVA FAR CDECL
230# endif
231# endif
232#endif
233
234#if defined (__BEOS__)
235# ifdef ZLIB_DLL
236# ifdef ZLIB_INTERNAL
237# define ZEXPORT __declspec(dllexport)
238# define ZEXPORTVA __declspec(dllexport)
239# else
240# define ZEXPORT __declspec(dllimport)
241# define ZEXPORTVA __declspec(dllimport)
242# endif
243# endif
244#endif
245
246#ifndef ZEXTERN
247# define ZEXTERN extern
248#endif
249#ifndef ZEXPORT
250# define ZEXPORT
251#endif
252#ifndef ZEXPORTVA
253# define ZEXPORTVA
254#endif
255
256#ifndef FAR
257# define FAR
258#endif
259
260#if !defined(__MACTYPES__)
261typedef unsigned char Byte; /* 8 bits */
262#endif
263typedef unsigned int uInt; /* 16 bits or more */
264typedef unsigned long uLong; /* 32 bits or more */
265
266#ifdef SMALL_MEDIUM
267 /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
268# define Bytef Byte FAR
269#else
270 typedef Byte FAR Bytef;
271#endif
272typedef char FAR charf;
273typedef int FAR intf;
274typedef uInt FAR uIntf;
275typedef uLong FAR uLongf;
276
277#ifdef STDC
278 typedef void const *voidpc;
279 typedef void FAR *voidpf;
280 typedef void *voidp;
281#else
282 typedef Byte const *voidpc;
283 typedef Byte FAR *voidpf;
284 typedef Byte *voidp;
285#endif
286
287#if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
288# include <sys/types.h> /* for off_t */
289# include <unistd.h> /* for SEEK_* and off_t */
290# ifdef VMS
291# include <unixio.h> /* for off_t */
292# endif
293# define z_off_t off_t
294#endif
295#ifndef SEEK_SET
296# define SEEK_SET 0 /* Seek from beginning of file. */
297# define SEEK_CUR 1 /* Seek from current position. */
298# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
299#endif
300#ifndef z_off_t
301# define z_off_t long
302#endif
303
304#if defined(__OS400__)
305# define NO_vsnprintf
306#endif
307
308#if defined(__MVS__)
309# define NO_vsnprintf
310# ifdef FAR
311# undef FAR
312# endif
313#endif
314
315/* MVS linker does not support external names larger than 8 bytes */
316#if defined(__MVS__)
317# pragma map(deflateInit_,"DEIN")
318# pragma map(deflateInit2_,"DEIN2")
319# pragma map(deflateEnd,"DEEND")
320# pragma map(deflateBound,"DEBND")
321# pragma map(inflateInit_,"ININ")
322# pragma map(inflateInit2_,"ININ2")
323# pragma map(inflateEnd,"INEND")
324# pragma map(inflateSync,"INSY")
325# pragma map(inflateSetDictionary,"INSEDI")
326# pragma map(compressBound,"CMBND")
327# pragma map(inflate_table,"INTABL")
328# pragma map(inflate_fast,"INFA")
329# pragma map(inflate_copyright,"INCOPY")
330#endif
331
332#endif /* ZCONF_H */
diff --git a/utils/zenutils/libraries/zlib123/zlib/zlib.3 b/utils/zenutils/libraries/zlib123/zlib/zlib.3
new file mode 100755
index 0000000000..f6b0da1176
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/zlib.3
@@ -0,0 +1,159 @@
1.TH ZLIB 3 "18 July 2005"
2.SH NAME
3zlib \- compression/decompression library
4.SH SYNOPSIS
5[see
6.I zlib.h
7for full description]
8.SH DESCRIPTION
9The
10.I zlib
11library is a general purpose data compression library.
12The code is thread safe.
13It provides in-memory compression and decompression functions,
14including integrity checks of the uncompressed data.
15This version of the library supports only one compression method (deflation)
16but other algorithms will be added later
17and will have the same stream interface.
18.LP
19Compression can be done in a single step if the buffers are large enough
20(for example if an input file is mmap'ed),
21or can be done by repeated calls of the compression function.
22In the latter case,
23the application must provide more input and/or consume the output
24(providing more output space) before each call.
25.LP
26The library also supports reading and writing files in
27.IR gzip (1)
28(.gz) format
29with an interface similar to that of stdio.
30.LP
31The library does not install any signal handler.
32The decoder checks the consistency of the compressed data,
33so the library should never crash even in case of corrupted input.
34.LP
35All functions of the compression library are documented in the file
36.IR zlib.h .
37The distribution source includes examples of use of the library
38in the files
39.I example.c
40and
41.IR minigzip.c .
42.LP
43Changes to this version are documented in the file
44.I ChangeLog
45that accompanies the source,
46and are concerned primarily with bug fixes and portability enhancements.
47.LP
48A Java implementation of
49.I zlib
50is available in the Java Development Kit 1.1:
51.IP
52http://www.javasoft.com/products/JDK/1.1/docs/api/Package-java.util.zip.html
53.LP
54A Perl interface to
55.IR zlib ,
56written by Paul Marquess (pmqs@cpan.org),
57is available at CPAN (Comprehensive Perl Archive Network) sites,
58including:
59.IP
60http://www.cpan.org/modules/by-module/Compress/
61.LP
62A Python interface to
63.IR zlib ,
64written by A.M. Kuchling (amk@magnet.com),
65is available in Python 1.5 and later versions:
66.IP
67http://www.python.org/doc/lib/module-zlib.html
68.LP
69A
70.I zlib
71binding for
72.IR tcl (1),
73written by Andreas Kupries (a.kupries@westend.com),
74is availlable at:
75.IP
76http://www.westend.com/~kupries/doc/trf/man/man.html
77.LP
78An experimental package to read and write files in .zip format,
79written on top of
80.I zlib
81by Gilles Vollant (info@winimage.com),
82is available at:
83.IP
84http://www.winimage.com/zLibDll/unzip.html
85and also in the
86.I contrib/minizip
87directory of the main
88.I zlib
89web site.
90.SH "SEE ALSO"
91The
92.I zlib
93web site can be found at either of these locations:
94.IP
95http://www.zlib.org
96.br
97http://www.gzip.org/zlib/
98.LP
99The data format used by the zlib library is described by RFC
100(Request for Comments) 1950 to 1952 in the files:
101.IP
102http://www.ietf.org/rfc/rfc1950.txt (concerning zlib format)
103.br
104http://www.ietf.org/rfc/rfc1951.txt (concerning deflate format)
105.br
106http://www.ietf.org/rfc/rfc1952.txt (concerning gzip format)
107.LP
108These documents are also available in other formats from:
109.IP
110ftp://ftp.uu.net/graphics/png/documents/zlib/zdoc-index.html
111.LP
112Mark Nelson (markn@ieee.org) wrote an article about
113.I zlib
114for the Jan. 1997 issue of Dr. Dobb's Journal;
115a copy of the article is available at:
116.IP
117http://dogma.net/markn/articles/zlibtool/zlibtool.htm
118.SH "REPORTING PROBLEMS"
119Before reporting a problem,
120please check the
121.I zlib
122web site to verify that you have the latest version of
123.IR zlib ;
124otherwise,
125obtain the latest version and see if the problem still exists.
126Please read the
127.I zlib
128FAQ at:
129.IP
130http://www.gzip.org/zlib/zlib_faq.html
131.LP
132before asking for help.
133Send questions and/or comments to zlib@gzip.org,
134or (for the Windows DLL version) to Gilles Vollant (info@winimage.com).
135.SH AUTHORS
136Version 1.2.3
137Copyright (C) 1995-2005 Jean-loup Gailly (jloup@gzip.org)
138and Mark Adler (madler@alumni.caltech.edu).
139.LP
140This software is provided "as-is,"
141without any express or implied warranty.
142In no event will the authors be held liable for any damages
143arising from the use of this software.
144See the distribution directory with respect to requirements
145governing redistribution.
146The deflate format used by
147.I zlib
148was defined by Phil Katz.
149The deflate and
150.I zlib
151specifications were written by L. Peter Deutsch.
152Thanks to all the people who reported problems and suggested various
153improvements in
154.IR zlib ;
155who are too numerous to cite here.
156.LP
157UNIX manual page by R. P. C. Rodgers,
158U.S. National Library of Medicine (rodgers@nlm.nih.gov).
159.\" end of man page
diff --git a/utils/zenutils/libraries/zlib123/zlib/zlib.h b/utils/zenutils/libraries/zlib123/zlib/zlib.h
new file mode 100755
index 0000000000..62d0e4675b
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/zlib.h
@@ -0,0 +1,1357 @@
1/* zlib.h -- interface of the 'zlib' general purpose compression library
2 version 1.2.3, July 18th, 2005
3
4 Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler
5
6 This software is provided 'as-is', without any express or implied
7 warranty. In no event will the authors be held liable for any damages
8 arising from the use of this software.
9
10 Permission is granted to anyone to use this software for any purpose,
11 including commercial applications, and to alter it and redistribute it
12 freely, subject to the following restrictions:
13
14 1. The origin of this software must not be misrepresented; you must not
15 claim that you wrote the original software. If you use this software
16 in a product, an acknowledgment in the product documentation would be
17 appreciated but is not required.
18 2. Altered source versions must be plainly marked as such, and must not be
19 misrepresented as being the original software.
20 3. This notice may not be removed or altered from any source distribution.
21
22 Jean-loup Gailly Mark Adler
23 jloup@gzip.org madler@alumni.caltech.edu
24
25
26 The data format used by the zlib library is described by RFCs (Request for
27 Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt
28 (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
29*/
30
31#ifndef ZLIB_H
32#define ZLIB_H
33
34#include "zconf.h"
35
36#ifdef __cplusplus
37extern "C" {
38#endif
39
40#define ZLIB_VERSION "1.2.3"
41#define ZLIB_VERNUM 0x1230
42
43/*
44 The 'zlib' compression library provides in-memory compression and
45 decompression functions, including integrity checks of the uncompressed
46 data. This version of the library supports only one compression method
47 (deflation) but other algorithms will be added later and will have the same
48 stream interface.
49
50 Compression can be done in a single step if the buffers are large
51 enough (for example if an input file is mmap'ed), or can be done by
52 repeated calls of the compression function. In the latter case, the
53 application must provide more input and/or consume the output
54 (providing more output space) before each call.
55
56 The compressed data format used by default by the in-memory functions is
57 the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
58 around a deflate stream, which is itself documented in RFC 1951.
59
60 The library also supports reading and writing files in gzip (.gz) format
61 with an interface similar to that of stdio using the functions that start
62 with "gz". The gzip format is different from the zlib format. gzip is a
63 gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
64
65 This library can optionally read and write gzip streams in memory as well.
66
67 The zlib format was designed to be compact and fast for use in memory
68 and on communications channels. The gzip format was designed for single-
69 file compression on file systems, has a larger header than zlib to maintain
70 directory information, and uses a different, slower check method than zlib.
71
72 The library does not install any signal handler. The decoder checks
73 the consistency of the compressed data, so the library should never
74 crash even in case of corrupted input.
75*/
76
77typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
78typedef void (*free_func) OF((voidpf opaque, voidpf address));
79
80struct internal_state;
81
82typedef struct z_stream_s {
83 Bytef *next_in; /* next input byte */
84 uInt avail_in; /* number of bytes available at next_in */
85 uLong total_in; /* total nb of input bytes read so far */
86
87 Bytef *next_out; /* next output byte should be put there */
88 uInt avail_out; /* remaining free space at next_out */
89 uLong total_out; /* total nb of bytes output so far */
90
91 char *msg; /* last error message, NULL if no error */
92 struct internal_state FAR *state; /* not visible by applications */
93
94 alloc_func zalloc; /* used to allocate the internal state */
95 free_func zfree; /* used to free the internal state */
96 voidpf opaque; /* private data object passed to zalloc and zfree */
97
98 int data_type; /* best guess about the data type: binary or text */
99 uLong adler; /* adler32 value of the uncompressed data */
100 uLong reserved; /* reserved for future use */
101} z_stream;
102
103typedef z_stream FAR *z_streamp;
104
105/*
106 gzip header information passed to and from zlib routines. See RFC 1952
107 for more details on the meanings of these fields.
108*/
109typedef struct gz_header_s {
110 int text; /* true if compressed data believed to be text */
111 uLong time; /* modification time */
112 int xflags; /* extra flags (not used when writing a gzip file) */
113 int os; /* operating system */
114 Bytef *extra; /* pointer to extra field or Z_NULL if none */
115 uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
116 uInt extra_max; /* space at extra (only when reading header) */
117 Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
118 uInt name_max; /* space at name (only when reading header) */
119 Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
120 uInt comm_max; /* space at comment (only when reading header) */
121 int hcrc; /* true if there was or will be a header crc */
122 int done; /* true when done reading gzip header (not used
123 when writing a gzip file) */
124} gz_header;
125
126typedef gz_header FAR *gz_headerp;
127
128/*
129 The application must update next_in and avail_in when avail_in has
130 dropped to zero. It must update next_out and avail_out when avail_out
131 has dropped to zero. The application must initialize zalloc, zfree and
132 opaque before calling the init function. All other fields are set by the
133 compression library and must not be updated by the application.
134
135 The opaque value provided by the application will be passed as the first
136 parameter for calls of zalloc and zfree. This can be useful for custom
137 memory management. The compression library attaches no meaning to the
138 opaque value.
139
140 zalloc must return Z_NULL if there is not enough memory for the object.
141 If zlib is used in a multi-threaded application, zalloc and zfree must be
142 thread safe.
143
144 On 16-bit systems, the functions zalloc and zfree must be able to allocate
145 exactly 65536 bytes, but will not be required to allocate more than this
146 if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
147 pointers returned by zalloc for objects of exactly 65536 bytes *must*
148 have their offset normalized to zero. The default allocation function
149 provided by this library ensures this (see zutil.c). To reduce memory
150 requirements and avoid any allocation of 64K objects, at the expense of
151 compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
152
153 The fields total_in and total_out can be used for statistics or
154 progress reports. After compression, total_in holds the total size of
155 the uncompressed data and may be saved for use in the decompressor
156 (particularly if the decompressor wants to decompress everything in
157 a single step).
158*/
159
160 /* constants */
161
162#define Z_NO_FLUSH 0
163#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
164#define Z_SYNC_FLUSH 2
165#define Z_FULL_FLUSH 3
166#define Z_FINISH 4
167#define Z_BLOCK 5
168/* Allowed flush values; see deflate() and inflate() below for details */
169
170#define Z_OK 0
171#define Z_STREAM_END 1
172#define Z_NEED_DICT 2
173#define Z_ERRNO (-1)
174#define Z_STREAM_ERROR (-2)
175#define Z_DATA_ERROR (-3)
176#define Z_MEM_ERROR (-4)
177#define Z_BUF_ERROR (-5)
178#define Z_VERSION_ERROR (-6)
179/* Return codes for the compression/decompression functions. Negative
180 * values are errors, positive values are used for special but normal events.
181 */
182
183#define Z_NO_COMPRESSION 0
184#define Z_BEST_SPEED 1
185#define Z_BEST_COMPRESSION 9
186#define Z_DEFAULT_COMPRESSION (-1)
187/* compression levels */
188
189#define Z_FILTERED 1
190#define Z_HUFFMAN_ONLY 2
191#define Z_RLE 3
192#define Z_FIXED 4
193#define Z_DEFAULT_STRATEGY 0
194/* compression strategy; see deflateInit2() below for details */
195
196#define Z_BINARY 0
197#define Z_TEXT 1
198#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
199#define Z_UNKNOWN 2
200/* Possible values of the data_type field (though see inflate()) */
201
202#define Z_DEFLATED 8
203/* The deflate compression method (the only one supported in this version) */
204
205#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
206
207#define zlib_version zlibVersion()
208/* for compatibility with versions < 1.0.2 */
209
210 /* basic functions */
211
212ZEXTERN const char * ZEXPORT zlibVersion OF((void));
213/* The application can compare zlibVersion and ZLIB_VERSION for consistency.
214 If the first character differs, the library code actually used is
215 not compatible with the zlib.h header file used by the application.
216 This check is automatically made by deflateInit and inflateInit.
217 */
218
219/*
220ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
221
222 Initializes the internal stream state for compression. The fields
223 zalloc, zfree and opaque must be initialized before by the caller.
224 If zalloc and zfree are set to Z_NULL, deflateInit updates them to
225 use default allocation functions.
226
227 The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
228 1 gives best speed, 9 gives best compression, 0 gives no compression at
229 all (the input data is simply copied a block at a time).
230 Z_DEFAULT_COMPRESSION requests a default compromise between speed and
231 compression (currently equivalent to level 6).
232
233 deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
234 enough memory, Z_STREAM_ERROR if level is not a valid compression level,
235 Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
236 with the version assumed by the caller (ZLIB_VERSION).
237 msg is set to null if there is no error message. deflateInit does not
238 perform any compression: this will be done by deflate().
239*/
240
241
242ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
243/*
244 deflate compresses as much data as possible, and stops when the input
245 buffer becomes empty or the output buffer becomes full. It may introduce some
246 output latency (reading input without producing any output) except when
247 forced to flush.
248
249 The detailed semantics are as follows. deflate performs one or both of the
250 following actions:
251
252 - Compress more input starting at next_in and update next_in and avail_in
253 accordingly. If not all input can be processed (because there is not
254 enough room in the output buffer), next_in and avail_in are updated and
255 processing will resume at this point for the next call of deflate().
256
257 - Provide more output starting at next_out and update next_out and avail_out
258 accordingly. This action is forced if the parameter flush is non zero.
259 Forcing flush frequently degrades the compression ratio, so this parameter
260 should be set only when necessary (in interactive applications).
261 Some output may be provided even if flush is not set.
262
263 Before the call of deflate(), the application should ensure that at least
264 one of the actions is possible, by providing more input and/or consuming
265 more output, and updating avail_in or avail_out accordingly; avail_out
266 should never be zero before the call. The application can consume the
267 compressed output when it wants, for example when the output buffer is full
268 (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
269 and with zero avail_out, it must be called again after making room in the
270 output buffer because there might be more output pending.
271
272 Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
273 decide how much data to accumualte before producing output, in order to
274 maximize compression.
275
276 If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
277 flushed to the output buffer and the output is aligned on a byte boundary, so
278 that the decompressor can get all input data available so far. (In particular
279 avail_in is zero after the call if enough output space has been provided
280 before the call.) Flushing may degrade compression for some compression
281 algorithms and so it should be used only when necessary.
282
283 If flush is set to Z_FULL_FLUSH, all output is flushed as with
284 Z_SYNC_FLUSH, and the compression state is reset so that decompression can
285 restart from this point if previous compressed data has been damaged or if
286 random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
287 compression.
288
289 If deflate returns with avail_out == 0, this function must be called again
290 with the same value of the flush parameter and more output space (updated
291 avail_out), until the flush is complete (deflate returns with non-zero
292 avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
293 avail_out is greater than six to avoid repeated flush markers due to
294 avail_out == 0 on return.
295
296 If the parameter flush is set to Z_FINISH, pending input is processed,
297 pending output is flushed and deflate returns with Z_STREAM_END if there
298 was enough output space; if deflate returns with Z_OK, this function must be
299 called again with Z_FINISH and more output space (updated avail_out) but no
300 more input data, until it returns with Z_STREAM_END or an error. After
301 deflate has returned Z_STREAM_END, the only possible operations on the
302 stream are deflateReset or deflateEnd.
303
304 Z_FINISH can be used immediately after deflateInit if all the compression
305 is to be done in a single step. In this case, avail_out must be at least
306 the value returned by deflateBound (see below). If deflate does not return
307 Z_STREAM_END, then it must be called again as described above.
308
309 deflate() sets strm->adler to the adler32 checksum of all input read
310 so far (that is, total_in bytes).
311
312 deflate() may update strm->data_type if it can make a good guess about
313 the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
314 binary. This field is only for information purposes and does not affect
315 the compression algorithm in any manner.
316
317 deflate() returns Z_OK if some progress has been made (more input
318 processed or more output produced), Z_STREAM_END if all input has been
319 consumed and all output has been produced (only when flush is set to
320 Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
321 if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
322 (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
323 fatal, and deflate() can be called again with more input and more output
324 space to continue compressing.
325*/
326
327
328ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
329/*
330 All dynamically allocated data structures for this stream are freed.
331 This function discards any unprocessed input and does not flush any
332 pending output.
333
334 deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
335 stream state was inconsistent, Z_DATA_ERROR if the stream was freed
336 prematurely (some input or output was discarded). In the error case,
337 msg may be set but then points to a static string (which must not be
338 deallocated).
339*/
340
341
342/*
343ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
344
345 Initializes the internal stream state for decompression. The fields
346 next_in, avail_in, zalloc, zfree and opaque must be initialized before by
347 the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
348 value depends on the compression method), inflateInit determines the
349 compression method from the zlib header and allocates all data structures
350 accordingly; otherwise the allocation will be deferred to the first call of
351 inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
352 use default allocation functions.
353
354 inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
355 memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
356 version assumed by the caller. msg is set to null if there is no error
357 message. inflateInit does not perform any decompression apart from reading
358 the zlib header if present: this will be done by inflate(). (So next_in and
359 avail_in may be modified, but next_out and avail_out are unchanged.)
360*/
361
362
363ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
364/*
365 inflate decompresses as much data as possible, and stops when the input
366 buffer becomes empty or the output buffer becomes full. It may introduce
367 some output latency (reading input without producing any output) except when
368 forced to flush.
369
370 The detailed semantics are as follows. inflate performs one or both of the
371 following actions:
372
373 - Decompress more input starting at next_in and update next_in and avail_in
374 accordingly. If not all input can be processed (because there is not
375 enough room in the output buffer), next_in is updated and processing
376 will resume at this point for the next call of inflate().
377
378 - Provide more output starting at next_out and update next_out and avail_out
379 accordingly. inflate() provides as much output as possible, until there
380 is no more input data or no more space in the output buffer (see below
381 about the flush parameter).
382
383 Before the call of inflate(), the application should ensure that at least
384 one of the actions is possible, by providing more input and/or consuming
385 more output, and updating the next_* and avail_* values accordingly.
386 The application can consume the uncompressed output when it wants, for
387 example when the output buffer is full (avail_out == 0), or after each
388 call of inflate(). If inflate returns Z_OK and with zero avail_out, it
389 must be called again after making room in the output buffer because there
390 might be more output pending.
391
392 The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
393 Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
394 output as possible to the output buffer. Z_BLOCK requests that inflate() stop
395 if and when it gets to the next deflate block boundary. When decoding the
396 zlib or gzip format, this will cause inflate() to return immediately after
397 the header and before the first block. When doing a raw inflate, inflate()
398 will go ahead and process the first block, and will return when it gets to
399 the end of that block, or when it runs out of data.
400
401 The Z_BLOCK option assists in appending to or combining deflate streams.
402 Also to assist in this, on return inflate() will set strm->data_type to the
403 number of unused bits in the last byte taken from strm->next_in, plus 64
404 if inflate() is currently decoding the last block in the deflate stream,
405 plus 128 if inflate() returned immediately after decoding an end-of-block
406 code or decoding the complete header up to just before the first byte of the
407 deflate stream. The end-of-block will not be indicated until all of the
408 uncompressed data from that block has been written to strm->next_out. The
409 number of unused bits may in general be greater than seven, except when
410 bit 7 of data_type is set, in which case the number of unused bits will be
411 less than eight.
412
413 inflate() should normally be called until it returns Z_STREAM_END or an
414 error. However if all decompression is to be performed in a single step
415 (a single call of inflate), the parameter flush should be set to
416 Z_FINISH. In this case all pending input is processed and all pending
417 output is flushed; avail_out must be large enough to hold all the
418 uncompressed data. (The size of the uncompressed data may have been saved
419 by the compressor for this purpose.) The next operation on this stream must
420 be inflateEnd to deallocate the decompression state. The use of Z_FINISH
421 is never required, but can be used to inform inflate that a faster approach
422 may be used for the single inflate() call.
423
424 In this implementation, inflate() always flushes as much output as
425 possible to the output buffer, and always uses the faster approach on the
426 first call. So the only effect of the flush parameter in this implementation
427 is on the return value of inflate(), as noted below, or when it returns early
428 because Z_BLOCK is used.
429
430 If a preset dictionary is needed after this call (see inflateSetDictionary
431 below), inflate sets strm->adler to the adler32 checksum of the dictionary
432 chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
433 strm->adler to the adler32 checksum of all output produced so far (that is,
434 total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
435 below. At the end of the stream, inflate() checks that its computed adler32
436 checksum is equal to that saved by the compressor and returns Z_STREAM_END
437 only if the checksum is correct.
438
439 inflate() will decompress and check either zlib-wrapped or gzip-wrapped
440 deflate data. The header type is detected automatically. Any information
441 contained in the gzip header is not retained, so applications that need that
442 information should instead use raw inflate, see inflateInit2() below, or
443 inflateBack() and perform their own processing of the gzip header and
444 trailer.
445
446 inflate() returns Z_OK if some progress has been made (more input processed
447 or more output produced), Z_STREAM_END if the end of the compressed data has
448 been reached and all uncompressed output has been produced, Z_NEED_DICT if a
449 preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
450 corrupted (input stream not conforming to the zlib format or incorrect check
451 value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
452 if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
453 Z_BUF_ERROR if no progress is possible or if there was not enough room in the
454 output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
455 inflate() can be called again with more input and more output space to
456 continue decompressing. If Z_DATA_ERROR is returned, the application may then
457 call inflateSync() to look for a good compression block if a partial recovery
458 of the data is desired.
459*/
460
461
462ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
463/*
464 All dynamically allocated data structures for this stream are freed.
465 This function discards any unprocessed input and does not flush any
466 pending output.
467
468 inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
469 was inconsistent. In the error case, msg may be set but then points to a
470 static string (which must not be deallocated).
471*/
472
473 /* Advanced functions */
474
475/*
476 The following functions are needed only in some special applications.
477*/
478
479/*
480ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
481 int level,
482 int method,
483 int windowBits,
484 int memLevel,
485 int strategy));
486
487 This is another version of deflateInit with more compression options. The
488 fields next_in, zalloc, zfree and opaque must be initialized before by
489 the caller.
490
491 The method parameter is the compression method. It must be Z_DEFLATED in
492 this version of the library.
493
494 The windowBits parameter is the base two logarithm of the window size
495 (the size of the history buffer). It should be in the range 8..15 for this
496 version of the library. Larger values of this parameter result in better
497 compression at the expense of memory usage. The default value is 15 if
498 deflateInit is used instead.
499
500 windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
501 determines the window size. deflate() will then generate raw deflate data
502 with no zlib header or trailer, and will not compute an adler32 check value.
503
504 windowBits can also be greater than 15 for optional gzip encoding. Add
505 16 to windowBits to write a simple gzip header and trailer around the
506 compressed data instead of a zlib wrapper. The gzip header will have no
507 file name, no extra data, no comment, no modification time (set to zero),
508 no header crc, and the operating system will be set to 255 (unknown). If a
509 gzip stream is being written, strm->adler is a crc32 instead of an adler32.
510
511 The memLevel parameter specifies how much memory should be allocated
512 for the internal compression state. memLevel=1 uses minimum memory but
513 is slow and reduces compression ratio; memLevel=9 uses maximum memory
514 for optimal speed. The default value is 8. See zconf.h for total memory
515 usage as a function of windowBits and memLevel.
516
517 The strategy parameter is used to tune the compression algorithm. Use the
518 value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
519 filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
520 string match), or Z_RLE to limit match distances to one (run-length
521 encoding). Filtered data consists mostly of small values with a somewhat
522 random distribution. In this case, the compression algorithm is tuned to
523 compress them better. The effect of Z_FILTERED is to force more Huffman
524 coding and less string matching; it is somewhat intermediate between
525 Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
526 Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
527 parameter only affects the compression ratio but not the correctness of the
528 compressed output even if it is not set appropriately. Z_FIXED prevents the
529 use of dynamic Huffman codes, allowing for a simpler decoder for special
530 applications.
531
532 deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
533 memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
534 method). msg is set to null if there is no error message. deflateInit2 does
535 not perform any compression: this will be done by deflate().
536*/
537
538ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
539 const Bytef *dictionary,
540 uInt dictLength));
541/*
542 Initializes the compression dictionary from the given byte sequence
543 without producing any compressed output. This function must be called
544 immediately after deflateInit, deflateInit2 or deflateReset, before any
545 call of deflate. The compressor and decompressor must use exactly the same
546 dictionary (see inflateSetDictionary).
547
548 The dictionary should consist of strings (byte sequences) that are likely
549 to be encountered later in the data to be compressed, with the most commonly
550 used strings preferably put towards the end of the dictionary. Using a
551 dictionary is most useful when the data to be compressed is short and can be
552 predicted with good accuracy; the data can then be compressed better than
553 with the default empty dictionary.
554
555 Depending on the size of the compression data structures selected by
556 deflateInit or deflateInit2, a part of the dictionary may in effect be
557 discarded, for example if the dictionary is larger than the window size in
558 deflate or deflate2. Thus the strings most likely to be useful should be
559 put at the end of the dictionary, not at the front. In addition, the
560 current implementation of deflate will use at most the window size minus
561 262 bytes of the provided dictionary.
562
563 Upon return of this function, strm->adler is set to the adler32 value
564 of the dictionary; the decompressor may later use this value to determine
565 which dictionary has been used by the compressor. (The adler32 value
566 applies to the whole dictionary even if only a subset of the dictionary is
567 actually used by the compressor.) If a raw deflate was requested, then the
568 adler32 value is not computed and strm->adler is not set.
569
570 deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
571 parameter is invalid (such as NULL dictionary) or the stream state is
572 inconsistent (for example if deflate has already been called for this stream
573 or if the compression method is bsort). deflateSetDictionary does not
574 perform any compression: this will be done by deflate().
575*/
576
577ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
578 z_streamp source));
579/*
580 Sets the destination stream as a complete copy of the source stream.
581
582 This function can be useful when several compression strategies will be
583 tried, for example when there are several ways of pre-processing the input
584 data with a filter. The streams that will be discarded should then be freed
585 by calling deflateEnd. Note that deflateCopy duplicates the internal
586 compression state which can be quite large, so this strategy is slow and
587 can consume lots of memory.
588
589 deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
590 enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
591 (such as zalloc being NULL). msg is left unchanged in both source and
592 destination.
593*/
594
595ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
596/*
597 This function is equivalent to deflateEnd followed by deflateInit,
598 but does not free and reallocate all the internal compression state.
599 The stream will keep the same compression level and any other attributes
600 that may have been set by deflateInit2.
601
602 deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
603 stream state was inconsistent (such as zalloc or state being NULL).
604*/
605
606ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
607 int level,
608 int strategy));
609/*
610 Dynamically update the compression level and compression strategy. The
611 interpretation of level and strategy is as in deflateInit2. This can be
612 used to switch between compression and straight copy of the input data, or
613 to switch to a different kind of input data requiring a different
614 strategy. If the compression level is changed, the input available so far
615 is compressed with the old level (and may be flushed); the new level will
616 take effect only at the next call of deflate().
617
618 Before the call of deflateParams, the stream state must be set as for
619 a call of deflate(), since the currently available input may have to
620 be compressed and flushed. In particular, strm->avail_out must be non-zero.
621
622 deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
623 stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
624 if strm->avail_out was zero.
625*/
626
627ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
628 int good_length,
629 int max_lazy,
630 int nice_length,
631 int max_chain));
632/*
633 Fine tune deflate's internal compression parameters. This should only be
634 used by someone who understands the algorithm used by zlib's deflate for
635 searching for the best matching string, and even then only by the most
636 fanatic optimizer trying to squeeze out the last compressed bit for their
637 specific input data. Read the deflate.c source code for the meaning of the
638 max_lazy, good_length, nice_length, and max_chain parameters.
639
640 deflateTune() can be called after deflateInit() or deflateInit2(), and
641 returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
642 */
643
644ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
645 uLong sourceLen));
646/*
647 deflateBound() returns an upper bound on the compressed size after
648 deflation of sourceLen bytes. It must be called after deflateInit()
649 or deflateInit2(). This would be used to allocate an output buffer
650 for deflation in a single pass, and so would be called before deflate().
651*/
652
653ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
654 int bits,
655 int value));
656/*
657 deflatePrime() inserts bits in the deflate output stream. The intent
658 is that this function is used to start off the deflate output with the
659 bits leftover from a previous deflate stream when appending to it. As such,
660 this function can only be used for raw deflate, and must be used before the
661 first deflate() call after a deflateInit2() or deflateReset(). bits must be
662 less than or equal to 16, and that many of the least significant bits of
663 value will be inserted in the output.
664
665 deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
666 stream state was inconsistent.
667*/
668
669ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
670 gz_headerp head));
671/*
672 deflateSetHeader() provides gzip header information for when a gzip
673 stream is requested by deflateInit2(). deflateSetHeader() may be called
674 after deflateInit2() or deflateReset() and before the first call of
675 deflate(). The text, time, os, extra field, name, and comment information
676 in the provided gz_header structure are written to the gzip header (xflag is
677 ignored -- the extra flags are set according to the compression level). The
678 caller must assure that, if not Z_NULL, name and comment are terminated with
679 a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
680 available there. If hcrc is true, a gzip header crc is included. Note that
681 the current versions of the command-line version of gzip (up through version
682 1.3.x) do not support header crc's, and will report that it is a "multi-part
683 gzip file" and give up.
684
685 If deflateSetHeader is not used, the default gzip header has text false,
686 the time set to zero, and os set to 255, with no extra, name, or comment
687 fields. The gzip header is returned to the default state by deflateReset().
688
689 deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
690 stream state was inconsistent.
691*/
692
693/*
694ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
695 int windowBits));
696
697 This is another version of inflateInit with an extra parameter. The
698 fields next_in, avail_in, zalloc, zfree and opaque must be initialized
699 before by the caller.
700
701 The windowBits parameter is the base two logarithm of the maximum window
702 size (the size of the history buffer). It should be in the range 8..15 for
703 this version of the library. The default value is 15 if inflateInit is used
704 instead. windowBits must be greater than or equal to the windowBits value
705 provided to deflateInit2() while compressing, or it must be equal to 15 if
706 deflateInit2() was not used. If a compressed stream with a larger window
707 size is given as input, inflate() will return with the error code
708 Z_DATA_ERROR instead of trying to allocate a larger window.
709
710 windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
711 determines the window size. inflate() will then process raw deflate data,
712 not looking for a zlib or gzip header, not generating a check value, and not
713 looking for any check values for comparison at the end of the stream. This
714 is for use with other formats that use the deflate compressed data format
715 such as zip. Those formats provide their own check values. If a custom
716 format is developed using the raw deflate format for compressed data, it is
717 recommended that a check value such as an adler32 or a crc32 be applied to
718 the uncompressed data as is done in the zlib, gzip, and zip formats. For
719 most applications, the zlib format should be used as is. Note that comments
720 above on the use in deflateInit2() applies to the magnitude of windowBits.
721
722 windowBits can also be greater than 15 for optional gzip decoding. Add
723 32 to windowBits to enable zlib and gzip decoding with automatic header
724 detection, or add 16 to decode only the gzip format (the zlib format will
725 return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
726 a crc32 instead of an adler32.
727
728 inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
729 memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
730 is set to null if there is no error message. inflateInit2 does not perform
731 any decompression apart from reading the zlib header if present: this will
732 be done by inflate(). (So next_in and avail_in may be modified, but next_out
733 and avail_out are unchanged.)
734*/
735
736ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
737 const Bytef *dictionary,
738 uInt dictLength));
739/*
740 Initializes the decompression dictionary from the given uncompressed byte
741 sequence. This function must be called immediately after a call of inflate,
742 if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
743 can be determined from the adler32 value returned by that call of inflate.
744 The compressor and decompressor must use exactly the same dictionary (see
745 deflateSetDictionary). For raw inflate, this function can be called
746 immediately after inflateInit2() or inflateReset() and before any call of
747 inflate() to set the dictionary. The application must insure that the
748 dictionary that was used for compression is provided.
749
750 inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
751 parameter is invalid (such as NULL dictionary) or the stream state is
752 inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
753 expected one (incorrect adler32 value). inflateSetDictionary does not
754 perform any decompression: this will be done by subsequent calls of
755 inflate().
756*/
757
758ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
759/*
760 Skips invalid compressed data until a full flush point (see above the
761 description of deflate with Z_FULL_FLUSH) can be found, or until all
762 available input is skipped. No output is provided.
763
764 inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
765 if no more input was provided, Z_DATA_ERROR if no flush point has been found,
766 or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
767 case, the application may save the current current value of total_in which
768 indicates where valid compressed data was found. In the error case, the
769 application may repeatedly call inflateSync, providing more input each time,
770 until success or end of the input data.
771*/
772
773ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
774 z_streamp source));
775/*
776 Sets the destination stream as a complete copy of the source stream.
777
778 This function can be useful when randomly accessing a large stream. The
779 first pass through the stream can periodically record the inflate state,
780 allowing restarting inflate at those points when randomly accessing the
781 stream.
782
783 inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
784 enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
785 (such as zalloc being NULL). msg is left unchanged in both source and
786 destination.
787*/
788
789ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
790/*
791 This function is equivalent to inflateEnd followed by inflateInit,
792 but does not free and reallocate all the internal decompression state.
793 The stream will keep attributes that may have been set by inflateInit2.
794
795 inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
796 stream state was inconsistent (such as zalloc or state being NULL).
797*/
798
799ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
800 int bits,
801 int value));
802/*
803 This function inserts bits in the inflate input stream. The intent is
804 that this function is used to start inflating at a bit position in the
805 middle of a byte. The provided bits will be used before any bytes are used
806 from next_in. This function should only be used with raw inflate, and
807 should be used before the first inflate() call after inflateInit2() or
808 inflateReset(). bits must be less than or equal to 16, and that many of the
809 least significant bits of value will be inserted in the input.
810
811 inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
812 stream state was inconsistent.
813*/
814
815ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
816 gz_headerp head));
817/*
818 inflateGetHeader() requests that gzip header information be stored in the
819 provided gz_header structure. inflateGetHeader() may be called after
820 inflateInit2() or inflateReset(), and before the first call of inflate().
821 As inflate() processes the gzip stream, head->done is zero until the header
822 is completed, at which time head->done is set to one. If a zlib stream is
823 being decoded, then head->done is set to -1 to indicate that there will be
824 no gzip header information forthcoming. Note that Z_BLOCK can be used to
825 force inflate() to return immediately after header processing is complete
826 and before any actual data is decompressed.
827
828 The text, time, xflags, and os fields are filled in with the gzip header
829 contents. hcrc is set to true if there is a header CRC. (The header CRC
830 was valid if done is set to one.) If extra is not Z_NULL, then extra_max
831 contains the maximum number of bytes to write to extra. Once done is true,
832 extra_len contains the actual extra field length, and extra contains the
833 extra field, or that field truncated if extra_max is less than extra_len.
834 If name is not Z_NULL, then up to name_max characters are written there,
835 terminated with a zero unless the length is greater than name_max. If
836 comment is not Z_NULL, then up to comm_max characters are written there,
837 terminated with a zero unless the length is greater than comm_max. When
838 any of extra, name, or comment are not Z_NULL and the respective field is
839 not present in the header, then that field is set to Z_NULL to signal its
840 absence. This allows the use of deflateSetHeader() with the returned
841 structure to duplicate the header. However if those fields are set to
842 allocated memory, then the application will need to save those pointers
843 elsewhere so that they can be eventually freed.
844
845 If inflateGetHeader is not used, then the header information is simply
846 discarded. The header is always checked for validity, including the header
847 CRC if present. inflateReset() will reset the process to discard the header
848 information. The application would need to call inflateGetHeader() again to
849 retrieve the header from the next gzip stream.
850
851 inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
852 stream state was inconsistent.
853*/
854
855/*
856ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
857 unsigned char FAR *window));
858
859 Initialize the internal stream state for decompression using inflateBack()
860 calls. The fields zalloc, zfree and opaque in strm must be initialized
861 before the call. If zalloc and zfree are Z_NULL, then the default library-
862 derived memory allocation routines are used. windowBits is the base two
863 logarithm of the window size, in the range 8..15. window is a caller
864 supplied buffer of that size. Except for special applications where it is
865 assured that deflate was used with small window sizes, windowBits must be 15
866 and a 32K byte window must be supplied to be able to decompress general
867 deflate streams.
868
869 See inflateBack() for the usage of these routines.
870
871 inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
872 the paramaters are invalid, Z_MEM_ERROR if the internal state could not
873 be allocated, or Z_VERSION_ERROR if the version of the library does not
874 match the version of the header file.
875*/
876
877typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
878typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
879
880ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
881 in_func in, void FAR *in_desc,
882 out_func out, void FAR *out_desc));
883/*
884 inflateBack() does a raw inflate with a single call using a call-back
885 interface for input and output. This is more efficient than inflate() for
886 file i/o applications in that it avoids copying between the output and the
887 sliding window by simply making the window itself the output buffer. This
888 function trusts the application to not change the output buffer passed by
889 the output function, at least until inflateBack() returns.
890
891 inflateBackInit() must be called first to allocate the internal state
892 and to initialize the state with the user-provided window buffer.
893 inflateBack() may then be used multiple times to inflate a complete, raw
894 deflate stream with each call. inflateBackEnd() is then called to free
895 the allocated state.
896
897 A raw deflate stream is one with no zlib or gzip header or trailer.
898 This routine would normally be used in a utility that reads zip or gzip
899 files and writes out uncompressed files. The utility would decode the
900 header and process the trailer on its own, hence this routine expects
901 only the raw deflate stream to decompress. This is different from the
902 normal behavior of inflate(), which expects either a zlib or gzip header and
903 trailer around the deflate stream.
904
905 inflateBack() uses two subroutines supplied by the caller that are then
906 called by inflateBack() for input and output. inflateBack() calls those
907 routines until it reads a complete deflate stream and writes out all of the
908 uncompressed data, or until it encounters an error. The function's
909 parameters and return types are defined above in the in_func and out_func
910 typedefs. inflateBack() will call in(in_desc, &buf) which should return the
911 number of bytes of provided input, and a pointer to that input in buf. If
912 there is no input available, in() must return zero--buf is ignored in that
913 case--and inflateBack() will return a buffer error. inflateBack() will call
914 out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
915 should return zero on success, or non-zero on failure. If out() returns
916 non-zero, inflateBack() will return with an error. Neither in() nor out()
917 are permitted to change the contents of the window provided to
918 inflateBackInit(), which is also the buffer that out() uses to write from.
919 The length written by out() will be at most the window size. Any non-zero
920 amount of input may be provided by in().
921
922 For convenience, inflateBack() can be provided input on the first call by
923 setting strm->next_in and strm->avail_in. If that input is exhausted, then
924 in() will be called. Therefore strm->next_in must be initialized before
925 calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
926 immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
927 must also be initialized, and then if strm->avail_in is not zero, input will
928 initially be taken from strm->next_in[0 .. strm->avail_in - 1].
929
930 The in_desc and out_desc parameters of inflateBack() is passed as the
931 first parameter of in() and out() respectively when they are called. These
932 descriptors can be optionally used to pass any information that the caller-
933 supplied in() and out() functions need to do their job.
934
935 On return, inflateBack() will set strm->next_in and strm->avail_in to
936 pass back any unused input that was provided by the last in() call. The
937 return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
938 if in() or out() returned an error, Z_DATA_ERROR if there was a format
939 error in the deflate stream (in which case strm->msg is set to indicate the
940 nature of the error), or Z_STREAM_ERROR if the stream was not properly
941 initialized. In the case of Z_BUF_ERROR, an input or output error can be
942 distinguished using strm->next_in which will be Z_NULL only if in() returned
943 an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
944 out() returning non-zero. (in() will always be called before out(), so
945 strm->next_in is assured to be defined if out() returns non-zero.) Note
946 that inflateBack() cannot return Z_OK.
947*/
948
949ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
950/*
951 All memory allocated by inflateBackInit() is freed.
952
953 inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
954 state was inconsistent.
955*/
956
957ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
958/* Return flags indicating compile-time options.
959
960 Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
961 1.0: size of uInt
962 3.2: size of uLong
963 5.4: size of voidpf (pointer)
964 7.6: size of z_off_t
965
966 Compiler, assembler, and debug options:
967 8: DEBUG
968 9: ASMV or ASMINF -- use ASM code
969 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
970 11: 0 (reserved)
971
972 One-time table building (smaller code, but not thread-safe if true):
973 12: BUILDFIXED -- build static block decoding tables when needed
974 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
975 14,15: 0 (reserved)
976
977 Library content (indicates missing functionality):
978 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
979 deflate code when not needed)
980 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
981 and decode gzip streams (to avoid linking crc code)
982 18-19: 0 (reserved)
983
984 Operation variations (changes in library functionality):
985 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
986 21: FASTEST -- deflate algorithm with only one, lowest compression level
987 22,23: 0 (reserved)
988
989 The sprintf variant used by gzprintf (zero is best):
990 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
991 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
992 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
993
994 Remainder:
995 27-31: 0 (reserved)
996 */
997
998
999 /* utility functions */
1000
1001/*
1002 The following utility functions are implemented on top of the
1003 basic stream-oriented functions. To simplify the interface, some
1004 default options are assumed (compression level and memory usage,
1005 standard memory allocation functions). The source code of these
1006 utility functions can easily be modified if you need special options.
1007*/
1008
1009ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
1010 const Bytef *source, uLong sourceLen));
1011/*
1012 Compresses the source buffer into the destination buffer. sourceLen is
1013 the byte length of the source buffer. Upon entry, destLen is the total
1014 size of the destination buffer, which must be at least the value returned
1015 by compressBound(sourceLen). Upon exit, destLen is the actual size of the
1016 compressed buffer.
1017 This function can be used to compress a whole file at once if the
1018 input file is mmap'ed.
1019 compress returns Z_OK if success, Z_MEM_ERROR if there was not
1020 enough memory, Z_BUF_ERROR if there was not enough room in the output
1021 buffer.
1022*/
1023
1024ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
1025 const Bytef *source, uLong sourceLen,
1026 int level));
1027/*
1028 Compresses the source buffer into the destination buffer. The level
1029 parameter has the same meaning as in deflateInit. sourceLen is the byte
1030 length of the source buffer. Upon entry, destLen is the total size of the
1031 destination buffer, which must be at least the value returned by
1032 compressBound(sourceLen). Upon exit, destLen is the actual size of the
1033 compressed buffer.
1034
1035 compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
1036 memory, Z_BUF_ERROR if there was not enough room in the output buffer,
1037 Z_STREAM_ERROR if the level parameter is invalid.
1038*/
1039
1040ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
1041/*
1042 compressBound() returns an upper bound on the compressed size after
1043 compress() or compress2() on sourceLen bytes. It would be used before
1044 a compress() or compress2() call to allocate the destination buffer.
1045*/
1046
1047ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
1048 const Bytef *source, uLong sourceLen));
1049/*
1050 Decompresses the source buffer into the destination buffer. sourceLen is
1051 the byte length of the source buffer. Upon entry, destLen is the total
1052 size of the destination buffer, which must be large enough to hold the
1053 entire uncompressed data. (The size of the uncompressed data must have
1054 been saved previously by the compressor and transmitted to the decompressor
1055 by some mechanism outside the scope of this compression library.)
1056 Upon exit, destLen is the actual size of the compressed buffer.
1057 This function can be used to decompress a whole file at once if the
1058 input file is mmap'ed.
1059
1060 uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
1061 enough memory, Z_BUF_ERROR if there was not enough room in the output
1062 buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
1063*/
1064
1065
1066typedef voidp gzFile;
1067
1068ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
1069/*
1070 Opens a gzip (.gz) file for reading or writing. The mode parameter
1071 is as in fopen ("rb" or "wb") but can also include a compression level
1072 ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
1073 Huffman only compression as in "wb1h", or 'R' for run-length encoding
1074 as in "wb1R". (See the description of deflateInit2 for more information
1075 about the strategy parameter.)
1076
1077 gzopen can be used to read a file which is not in gzip format; in this
1078 case gzread will directly read from the file without decompression.
1079
1080 gzopen returns NULL if the file could not be opened or if there was
1081 insufficient memory to allocate the (de)compression state; errno
1082 can be checked to distinguish the two cases (if errno is zero, the
1083 zlib error is Z_MEM_ERROR). */
1084
1085ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
1086/*
1087 gzdopen() associates a gzFile with the file descriptor fd. File
1088 descriptors are obtained from calls like open, dup, creat, pipe or
1089 fileno (in the file has been previously opened with fopen).
1090 The mode parameter is as in gzopen.
1091 The next call of gzclose on the returned gzFile will also close the
1092 file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
1093 descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
1094 gzdopen returns NULL if there was insufficient memory to allocate
1095 the (de)compression state.
1096*/
1097
1098ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
1099/*
1100 Dynamically update the compression level or strategy. See the description
1101 of deflateInit2 for the meaning of these parameters.
1102 gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
1103 opened for writing.
1104*/
1105
1106ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
1107/*
1108 Reads the given number of uncompressed bytes from the compressed file.
1109 If the input file was not in gzip format, gzread copies the given number
1110 of bytes into the buffer.
1111 gzread returns the number of uncompressed bytes actually read (0 for
1112 end of file, -1 for error). */
1113
1114ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
1115 voidpc buf, unsigned len));
1116/*
1117 Writes the given number of uncompressed bytes into the compressed file.
1118 gzwrite returns the number of uncompressed bytes actually written
1119 (0 in case of error).
1120*/
1121
1122ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
1123/*
1124 Converts, formats, and writes the args to the compressed file under
1125 control of the format string, as in fprintf. gzprintf returns the number of
1126 uncompressed bytes actually written (0 in case of error). The number of
1127 uncompressed bytes written is limited to 4095. The caller should assure that
1128 this limit is not exceeded. If it is exceeded, then gzprintf() will return
1129 return an error (0) with nothing written. In this case, there may also be a
1130 buffer overflow with unpredictable consequences, which is possible only if
1131 zlib was compiled with the insecure functions sprintf() or vsprintf()
1132 because the secure snprintf() or vsnprintf() functions were not available.
1133*/
1134
1135ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
1136/*
1137 Writes the given null-terminated string to the compressed file, excluding
1138 the terminating null character.
1139 gzputs returns the number of characters written, or -1 in case of error.
1140*/
1141
1142ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
1143/*
1144 Reads bytes from the compressed file until len-1 characters are read, or
1145 a newline character is read and transferred to buf, or an end-of-file
1146 condition is encountered. The string is then terminated with a null
1147 character.
1148 gzgets returns buf, or Z_NULL in case of error.
1149*/
1150
1151ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
1152/*
1153 Writes c, converted to an unsigned char, into the compressed file.
1154 gzputc returns the value that was written, or -1 in case of error.
1155*/
1156
1157ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
1158/*
1159 Reads one byte from the compressed file. gzgetc returns this byte
1160 or -1 in case of end of file or error.
1161*/
1162
1163ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
1164/*
1165 Push one character back onto the stream to be read again later.
1166 Only one character of push-back is allowed. gzungetc() returns the
1167 character pushed, or -1 on failure. gzungetc() will fail if a
1168 character has been pushed but not read yet, or if c is -1. The pushed
1169 character will be discarded if the stream is repositioned with gzseek()
1170 or gzrewind().
1171*/
1172
1173ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
1174/*
1175 Flushes all pending output into the compressed file. The parameter
1176 flush is as in the deflate() function. The return value is the zlib
1177 error number (see function gzerror below). gzflush returns Z_OK if
1178 the flush parameter is Z_FINISH and all output could be flushed.
1179 gzflush should be called only when strictly necessary because it can
1180 degrade compression.
1181*/
1182
1183ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
1184 z_off_t offset, int whence));
1185/*
1186 Sets the starting position for the next gzread or gzwrite on the
1187 given compressed file. The offset represents a number of bytes in the
1188 uncompressed data stream. The whence parameter is defined as in lseek(2);
1189 the value SEEK_END is not supported.
1190 If the file is opened for reading, this function is emulated but can be
1191 extremely slow. If the file is opened for writing, only forward seeks are
1192 supported; gzseek then compresses a sequence of zeroes up to the new
1193 starting position.
1194
1195 gzseek returns the resulting offset location as measured in bytes from
1196 the beginning of the uncompressed stream, or -1 in case of error, in
1197 particular if the file is opened for writing and the new starting position
1198 would be before the current position.
1199*/
1200
1201ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
1202/*
1203 Rewinds the given file. This function is supported only for reading.
1204
1205 gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
1206*/
1207
1208ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
1209/*
1210 Returns the starting position for the next gzread or gzwrite on the
1211 given compressed file. This position represents a number of bytes in the
1212 uncompressed data stream.
1213
1214 gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
1215*/
1216
1217ZEXTERN int ZEXPORT gzeof OF((gzFile file));
1218/*
1219 Returns 1 when EOF has previously been detected reading the given
1220 input stream, otherwise zero.
1221*/
1222
1223ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
1224/*
1225 Returns 1 if file is being read directly without decompression, otherwise
1226 zero.
1227*/
1228
1229ZEXTERN int ZEXPORT gzclose OF((gzFile file));
1230/*
1231 Flushes all pending output if necessary, closes the compressed file
1232 and deallocates all the (de)compression state. The return value is the zlib
1233 error number (see function gzerror below).
1234*/
1235
1236ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
1237/*
1238 Returns the error message for the last error which occurred on the
1239 given compressed file. errnum is set to zlib error number. If an
1240 error occurred in the file system and not in the compression library,
1241 errnum is set to Z_ERRNO and the application may consult errno
1242 to get the exact error code.
1243*/
1244
1245ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
1246/*
1247 Clears the error and end-of-file flags for file. This is analogous to the
1248 clearerr() function in stdio. This is useful for continuing to read a gzip
1249 file that is being written concurrently.
1250*/
1251
1252 /* checksum functions */
1253
1254/*
1255 These functions are not related to compression but are exported
1256 anyway because they might be useful in applications using the
1257 compression library.
1258*/
1259
1260ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
1261/*
1262 Update a running Adler-32 checksum with the bytes buf[0..len-1] and
1263 return the updated checksum. If buf is NULL, this function returns
1264 the required initial value for the checksum.
1265 An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
1266 much faster. Usage example:
1267
1268 uLong adler = adler32(0L, Z_NULL, 0);
1269
1270 while (read_buffer(buffer, length) != EOF) {
1271 adler = adler32(adler, buffer, length);
1272 }
1273 if (adler != original_adler) error();
1274*/
1275
1276ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
1277 z_off_t len2));
1278/*
1279 Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
1280 and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
1281 each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
1282 seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
1283*/
1284
1285ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
1286/*
1287 Update a running CRC-32 with the bytes buf[0..len-1] and return the
1288 updated CRC-32. If buf is NULL, this function returns the required initial
1289 value for the for the crc. Pre- and post-conditioning (one's complement) is
1290 performed within this function so it shouldn't be done by the application.
1291 Usage example:
1292
1293 uLong crc = crc32(0L, Z_NULL, 0);
1294
1295 while (read_buffer(buffer, length) != EOF) {
1296 crc = crc32(crc, buffer, length);
1297 }
1298 if (crc != original_crc) error();
1299*/
1300
1301ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
1302
1303/*
1304 Combine two CRC-32 check values into one. For two sequences of bytes,
1305 seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
1306 calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
1307 check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
1308 len2.
1309*/
1310
1311
1312 /* various hacks, don't look :) */
1313
1314/* deflateInit and inflateInit are macros to allow checking the zlib version
1315 * and the compiler's view of z_stream:
1316 */
1317ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
1318 const char *version, int stream_size));
1319ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
1320 const char *version, int stream_size));
1321ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
1322 int windowBits, int memLevel,
1323 int strategy, const char *version,
1324 int stream_size));
1325ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
1326 const char *version, int stream_size));
1327ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
1328 unsigned char FAR *window,
1329 const char *version,
1330 int stream_size));
1331#define deflateInit(strm, level) \
1332 deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
1333#define inflateInit(strm) \
1334 inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
1335#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
1336 deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
1337 (strategy), ZLIB_VERSION, sizeof(z_stream))
1338#define inflateInit2(strm, windowBits) \
1339 inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
1340#define inflateBackInit(strm, windowBits, window) \
1341 inflateBackInit_((strm), (windowBits), (window), \
1342 ZLIB_VERSION, sizeof(z_stream))
1343
1344
1345#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
1346 struct internal_state {int dummy;}; /* hack for buggy compilers */
1347#endif
1348
1349ZEXTERN const char * ZEXPORT zError OF((int));
1350ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
1351ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
1352
1353#ifdef __cplusplus
1354}
1355#endif
1356
1357#endif /* ZLIB_H */
diff --git a/utils/zenutils/libraries/zlib123/zlib/zutil.c b/utils/zenutils/libraries/zlib123/zlib/zutil.c
new file mode 100755
index 0000000000..0f4bd7871d
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/zutil.c
@@ -0,0 +1,318 @@
1/* zutil.c -- target dependent utility functions for the compression library
2 * Copyright (C) 1995-2005 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/* @(#) $Id$ */
7
8#include "zutil.h"
9
10#ifndef NO_DUMMY_DECL
11struct internal_state {int dummy;}; /* for buggy compilers */
12#endif
13
14const char * const z_errmsg[10] = {
15"need dictionary", /* Z_NEED_DICT 2 */
16"stream end", /* Z_STREAM_END 1 */
17"", /* Z_OK 0 */
18"file error", /* Z_ERRNO (-1) */
19"stream error", /* Z_STREAM_ERROR (-2) */
20"data error", /* Z_DATA_ERROR (-3) */
21"insufficient memory", /* Z_MEM_ERROR (-4) */
22"buffer error", /* Z_BUF_ERROR (-5) */
23"incompatible version",/* Z_VERSION_ERROR (-6) */
24""};
25
26
27const char * ZEXPORT zlibVersion()
28{
29 return ZLIB_VERSION;
30}
31
32uLong ZEXPORT zlibCompileFlags()
33{
34 uLong flags;
35
36 flags = 0;
37 switch (sizeof(uInt)) {
38 case 2: break;
39 case 4: flags += 1; break;
40 case 8: flags += 2; break;
41 default: flags += 3;
42 }
43 switch (sizeof(uLong)) {
44 case 2: break;
45 case 4: flags += 1 << 2; break;
46 case 8: flags += 2 << 2; break;
47 default: flags += 3 << 2;
48 }
49 switch (sizeof(voidpf)) {
50 case 2: break;
51 case 4: flags += 1 << 4; break;
52 case 8: flags += 2 << 4; break;
53 default: flags += 3 << 4;
54 }
55 switch (sizeof(z_off_t)) {
56 case 2: break;
57 case 4: flags += 1 << 6; break;
58 case 8: flags += 2 << 6; break;
59 default: flags += 3 << 6;
60 }
61#ifdef DEBUG
62 flags += 1 << 8;
63#endif
64#if defined(ASMV) || defined(ASMINF)
65 flags += 1 << 9;
66#endif
67#ifdef ZLIB_WINAPI
68 flags += 1 << 10;
69#endif
70#ifdef BUILDFIXED
71 flags += 1 << 12;
72#endif
73#ifdef DYNAMIC_CRC_TABLE
74 flags += 1 << 13;
75#endif
76#ifdef NO_GZCOMPRESS
77 flags += 1L << 16;
78#endif
79#ifdef NO_GZIP
80 flags += 1L << 17;
81#endif
82#ifdef PKZIP_BUG_WORKAROUND
83 flags += 1L << 20;
84#endif
85#ifdef FASTEST
86 flags += 1L << 21;
87#endif
88#ifdef STDC
89# ifdef NO_vsnprintf
90 flags += 1L << 25;
91# ifdef HAS_vsprintf_void
92 flags += 1L << 26;
93# endif
94# else
95# ifdef HAS_vsnprintf_void
96 flags += 1L << 26;
97# endif
98# endif
99#else
100 flags += 1L << 24;
101# ifdef NO_snprintf
102 flags += 1L << 25;
103# ifdef HAS_sprintf_void
104 flags += 1L << 26;
105# endif
106# else
107# ifdef HAS_snprintf_void
108 flags += 1L << 26;
109# endif
110# endif
111#endif
112 return flags;
113}
114
115#ifdef DEBUG
116
117# ifndef verbose
118# define verbose 0
119# endif
120int z_verbose = verbose;
121
122void z_error (m)
123 char *m;
124{
125 fprintf(stderr, "%s\n", m);
126 exit(1);
127}
128#endif
129
130/* exported to allow conversion of error code to string for compress() and
131 * uncompress()
132 */
133const char * ZEXPORT zError(err)
134 int err;
135{
136 return ERR_MSG(err);
137}
138
139#if defined(_WIN32_WCE)
140 /* The Microsoft C Run-Time Library for Windows CE doesn't have
141 * errno. We define it as a global variable to simplify porting.
142 * Its value is always 0 and should not be used.
143 */
144 int errno = 0;
145#endif
146
147#ifndef HAVE_MEMCPY
148
149void zmemcpy(dest, source, len)
150 Bytef* dest;
151 const Bytef* source;
152 uInt len;
153{
154 if (len == 0) return;
155 do {
156 *dest++ = *source++; /* ??? to be unrolled */
157 } while (--len != 0);
158}
159
160int zmemcmp(s1, s2, len)
161 const Bytef* s1;
162 const Bytef* s2;
163 uInt len;
164{
165 uInt j;
166
167 for (j = 0; j < len; j++) {
168 if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
169 }
170 return 0;
171}
172
173void zmemzero(dest, len)
174 Bytef* dest;
175 uInt len;
176{
177 if (len == 0) return;
178 do {
179 *dest++ = 0; /* ??? to be unrolled */
180 } while (--len != 0);
181}
182#endif
183
184
185#ifdef SYS16BIT
186
187#ifdef __TURBOC__
188/* Turbo C in 16-bit mode */
189
190# define MY_ZCALLOC
191
192/* Turbo C malloc() does not allow dynamic allocation of 64K bytes
193 * and farmalloc(64K) returns a pointer with an offset of 8, so we
194 * must fix the pointer. Warning: the pointer must be put back to its
195 * original form in order to free it, use zcfree().
196 */
197
198#define MAX_PTR 10
199/* 10*64K = 640K */
200
201local int next_ptr = 0;
202
203typedef struct ptr_table_s {
204 voidpf org_ptr;
205 voidpf new_ptr;
206} ptr_table;
207
208local ptr_table table[MAX_PTR];
209/* This table is used to remember the original form of pointers
210 * to large buffers (64K). Such pointers are normalized with a zero offset.
211 * Since MSDOS is not a preemptive multitasking OS, this table is not
212 * protected from concurrent access. This hack doesn't work anyway on
213 * a protected system like OS/2. Use Microsoft C instead.
214 */
215
216voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
217{
218 voidpf buf = opaque; /* just to make some compilers happy */
219 ulg bsize = (ulg)items*size;
220
221 /* If we allocate less than 65520 bytes, we assume that farmalloc
222 * will return a usable pointer which doesn't have to be normalized.
223 */
224 if (bsize < 65520L) {
225 buf = farmalloc(bsize);
226 if (*(ush*)&buf != 0) return buf;
227 } else {
228 buf = farmalloc(bsize + 16L);
229 }
230 if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
231 table[next_ptr].org_ptr = buf;
232
233 /* Normalize the pointer to seg:0 */
234 *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
235 *(ush*)&buf = 0;
236 table[next_ptr++].new_ptr = buf;
237 return buf;
238}
239
240void zcfree (voidpf opaque, voidpf ptr)
241{
242 int n;
243 if (*(ush*)&ptr != 0) { /* object < 64K */
244 farfree(ptr);
245 return;
246 }
247 /* Find the original pointer */
248 for (n = 0; n < next_ptr; n++) {
249 if (ptr != table[n].new_ptr) continue;
250
251 farfree(table[n].org_ptr);
252 while (++n < next_ptr) {
253 table[n-1] = table[n];
254 }
255 next_ptr--;
256 return;
257 }
258 ptr = opaque; /* just to make some compilers happy */
259 Assert(0, "zcfree: ptr not found");
260}
261
262#endif /* __TURBOC__ */
263
264
265#ifdef M_I86
266/* Microsoft C in 16-bit mode */
267
268# define MY_ZCALLOC
269
270#if (!defined(_MSC_VER) || (_MSC_VER <= 600))
271# define _halloc halloc
272# define _hfree hfree
273#endif
274
275voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
276{
277 if (opaque) opaque = 0; /* to make compiler happy */
278 return _halloc((long)items, size);
279}
280
281void zcfree (voidpf opaque, voidpf ptr)
282{
283 if (opaque) opaque = 0; /* to make compiler happy */
284 _hfree(ptr);
285}
286
287#endif /* M_I86 */
288
289#endif /* SYS16BIT */
290
291
292#ifndef MY_ZCALLOC /* Any system without a special alloc function */
293
294#ifndef STDC
295extern voidp malloc OF((uInt size));
296extern voidp calloc OF((uInt items, uInt size));
297extern void free OF((voidpf ptr));
298#endif
299
300voidpf zcalloc (opaque, items, size)
301 voidpf opaque;
302 unsigned items;
303 unsigned size;
304{
305 if (opaque) items += size - size; /* make compiler happy */
306 return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
307 (voidpf)calloc(items, size);
308}
309
310void zcfree (opaque, ptr)
311 voidpf opaque;
312 voidpf ptr;
313{
314 free(ptr);
315 if (opaque) return; /* make compiler happy */
316}
317
318#endif /* MY_ZCALLOC */
diff --git a/utils/zenutils/libraries/zlib123/zlib/zutil.h b/utils/zenutils/libraries/zlib123/zlib/zutil.h
new file mode 100755
index 0000000000..0ba6e02087
--- /dev/null
+++ b/utils/zenutils/libraries/zlib123/zlib/zutil.h
@@ -0,0 +1,269 @@
1/* zutil.h -- internal interface and configuration of the compression library
2 * Copyright (C) 1995-2005 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/* WARNING: this file should *not* be used by applications. It is
7 part of the implementation of the compression library and is
8 subject to change. Applications should only use zlib.h.
9 */
10
11/* @(#) $Id$ */
12
13#ifndef ZUTIL_H
14#define ZUTIL_H
15
16#define ZLIB_INTERNAL
17#include "zlib.h"
18
19#ifdef STDC
20# ifndef _WIN32_WCE
21# include <stddef.h>
22# endif
23# include <string.h>
24# include <stdlib.h>
25#endif
26#ifdef NO_ERRNO_H
27# ifdef _WIN32_WCE
28 /* The Microsoft C Run-Time Library for Windows CE doesn't have
29 * errno. We define it as a global variable to simplify porting.
30 * Its value is always 0 and should not be used. We rename it to
31 * avoid conflict with other libraries that use the same workaround.
32 */
33# define errno z_errno
34# endif
35 extern int errno;
36#else
37# ifndef _WIN32_WCE
38# include <errno.h>
39# endif
40#endif
41
42#ifndef local
43# define local static
44#endif
45/* compile with -Dlocal if your debugger can't find static symbols */
46
47typedef unsigned char uch;
48typedef uch FAR uchf;
49typedef unsigned short ush;
50typedef ush FAR ushf;
51typedef unsigned long ulg;
52
53extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
54/* (size given to avoid silly warnings with Visual C++) */
55
56#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
57
58#define ERR_RETURN(strm,err) \
59 return (strm->msg = (char*)ERR_MSG(err), (err))
60/* To be used only when the state is known to be valid */
61
62 /* common constants */
63
64#ifndef DEF_WBITS
65# define DEF_WBITS MAX_WBITS
66#endif
67/* default windowBits for decompression. MAX_WBITS is for compression only */
68
69#if MAX_MEM_LEVEL >= 8
70# define DEF_MEM_LEVEL 8
71#else
72# define DEF_MEM_LEVEL MAX_MEM_LEVEL
73#endif
74/* default memLevel */
75
76#define STORED_BLOCK 0
77#define STATIC_TREES 1
78#define DYN_TREES 2
79/* The three kinds of block type */
80
81#define MIN_MATCH 3
82#define MAX_MATCH 258
83/* The minimum and maximum match lengths */
84
85#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
86
87 /* target dependencies */
88
89#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
90# define OS_CODE 0x00
91# if defined(__TURBOC__) || defined(__BORLANDC__)
92# if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
93 /* Allow compilation with ANSI keywords only enabled */
94 void _Cdecl farfree( void *block );
95 void *_Cdecl farmalloc( unsigned long nbytes );
96# else
97# include <alloc.h>
98# endif
99# else /* MSC or DJGPP */
100# include <malloc.h>
101# endif
102#endif
103
104#ifdef AMIGA
105# define OS_CODE 0x01
106#endif
107
108#if defined(VAXC) || defined(VMS)
109# define OS_CODE 0x02
110# define F_OPEN(name, mode) \
111 fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
112#endif
113
114#if defined(ATARI) || defined(atarist)
115# define OS_CODE 0x05
116#endif
117
118#ifdef OS2
119# define OS_CODE 0x06
120# ifdef M_I86
121 #include <malloc.h>
122# endif
123#endif
124
125#if defined(MACOS) || defined(TARGET_OS_MAC)
126# define OS_CODE 0x07
127# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
128# include <unix.h> /* for fdopen */
129# else
130# ifndef fdopen
131# define fdopen(fd,mode) NULL /* No fdopen() */
132# endif
133# endif
134#endif
135
136#ifdef TOPS20
137# define OS_CODE 0x0a
138#endif
139
140#ifdef WIN32
141# ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
142# define OS_CODE 0x0b
143# endif
144#endif
145
146#ifdef __50SERIES /* Prime/PRIMOS */
147# define OS_CODE 0x0f
148#endif
149
150#if defined(_BEOS_) || defined(RISCOS)
151# define fdopen(fd,mode) NULL /* No fdopen() */
152#endif
153
154#if (defined(_MSC_VER) && (_MSC_VER > 600))
155# if defined(_WIN32_WCE)
156# define fdopen(fd,mode) NULL /* No fdopen() */
157# ifndef _PTRDIFF_T_DEFINED
158 typedef int ptrdiff_t;
159# define _PTRDIFF_T_DEFINED
160# endif
161# else
162# define fdopen(fd,type) _fdopen(fd,type)
163# endif
164#endif
165
166 /* common defaults */
167
168#ifndef OS_CODE
169# define OS_CODE 0x03 /* assume Unix */
170#endif
171
172#ifndef F_OPEN
173# define F_OPEN(name, mode) fopen((name), (mode))
174#endif
175
176 /* functions */
177
178#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
179# ifndef HAVE_VSNPRINTF
180# define HAVE_VSNPRINTF
181# endif
182#endif
183#if defined(__CYGWIN__)
184# ifndef HAVE_VSNPRINTF
185# define HAVE_VSNPRINTF
186# endif
187#endif
188#ifndef HAVE_VSNPRINTF
189# ifdef MSDOS
190 /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
191 but for now we just assume it doesn't. */
192# define NO_vsnprintf
193# endif
194# ifdef __TURBOC__
195# define NO_vsnprintf
196# endif
197# ifdef WIN32
198 /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
199# if !defined(vsnprintf) && !defined(NO_vsnprintf)
200# define vsnprintf _vsnprintf
201# endif
202# endif
203# ifdef __SASC
204# define NO_vsnprintf
205# endif
206#endif
207#ifdef VMS
208# define NO_vsnprintf
209#endif
210
211#if defined(pyr)
212# define NO_MEMCPY
213#endif
214#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
215 /* Use our own functions for small and medium model with MSC <= 5.0.
216 * You may have to use the same strategy for Borland C (untested).
217 * The __SC__ check is for Symantec.
218 */
219# define NO_MEMCPY
220#endif
221#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
222# define HAVE_MEMCPY
223#endif
224#ifdef HAVE_MEMCPY
225# ifdef SMALL_MEDIUM /* MSDOS small or medium model */
226# define zmemcpy _fmemcpy
227# define zmemcmp _fmemcmp
228# define zmemzero(dest, len) _fmemset(dest, 0, len)
229# else
230# define zmemcpy memcpy
231# define zmemcmp memcmp
232# define zmemzero(dest, len) memset(dest, 0, len)
233# endif
234#else
235 extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
236 extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
237 extern void zmemzero OF((Bytef* dest, uInt len));
238#endif
239
240/* Diagnostic functions */
241#ifdef DEBUG
242# include <stdio.h>
243 extern int z_verbose;
244 extern void z_error OF((char *m));
245# define Assert(cond,msg) {if(!(cond)) z_error(msg);}
246# define Trace(x) {if (z_verbose>=0) fprintf x ;}
247# define Tracev(x) {if (z_verbose>0) fprintf x ;}
248# define Tracevv(x) {if (z_verbose>1) fprintf x ;}
249# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
250# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
251#else
252# define Assert(cond,msg)
253# define Trace(x)
254# define Tracev(x)
255# define Tracevv(x)
256# define Tracec(c,x)
257# define Tracecv(c,x)
258#endif
259
260
261voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
262void zcfree OF((voidpf opaque, voidpf ptr));
263
264#define ZALLOC(strm, items, size) \
265 (*((strm)->zalloc))((strm)->opaque, (items), (size))
266#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
267#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
268
269#endif /* ZUTIL_H */
diff --git a/utils/zenutils/notes.txt b/utils/zenutils/notes.txt
new file mode 100755
index 0000000000..0848718ac2
--- /dev/null
+++ b/utils/zenutils/notes.txt
@@ -0,0 +1,77 @@
1zenutils is a collection of utilities for working with firmwares of the Creative Zen range.
2
3The utilities are split into 3 categories:
41) update_*
5 Operates on the Creative firmware updater executable.
62) firmware_*
7 Operates on the Creative firmware archive.
83) zen_crypt
9 Operates on the parts of the firmware archive which requires cryptography.
10
11
12General usage:
13--------------
14A typical use scenario would be: download the firmware updater and run
15 update_extract on it to obtain the firmware archive which it contains.
16Run firmware_extract on the firmware archive to obtain the files
17 which the firmware archive contains and a make file that can later be used
18 to create a new firmware archive. Edit* the extracted files of
19 interest and optionally the associated make file. Create a new firmware
20 archive by running firmware_make. If a NULL entry is present in the firmware
21 then it's signature has to be updated running zen_crypt. If on windows, you
22 can use update_patch to write your newly created firmware archive to the
23 updater executable which you originally extracted it from. The new updater
24 will update your player with the modifications you've made.
25
26* If you're creating or editing executable code, such as the CENC or ©TL entries,
27you'll need to use zen_crypt to decrypt and/or encrypt them.
28In addition, executable code on some players that use the ©TL entries also needs
29 to be signed using zen_crypt, prior to encrypting them.
30Encrypting FBOOT and FRESC is not supported, as these contain the executable
31 code that makes up the critical Rescue Mode software, contained in flash.
32As opposed to CENC and ©TL which ultimately ends up being stored in the players
33 filesystem as a file named Jukebox2.jrm.
34
35
36Important:
37----------
38The only entries required in a firmware archive is CINF and if present, NULL.
39Including either FBOOT, FRESC or EXT0 in your firmware archive is not advised,
40 the first two are required for the Rescue Mode software operation and EXT0 is
41 unknown, but given that it's contents is sent to an internal device named mcu0,
42 the consequences of failure could be fatal to your player.
43
44
45Supported players:
46------------------
47zen_crypt supports signing, verification, decryption and encryption on the
48 following Creative Zen players:
49 Vision:M (default if no player is specified)
50 Vision W
51 Micro
52 MicroPhoto
53 Sleek
54 SleekPhoto
55 Touch
56 Xtra
57
58The other utilities are not player specific and may work on players not listed.
59Although the Vision:M is the only player I've fully tested.
60
61
62Building the sources:
63---------------------
64The source code uses the CMake (www.cmake.org) build system.
65Once you've installed CMake, you'll need to run it to produce make files for
66 your system. I would recommend producing the make files within in the 'build'
67 directory of this package. Which can be done by typing:
68 zenutils\build\>cmake -g "Visual Studio 8 2005" ..
69 (for msvc8 on windows)
70 or:
71 ~zenutils/build/$ cmake -g "Unix Makefiles" ..
72 (for various 'nixes)
73The windows example will produce a solution file for msvc8.
74The 'nix example will produce a makefile which can be built using make.
75
76The executables will be placed within the 'bin' directory, once built.
77
diff --git a/utils/zenutils/source/CMakeLists.txt b/utils/zenutils/source/CMakeLists.txt
new file mode 100755
index 0000000000..e3d44fd036
--- /dev/null
+++ b/utils/zenutils/source/CMakeLists.txt
@@ -0,0 +1,6 @@
1ADD_SUBDIRECTORY(firmware_extract)
2ADD_SUBDIRECTORY(firmware_make)
3ADD_SUBDIRECTORY(shared)
4ADD_SUBDIRECTORY(update_extract)
5ADD_SUBDIRECTORY(update_patch)
6ADD_SUBDIRECTORY(zen_crypt)
diff --git a/utils/zenutils/source/firmware_extract/CMakeLists.txt b/utils/zenutils/source/firmware_extract/CMakeLists.txt
new file mode 100755
index 0000000000..3814f03612
--- /dev/null
+++ b/utils/zenutils/source/firmware_extract/CMakeLists.txt
@@ -0,0 +1,3 @@
1ADD_EXECUTABLE(firmware_extract main.cpp)
2
3TARGET_LINK_LIBRARIES(firmware_extract shared)
diff --git a/utils/zenutils/source/firmware_extract/main.cpp b/utils/zenutils/source/firmware_extract/main.cpp
new file mode 100755
index 0000000000..c677a91a75
--- /dev/null
+++ b/utils/zenutils/source/firmware_extract/main.cpp
@@ -0,0 +1,243 @@
1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#include <iostream>
20#include <ctime>
21#include <getpot/getpot.hpp>
22#include <utils.h>
23#include <firmware.h>
24
25
26static const char VERSION[] = "0.1";
27
28
29void print_version()
30{
31 std::cout
32 << "firmware_extract - Extracts files from a Creative firmware."
33 << std::endl
34 << "Version " << VERSION << std::endl
35 << "Copyright (c) 2007 Rasmus Ry" << std::endl;
36}
37
38void print_help()
39{
40 print_version();
41 std::cout
42 << "Usage: firmware_extract [command] [options]" << std::endl
43 << std::endl
44 << " Commands:" << std::endl
45 << " -h,--help" << std::endl
46 << " prints this message." << std::endl
47 << " -f,--firmware [file]" << std::endl
48 << " specifies the firmware arhive file name." << std::endl
49 << std::endl
50 << " Options:" << std::endl
51 << " -V,--verbose" << std::endl
52 << " prints verbose messages." << std::endl
53 << " -p,--prefix [prefix]" << std::endl
54 << " specifies a file name prefix for the extracted files." << std::endl
55 << std::endl
56 ;
57}
58
59
60struct save_entry_functor
61{
62 save_entry_functor(const std::string& fileprefix)
63 : _fileprefix(fileprefix) {}
64
65 bool operator()(const zen::firmware_entry& entry)
66 {
67 std::string filename = _fileprefix + entry.get_content_name();
68 std::ofstream ofs;
69 ofs.open(filename.c_str(), std::ios::binary);
70 if (!ofs)
71 false;
72
73 size_t off = entry.get_content_offset();
74 std::streamsize size = entry.get_bytes().size() - off;
75 ofs.write((const char*)&entry.get_bytes()[off], size);
76
77 return ofs.good();
78 }
79
80 const std::string& _fileprefix;
81}; //struct save_entry_functor
82
83struct print_entry_functor
84{
85 print_entry_functor(std::ostream& os, const std::string& fileprefix)
86 : _os(os), _fileprefix(fileprefix), num(0) {}
87
88 bool operator()(const zen::firmware_entry& entry)
89 {
90 std::string filename = _fileprefix + entry.get_content_name();
91 if (!num)
92 _os << "[./" << num++ << "]" << std::endl;
93 else
94 _os << "[../" << num++ << "]" << std::endl;
95 _os << "tag = " << entry.get_name() << std::endl;
96
97 if (entry.get_content_offset())
98 _os << "name = " << entry.get_content_name() << std::endl;
99
100 _os << "file = \'" << shared::double_quote(filename) << "\'"
101 << std::endl;
102
103 return _os.good();
104 }
105
106 std::ostream& _os;
107 const std::string& _fileprefix;
108 int num;
109}; //struct print_entry_functor
110
111
112int process_arguments(int argc, char* argv[])
113{
114 //--------------------------------------------------------------------
115 // Parse input variables.
116 //--------------------------------------------------------------------
117
118 GetPot cl(argc, argv);
119 if (cl.size() == 1 || cl.search(2, "-h", "--help"))
120 {
121 print_help();
122 return 1;
123 }
124
125 std::string firmwarename;
126 if (cl.search("-f") || cl.search("--firmware"))
127 firmwarename = cl.next("");
128 if (firmwarename.empty())
129 {
130 std::cerr << "Firmware archive must be specified." << std::endl;
131 return 2;
132 }
133
134 bool verbose = false;
135 if (cl.search("-V") || cl.search("--verbose"))
136 verbose = true;
137
138 std::string prefixname = shared::remove_extension(firmwarename) + "_";
139 if (cl.search("-p") || cl.search("--prefix"))
140 prefixname = cl.next(prefixname.c_str());
141
142
143 //--------------------------------------------------------------------
144 // Read the firmware archive.
145 //--------------------------------------------------------------------
146
147 if (verbose)
148 std::cout << "[*] Reading firmware archive..." << std::endl;
149
150 zen::firmware_archive archive(false);
151 std::ifstream ifs;
152 ifs.open(firmwarename.c_str(), std::ios::binary);
153 if (!ifs)
154 {
155 std::cerr << "Failed to open the firmware archive." << std::endl;
156 return 3;
157 }
158
159 if (!archive.read(ifs))
160 {
161 std::cerr << "Failed to read the firmware archive." << std::endl;
162 return 4;
163 }
164
165
166 //--------------------------------------------------------------------
167 // Generate a make file for the extracted firmware archive.
168 //--------------------------------------------------------------------
169
170 // Get make filename for the given input file.
171 std::string makefile = shared::replace_extension(firmwarename, ".mk");
172
173 if (verbose)
174 std::cout << "[*] Producing make file..." << std::endl;
175
176
177 // Produce make file for the given input file.
178 std::ofstream ofs;
179 ofs.open(makefile.c_str(), std::ios::binary);
180 if (!ofs)
181 {
182 std::cerr << "Failed to create firmware archive make file."
183 << std::endl;
184 return 5;
185 }
186
187 time_t timeval = time(NULL);
188 ofs << "# Make file generated at: " << ctime(&timeval);
189 ofs << "endian = " << (archive.is_big_endian() ? "big" : "little")
190 << std::endl;
191 ofs << "signed = " << (archive.is_signed() ? "true" : "false")
192 << std::endl;
193
194 ofs << "[children]" << std::endl;
195 ofs << "count = " << archive.get_children().size() << std::endl;
196
197 std::for_each(archive.get_children().begin(),
198 archive.get_children().end(),
199 print_entry_functor(ofs, prefixname));
200
201 ofs << "[neighbours]" << std::endl;
202 ofs << "count = " << archive.get_neighbours().size() << std::endl;
203 std::for_each(archive.get_neighbours().begin(),
204 archive.get_neighbours().end(),
205 print_entry_functor(ofs, prefixname));
206
207
208 //--------------------------------------------------------------------
209 // Save firmware entries.
210 //--------------------------------------------------------------------
211
212 if (verbose)
213 std::cout << "[*] Saving firmware entries..." << std::endl;
214
215 std::for_each(archive.get_children().begin(),
216 archive.get_children().end(),
217 save_entry_functor(prefixname));
218
219 std::for_each(archive.get_neighbours().begin(),
220 archive.get_neighbours().end(),
221 save_entry_functor(prefixname));
222
223 return 0;
224}
225
226int main(int argc, char* argv[])
227{
228 try
229 {
230 return process_arguments(argc, argv);
231 }
232 catch (const std::exception& xcpt)
233 {
234 std::cerr << "Exception caught: " << xcpt.what() << std::endl;
235 return -1;
236 }
237 catch (...)
238 {
239 std::cerr << "Unknown exception caught." << std::endl;
240 return -2;
241 }
242 return -3;
243}
diff --git a/utils/zenutils/source/firmware_make/CMakeLists.txt b/utils/zenutils/source/firmware_make/CMakeLists.txt
new file mode 100755
index 0000000000..518a008730
--- /dev/null
+++ b/utils/zenutils/source/firmware_make/CMakeLists.txt
@@ -0,0 +1,3 @@
1ADD_EXECUTABLE(firmware_make main.cpp)
2
3TARGET_LINK_LIBRARIES (firmware_make shared)
diff --git a/utils/zenutils/source/firmware_make/main.cpp b/utils/zenutils/source/firmware_make/main.cpp
new file mode 100755
index 0000000000..b0602b6ffe
--- /dev/null
+++ b/utils/zenutils/source/firmware_make/main.cpp
@@ -0,0 +1,261 @@
1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#include <iostream>
20#include <sstream>
21#include <getpot/getpot.hpp>
22#include <file.h>
23#include <firmware.h>
24#include <utils.h>
25
26
27static const char VERSION[] = "0.1";
28
29void print_version()
30{
31 std::cout
32 << "firmware_make - Creates a Creative firmware archive." << std::endl
33 << "Version " << VERSION << std::endl
34 << "Copyright (c) 2007 Rasmus Ry" << std::endl;
35}
36
37void print_help()
38{
39 print_version();
40 std::cout << std::endl
41 << "Usage: firmware_make [command] [options]" << std::endl
42 << std::endl
43 << " Commands:" << std::endl
44 << " -h,--help" << std::endl
45 << " prints this message." << std::endl
46 << " -m,--makefile [file]" << std::endl
47 << " specifies the .mk file to build the firmware archive from."
48 << std::endl << std::endl
49 << " Options:" << std::endl
50 << " -V,--verbose" << std::endl
51 << " prints verbose messages." << std::endl
52 << " -f,--firmware [file]" << std::endl
53 << " specifies the output firmware file name" << std::endl
54 << std::endl
55 ;
56}
57
58dword get_tag_value(std::string tag)
59{
60 if (tag[0] == '0' && tag[1] == 'x')
61 {
62 dword val = 0;
63 if (sscanf(tag.c_str(), "0x%08X", &val) == 1)
64 return val;
65 if (sscanf(tag.c_str(), "0x%08x", &val) == 1)
66 return val;
67 }
68 else
69 {
70 return shared::swap(*(dword*)&tag[0]);
71 }
72 return 0;
73}
74
75bool process_child(const GetPot& mkfile, const std::string& root, int index,
76 zen::firmware_entry& entry)
77{
78 std::stringstream sstm;
79 sstm << root << "/" << index;
80 std::string var = sstm.str() + "/tag";
81 std::string tag = mkfile(var.c_str(), "");
82 var = sstm.str() + "/name";
83 std::string name = mkfile(var.c_str(), "");
84 var = sstm.str() + "/file";
85 std::string file = mkfile(var.c_str(), "");
86
87 if (file.empty() || tag.empty())
88 {
89 std::cerr << "Invalid file or tag for var: " << sstm.str()
90 << std::endl;
91 return false;
92 }
93
94 shared::bytes buffer;
95 if (!shared::read_file(file, buffer))
96 {
97 std::cerr << "Failed to read the file: " << file << std::endl;
98 return false;
99 }
100
101 entry.get_bytes().clear();
102 entry.get_header().tag = get_tag_value(tag);
103 size_t contoff = entry.get_content_offset();
104 if (contoff)
105 {
106 entry.get_bytes().resize(contoff, 0);
107 if (!name.empty())
108 {
109 size_t endoff = entry.is_big_endian() ? 1 : 0;
110 for (int i = 0; i < name.size(); ++i)
111 entry.get_bytes()[i * 2 + endoff] = name[i];
112 }
113 }
114 entry.get_bytes().insert(entry.get_bytes().end(), buffer.begin(),
115 buffer.end());
116
117 entry.get_header().size = entry.get_bytes().size();
118
119 return true;
120}
121
122int process_arguments(int argc, char* argv[])
123{
124 //--------------------------------------------------------------------
125 // Parse input variables.
126 //--------------------------------------------------------------------
127
128 GetPot cl(argc, argv);
129 if (cl.size() == 1 || cl.search(2, "-h", "--help"))
130 {
131 print_help();
132 return 1;
133 }
134
135 std::string makefile;
136 if (cl.search("-m") || cl.search("--makefile"))
137 makefile = cl.next("");
138 if (makefile.empty())
139 {
140 std::cerr << "Makefile must be specified." << std::endl;
141 return 2;
142 }
143
144 std::string firmware;
145 if (cl.search("-f") || cl.search("--firmware"))
146 firmware = cl.next("");
147 if (firmware.empty())
148 {
149 std::cerr << "Firmware must be specified." << std::endl;
150 return 3;
151 }
152
153 bool verbose = false;
154 if (cl.search("-V") || cl.search("--verbose"))
155 verbose = true;
156
157 GetPot mkfile(makefile.c_str());
158 if (verbose)
159 mkfile.print();
160
161 bool big_endian;
162 std::string endian = mkfile("endian", "little");
163 if (endian == "little")
164 {
165 big_endian = false;
166 }
167 else if (endian == "big")
168 {
169 big_endian = true;
170 }
171 else
172 {
173 std::cerr << "Invalid value of 'endian'" << std::endl;
174 return 4;
175 }
176
177 zen::firmware_archive archive(big_endian);
178 int childcount = mkfile("children/count", 0);
179 if (!childcount)
180 {
181 std::cerr << "A firmware archive must have at least one child entry."
182 << std::endl;
183 return 5;
184 }
185
186 for (int i = 0; i < childcount; i++)
187 {
188 zen::firmware_entry entry(big_endian);
189 if (!process_child(mkfile, "children", i, entry))
190 {
191 return 6;
192 }
193 archive.get_children().push_back(entry);
194 }
195
196 int neighbourcount = mkfile("neighbours/count", 0);
197 for (int i = 0; i < neighbourcount; i++)
198 {
199 zen::firmware_entry entry(big_endian);
200 if (!process_child(mkfile, "neighbours", i, entry))
201 {
202 return 7;
203 }
204 archive.get_neighbours().push_back(entry);
205 }
206
207 std::ofstream ofs;
208 ofs.open(firmware.c_str(), std::ios::out|std::ios::binary|std::ios::trunc);
209 if (!ofs)
210 {
211 std::cerr << "Failed to create the firmware file." << std::endl;
212 return 8;
213 }
214
215 if (!archive.write(ofs))
216 {
217 std::cerr << "Failed to save the firmware archive." << std::endl;
218 return 9;
219 }
220 ofs.close();
221
222 size_t length = archive.calc_size();
223 if (!length)
224 {
225 std::cerr << "Failed to determine the size of the firmware archive."
226 << std::endl;
227 return 10;
228 }
229
230 int align = length % 4;
231 if (align)
232 {
233 shared::bytes padding(4 - align, 0);
234 if (!shared::write_file(firmware, padding, false, length))
235 {
236 std::cerr << "Failed to write padding data." << std::endl;
237 return 11;
238 }
239 }
240
241 return 0;
242}
243
244int main(int argc, char* argv[])
245{
246 try
247 {
248 return process_arguments(argc, argv);
249 }
250 catch (const std::exception& xcpt)
251 {
252 std::cerr << "Exception caught: " << xcpt.what() << std::endl;
253 return -1;
254 }
255 catch (...)
256 {
257 std::cerr << "Unknown exception caught." << std::endl;
258 return -2;
259 }
260 return -3;
261}
diff --git a/utils/zenutils/source/shared/CMakeLists.txt b/utils/zenutils/source/shared/CMakeLists.txt
new file mode 100755
index 0000000000..2e42dbbe74
--- /dev/null
+++ b/utils/zenutils/source/shared/CMakeLists.txt
@@ -0,0 +1,16 @@
1PROJECT(shared)
2
3# source files for shared
4SET(shared_srcs
5 cenc.cpp
6 crypt.cpp
7 file.cpp
8 firmware.cpp
9 pe.cpp
10 updater.cpp
11 utils.cpp
12)
13
14ADD_LIBRARY(shared ${shared_srcs})
15TARGET_LINK_LIBRARIES(shared pelib)
16TARGET_LINK_LIBRARIES(shared zlib)
diff --git a/utils/zenutils/source/shared/cenc.cpp b/utils/zenutils/source/shared/cenc.cpp
new file mode 100755
index 0000000000..932bee4625
--- /dev/null
+++ b/utils/zenutils/source/shared/cenc.cpp
@@ -0,0 +1,333 @@
1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#include "cenc.h"
20#include <firmware.h>
21#include <stdexcept>
22
23
24namespace {
25const byte CODE_MASK = 0xC0;
26const byte ARGS_MASK = 0x3F;
27
28const byte REPEAT_CODE = 0x00;
29const byte BLOCK_CODE = 0x40;
30const byte LONG_RUN_CODE = 0x80;
31const byte SHORT_RUN_CODE = 0xC0;
32
33const byte BLOCK_ARGS = 0x1F;
34const byte BLOCK_MODE = 0x20;
35
36
37void decode_run(byte* dst, word len, byte val,
38 int& dstidx)
39{
40 memset(dst + dstidx, val, len);
41 dstidx += len;
42}
43
44void decode_pattern(byte* src, byte* dst,
45 word len, int& srcidx, int& dstidx,
46 bool bdecode, int npasses)
47{
48 for (int i = 0; i < npasses; i++)
49 {
50 if (bdecode)
51 {
52 for (int j = 0; j < len; j++)
53 {
54 word c, d;
55 c = src[srcidx + j];
56 d = (c >> 5) & 7;
57 c = (c << 3) & 0xF8;
58 src[srcidx + j] = static_cast<byte>(c | d);
59 }
60 bdecode = false;
61 }
62 memcpy(dst + dstidx, src + srcidx, len);
63 dstidx += len;
64 }
65 srcidx += len;
66}
67}; //namespace
68
69int zen::cenc_decode(byte* src, int srclen, byte* dst, int dstlen)
70{
71 if (!src || !srclen || !dst || !dstlen)
72 {
73 throw std::invalid_argument("Invalid argument(s).");
74 }
75
76 int i = 0, j = 0;
77 do
78 {
79 word c, d, e;
80 c = src[i++];
81 switch (c & CODE_MASK)
82 {
83 case REPEAT_CODE: // 2 bytes
84 d = src[i++];
85 d = d + 2;
86
87 e = (c & ARGS_MASK) + 2;
88
89 decode_pattern(src, dst, e, i, j, false, d);
90 break;
91
92 case BLOCK_CODE: // 1/2/3 bytes
93 d = c & BLOCK_ARGS;
94 if (!(c & BLOCK_MODE))
95 {
96 e = src[i++];
97 e = (d << 8) + (e + 0x21);
98
99 d = static_cast<word>(i ^ j);
100 }
101 else
102 {
103 e = d + 1;
104
105 d = static_cast<word>(i ^ j);
106 }
107 if (d & 1)
108 {
109 i++;
110 }
111
112 decode_pattern(src, dst, e, i, j, true, 1);
113 break;
114
115 case LONG_RUN_CODE: // 3 bytes
116 d = src[i++];
117 e = ((c & ARGS_MASK) << 8) + (d + 0x42);
118
119 d = src[i++];
120 d = ((d & 7) << 5) | ((d >> 3) & 0x1F);
121
122 decode_run(dst, e, static_cast<byte>(d), j);
123 break;
124
125 case SHORT_RUN_CODE: // 2 bytes
126 d = src[i++];
127 d = ((d & 3) << 6) | ((d >> 2) & 0x3F);
128
129 e = (c & ARGS_MASK) + 2;
130
131 decode_run(dst, e, static_cast<byte>(d), j);
132 break;
133 };
134 } while (i < srclen && j < dstlen);
135
136 return j;
137}
138
139namespace {
140int encode_run(byte* dst, int& dstidx, byte val, int len, int dstlen)
141{
142 if (len < 2)
143 throw std::invalid_argument("Length is too small.");
144
145 int ret = 0;
146 if (len <= 0x41)
147 {
148 if ((dstidx + 2) > dstlen)
149 throw std::runtime_error("Not enough space to store run.");
150
151 dst[dstidx++] = SHORT_RUN_CODE | (((len - 2) & ARGS_MASK));
152 dst[dstidx++] = ((val >> 6) & 3) | ((val & 0x3F) << 2);
153
154 ret = 2;
155 }
156 else if (len <= 0x4041)
157 {
158 if ((dstidx + 3) > dstlen)
159 throw std::runtime_error("Not enough space to store run.");
160
161 byte b1 = (len - 0x42) >> 8;
162 byte b2 = (len - 0x42) & 0xFF;
163
164 dst[dstidx++] = LONG_RUN_CODE | ((b1 & ARGS_MASK));
165 dst[dstidx++] = b2;
166 dst[dstidx++] = ((val >> 5) & 7) | ((val & 0x1F) << 3);
167
168 ret = 3;
169 }
170 else
171 {
172 int long_count = len / 0x4041;
173 int short_len = len % 0x4041;
174 bool toosmall = short_len == 1;
175
176 int run_len = 0x4041;
177 for (int i = 0; i < long_count; i++)
178 {
179 if (toosmall && (i == (long_count-1)))
180 {
181 run_len--;
182 toosmall = false;
183 }
184 int tmp = encode_run(dst, dstidx, val, run_len, dstlen);
185 if (!tmp) return 0;
186 ret += tmp;
187 len -= run_len;
188 }
189
190 if (len)
191 {
192 int short_count = len / 0x41;
193 int short_rest = short_count ? (len % 0x41) : 0;
194 toosmall = short_rest == 1;
195
196 run_len = 0x41;
197 for (int i = 0; i < short_count; i++)
198 {
199 if (toosmall && (i == (short_count-1)))
200 {
201 run_len--;
202 toosmall = false;
203 }
204 int tmp = encode_run(dst, dstidx, val, run_len, dstlen);
205 if (!tmp) return 0;
206 ret += tmp;
207 len -= run_len;
208 }
209 int tmp = encode_run(dst, dstidx, val, len, dstlen);
210 if (!tmp) return 0;
211 ret += tmp;
212 len -= len;
213 }
214 }
215
216 return ret;
217}
218
219int encode_block(byte* dst, int& dstidx, byte* src, int& srcidx, int len,
220 int dstlen)
221{
222 if (len < 1)
223 throw std::invalid_argument("Length is too small.");
224
225 int startidx = dstidx;
226 if (len < 0x21)
227 {
228 if ((dstidx + 2 + len) > dstlen)
229 throw std::runtime_error("Not enough space to store block.");
230
231 dst[dstidx++] = BLOCK_CODE | BLOCK_MODE | ((len - 1) & BLOCK_ARGS);
232 if ((dstidx ^ srcidx) & 1)
233 dst[dstidx++] = 0;
234
235 for (int i = 0; i < len; i++)
236 {
237 byte c = src[srcidx++];
238 byte d = (c & 7) << 5;
239 c = (c & 0xF8) >> 3;
240 dst[dstidx++] = c | d;
241 }
242 }
243 else if (len < 0x2021)
244 {
245 if ((dstidx + 3 + len) > dstlen)
246 throw std::runtime_error("Not enough space to store block.");
247
248 dst[dstidx++] = BLOCK_CODE | (((len - 0x21) >> 8) & BLOCK_ARGS);
249 dst[dstidx++] = (len - 0x21) & 0xFF;
250 if ((dstidx ^ srcidx) & 1)
251 dst[dstidx++] = 0;
252
253 for (int i = 0; i < len; i++)
254 {
255 byte c = src[srcidx++];
256 byte d = (c & 7) << 5;
257 c = (c & 0xF8) >> 3;
258 dst[dstidx++] = c | d;
259 }
260 }
261 else
262 {
263 int longblocks = len / 0x2020;
264 int rest = len % 0x2020;
265 for (int i = 0; i < longblocks; i++)
266 {
267 int tmp = encode_block(dst, dstidx, src, srcidx, 0x2020, dstlen);
268 if (!tmp) return 0;
269 }
270 if (rest)
271 {
272 int shortblocks = rest / 0x20;
273 for (int i = 0; i < shortblocks; i++)
274 {
275 int tmp = encode_block(dst, dstidx, src, srcidx, 0x20, dstlen);
276 if (!tmp) return 0;
277 }
278 rest = rest % 0x20;
279 int tmp = encode_block(dst, dstidx, src, srcidx, rest, dstlen);
280 if (!tmp) return 0;
281 }
282 }
283
284 return (dstidx - startidx);
285}
286}; //namespace
287
288int zen::cenc_encode(byte* src, int srclen, byte* dst, int dstlen)
289{
290 if (!src || !srclen || !dst || !dstlen)
291 {
292 throw std::invalid_argument("Invalid argument(s).");
293 }
294
295 int i = 0, j = 0, k = 0;
296 word c, d, e;
297 int runlen = 0;
298 while (i < srclen && j < dstlen)
299 {
300 k = i;
301 c = src[i++];
302 runlen = 1;
303 while (i < srclen && src[i] == c)
304 {
305 runlen++;
306 i++;
307 }
308 if (runlen >= 2)
309 {
310 if (!encode_run(dst, j, c, runlen, dstlen))
311 return 0;
312 }
313 else
314 {
315 runlen = 0;
316 i = k;
317 while (i < (srclen - 1) && (src[i] != src[i + 1]))
318 {
319 runlen++;
320 i++;
321 }
322 if (i == (srclen - 1))
323 {
324 runlen++;
325 i++;
326 }
327 if (!encode_block(dst, j, src, k, runlen, dstlen))
328 return 0;
329 }
330 }
331
332 return j;
333}
diff --git a/utils/zenutils/source/shared/cenc.h b/utils/zenutils/source/shared/cenc.h
new file mode 100755
index 0000000000..12a7c92516
--- /dev/null
+++ b/utils/zenutils/source/shared/cenc.h
@@ -0,0 +1,29 @@
1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#ifndef ZEN_CENC_H_INCLUDED
20#define ZEN_CENC_H_INCLUDED
21
22#include <utils.h>
23
24namespace zen {
25 int cenc_decode(byte* src, int srclen, byte* dst, int dstlen);
26 int cenc_encode(byte* src, int srclen, byte* dst, int dstlen);
27}; //namespace zen
28
29#endif //CENC_H_INCLUDED
diff --git a/utils/zenutils/source/shared/crypt.cpp b/utils/zenutils/source/shared/crypt.cpp
new file mode 100755
index 0000000000..9c2d33870c
--- /dev/null
+++ b/utils/zenutils/source/shared/crypt.cpp
@@ -0,0 +1,91 @@
1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#include "crypt.h"
20#include <stdexcept>
21#include <beecrypt/hmacsha1.h>
22#include <beecrypt/blockmode.h>
23#include <beecrypt/blowfish.h>
24
25
26bool zen::hmac_sha1_calc(const byte* key, size_t keylen, const byte* data,
27 size_t datalen, byte* sig, size_t* siglen)
28{
29 hmacsha1Param param;
30 if (hmacsha1Setup(&param, key, keylen * 8))
31 return false;
32 if (hmacsha1Update(&param, data, datalen))
33 return false;
34 if (hmacsha1Digest(&param, sig))
35 return false;
36 return true;
37}
38
39bool zen::bf_cbc_encrypt(const byte* key, size_t keylen, byte* data,
40 size_t datalen, const byte* iv)
41{
42 if (datalen % blowfish.blocksize)
43 throw std::invalid_argument(
44 "The length must be aligned on a 8 byte boundary.");
45
46 blowfishParam param;
47 if (blowfishSetup(&param, key, keylen * 8, ENCRYPT))
48 return false;
49 if (blowfishSetIV(&param, iv))
50 return false;
51
52 byte* plain = new byte[datalen];
53 memcpy(plain, data, datalen);
54
55 unsigned int nblocks = datalen / blowfish.blocksize;
56 if (blockEncryptCBC(&blowfish, &param, (uint32_t*)data, (uint32_t*)plain,
57 nblocks))
58 {
59 delete [] plain;
60 return false;
61 }
62
63 return true;
64}
65
66bool zen::bf_cbc_decrypt(const byte* key, size_t keylen, byte* data,
67 size_t datalen, const byte* iv)
68{
69 if (datalen % blowfish.blocksize)
70 throw std::invalid_argument(
71 "The length must be aligned on a 8 byte boundary.");
72
73 blowfishParam param;
74 if (blowfishSetup(&param, key, keylen * 8, ENCRYPT))
75 return false;
76 if (blowfishSetIV(&param, iv))
77 return false;
78
79 byte* cipher = new byte[datalen];
80 memcpy(cipher, data, datalen);
81
82 unsigned int nblocks = datalen / blowfish.blocksize;
83 if (blockDecryptCBC(&blowfish, &param, (uint32_t*)data, (uint32_t*)cipher,
84 nblocks))
85 {
86 delete [] cipher;
87 return false;
88 }
89
90 return true;
91}
diff --git a/utils/zenutils/source/shared/crypt.h b/utils/zenutils/source/shared/crypt.h
new file mode 100755
index 0000000000..a057055b70
--- /dev/null
+++ b/utils/zenutils/source/shared/crypt.h
@@ -0,0 +1,30 @@
1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#ifndef ZEN_CRYPT_H_INCLUDED
20#define ZEN_CRYPT_H_INCLUDED
21
22#include <utils.h>
23
24namespace zen {
25 bool hmac_sha1_calc(const byte* key, size_t keylen, const byte* data, size_t datalen, byte* sig, size_t* siglen);
26 bool bf_cbc_encrypt(const byte* key, size_t keylen, byte* data, size_t datalen, const byte* iv);
27 bool bf_cbc_decrypt(const byte* key, size_t keylen, byte* data, size_t datalen, const byte* iv);
28}; //namespace zen
29
30#endif //ZEN_CRYPT_H_INCLUDED
diff --git a/utils/zenutils/source/shared/file.cpp b/utils/zenutils/source/shared/file.cpp
new file mode 100755
index 0000000000..2c31498972
--- /dev/null
+++ b/utils/zenutils/source/shared/file.cpp
@@ -0,0 +1,106 @@
1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#include "file.h"
20#include <fstream>
21
22
23bool shared::read_file(const std::string& filename, bytes& buffer,
24 std::streampos offset, std::streamsize count)
25{
26 std::ifstream ifs;
27 ifs.open(filename.c_str(), std::ios::binary);
28 if (!ifs)
29 {
30 return false;
31 }
32
33 std::ifstream::pos_type startpos = offset;
34 ifs.seekg(offset, std::ios::beg);
35 if (count == -1)
36 ifs.seekg(0, std::ios::end);
37 else
38 ifs.seekg(count, std::ios::cur);
39 std::ifstream::pos_type endpos = ifs.tellg();
40
41 buffer.resize(endpos-startpos);
42 ifs.seekg(offset, std::ios::beg);
43
44 ifs.read((char*)&buffer[0], endpos-startpos);
45
46 ifs.close();
47 return ifs.good();
48}
49
50
51bool shared::write_file(const std::string& filename, bytes& buffer,
52 bool truncate, std::streampos offset,
53 std::streamsize count)
54{
55 std::ios::openmode mode = std::ios::in|std::ios::out|std::ios::binary;
56 if (truncate)
57 mode |= std::ios::trunc;
58
59 std::fstream ofs;
60 ofs.open(filename.c_str(), mode);
61 if (!ofs)
62 {
63 return false;
64 }
65
66 if (count == -1)
67 count = buffer.size();
68 else if (count > buffer.size())
69 return false;
70
71 ofs.seekg(offset, std::ios::beg);
72
73 ofs.write((char*)&buffer[0], count);
74
75 ofs.close();
76 return ofs.good();
77}
78
79bool shared::file_exists(const std::string& filename)
80{
81 std::ifstream ifs;
82 ifs.open(filename.c_str(), std::ios::in);
83 if (ifs.is_open())
84 {
85 ifs.close();
86 return true;
87 }
88 return false;
89}
90
91bool shared::copy_file(const std::string& srcname, const std::string& dstname)
92{
93 bytes buffer;
94 if (!read_file(srcname, buffer))
95 return false;
96 return write_file(dstname, buffer, true);
97}
98
99bool shared::backup_file(const std::string& filename, bool force)
100{
101 std::string backupname = filename + ".bak";
102 if (!force)
103 if (file_exists(backupname))
104 return true;
105 return copy_file(filename, backupname);
106}
diff --git a/utils/zenutils/source/shared/file.h b/utils/zenutils/source/shared/file.h
new file mode 100755
index 0000000000..8fa533c981
--- /dev/null
+++ b/utils/zenutils/source/shared/file.h
@@ -0,0 +1,36 @@
1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#ifndef SHARED_FILE_H_INCLUDED
20#define SHARED_FILE_H_INCLUDED
21
22#include <string>
23#include <iostream>
24#include "utils.h"
25
26namespace shared {
27 bool read_file(const std::string& filename, bytes& buffer,
28 std::streampos offset = 0, std::streamsize count = -1);
29 bool write_file(const std::string& filename, bytes& buffer, bool truncate,
30 std::streampos offset = 0, std::streamsize count = -1);
31 bool file_exists(const std::string& filename);
32 bool copy_file(const std::string& srcname, const std::string& dstname);
33 bool backup_file(const std::string& filename, bool force = false);
34}; //namespace shared
35
36#endif //SHARED_FILE_H_INCLUDED
diff --git a/utils/zenutils/source/shared/firmware.cpp b/utils/zenutils/source/shared/firmware.cpp
new file mode 100755
index 0000000000..7767b55d8f
--- /dev/null
+++ b/utils/zenutils/source/shared/firmware.cpp
@@ -0,0 +1,387 @@
1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#include "firmware.h"
20#include <iostream>
21#include <stdexcept>
22
23
24zen::firmware_entry::firmware_entry(bool big_endian)
25 : _big_endian(big_endian)
26{
27}
28
29zen::firmware_entry::firmware_entry(const firmware_entry& copy)
30{
31 assign(copy);
32}
33
34zen::firmware_entry& zen::firmware_entry::operator=(const firmware_entry& right)
35{
36 assign(right);
37 return *this;
38}
39
40
41bool zen::firmware_entry::read(std::istream& is)
42{
43 // Read the header.
44 is.read((char*)&_header, sizeof(firmware_header_t));
45 if (!is.good())
46 return false;
47
48 // If the firmware is big-endian, swap the header values to little-endian.
49 if (_big_endian)
50 {
51 _header.tag = shared::swap(_header.tag);
52 if (_header.tag != 'NULL')
53 {
54 _header.size = shared::swap(_header.size);
55 }
56 }
57
58 // Resize the bytes buffer to the size specified in the header.
59 _bytes.resize(_header.size);
60
61 // Read the entry contents.
62 is.read(reinterpret_cast<char*>(&_bytes[0]),
63 _header.size);
64
65 return is.good();
66}
67
68bool zen::firmware_entry::write(std::ostream& os) const
69{
70 // Form a header using the current size of the bytes buffer.
71 firmware_header_t header = {
72 _header.tag,
73 static_cast<dword>(_bytes.size())
74 };
75
76 // If the firmware is big-endian, swap the header values back into big-endian.
77 if (_big_endian)
78 {
79 if (header.tag != 'NULL')
80 {
81 header.size = shared::swap(header.size);
82 }
83 header.tag = shared::swap(header.tag);
84 }
85
86 // Write the header.
87 os.write((const char*)&header, sizeof(firmware_header_t));
88 if (!os.good())
89 return false;
90
91 // Write the entry contents.
92 os.write(reinterpret_cast<const char*>(&_bytes[0]),
93 static_cast<std::streamsize>(_bytes.size()));
94
95 return os.good();
96}
97
98
99bool zen::firmware_entry::is_big_endian() const
100{
101 return _big_endian;
102}
103
104const zen::firmware_header_t& zen::firmware_entry::get_header() const
105{
106 return _header;
107}
108zen::firmware_header_t& zen::firmware_entry::get_header()
109{
110 return _header;
111}
112
113const shared::bytes& zen::firmware_entry::get_bytes() const
114{
115 return _bytes;
116}
117shared::bytes& zen::firmware_entry::get_bytes()
118{
119 return _bytes;
120}
121
122
123std::string zen::firmware_entry::get_name() const
124{
125 char name[5];
126 *(dword*)name = shared::swap(_header.tag);
127 name[4] = '\0';
128
129 // Determine if all characters in the tag are printable.
130 bool isprintable = true;
131 for (int i = 0; i < 4; i++)
132 {
133 if (!isprint((byte)name[i]))
134 {
135 isprintable = false;
136 break;
137 }
138 }
139
140 // If they are, simply return the tag as a string.
141 if (isprintable)
142 {
143 return std::string(name);
144 }
145
146 // Otherwise, encode the tag into a hexadecimal string.
147 char buffer[11];
148 sprintf(buffer, "0x%08x", _header.tag);
149 return std::string(buffer);
150}
151
152std::string zen::firmware_entry::get_content_name() const
153{
154 std::string name = get_name();
155 if (name == "DATA")
156 {
157 name = "";
158 int nameoff = is_big_endian() ? 1 : 0;
159 for (int i = 0; i < 16; i++)
160 {
161 char c = get_bytes()[i * 2 + nameoff];
162 if (!c)
163 break;
164 name += c;
165 }
166 }
167 else if (name == "EXT0")
168 {
169 name = "";
170 int nameoff = is_big_endian() ? 1 : 0;
171 for (int i = 0; i < 12; i++)
172 {
173 char c = get_bytes()[i * 2 + nameoff];
174 if (!c)
175 break;
176 name += c;
177 }
178 }
179 return name;
180}
181
182size_t zen::firmware_entry::get_content_offset() const
183{
184 std::string name = get_name();
185 if (name == "DATA")
186 {
187 return 32;
188 }
189 else if (name == "EXT0")
190 {
191 return 24;
192 }
193 return 0;
194}
195
196size_t zen::firmware_entry::calc_size() const
197{
198 return _bytes.size() + sizeof(firmware_header_t);
199}
200
201
202void zen::firmware_entry::assign(const firmware_entry& copy)
203{
204 _big_endian = copy._big_endian;
205 _header.tag = copy._header.tag;
206 _header.size = copy._header.size;
207 _bytes.assign(copy._bytes.begin(), copy._bytes.end());
208}
209
210
211
212zen::firmware_archive::firmware_archive(bool big_endian)
213 : _big_endian(big_endian)
214{
215}
216
217zen::firmware_archive::firmware_archive(const firmware_archive& copy)
218{
219 assign(copy);
220}
221
222zen::firmware_archive& zen::firmware_archive::operator=(const firmware_archive& right)
223{
224 assign(right);
225 return *this;
226}
227
228
229bool zen::firmware_archive::read(std::istream& is)
230{
231 // Read the root entry's header.
232 firmware_header_t root;
233 is.read((char*)&root, sizeof(firmware_header_t));
234 if (!is.good())
235 return false;
236
237 if ((root.tag != 'CIFF') && (root.tag != 'FFIC'))
238 {
239 throw std::runtime_error("Invalid firmware archive format!");
240 }
241
242 _big_endian = root.tag == 'FFIC' ? true : false;
243 if (_big_endian)
244 {
245 root.tag = shared::swap(root.tag);
246 root.size = shared::swap(root.size);
247 }
248
249 // Save the current stream position.
250 std::istream::pos_type endpos = is.tellg();
251 std::istream::pos_type curpos = endpos;
252 endpos += std::istream::pos_type(root.size);
253
254 // Read untill the end of the root entry contents.
255 while (curpos < endpos)
256 {
257 firmware_entry entry(_big_endian);
258 if (!entry.read(is))
259 return false;
260
261 _children.push_back(entry);
262 curpos = is.tellg();
263 }
264
265 curpos = is.tellg();
266 is.seekg(0, std::ios::end);
267 endpos = is.tellg();
268 is.seekg(curpos);
269
270 // Read untill the end of the file.
271 while (((size_t)curpos + sizeof(firmware_header_t)) < endpos)
272 {
273 firmware_entry entry(_big_endian);
274 if (!entry.read(is))
275 return false;
276
277 _neighbours.push_back(entry);
278 curpos = is.tellg();
279 }
280
281 return true;
282}
283
284bool zen::firmware_archive::write(std::ostream& os) const
285{
286 // Read the root entry's header.
287 firmware_header_t root = {'CIFF', 0};
288
289 // Calculate the total size of all the children entries.
290 for (firmware_entries::const_iterator i = _children.begin();
291 i != _children.end(); ++i)
292 {
293 root.size += i->calc_size();
294 }
295
296 // If the firmware is big-endian, swap the header values back into big-endian.
297 if (_big_endian)
298 {
299 root.tag = shared::swap(root.tag);
300 root.size = shared::swap(root.size);
301 }
302
303 // Write the header.
304 os.write((const char*)&root, sizeof(firmware_header_t));
305 if (!os.good())
306 return false;
307
308 // Write all the child entries.
309 for (firmware_entries::const_iterator i = _children.begin();
310 i != _children.end(); ++i)
311 {
312 if (!i->write(os))
313 return false;
314 }
315
316 // Write all the neighbour entries.
317 for (firmware_entries::const_iterator i = _neighbours.begin();
318 i != _neighbours.end(); ++i)
319 {
320 if (!i->write(os))
321 return false;
322 }
323
324 return true;
325}
326
327
328bool zen::firmware_archive::is_big_endian() const
329{
330 return _big_endian;
331}
332
333const zen::firmware_entries& zen::firmware_archive::get_children() const
334{
335 return _children;
336}
337zen::firmware_entries& zen::firmware_archive::get_children()
338{
339 return _children;
340}
341
342const zen::firmware_entries& zen::firmware_archive::get_neighbours() const
343{
344 return _neighbours;
345}
346zen::firmware_entries& zen::firmware_archive::get_neighbours()
347{
348 return _neighbours;
349}
350
351bool zen::firmware_archive::is_signed() const
352{
353 for (firmware_entries::const_iterator i = _neighbours.begin();
354 i != _neighbours.end(); i++)
355 {
356 if (i->get_name() == "NULL")
357 return true;
358 }
359 return false;
360}
361
362size_t zen::firmware_archive::calc_size() const
363{
364 size_t size = sizeof(firmware_header_t);
365
366 for (firmware_entries::const_iterator i = _children.begin();
367 i != _children.end(); i++)
368 {
369 size += i->calc_size();
370 }
371
372 for (firmware_entries::const_iterator i = _neighbours.begin();
373 i != _neighbours.end(); i++)
374 {
375 size += i->calc_size();
376 }
377
378 return size;
379}
380
381
382void zen::firmware_archive::assign(const firmware_archive& copy)
383{
384 _big_endian = copy._big_endian;
385 _children.assign(copy._children.begin(), copy._children.end());
386 _neighbours.assign(copy._neighbours.begin(), copy._neighbours.end());
387}
diff --git a/utils/zenutils/source/shared/firmware.h b/utils/zenutils/source/shared/firmware.h
new file mode 100755
index 0000000000..3542186590
--- /dev/null
+++ b/utils/zenutils/source/shared/firmware.h
@@ -0,0 +1,92 @@
1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#ifndef ZEN_FIRMWARE_H_INCLUDED
20#define ZEN_FIRMWARE_H_INCLUDED
21
22#include <list>
23#include <utils.h>
24
25namespace zen {
26 struct firmware_header_t
27 {
28 dword tag;
29 dword size;
30 }; //struct firmware_header_t
31
32 class firmware_entry
33 {
34 public:
35 firmware_entry(bool big_endian);
36 firmware_entry(const firmware_entry& copy);
37 firmware_entry& operator=(const firmware_entry& right);
38
39 bool read(std::istream& is);
40 bool write(std::ostream& os) const;
41
42 bool is_big_endian() const;
43 const firmware_header_t& get_header() const;
44 firmware_header_t& get_header();
45 const shared::bytes& get_bytes() const;
46 shared::bytes& get_bytes();
47
48 std::string get_name() const;
49 std::string get_content_name() const;
50 size_t get_content_offset() const;
51 size_t calc_size() const;
52
53 protected:
54 void assign(const firmware_entry& copy);
55
56 private:
57 bool _big_endian;
58 firmware_header_t _header;
59 shared::bytes _bytes;
60 }; //class firmware_entry
61
62 typedef std::list<firmware_entry> firmware_entries;
63
64 class firmware_archive
65 {
66 public:
67 firmware_archive(bool big_endian);
68 firmware_archive(const firmware_archive& copy);
69 firmware_archive& operator=(const firmware_archive& right);
70
71 bool read(std::istream& is);
72 bool write(std::ostream& os) const;
73
74 bool is_big_endian() const;
75 const firmware_entries& get_children() const;
76 firmware_entries& get_children();
77 const firmware_entries& get_neighbours() const;
78 firmware_entries& get_neighbours();
79 bool is_signed() const;
80 size_t calc_size() const;
81
82 protected:
83 void assign(const firmware_archive& copy);
84
85 private:
86 firmware_entries _children;
87 firmware_entries _neighbours;
88 bool _big_endian;
89 }; //class firmware_archive
90}; //namespace zen
91
92#endif //ZEN_FIRMWARE_ARCHIVE_H_INCLUDED
diff --git a/utils/zenutils/source/shared/pe.cpp b/utils/zenutils/source/shared/pe.cpp
new file mode 100755
index 0000000000..c86ec6c8cc
--- /dev/null
+++ b/utils/zenutils/source/shared/pe.cpp
@@ -0,0 +1,128 @@
1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#include "pe.h"
20
21
22shared::pe_file::pe_file(PeLib::PeFile* pef) : _pef(pef)
23{
24}
25shared::pe_file::~pe_file()
26{
27 if (_pef != NULL)
28 delete _pef;
29}
30
31bool shared::pe_file::is_valid() const
32{
33 if (_pef->getBits() == 32)
34 {
35 PeLib::PeHeader32& pef32 = static_cast<PeLib::PeFile32*>(_pef)->peHeader();
36 if (!pef32.isValid())
37 return false;
38 return true;
39 }
40 else if (_pef->getBits() == 64)
41 {
42 PeLib::PeHeader64& pef64 = static_cast<PeLib::PeFile64*>(_pef)->peHeader();
43 if (!pef64.isValid())
44 return false;
45 return true;
46 }
47 return false;
48}
49
50bool shared::pe_file::read(const std::string& filename)
51{
52 if (_pef != NULL)
53 {
54 delete _pef;
55 _pef = NULL;
56 }
57
58 _pef = PeLib::openPeFile(filename);
59 if (!_pef)
60 {
61 return false;
62 }
63 if (_pef->readMzHeader())
64 {
65 delete _pef;
66 return false;
67 }
68 if (!_pef->mzHeader().isValid())
69 {
70 delete _pef;
71 return false;
72 }
73 if (_pef->readPeHeader())
74 {
75 delete _pef;
76 return false;
77 }
78 if (!is_valid())
79 {
80 delete _pef;
81 return false;
82 }
83 return true;
84}
85
86bool shared::pe_file::find_section(const std::string& name, section_info& info) const
87{
88 if (_pef->getBits() == 32)
89 return find_section(static_cast<PeLib::PeFile32*>(_pef),
90 name, info);
91 else if (_pef->getBits() == 64)
92 return find_section(static_cast<PeLib::PeFile64*>(_pef),
93 name, info);
94 return false;
95}
96
97bool shared::pe_file::add_section(const std::string& name,
98 const bytes& buffer, section_info& info)
99{
100 if (_pef->getBits() == 32)
101 {
102 return add_section(static_cast<PeLib::PeFile32*>(_pef),
103 name, buffer, info);
104 }
105 else if (_pef->getBits() == 64)
106 {
107 return add_section(static_cast<PeLib::PeFile64*>(_pef),
108 name, buffer, info);
109 }
110 return false;
111}
112
113dword shared::pe_file::get_image_base() const
114{
115 if (_pef->getBits() == 32)
116 return static_cast<PeLib::PeFile32*>(_pef)->peHeader().getImageBase();
117 else
118 return static_cast<PeLib::PeFile64*>(_pef)->peHeader().getImageBase();
119 return 0;
120}
121dword shared::pe_file::pa_to_va(dword pa) const
122{
123 if (_pef->getBits() == 32)
124 return static_cast<PeLib::PeFile32*>(_pef)->peHeader().offsetToVa(pa);
125 else
126 return static_cast<PeLib::PeFile64*>(_pef)->peHeader().offsetToVa(pa);
127 return 0;
128}
diff --git a/utils/zenutils/source/shared/pe.h b/utils/zenutils/source/shared/pe.h
new file mode 100755
index 0000000000..92a272d3c7
--- /dev/null
+++ b/utils/zenutils/source/shared/pe.h
@@ -0,0 +1,142 @@
1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#ifndef SHARED_PE_H_INCLUDED
20#define SHARED_PE_H_INCLUDED
21
22#include <string>
23#include <pelib/PeLib.h>
24#include <utils.h>
25
26namespace shared {
27 struct section_info
28 {
29 word index;
30 dword virtual_address;
31 dword virtual_size;
32 dword raw_address;
33 dword raw_size;
34 dword characteristics;
35 }; //struct section_info
36
37 class pe_file
38 {
39 public:
40 pe_file(PeLib::PeFile* pef = NULL);
41 ~pe_file();
42
43 bool is_valid() const;
44 bool read(const std::string& filename);
45 bool find_section(const std::string& name, section_info& info) const;
46 bool add_section(const std::string& name, const bytes& buffer, section_info& info);
47 dword get_image_base() const;
48 dword pa_to_va(PeLib::dword pa) const;
49
50 protected:
51 template <int _Bits>
52 static bool find_section(const PeLib::PeFileT<_Bits>* pef,
53 const std::string& name, section_info& info);
54 template <int _Bits>
55 static bool add_section(PeLib::PeFileT<_Bits>* pef,
56 const std::string& name, const bytes& buffer,
57 section_info& info);
58
59 private:
60 PeLib::PeFile* _pef;
61 }; //class pe_file
62
63
64 template <int _Bits>
65 bool pe_file::find_section(const PeLib::PeFileT<_Bits>* pef,
66 const std::string& name, section_info& info)
67 {
68 for (PeLib::word i = 0; i < pef->peHeader().getNumberOfSections(); i++)
69 {
70 if (pef->peHeader().getSectionName(i) == name)
71 {
72 info.index = i;
73 info.virtual_address = pef->peHeader().getVirtualAddress(i);
74 info.virtual_size = pef->peHeader().getVirtualSize(i);
75 info.raw_address = pef->peHeader().getPointerToRawData(i);
76 info.raw_size = pef->peHeader().getSizeOfRawData(i);
77 info.characteristics = pef->peHeader().getCharacteristics(i);
78 return true;
79 }
80 }
81 return false;
82 }
83
84 template <int _Bits>
85 bool pe_file::add_section(PeLib::PeFileT<_Bits>* pef,
86 const std::string& name, const bytes& buffer,
87 section_info& info)
88 {
89 using namespace PeLib;
90
91 // Check if the last section has the same name as the one being added.
92 PeLib::word secnum = pef->peHeader().getNumberOfSections();
93 if (pef->peHeader().getSectionName(secnum-1) == name)
94 {
95 // If it is, we change the attributes of the existing section.
96 secnum = secnum - 1;
97 pef->peHeader().setSizeOfRawData(secnum,
98 alignOffset(buffer.size(),
99 pef->peHeader().getFileAlignment()));
100 pef->peHeader().setVirtualSize(secnum,
101 alignOffset(buffer.size(),
102 pef->peHeader().getSectionAlignment()));
103 PeLib::dword chars = pef->peHeader().getCharacteristics(secnum-1);
104 pef->peHeader().setCharacteristics(secnum,
105 chars | PELIB_IMAGE_SCN_MEM_WRITE | PELIB_IMAGE_SCN_MEM_READ);
106 }
107 else
108 {
109 // Otherwise we add a new section.
110 if (pef->peHeader().addSection(name, buffer.size()) != NO_ERROR)
111 {
112 return false;
113 }
114 pef->peHeader().makeValid(pef->mzHeader().getAddressOfPeHeader());
115 pef->peHeader().write(pef->getFileName(), pef->mzHeader().getAddressOfPeHeader());
116 }
117
118 // Save the section headers to the file.
119 if (pef->peHeader().writeSections(pef->getFileName()) != NO_ERROR)
120 {
121 return false;
122 }
123
124 // Save the section data to the file.
125 if (pef->peHeader().writeSectionData(pef->getFileName(), secnum, buffer) != NO_ERROR)
126 {
127 return false;
128 }
129
130 // Fill out the section information.
131 info.index = secnum;
132 info.virtual_address = pef->peHeader().getVirtualAddress(secnum);
133 info.virtual_size = pef->peHeader().getVirtualSize(secnum);
134 info.raw_address = pef->peHeader().getPointerToRawData(secnum);
135 info.raw_size = pef->peHeader().getSizeOfRawData(secnum);
136 info.characteristics = pef->peHeader().getCharacteristics(secnum);
137
138 return true;
139 }
140}; //namespace shared
141
142#endif //SHARED_PE_H_INCLUDED
diff --git a/utils/zenutils/source/shared/shared.cpp b/utils/zenutils/source/shared/shared.cpp
new file mode 100755
index 0000000000..e69de29bb2
--- /dev/null
+++ b/utils/zenutils/source/shared/shared.cpp
diff --git a/utils/zenutils/source/shared/updater.cpp b/utils/zenutils/source/shared/updater.cpp
new file mode 100755
index 0000000000..77d3f2876c
--- /dev/null
+++ b/utils/zenutils/source/shared/updater.cpp
@@ -0,0 +1,151 @@
1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#include "updater.h"
20#include <file.h>
21#include <pe.h>
22#include <utils.h>
23
24
25const char* zen::find_firmware_key(const byte* buffer, size_t len)
26{
27 char szkey1[] = "34d1";
28 size_t cchkey1 = strlen(szkey1);
29 char szkey2[] = "TbnCboEbn";
30 size_t cchkey2 = strlen(szkey2);
31 for (int i = 0; i < static_cast<int>(len); i++)
32 {
33 if (len >= cchkey1)
34 {
35 if (!strncmp((char*)&buffer[i], szkey1, cchkey1))
36 {
37 return (const char*)&buffer[i];
38 }
39 }
40 if (len >= cchkey2)
41 {
42 if (!strncmp((char*)&buffer[i], szkey2, cchkey2))
43 {
44 return (const char*)&buffer[i];
45 }
46 }
47 }
48 return NULL;
49}
50
51dword zen::find_firmware_offset(byte* buffer, size_t len)
52{
53 for (dword i = 0; i < static_cast<dword>(len); i += 0x10)
54 {
55 dword size = *(dword*)&buffer[i];
56 if (size < (i + len) && size > (len >> 1))
57 {
58 if (buffer[i + sizeof(dword)] != 0
59 && buffer[i + sizeof(dword) + 1] != 0
60 && buffer[i + sizeof(dword) + 2] != 0
61 && buffer[i + sizeof(dword) + 3] != 0)
62 {
63 return i;
64 }
65 }
66 }
67 return 0;
68}
69
70bool zen::find_firmware_archive(const std::string& filename, dword& va, dword& pa)
71{
72 shared::pe_file pef;
73 if (!pef.read(filename))
74 {
75 return false;
76 }
77 shared::section_info data_section;
78 if (!pef.find_section(".data", data_section))
79 {
80 return false;
81 }
82 shared::bytes buffer;
83 if (!shared::read_file(filename, buffer, data_section.raw_address,
84 data_section.raw_size))
85 {
86 return false;
87 }
88 dword offset = find_firmware_offset(&buffer[0], buffer.size());
89 if (!offset)
90 {
91 return false;
92 }
93 va = data_section.virtual_address + offset;
94 pa = data_section.raw_address + offset;
95
96 return true;
97}
98
99
100bool zen::crypt_firmware(const char* key, byte* buffer, size_t len)
101{
102 // Determine if the key length is dword aligned.
103 int keylen = strlen(key);
104 int keylen_rem = keylen % sizeof(dword);
105
106 // Determine how many times the key must be repeated to be dword aligned.
107 int keycycle = keylen_rem ? (sizeof(dword) / keylen_rem) : 1;
108 int keyscount = (keylen * keycycle) / sizeof(dword);
109
110 // Allocate a buffer to hold the key as an array of dwords.
111 dword* keys = new dword[keyscount];
112
113 // Copy the key into the key array, whilst mutating it.
114 for (int i = 0; i < keyscount; i++)
115 {
116 dword val;
117 int keyoffset = (i * sizeof(dword)) % keylen;
118 if ((keyoffset+sizeof(dword)) < keylen)
119 {
120 val = *(dword*)&key[keyoffset];
121 }
122 else
123 {
124 val = key[keyoffset]
125 | (key[(keyoffset + 1) % keylen] << 8)
126 | (key[(keyoffset + 2) % keylen] << 16)
127 | (key[(keyoffset + 3) % keylen] << 24);
128 }
129 keys[i] = (val - 0x01010101) | 0x80808080;
130 }
131
132 // Determine the number of dwords in the buffer.
133 int len_div = len / sizeof(dword);
134
135 // Decrypt all dwords of the buffer.
136 for (int i = 0; i < len_div; i++)
137 {
138 ((dword*)buffer)[i] ^= keys[i % keyscount];
139 }
140
141 // Determine the remaining number of bytes in the buffer.
142 int len_rem = len % sizeof(dword);
143
144 // Decrypt the remaining number of bytes in the buffer.
145 for (int i = len_div * sizeof(dword); i < len; i++)
146 {
147 buffer[i] ^= ((key[i % keylen] - 0x01) | 0x80);
148 }
149
150 return true;
151}
diff --git a/utils/zenutils/source/shared/updater.h b/utils/zenutils/source/shared/updater.h
new file mode 100755
index 0000000000..57f9979c30
--- /dev/null
+++ b/utils/zenutils/source/shared/updater.h
@@ -0,0 +1,32 @@
1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#ifndef ZEN_UPDATER_H_INCLUDED
20#define ZEN_UPDATER_H_INCLUDED
21
22#include <pelib/PeLib.h>
23#include <utils.h>
24
25namespace zen {
26 const char* find_firmware_key(const byte* buffer, size_t len);
27 dword find_firmware_offset(byte* buffer, size_t len);
28 bool find_firmware_archive(const std::string& filename, dword& va, dword& pa);
29 bool crypt_firmware(const char* key, byte* buffer, size_t len);
30}; //namespace zen
31
32#endif //ZEN_UPDATER_H_INCLUDED
diff --git a/utils/zenutils/source/shared/utils.cpp b/utils/zenutils/source/shared/utils.cpp
new file mode 100755
index 0000000000..8f45de5d3f
--- /dev/null
+++ b/utils/zenutils/source/shared/utils.cpp
@@ -0,0 +1,211 @@
1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#include "utils.h"
20#include <fstream>
21#include <zlib/zlib.h>
22
23
24std::string shared::replace_extension(const std::string& filename, const std::string& extension)
25{
26 std::string newname;
27 const char* name = filename.c_str();
28 const char* ext = strrchr(name, '.');
29 if (ext)
30 {
31 // If an extension was found, replace it.
32 newname.assign(name, ext-name);
33 newname += extension;
34 }
35 else
36 {
37 // If an extension was not found, append it.
38 newname = name;
39 newname += extension;
40 }
41 return newname;
42}
43
44std::string shared::remove_extension(const std::string& filename)
45{
46 std::string newname;
47 const char* name = filename.c_str();
48 const char* ext = strrchr(name, '.');
49 if (ext)
50 {
51 newname.assign(name, ext-name);
52 }
53 else
54 {
55 newname = name;
56 }
57 return newname;
58}
59
60std::string shared::double_quote(const std::string& str)
61{
62 std::string out;
63 for (int i = 0, j = str.length(); i < j; i++)
64 {
65 if (str[i] == '\\')
66 out += "\\\\";
67 else
68 out += str[i];
69 }
70 return out;
71}
72
73bool shared::inflate_to_file(const bytes& buffer, const char* filename)
74{
75 // Open output file.
76 std::ofstream ofs;
77 ofs.open(filename, std::ios::binary);
78 if (!ofs)
79 {
80 return false;
81 }
82
83 // Initialize zlib.
84 z_stream d_stream; // decompression stream
85
86 d_stream.zalloc = Z_NULL;
87 d_stream.zfree = Z_NULL;
88 d_stream.opaque = Z_NULL;
89
90 d_stream.next_in = const_cast<bytes::value_type*>(&buffer[0]);
91 d_stream.avail_in = static_cast<uInt>(buffer.size());
92
93 int ret = inflateInit(&d_stream);
94 if (ret != Z_OK)
95 return false;
96
97 // Allocate buffer to hold the inflated data.
98 const size_t BUFSIZE = 1048576;
99 Bytef* infbuf = new Bytef[BUFSIZE];
100 if (!infbuf)
101 return false;
102
103 // Decompress untill the end of the input buffer.
104 uLong totalout = 0;
105 bool bLoop = true;
106 while (bLoop)
107 {
108 d_stream.next_out = infbuf;
109 d_stream.avail_out = BUFSIZE;
110
111 ret = inflate(&d_stream, Z_NO_FLUSH);
112 if (ret == Z_STREAM_END)
113 {
114 bLoop = false;
115 }
116 else if (ret != Z_OK)
117 {
118 inflateEnd(&d_stream);
119 delete [] infbuf;
120 return false;
121 }
122
123 // Write the inflated data to the output file.
124 if (!ofs.write((const char*)infbuf, d_stream.total_out-totalout))
125 {
126 inflateEnd(&d_stream);
127 delete [] infbuf;
128 return false;
129 }
130 totalout = d_stream.total_out;
131 }
132
133 // Cleanup and return.
134 inflateEnd(&d_stream);
135 delete [] infbuf;
136
137 return true;
138}
139
140bool shared::deflate_to_file(const bytes& buffer, const char* filename)
141{
142 // Open output file.
143 std::ofstream ofs;
144 ofs.open(filename, std::ios::binary);
145 if (!ofs)
146 {
147 return false;
148 }
149
150 // Initialize zlib.
151 z_stream c_stream; // compression stream.
152
153 c_stream.zalloc = Z_NULL;
154 c_stream.zfree = Z_NULL;
155 c_stream.opaque = Z_NULL;
156
157 int ret = deflateInit(&c_stream, Z_BEST_COMPRESSION);
158 if (ret != Z_OK)
159 return false;
160
161 // Allocate buffer to hold the deflated data.
162 const size_t BUFSIZE = 1048576;
163 Bytef* defbuf = new Bytef[BUFSIZE];
164 if (!defbuf)
165 return false;
166
167 c_stream.avail_in = static_cast<uInt>(buffer.size());
168 c_stream.next_in = const_cast<bytes::value_type*>(&buffer[0]);
169
170 // Compress until end of the buffer.
171 uLong totalout = 0;
172 bool bLoop = true;
173 while (bLoop)
174 {
175 c_stream.avail_out = BUFSIZE;
176 c_stream.next_out = defbuf;
177
178 ret = deflate(&c_stream, Z_NO_FLUSH); // no bad return value
179 if (ret == Z_STREAM_END)
180 {
181 bLoop = false;
182 }
183 else if (ret == Z_BUF_ERROR && !c_stream.avail_in)
184 {
185 ret = deflate(&c_stream, Z_FINISH); // no bad return value
186 bLoop = false;
187 }
188 else if (ret != Z_OK)
189 {
190 deflateEnd(&c_stream);
191 delete [] defbuf;
192 return false;
193 }
194
195 // Write the inflated data to the output file.
196 if (!ofs.write((const char*)defbuf, c_stream.total_out-totalout))
197 {
198 deflateEnd(&c_stream);
199 delete [] defbuf;
200 return false;
201 }
202
203 totalout = c_stream.total_out;
204 }
205
206 // Clean up and return.
207 deflateEnd(&c_stream);
208 delete [] defbuf;
209
210 return true;
211}
diff --git a/utils/zenutils/source/shared/utils.h b/utils/zenutils/source/shared/utils.h
new file mode 100755
index 0000000000..ca9e291514
--- /dev/null
+++ b/utils/zenutils/source/shared/utils.h
@@ -0,0 +1,68 @@
1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#ifndef SHARED_UTILS_H_INCLUDED
20#define SHARED_UTILS_H_INCLUDED
21
22#include <vector>
23#include <pelib/PeLib.h>
24
25#ifndef byte
26typedef PeLib::byte byte;
27#endif
28#ifndef word
29typedef PeLib::word word;
30#endif
31#ifndef dword
32typedef PeLib::dword dword;
33#endif
34
35namespace shared {
36 typedef std::vector<byte> bytes;
37
38 inline dword swap(dword val)
39 {
40 return ((val & 0xFF) << 24)
41 | ((val & 0xFF00) << 8)
42 | ((val & 0xFF0000) >> 8)
43 | ((val & 0xFF000000) >> 24);
44 }
45
46 template <typename _Type>
47 inline void reverse(_Type* start, _Type* end)
48 {
49 while (start < end)
50 {
51 *start ^= *end;
52 *end ^= *start;
53 *start ^= *end;
54 start++;
55 end--;
56 }
57 }
58
59 std::string replace_extension(const std::string& filename, const std::string& extension);
60 std::string remove_extension(const std::string& filename);
61 std::string get_path(const std::string& filename);
62 std::string double_quote(const std::string& str);
63
64 bool inflate_to_file(const bytes& buffer, const char* filename);
65 bool deflate_to_file(const bytes& buffer, const char* filename);
66}; //namespace shared
67
68#endif //SHARED_UTILS_H_INCLUDED
diff --git a/utils/zenutils/source/update_extract/CMakeLists.txt b/utils/zenutils/source/update_extract/CMakeLists.txt
new file mode 100755
index 0000000000..813e389bed
--- /dev/null
+++ b/utils/zenutils/source/update_extract/CMakeLists.txt
@@ -0,0 +1,3 @@
1ADD_EXECUTABLE(update_extract main.cpp)
2
3TARGET_LINK_LIBRARIES (update_extract shared)
diff --git a/utils/zenutils/source/update_extract/main.cpp b/utils/zenutils/source/update_extract/main.cpp
new file mode 100755
index 0000000000..0fae29e00c
--- /dev/null
+++ b/utils/zenutils/source/update_extract/main.cpp
@@ -0,0 +1,279 @@
1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#include <iostream>
20#include <iomanip>
21#include <ctime>
22#include <getpot/getpot.hpp>
23#include <file.h>
24#include <updater.h>
25#include <utils.h>
26
27
28static const char VERSION[] = "0.1";
29
30void print_version()
31{
32 std::cout
33 << "update_extract - Extracts a Creative firmware from an updater"
34 " executable." << std::endl
35 << "Version " << VERSION << std::endl
36 << "Copyright (c) 2007 Rasmus Ry" << std::endl;
37}
38
39void print_help()
40{
41 print_version();
42 std::cout << std::endl
43 << "Usage: update_extract [command] [options]" << std::endl
44 << std::endl
45 << " Commands:" << std::endl
46 << " -h,--help" << std::endl
47 << " prints this message." << std::endl
48 << " -u,--updater [file]" << std::endl
49 << " specifies the updater executable." << std::endl
50 << std::endl
51 << " Options:" << std::endl
52 << " -V,--verbose" << std::endl
53 << " prints verbose messages." << std::endl
54 << " -f,--firmware [file]" << std::endl
55 << " specifies the firmware arhive file name." << std::endl
56 << " -k,--key [key]" << std::endl
57 << " specifies the firmware archive key." << std::endl
58 << " -o,--offset [offset]" << std::endl
59 << " specifies the firmware archive offset in c-style"
60 " hexadecimal." << std::endl
61 << std::endl
62 ;
63}
64
65std::string options_name(const std::string& name)
66{
67 return shared::replace_extension(name, ".opt");
68}
69
70std::string default_firmware_name(const std::string& name)
71{
72 return shared::replace_extension(name, "_rk.bin");
73}
74
75int process_arguments(int argc, char* argv[])
76{
77 //--------------------------------------------------------------------
78 // Parse input variables.
79 //--------------------------------------------------------------------
80
81 GetPot cl(argc, argv);
82 if (cl.size() == 1 || cl.search(2, "-h", "--help"))
83 {
84 print_help();
85 return 1;
86 }
87
88 std::string updatername;
89 if (cl.search("-u") || cl.search("--updater"))
90 updatername = cl.next("");
91 if (updatername.empty())
92 {
93 std::cerr << "Updater executable must be specified." << std::endl;
94 return 2;
95 }
96
97 std::string firmarename = default_firmware_name(updatername);
98 if (cl.search("-f") || cl.search("--firmware"))
99 firmarename = cl.next(firmarename.c_str());
100
101 bool verbose = false;
102 if (cl.search("-V") || cl.search("--verbose"))
103 verbose = true;
104
105 // Get or find the firmware archive key.
106 std::string key;
107 if (cl.search("-k") || cl.search("--key"))
108 key = cl.next("");
109
110 if (key.empty())
111 {
112 if (verbose)
113 std::cout << "[*] Looking for firmware archive key..."
114 << std::endl;
115 shared::bytes buffer;
116 if (!shared::read_file(updatername, buffer))
117 {
118 std::cerr << "Failed to read the firmware updater executable."
119 << std::endl;
120 return 3;
121 }
122 key = zen::find_firmware_key(&buffer[0], buffer.size());
123 if (key.empty())
124 {
125 std::cerr << "Failed to find the firmware archive key."
126 << std::endl;
127 return 4;
128 }
129 }
130
131 // Get or find the firmware archive offset.
132 std::string offset;
133 dword offset_pa = 0;
134 if (cl.search("-o") || cl.search("--ofset"))
135 offset = cl.next("");
136
137 if (offset.empty())
138 {
139 if (verbose)
140 std::cout << "[*] Looking for firmware archive offset..."
141 << std::endl;
142
143 dword offset_va = 0;
144 if (!zen::find_firmware_archive(updatername, offset_va, offset_pa))
145 {
146 std::cerr << "Failed to find the firmware archive offset."
147 << std::endl;
148 return 5;
149 }
150 }
151 else
152 {
153 int offset_val;
154 if (!sscanf(offset.c_str(), "0x%x", &offset_val))
155 {
156 if (!sscanf(offset.c_str(), "0x%X", &offset_val))
157 {
158 std::cerr << "\'" << offset
159 << "\' is not a valid c-style hexadecimal value."
160 << std::endl;
161 return 6;
162 }
163 }
164 offset_pa = static_cast<dword>(offset_val);
165 }
166
167 // Read firmware archive size.
168 shared::bytes buffer;
169 if (!shared::read_file(updatername, buffer, offset_pa, sizeof(dword)))
170 {
171 std::cerr << "Failed to read the firmware archive size." << std::endl;
172 return 7;
173 }
174 dword archive_size = *(dword*)&buffer[0];
175
176 if (verbose)
177 {
178 std::cout << "[*] Printing input variables..." << std::endl;
179 std::cout << " Updater executable: " << updatername << std::endl;
180 std::cout << " Firmware archive: " << firmarename << std::endl;
181 std::cout << " Key: " << key << std::endl;
182 std::cout << " Offset: "
183 << std::hex << std::showbase << std::setw(10)
184 << std::setfill('0') << std::internal
185 << offset_pa << std::endl;
186 std::cout << " Size: "
187 << std::hex << std::showbase << std::setw(10)
188 << std::setfill('0') << std::internal
189 << archive_size << std::endl;
190 }
191
192
193 //--------------------------------------------------------------------
194 // Extract the firmware archive from the updater.
195 //--------------------------------------------------------------------
196
197 if (verbose)
198 std::cout << "[*] Reading firmware archive..." << std::endl;
199
200 // Read the firmware archive.
201 offset_pa += sizeof(dword);
202 if (!shared::read_file(updatername, buffer, offset_pa, archive_size))
203 {
204 std::cerr << "Failed to read the firmware archive." << std::endl;
205 return 8;
206 }
207
208 if (verbose)
209 std::cout << "[*] Decrypting firmware archive..." << std::endl;
210
211 // Decrypt the firmware archive.
212 if (!zen::crypt_firmware(key.c_str(), &buffer[0], buffer.size()))
213 {
214 std::cerr << "Failed to decrypt the firmware archive." << std::endl;
215 return 9;
216 }
217
218 if (verbose)
219 std::cout << "[*] Decompressing firmware archive..." << std::endl;
220
221 // Inflate the firmware archive to the output file.
222 if (!shared::inflate_to_file(buffer, firmarename.c_str()))
223 {
224 std::cerr << "Failed to decompress the firmware archive." << std::endl;
225 return 10;
226 }
227
228
229 //--------------------------------------------------------------------
230 // Generate an options file for the extracted firmware archive.
231 //--------------------------------------------------------------------
232
233 // Get options filename for the given input file.
234 std::string optionsname = options_name(updatername);
235
236 if (verbose)
237 std::cout << "[*] Producing options file..." << std::endl;
238
239 // Produce options file for the given input file.
240 std::ofstream ofs;
241 ofs.open(optionsname.c_str(), std::ios::binary);
242 if (!ofs)
243 {
244 std::cerr << "Failed to create firmware archive options file."
245 << std::endl;
246 return 11;
247 }
248
249 time_t timeval = time(NULL);
250 ofs << "# Options file generated at: " << ctime(&timeval)
251 << "updater = \'" << shared::double_quote(updatername) << "\'"
252 << std::endl
253 << "firmware = \'" << shared::double_quote(firmarename) << "\'"
254 << std::endl
255 << "offset = " << (offset_pa - sizeof(dword)) << std::endl
256 << "size = " << archive_size << std::endl
257 << "key = \'" << key << "\'" << std::endl;
258
259 return 0;
260}
261
262int main(int argc, char* argv[])
263{
264 try
265 {
266 return process_arguments(argc, argv);
267 }
268 catch (const std::exception& xcpt)
269 {
270 std::cerr << "Exception caught: " << xcpt.what() << std::endl;
271 return -1;
272 }
273 catch (...)
274 {
275 std::cerr << "Unknown exception caught." << std::endl;
276 return -2;
277 }
278 return -3;
279}
diff --git a/utils/zenutils/source/update_patch/CMakeLists.txt b/utils/zenutils/source/update_patch/CMakeLists.txt
new file mode 100755
index 0000000000..11474b7ff8
--- /dev/null
+++ b/utils/zenutils/source/update_patch/CMakeLists.txt
@@ -0,0 +1,3 @@
1ADD_EXECUTABLE(update_patch main.cpp)
2
3TARGET_LINK_LIBRARIES (update_patch shared)
diff --git a/utils/zenutils/source/update_patch/main.cpp b/utils/zenutils/source/update_patch/main.cpp
new file mode 100755
index 0000000000..d48797b46d
--- /dev/null
+++ b/utils/zenutils/source/update_patch/main.cpp
@@ -0,0 +1,409 @@
1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#include <iostream>
20#include <iomanip>
21#include <cstdio>
22#include <getpot/getpot.hpp>
23#include <file.h>
24#include <updater.h>
25#include <utils.h>
26#include <pe.h>
27
28
29static const char VERSION[] = "0.1";
30
31void print_version()
32{
33 std::cout
34 << "update_patch - Patches a Creative firmware into an updater"
35 " executable." << std::endl
36 << "Version " << VERSION << std::endl
37 << "Copyright (c) 2007 Rasmus Ry" << std::endl;
38}
39
40void print_help()
41{
42 print_version();
43 std::cout << std::endl
44 << "Usage: update_patch [command] [options]" << std::endl
45 << std::endl
46 << " Commands:" << std::endl
47 << " -h,--help" << std::endl
48 << " prints this message." << std::endl
49 << " -u,--updater [file]" << std::endl
50 << " specifies the updater executable." << std::endl
51 << std::endl
52 << " Options:" << std::endl
53 << " -V,--verbose" << std::endl
54 << " prints verbose messages." << std::endl
55 << " -f,--firmware [file]" << std::endl
56 << " specifies the firmware arhive file name." << std::endl
57 << " -k,--key [key]" << std::endl
58 << " specifies the firmware archive key." << std::endl
59 << " -o,--offset [offset]" << std::endl
60 << " specifies the firmware archive offset in c-style"
61 " hexadecimal." << std::endl
62 << std::endl
63 ;
64}
65
66std::string options_name(const std::string& name)
67{
68 return shared::replace_extension(name, ".opt");
69}
70
71std::string default_firmware_name(const std::string& name)
72{
73 return shared::replace_extension(name, "_rk.bin");
74}
75
76int process_arguments(int argc, char* argv[])
77{
78 //--------------------------------------------------------------------
79 // Parse input variables.
80 //--------------------------------------------------------------------
81
82 GetPot cl(argc, argv);
83 if (cl.size() == 1 || cl.search(2, "-h", "--help"))
84 {
85 print_help();
86 return 1;
87 }
88
89 std::string updatername;
90 if (cl.search("-u") || cl.search("--updater"))
91 updatername = cl.next("");
92 if (updatername.empty())
93 {
94 std::cerr << "Updater executable must be specified." << std::endl;
95 return 2;
96 }
97
98 bool verbose = false;
99 if (cl.search("-V") || cl.search("--verbose"))
100 verbose = true;
101
102 if (verbose)
103 std::cout << "[*] Parsing options file..." << std::endl;
104
105 GetPot optfile(options_name(updatername.c_str()).c_str());
106 if (verbose)
107 optfile.print();
108
109 std::string firmwarename = optfile("firmware",
110 default_firmware_name(updatername).c_str());
111 dword offset_pa = optfile("offset", 0);
112 dword size = optfile("size", 0);
113 std::string key = optfile("key", "");
114
115 if (cl.search("-f") || cl.search("--firmware"))
116 firmwarename = cl.next(firmwarename.c_str());
117
118 std::string offset;
119 if (cl.search("-o") || cl.search("--offset"))
120 offset = cl.next("");
121
122 if (offset.empty() && !offset_pa)
123 {
124 if (verbose)
125 std::cout << "[*] Looking for firmware archive offset..."
126 << std::endl;
127
128 dword offset_va = 0;
129 if (!zen::find_firmware_archive(updatername, offset_va, offset_pa))
130 {
131 std::cerr << "Failed to find the firmware archive offset."
132 << std::endl;
133 return 3;
134 }
135 }
136 else if (!offset_pa)
137 {
138 int offset_val;
139 if (!sscanf(offset.c_str(), "0x%x", &offset_val))
140 {
141 if (!sscanf(offset.c_str(), "0x%X", &offset_val))
142 {
143 std::cerr << "\'" << offset
144 << "\' is not a valid c-style hexadecimal value."
145 << std::endl;
146 return 4;
147 }
148 }
149 offset_pa = static_cast<dword>(offset_val);
150 }
151
152 if (key.empty())
153 {
154 if (verbose)
155 std::cout << "[*] Looking for firmware archive key..."
156 << std::endl;
157 shared::bytes buffer;
158 if (!shared::read_file(updatername, buffer))
159 {
160 std::cerr << "Failed to read the firmware updater executable."
161 << std::endl;
162 return 5;
163 }
164 key = zen::find_firmware_key(&buffer[0], buffer.size());
165 if (key.empty())
166 {
167 std::cerr << "Failed to find the firmware archive key."
168 << std::endl;
169 return 6;
170 }
171 }
172
173 if (verbose)
174 {
175 std::cout << "[*] Printing input variables..." << std::endl;
176 std::cout << " Updater executable: " << updatername << std::endl;
177 std::cout << " Firmware archive: " << firmwarename << std::endl;
178 std::cout << " Key: " << key << std::endl;
179 std::cout << " Offset: "
180 << std::hex << std::showbase << std::setw(10)
181 << std::setfill('0') << std::internal
182 << offset_pa << std::endl;
183 std::cout << " Size: "
184 << std::hex << std::showbase << std::setw(10)
185 << std::setfill('0') << std::internal
186 << size << std::endl;
187 }
188
189
190 //--------------------------------------------------------------------
191 // Prepare the firmware archive for being patched into the updater.
192 //--------------------------------------------------------------------
193
194 if (verbose)
195 std::cout << "[*] Reading firmware archive..." << std::endl;
196
197 shared::bytes buffer;
198 if (!shared::read_file(firmwarename, buffer))
199 {
200 std::cerr << "Failed to read the firmware archive." << std::endl;
201 return 7;
202 }
203
204 if (verbose)
205 std::cout << " Bytes read: "
206 << std::hex << std::showbase << std::setw(10)
207 << std::setfill('0') << std::internal
208 << buffer.size() << std::endl;
209
210 if (verbose)
211 std::cout << "[*] Compressing firmware archive..." << std::endl;
212
213 std::string compfirmware = shared::replace_extension(firmwarename, ".def");
214 if (!shared::deflate_to_file(buffer, compfirmware.c_str()))
215 {
216 std::cerr << "Failed to compress the firmware archive." << std::endl;
217 return 8;
218 }
219
220 if (verbose)
221 std::cout << "[*] Reading compressed firmware archive..." << std::endl;
222
223 if (!shared::read_file(compfirmware, buffer))
224 {
225 std::cerr << "Failed to read the compressed firmware archive."
226 << std::endl;
227 return 9;
228 }
229
230 if (verbose)
231 std::cout << " Bytes read: "
232 << std::hex << std::showbase << std::setw(10)
233 << std::setfill('0') << std::internal
234 << buffer.size() << std::endl;
235
236 // Delete the temporary firmware file.
237 std::remove(compfirmware.c_str());
238
239 if (verbose)
240 std::cout << "[*] Encrypting compressed firmware archive..."
241 << std::endl;
242
243 if (!zen::crypt_firmware(key.c_str(), &buffer[0], buffer.size()))
244 {
245 std::cerr << "Failed to encrypt the compressed firmware archive."
246 << std::endl;
247 return 10;
248 }
249
250
251 //--------------------------------------------------------------------
252 // Backup the updater and patch the firmware archive into it.
253 //--------------------------------------------------------------------
254
255 if (verbose)
256 std::cout << "[*] Backing up the updater executable..." << std::endl;
257
258 if (!shared::backup_file(updatername))
259 {
260 std::cerr << "Failed to backup the updater executable." << std::endl;
261 return 11;
262 }
263
264 // Is there enough space within the existing firmware archive
265 // to hold the new one?
266 if (size < buffer.size())
267 {
268 // No, we need to add a new section to hold the new firmware archive.
269 if (verbose)
270 std::cout << "[*] Adding new section to the updater executable..."
271 << std::endl;
272
273 // Construct a new buffer with the archive size prepended.
274 shared::bytes newbuffer(buffer.size() + sizeof(dword));
275 *(dword*)&newbuffer[0] = static_cast<dword>(buffer.size());
276 std::copy(buffer.begin(), buffer.end(), &newbuffer[4]);
277
278 // Read the updater portable executable.
279 shared::pe_file pef;
280 if (!pef.read(updatername))
281 {
282 std::cerr << "Failed to read the updater portable executable"
283 " structure." << std::endl;
284 return 12;
285 }
286
287 // Add a new section to the updater, containing the encrypted
288 // firmware archive.
289 shared::section_info newsection;
290 if (!pef.add_section(".firm", newbuffer, newsection))
291 {
292 std::cerr << "Failed to add an extra section to the updater"
293 " executable." << std::endl;
294 return 13;
295 }
296
297 if (verbose)
298 std::cout << "[*] Relocating code references to the firmware"
299 " archive..." << std::endl;
300
301 // Locate the code section.
302 shared::section_info textsection;
303 if (!pef.find_section(".text", textsection))
304 {
305 std::cerr << "Failed to find the code section in the updater"
306 " executable." << std::endl;
307 return 14;
308 }
309
310 // Read the code section data.
311 if (!shared::read_file(updatername, buffer, textsection.raw_address,
312 textsection.raw_size))
313 {
314 std::cerr << "Failed to read the code section from the updater"
315 " executable." << std::endl;
316 return 15;
317 }
318
319 // Determine the addresses of the new and old firmware archives.
320 dword oldva = pef.pa_to_va(offset_pa);
321 dword newva = pef.pa_to_va(newsection.raw_address);
322 if (!oldva || !newva)
323 {
324 std::cerr << "Failed to compute address of the new or old"
325 " archive." << std::endl;
326 return 16;
327 }
328
329 // Relocate references to the old firmware archive.
330 dword imgbase = pef.get_image_base();
331 for (int i = 0, j = buffer.size() - sizeof(dword) + 1; i < j; i++)
332 {
333 dword val = *(dword*)&buffer[i];
334 if (val >= oldva && val <= (oldva + 3))
335 {
336 *(dword*)&buffer[i] = newva + (val - oldva);
337 if (verbose)
338 std::cout << " "
339 << std::hex << std::showbase << std::setw(10)
340 << std::setfill('0') << std::internal
341 << (imgbase + textsection.virtual_address + i)
342 << ": "
343 << std::hex << std::showbase << std::setw(10)
344 << std::setfill('0') << std::internal
345 << val
346 << " -> "
347 << std::hex << std::showbase << std::setw(10)
348 << std::setfill('0') << std::internal
349 << (newva + (val - oldva)) << std::endl;
350 }
351 }
352
353 // Write the relocated code section data.
354 if (!shared::write_file(updatername, buffer, false, textsection.raw_address,
355 buffer.size()))
356 {
357 std::cerr << "Failed to write the relocated code section to the"
358 " updater executable." << std::endl;
359 return 17;
360 }
361 } //if (size < buffer.size())
362 else
363 {
364 // Yes, overwrite the existing firmware archive.
365 if (verbose)
366 std::cout << "[*] Overwriting existing firmware archive..."
367 << std::endl;
368
369 shared::bytes archive_size(sizeof(dword));
370 *(dword*)&archive_size[0] = buffer.size();
371
372 if (!shared::write_file(updatername, archive_size, false, offset_pa,
373 archive_size.size()))
374 {
375 std::cerr << "Failed to write archive size to the updater"
376 " executable." << std::endl;
377 return 18;
378 }
379
380 if (!shared::write_file(updatername, buffer, false,
381 offset_pa+archive_size.size(), buffer.size()))
382 {
383 std::cerr << "Failed to write the new archive to the updater"
384 " exectuable." << std::endl;
385 return 19;
386 }
387 }
388
389 return 0;
390}
391
392int main(int argc, char* argv[])
393{
394 try
395 {
396 return process_arguments(argc, argv);
397 }
398 catch (const std::exception& xcpt)
399 {
400 std::cerr << "Exception caught: " << xcpt.what() << std::endl;
401 return -1;
402 }
403 catch (...)
404 {
405 std::cerr << "Unknown exception caught." << std::endl;
406 return -2;
407 }
408 return -3;
409}
diff --git a/utils/zenutils/source/zen_crypt/CMakeLists.txt b/utils/zenutils/source/zen_crypt/CMakeLists.txt
new file mode 100755
index 0000000000..e88e8951a5
--- /dev/null
+++ b/utils/zenutils/source/zen_crypt/CMakeLists.txt
@@ -0,0 +1,4 @@
1ADD_EXECUTABLE(zen_crypt main.cpp)
2
3TARGET_LINK_LIBRARIES(zen_crypt shared)
4TARGET_LINK_LIBRARIES(zen_crypt beecrypt)
diff --git a/utils/zenutils/source/zen_crypt/main.cpp b/utils/zenutils/source/zen_crypt/main.cpp
new file mode 100755
index 0000000000..8301cbbea5
--- /dev/null
+++ b/utils/zenutils/source/zen_crypt/main.cpp
@@ -0,0 +1,687 @@
1/* zenutils - Utilities for working with creative firmwares.
2 * Copyright 2007 (c) Rasmus Ry <rasmus.ry{at}gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19#include <iostream>
20#include <getpot/getpot.hpp>
21#include <cenc.h>
22#include <crypt.h>
23#include <file.h>
24#include <firmware.h>
25#include <utils.h>
26
27
28namespace {
29enum command_t
30{
31 cmd_none = 0,
32 cmd_sign,
33 cmd_verify,
34 cmd_encrypt,
35 cmd_decrypt
36};
37
38enum mode_t
39{
40 mode_none = 0,
41 mode_cenc,
42 mode_fresc,
43 mode_tl
44};
45
46struct player_info_t
47{
48 const char* name;
49 const char* null_key; // HMAC-SHA1 key
50 const char* fresc_key; // BlowFish key
51 const char* tl_key; // BlowFish key
52 bool big_endian;
53};
54}; //namespace
55
56
57static const char VERSION[] = "0.1";
58
59static const char null_key_v1[] = "CTL:N0MAD|PDE0.SIGN.";
60static const char null_key_v2[] = "CTL:N0MAD|PDE0.DPMP.";
61
62static const char fresc_key[] = "Copyright (C) CTL. -"
63 " zN0MAD iz v~p0wderful!";
64
65static const char tl_zvm_key[] = "1sN0TM3D az u~may th1nk*"
66 "Creative Zen Vision:M";
67static const char tl_zvw_key[] = "1sN0TM3D az u~may th1nk*"
68 "Creative ZEN Vision W";
69static const char tl_zm_key[] = "1sN0TM3D az u~may th1nk*"
70 "Creative Zen Micro";
71static const char tl_zmp_key[] = "1sN0TM3D az u~may th1nk*"
72 "Creative Zen MicroPhoto";
73static const char tl_zs_key[] = "1sN0TM3D az u~may th1nk*"
74 "Creative Zen Sleek";
75static const char tl_zsp_key[] = "1sN0TM3D az u~may th1nk*"
76 "Creative Zen Sleek Photo";
77static const char tl_zt_key[] = "1sN0TM3D az u~may th1nk*"
78 "Creative Zen Touch";
79static const char tl_zx_key[] = "1sN0TM3D az u~may th1nk*"
80 "NOMAD Jukebox Zen Xtra";
81
82player_info_t players[] = {
83 {"Vision:M", null_key_v2, fresc_key, tl_zvm_key, false},
84 {"Vision W", null_key_v2, fresc_key, tl_zvw_key, false},
85 {"Micro", null_key_v1, fresc_key, tl_zm_key, true},
86 {"MicroPhoto", null_key_v1, fresc_key, tl_zmp_key, true},
87 {"Sleek", null_key_v1, fresc_key, tl_zs_key, true},
88 {"SleekPhoto", null_key_v1, fresc_key, tl_zsp_key, true},
89 {"Touch", null_key_v1, fresc_key, tl_zt_key, true},
90 {"Xtra", null_key_v1, fresc_key, tl_zx_key, true},
91 {NULL, NULL, NULL, NULL, false}
92};
93
94
95player_info_t* find_player_info(std::string player)
96{
97 for (int i = 0; players[i].name != NULL; i++)
98 {
99 if (!stricmp(players[i].name, player.c_str()))
100 {
101 return &players[i];
102 }
103 }
104 return NULL;
105}
106
107void print_version()
108{
109 std::cout
110 << "zen_crypt - A utility for encrypting, decrypting or signing"
111 " Creative firmwares." << std::endl
112 << "Version " << VERSION << std::endl
113 << "Copyright (c) 2007 Rasmus Ry" << std::endl;
114}
115
116void print_help()
117{
118 print_version();
119 std::cout << std::endl
120 << "Usage: zen_crypt [command] [options]" << std::endl
121 << std::endl
122 << " Commands:" << std::endl
123 << " -h,--help" << std::endl
124 << " prints this message." << std::endl
125 << " -s,--sign" << std::endl
126 << " signs a given input file." << std::endl
127 << " -v,--verify" << std::endl
128 << " verifies a signed input file." << std::endl
129 << " -e,--encrypt" << std::endl
130 << " encrypts a given input file." << std::endl
131 << " -d,--decrypt" << std::endl
132 << " decrypts a given input file." << std::endl
133 << std::endl
134 << " Options:" << std::endl
135 << " -V,--verbose" << std::endl
136 << " prints verbose messages." << std::endl
137 << " -b,--big-endian" << std::endl
138 << " specifies that the input is big-endian, default is"
139 " little-endian." << std::endl
140 << " -i,--input [file]" << std::endl
141 << " specifies the input file." << std::endl
142 << " -o,--output [file]" << std::endl
143 << " specifies the output file." << std::endl
144 << " -m,--mode [CENC|FRESC|TL]" << std::endl
145 << " specifies which algorithm to use." << std::endl
146 << " -k,--key [player|key]" << std::endl
147 << " specifies which key to use." << std::endl
148 << std::endl
149 ;
150 std::cout << " Players:" << std::endl;
151 for (int i = 0; players[i].name != NULL; i++)
152 {
153 std::cout << " " << players[i].name;
154 if (!i)
155 std::cout << " (default)";
156 std::cout << std::endl;
157 }
158}
159
160size_t find_null_signature(shared::bytes& data)
161{
162 size_t index = data.size();
163 if (index < (20 + 8 + 7))
164 return 0;
165 index -= 20 + 8;
166 for (int i = 0; i < 7; i++)
167 {
168 if (*(dword*)&data[index-i] == 'NULL' ||
169 *(dword*)&data[index-i] == 'LLUN')
170 {
171 return index-i;
172 }
173 }
174 return 0;
175}
176
177
178bool sign(shared::bytes& data, player_info_t* pi, const std::string& file,
179 bool verbose)
180{
181 if (verbose)
182 std::cout << "[*] Checking for the presence of an existing"
183 " NULL signature..." << std::endl;
184 size_t index = find_null_signature(data);
185 if (index)
186 {
187 if (verbose)
188 std::cout << "[*] Found NULL signature at: "
189 << std::hex << index << std::endl;
190
191 if (verbose)
192 std::cout << "[*] Computing digest..." << std::endl;
193
194 shared::bytes digest(20);
195 if (!zen::hmac_sha1_calc((const byte*)pi->null_key,
196 strlen(pi->null_key)+1, &data[0], index,
197 &digest[0], NULL))
198 {
199 std::cerr << "Failed to compute digest." << std::endl;
200 return false;
201 }
202
203 if (verbose)
204 std::cout << "[*] Writing file data..." << std::endl;
205
206 if (!shared::write_file(file, data, true))
207 {
208 std::cerr << "Failed to write file data." << std::endl;
209 return false;
210 }
211
212 if (verbose)
213 std::cout << "[*] Writing digest data..." << std::endl;
214
215 if (!shared::write_file(file, digest, false, index+8))
216 {
217 std::cerr << "Failed to write digest data." << std::endl;
218 return false;
219 }
220 }
221 else
222 {
223 if (verbose)
224 std::cout << "[*] Computing digest..." << std::endl;
225
226 shared::bytes signature(20+8);
227 if (!zen::hmac_sha1_calc((const byte*)pi->null_key,
228 strlen(pi->null_key)+1, &data[0], data.size(),
229 &signature[8], NULL))
230 {
231 std::cerr << "Failed to compute digest." << std::endl;
232 return false;
233 }
234
235
236 zen::firmware_header_t header = {'NULL', 20};
237 if (pi->big_endian)
238 {
239 header.tag = shared::swap(header.tag);
240 header.size = shared::swap(header.size);
241 }
242 memcpy(&signature[0], &header, sizeof(zen::firmware_header_t));
243
244 if (verbose)
245 std::cout << "[*] Writing file data..." << std::endl;
246
247 if (!shared::write_file(file, data, true))
248 {
249 std::cerr << "Failed to write file data." << std::endl;
250 return false;
251 }
252
253 if (verbose)
254 std::cout << "[*] Writing signature data..." << std::endl;
255
256 if (!shared::write_file(file, signature, false, data.size()))
257 {
258 std::cerr << "Failed to write signature data." << std::endl;
259 return false;
260 }
261
262 if (verbose)
263 std::cout << "[*] Ensuring that the file length is"
264 " 32-bit aligned..." << std::endl;
265
266 int length = data.size() + signature.size();
267 int align = length % 4;
268 if (align)
269 {
270 shared::bytes padding(4 - align, 0);
271 if (!shared::write_file(file, padding, false, length))
272 {
273 std::cerr << "Failed to write padding data." << std::endl;
274 return false;
275 }
276 }
277 }
278
279 return true;
280}
281
282bool verify(shared::bytes& data, player_info_t* pi, bool verbose)
283{
284 if (verbose)
285 std::cout << "[*] Checking for the presence of an existing"
286 " NULL signature..." << std::endl;
287 size_t index = find_null_signature(data);
288 if (!index)
289 {
290 std::cerr << "No NULL signature present in the input file."
291 << std::endl;
292 return false;
293 }
294 if (verbose)
295 std::cout << "[*] Found NULL signature at: "
296 << std::hex << index << std::endl;
297
298 if (verbose)
299 std::cout << "[*] Computing digest..." << std::endl;
300
301 byte digest[20];
302 if (!zen::hmac_sha1_calc((const byte*)pi->null_key, strlen(pi->null_key)+1,
303 &data[0], index, digest, NULL))
304 {
305 std::cerr << "Failed to compute digest." << std::endl;
306 return false;
307 }
308
309 if (verbose)
310 std::cout << "[*] Verifying NULL signature digest..." << std::endl;
311
312 if (memcmp(&digest[0], &data[index+8], 20))
313 {
314 std::cerr << "The NULL signature contains an incorrect digest."
315 << std::endl;
316 return false;
317 }
318
319 return true;
320}
321
322bool encrypt(shared::bytes& data, int mode, player_info_t* pi,
323 const std::string& file, bool verbose)
324{
325 if (mode == mode_cenc)
326 {
327 if (verbose)
328 std::cout << "[*] Encoding input file..." << std::endl;
329
330 shared::bytes outbuf(data.size() * 2);
331 int len = zen::cenc_encode(&data[0], data.size(), &outbuf[0], outbuf.size());
332 if (!len)
333 {
334 std::cerr << "Failed to encode the input file." << std::endl;
335 return false;
336 }
337
338 if (verbose)
339 std::cout << "[*] Writing decoded length to file..." << std::endl;
340
341 shared::bytes length(sizeof(dword));
342 *(dword*)&length[0] = pi->big_endian ? shared::swap(data.size()) : data.size();
343 if (!shared::write_file(file, length, true))
344 {
345 std::cerr << "Failed to write the file data." << std::endl;
346 return false;
347 }
348
349 if (verbose)
350 std::cout << "[*] Writing file data..." << std::endl;
351
352 if (!shared::write_file(file, outbuf, sizeof(dword), len))
353 {
354 std::cerr << "Failed to write the file data." << std::endl;
355 return false;
356 }
357 }
358 else if (mode == mode_fresc)
359 {
360 std::cerr << "FRESC mode is not supported." << std::endl;
361 return false;
362 }
363 else if (mode == mode_tl)
364 {
365 if (verbose)
366 std::cout << "[*] Encoding input file..." << std::endl;
367
368 shared::bytes outbuf(data.size() * 2);
369 *(dword*)&outbuf[0] = pi->big_endian ? shared::swap(data.size()) : data.size();
370 int len = zen::cenc_encode(&data[0], data.size(),
371 &outbuf[sizeof(dword)],
372 outbuf.size()-sizeof(dword));
373 if (!len)
374 {
375 std::cerr << "Failed to encode the input file." << std::endl;
376 return false;
377 }
378 len += sizeof(dword);
379
380 int align = len % 8;
381 align = align ? (8 - align) : 0;
382 len += align;
383
384 if (verbose)
385 std::cout << "[*] Encrypting encoded data..." << std::endl;
386
387 dword iv[2] = {0, shared::swap(len)};
388 if (!zen::bf_cbc_encrypt((const byte*)pi->tl_key, strlen(pi->tl_key)+1,
389 &outbuf[0], len, (const byte*)iv))
390 {
391 std::cerr << "Failed to decrypt the input file." << std::endl;
392 return false;
393 }
394
395 if (verbose)
396 std::cout << "[*] Writing file data..." << std::endl;
397
398 if (!shared::write_file(file, outbuf, true, 0, len))
399 {
400 std::cerr << "Failed to save the output file." << std::endl;
401 return false;
402 }
403 }
404 else
405 {
406 std::cerr << "Invalid mode specified." << std::endl;
407 return false;
408 }
409
410 return true;
411}
412
413bool decrypt(shared::bytes& data, int mode, player_info_t* pi,
414 const std::string& file, bool verbose)
415{
416 if (mode == mode_cenc)
417 {
418 dword length = *(dword*)&data[0];
419 length = pi->big_endian ? shared::swap(length) : length;
420
421 if (verbose)
422 std::cout << "[*] Decoding input file..." << std::endl;
423
424 shared::bytes outbuf(length);
425 if (!zen::cenc_decode(&data[sizeof(dword)], data.size()-sizeof(dword),
426 &outbuf[0], length))
427 {
428 std::cerr << "Failed to decode the input file." << std::endl;
429 return false;
430 }
431
432 if (verbose)
433 std::cout << "[*] Writing file data..." << std::endl;
434
435 if (!shared::write_file(file, outbuf, true))
436 {
437 std::cerr << "Failed to write the file data." << std::endl;
438 return false;
439 }
440 }
441 else if (mode == mode_fresc)
442 {
443 if (verbose)
444 std::cout << "[*] Decrypting input file..." << std::endl;
445
446 dword iv[2] = {shared::swap(data.size()), 0};
447 if (!zen::bf_cbc_decrypt((const byte*)pi->fresc_key,
448 strlen(pi->fresc_key)+1, &data[0],
449 data.size(), (const byte*)iv))
450 {
451 std::cerr << "Failed to decrypt the input file." << std::endl;
452 return false;
453 }
454
455 if (verbose)
456 std::cout << "[*] Writing file data..." << std::endl;
457
458 if (!shared::write_file(file, data, true))
459 {
460 std::cerr << "Failed to save the output file." << std::endl;
461 return false;
462 }
463 }
464 else if (mode == mode_tl)
465 {
466 if (verbose)
467 std::cout << "[*] Decrypting input file..." << std::endl;
468
469 dword iv[2] = {0, shared::swap(data.size())};
470 if (!zen::bf_cbc_decrypt((const byte*)pi->tl_key, strlen(pi->tl_key)+1,
471 &data[0], data.size(), (const byte*)iv))
472 {
473 std::cerr << "Failed to decrypt the input file." << std::endl;
474 return false;
475 }
476
477 dword length = *(dword*)&data[0];
478 length = pi->big_endian ? shared::swap(length) : length;
479 if (length > (data.size() * 3))
480 {
481 std::cerr << "Decrypted length is unexpectedly large: "
482 << std::hex << length
483 << " Check the endian and key settings." << std::endl;
484 return false;
485 }
486
487 if (verbose)
488 std::cout << "[*] Decoding decrypted data..." << std::endl;
489
490 shared::bytes outbuf(length);
491 if (!zen::cenc_decode(&data[sizeof(dword)], data.size()-sizeof(dword),
492 &outbuf[0], length))
493 {
494 std::cerr << "Failed to decode the input file." << std::endl;
495 return false;
496 }
497
498 if (verbose)
499 std::cout << "[*] Writing file data..." << std::endl;
500
501 if (!shared::write_file(file, outbuf, true))
502 {
503 std::cerr << "Failed to save the output file." << std::endl;
504 return false;
505 }
506 }
507 else
508 {
509 std::cerr << "Invalid mode specified." << std::endl;
510 return false;
511 }
512
513 return true;
514}
515
516int process_arguments(int argc, char*argv[])
517{
518 //--------------------------------------------------------------------
519 // Parse input variables.
520 //--------------------------------------------------------------------
521
522 GetPot cl(argc, argv);
523 if (cl.size() == 1 || cl.search(2, "-h", "--help"))
524 {
525 print_help();
526 return 1;
527 }
528
529 int command = cmd_none;
530 if (cl.search(2, "-s", "--sign"))
531 command = cmd_sign;
532 else if (cl.search(2, "-v", "--verify"))
533 command = cmd_verify;
534 else if (cl.search(2, "-e", "--encrypt"))
535 command = cmd_encrypt;
536 else if (cl.search(2, "-d", "--decrypt"))
537 command = cmd_decrypt;
538
539 if (command == cmd_none)
540 {
541 std::cerr << "No command specified." << std::endl;
542 return 2;
543 }
544
545 int mode = mode_none;
546 if (command == cmd_encrypt || command == cmd_decrypt)
547 {
548 if (!cl.search(2, "-m", "--mode"))
549 {
550 std::cerr << "The specified command requires that"
551 " a mode is specified."
552 << std::endl;
553 return 3;
554 }
555 std::string name = cl.next("");
556 if (!name.empty())
557 {
558 if (!stricmp(name.c_str(), "CENC"))
559 mode = mode_cenc;
560 else if (!stricmp(name.c_str(), "FRESC"))
561 mode = mode_fresc;
562 else if (!stricmp(name.c_str(), "TL"))
563 mode = mode_tl;
564 }
565 if (mode == mode_none)
566 {
567 std::cerr << "Invalid mode specified." << std::endl;
568 return 4;
569 }
570 }
571
572 bool verbose = false;
573 if (cl.search(2, "-V", "--verbose"))
574 verbose = true;
575
576 bool big_endian = false;
577 if (cl.search(2, "-b", "--big-endian"))
578 big_endian = true;
579
580 std::string infile;
581 if (cl.search(2, "-i", "--input"))
582 infile = cl.next("");
583 if (infile.empty())
584 {
585 std::cerr << "An input file must be specified." << std::endl;
586 return 5;
587 }
588
589 std::string outfile = infile;
590 if (cl.search(2, "-o", "--output"))
591 outfile = cl.next(outfile.c_str());
592
593 player_info_t* pi = &players[0];
594 std::string key;
595 if (cl.search(2, "-k", "--key"))
596 key = cl.next("");
597 if (!key.empty())
598 {
599 player_info_t* pitmp = find_player_info(key);
600 if (pitmp != NULL)
601 pi = pitmp;
602 else
603 {
604 static player_info_t player = {
605 NULL, key.c_str(), key.c_str(), key.c_str(), false
606 };
607 pi = &player;
608 }
609 }
610 if (big_endian)
611 pi->big_endian = big_endian;
612
613
614 //--------------------------------------------------------------------
615 // Read the input file.
616 //--------------------------------------------------------------------
617
618 if (verbose)
619 std::cout << "[*] Reading input file..." << std::endl;
620
621 shared::bytes buffer;
622 if (!shared::read_file(infile, buffer))
623 {
624 std::cerr << "Failed to read the input file." << std::endl;
625 return 6;
626 }
627
628
629 //--------------------------------------------------------------------
630 // Process the input file.
631 //--------------------------------------------------------------------
632
633 switch (command)
634 {
635 case cmd_sign:
636 if (verbose)
637 std::cout << "[*] Signing input file..." << std::endl;
638 if (!sign(buffer, pi, outfile, verbose))
639 return 7;
640 std::cout << "Successfully signed the input file." << std::endl;
641 break;
642 case cmd_verify:
643 if (verbose)
644 std::cout << "[*] Verifying signature on input file..."
645 << std::endl;
646 if (!verify(buffer, pi, verbose))
647 return 8;
648 std::cout << "Successfully verified the input file signature."
649 << std::endl;
650 break;
651 case cmd_encrypt:
652 if (verbose)
653 std::cout << "[*] Encrypting input file..." << std::endl;
654 if (!encrypt(buffer, mode, pi, outfile, verbose))
655 return 9;
656 std::cout << "Successfully encrypted the input file." << std::endl;
657 break;
658 case cmd_decrypt:
659 if (verbose)
660 std::cout << "[*] Decrypting input file..." << std::endl;
661 if (!decrypt(buffer, mode, pi, outfile, verbose))
662 return 10;
663 std::cout << "Successfully decrypted the input file." << std::endl;
664 break;
665 };
666
667 return 0;
668}
669
670int main(int argc, char* argv[])
671{
672 try
673 {
674 return process_arguments(argc, argv);
675 }
676 catch (const std::exception& xcpt)
677 {
678 std::cerr << "Exception caught: " << xcpt.what() << std::endl;
679 return -1;
680 }
681 catch (...)
682 {
683 std::cerr << "Unknown exception caught." << std::endl;
684 return -2;
685 }
686 return -3;
687}