summaryrefslogtreecommitdiff
path: root/utils/zenutils/libraries/pelib-0.9/pelib
diff options
context:
space:
mode:
Diffstat (limited to 'utils/zenutils/libraries/pelib-0.9/pelib')
-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
33 files changed, 12617 insertions, 0 deletions
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