1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
#include "../include.h"
#include "util.h"
#include "io.h"
#include "syscalls.h"
std::string util::wide_to_multibyte(const std::wstring& str) {
std::string ret;
size_t str_len;
// check if not empty str
if (str.empty())
return{};
// count size
str_len = WideCharToMultiByte(CP_UTF8, 0, &str[0], str.size(), 0, 0, 0, 0);
// setup return value
ret.resize(str_len);
// final conversion
WideCharToMultiByte(CP_UTF8, 0, &str[0], str.size(), &ret[0], str_len, 0, 0);
return ret;
}
std::wstring util::multibyte_to_wide(const std::string& str) {
size_t size;
std::wstring out;
// get size
size = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.size() + 1, 0, 0);
out.resize(size);
// finally convert
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.size() + 1, &out[0], size);
return out;
}
bool util::close_handle(HANDLE handle) {
if (!handle) {
io::log_error("invalid handle to close.");
return false;
}
static auto nt_close = g_syscalls.get<native::NtClose>("NtClose");
auto status = nt_close(handle);
if (!NT_SUCCESS(status)) {
io::log_error("failed to close {}, status {:#X}.", handle, (status & 0xFFFFFFFF));
return false;
}
return true;
}
void pe::get_all_modules(std::unordered_map<std::string, virtual_image>& modules) {
auto peb = util::peb();
if (!peb) return;
if (!peb->Ldr->InMemoryOrderModuleList.Flink) return;
auto* list = &peb->Ldr->InMemoryOrderModuleList;
for (auto i = list->Flink; i != list; i = i->Flink) {
auto entry = CONTAINING_RECORD(i, native::LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
if (!entry)
continue;
auto name = util::wide_to_multibyte(entry->BaseDllName.Buffer);
std::transform(name.begin(), name.end(), name.begin(), ::tolower);
modules[name] = virtual_image(entry->DllBase);
}
}
|