ETISS 0.8.0
Extendable Translating Instruction Set Simulator (version 0.8.0)
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
Memory.cpp
Go to the documentation of this file.
1/*
2 * Taken from https://bitbucket.org/rafzi/hacklib
3 */
4
5#include "etiss/Memory.h"
6#include <stdexcept>
7
8
9#ifdef _WIN32
10
11#include <Windows.h>
12
13etiss::ModuleHandle etiss::GetModuleByName(const std::string &name)
14{
15 if (name == "")
16 {
17 return GetModuleHandleA(NULL);
18 }
19 else
20 {
21 return GetModuleHandleA(name.c_str());
22 }
23}
24
26{
28
29 if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
30 (LPCTSTR)adr, &hModule) == 0)
31 {
32 if (GetLastError() != ERROR_MOD_NOT_FOUND)
33 {
34 throw std::runtime_error("GetModuleHandleEx failed");
35 }
36 }
37
38 return hModule;
39}
40
42{
43 char path[MAX_PATH];
44
45 if (GetModuleFileNameA(hModule, path, MAX_PATH) == 0)
46 {
47 throw std::runtime_error("GetModuleFileName failed");
48 }
49
50 return path;
51}
52#else
53
54#include <dlfcn.h>
55
57{
58 void *handle;
59 if (name == "")
60 {
61 handle = dlopen(NULL, RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD);
62 }
63 else
64 {
65 handle = dlopen(name.c_str(), RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD);
66 }
67
68 if (handle)
69 {
70 // This is undocumented, but works and is easy.
71 auto hModule = *(etiss::ModuleHandle *)handle;
72 if (!hModule)
73 {
74 hModule = (etiss::ModuleHandle)0x400000;
75 }
76 dlclose(handle);
77 return hModule;
78 }
79 else
80 {
82 }
83}
84
86{
87 Dl_info info = { 0 };
88 dladdr((void *)adr, &info);
89 return info.dli_fbase;
90}
91
93{
94 Dl_info info = { 0 };
95 if (dladdr((void *)hModule, &info) == 0)
96 {
97 throw std::runtime_error("dladdr failed");
98 }
99 return info.dli_fname;
100}
101
102#endif
103
104
105
107{
108 static etiss::ModuleHandle hModule = 0;
109
110 if (!hModule)
111 {
113 }
114
115 return hModule;
116}
118{
119 static std::string modulePath;
120
121 if (modulePath == "")
122 {
124 }
125
126 return modulePath;
127}
void * ModuleHandle
Represents a module handle. Analogous to Windows this represents the module base address,...
Definition Memory.h:31
etiss::ModuleHandle GetModuleByAddress(uintptr_t adr)
Definition Memory.cpp:85
std::string GetCurrentModulePath()
Returns the abolute path with filename to the own dynamic library.
Definition Memory.cpp:117
etiss::ModuleHandle GetModuleByName(const std::string &name="")
Definition Memory.cpp:56
static const ModuleHandle NullModuleHandle
Represents a null value for hl::ModuleHandle.
Definition Memory.h:34
std::string GetModulePath(etiss::ModuleHandle hModule)
Definition Memory.cpp:92
etiss::ModuleHandle GetCurrentModule()
Returns the module handle to the own dynamic library.
Definition Memory.cpp:106
#define NULL
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...