libPeConv
A library to load, manipulate, dump PE files.
Loading...
Searching...
No Matches
exceptions_parser.cpp
Go to the documentation of this file.
2
4
5#ifdef _DEBUG
6#include <iostream>
7#endif
8
9#ifdef _WIN64
10bool peconv::setup_exceptions(IN BYTE* modulePtr, IN size_t moduleSize)
11{
12 if (moduleSize == 0) {
13 const DWORD img_size = peconv::get_image_size((BYTE*)modulePtr);
14 if (!img_size) {
15 return false; // invalid image
16 }
17 moduleSize = img_size;
18 }
19 IMAGE_DATA_DIRECTORY* my_dir = peconv::get_directory_entry((const BYTE*)modulePtr, IMAGE_DIRECTORY_ENTRY_EXCEPTION);
20 if (!my_dir || !my_dir->VirtualAddress || !my_dir->Size) {
21 return false;
22 }
23 RUNTIME_FUNCTION* exceptions_list = (RUNTIME_FUNCTION*)(my_dir->VirtualAddress + (ULONG_PTR)modulePtr);
24 if (!validate_ptr(modulePtr, moduleSize, exceptions_list, my_dir->Size)) {
25 return false;
26 }
27 //validate exceptions table:
28 const size_t except_max_count = my_dir->Size / sizeof(RUNTIME_FUNCTION);
29#ifdef _DEBUG
30 std::cout << "[+] Found exception table of: " << std::dec << except_max_count << " entries\n";
31#endif
32 size_t i = 0;
33 for (i = 0; i < except_max_count; i++) {
34 RUNTIME_FUNCTION next_func = exceptions_list[i];
35 BYTE* start_ptr = next_func.BeginAddress + modulePtr;
36#if defined(_M_AMD64)
37 size_t func_size = next_func.EndAddress - next_func.BeginAddress;
38#elif defined(_M_ARM64)
39 size_t func_size = next_func.FunctionLength;
40#endif
41 if (!validate_ptr(modulePtr, moduleSize, start_ptr, func_size)) {
42 break;
43 }
44 }
45#ifdef _DEBUG
46 std::cout << "[+] Valid exception entries: " << std::dec << i << " entries\n";
47#endif
48 if (i == 0) {
49#ifdef _DEBUG
50 std::cerr << "[-] None of the exceptions was valid\n";
51#endif
52 // none of the exceptions was valid
53 return false;
54 }
55 if (RtlAddFunctionTable(exceptions_list, (DWORD)i, (ULONG_PTR)modulePtr)) {
56 return true;
57 }
58 return false;
59}
60#endif
Functions related to Exceptions Table.
bool validate_ptr(IN const void *buffer_bgn, IN size_t buffer_size, IN const void *field_bgn, IN size_t field_size)
DWORD get_image_size(IN const BYTE *payload)
IMAGE_DATA_DIRECTORY * get_directory_entry(IN const BYTE *pe_buffer, IN DWORD dir_id, IN bool allow_empty=false)
Wrappers over various fields in the PE header. Read, write, parse PE headers.