forked from Tracktion/choc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
choc_MemoryDLL.h
529 lines (417 loc) · 19.9 KB
/
choc_MemoryDLL.h
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
//
// ██████ ██ ██ ██████ ██████
// ██ ██ ██ ██ ██ ██ ** Classy Header-Only Classes **
// ██ ███████ ██ ██ ██
// ██ ██ ██ ██ ██ ██ https://github.com/Tracktion/choc
// ██████ ██ ██ ██████ ██████
//
// CHOC is (C)2022 Tracktion Corporation, and is offered under the terms of the ISC license:
//
// Permission to use, copy, modify, and/or distribute this software for any purpose with or
// without fee is hereby granted, provided that the above copyright notice and this permission
// notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
// WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
// CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#ifndef CHOC_MEMORYDLL_HEADER_INCLUDED
#define CHOC_MEMORYDLL_HEADER_INCLUDED
#include <stddef.h>
#include <memory>
#include <string>
namespace choc::memory
{
/**
MemoryDLL is an egregious hack that allows you to load DLL files from a chunk
of memory in the same way you might load them from a file on disk.
This opens up the ability to do horrible things such as embedding a random DLL
in a chunk of C++ code, so that it gets baked directly into your executable..
That means that if your app requires a 3rd-party DLL but you don't want the hassle
of having to install the DLL file in the right place on your users' machines, you
could use this trick to embed it invisibly inside your executable...
Currently this is only implemented for Windows DLLs, but a linux/OSX loader for
.dylibs is also totally feasible if anyone fancies having a go :)
@see DynamicLibrary
*/
struct MemoryDLL
{
MemoryDLL() = default;
MemoryDLL (MemoryDLL&&) = default;
MemoryDLL& operator= (MemoryDLL&&) = default;
~MemoryDLL();
/// Attempts to load a chunk of memory that contains a DLL file image.
MemoryDLL (const void* data, size_t size);
/// Returns a pointer to the function with this name, or nullptr if not found.
void* findFunction (std::string_view functionName);
/// Returns true if the library was successfully loaded
operator bool() const { return pimpl != nullptr; }
private:
struct Pimpl;
std::unique_ptr<Pimpl> pimpl;
};
} // namespace choc::memory
//==============================================================================
// _ _ _ _
// __| | ___ | |_ __ _ (_)| | ___
// / _` | / _ \| __| / _` || || |/ __|
// | (_| || __/| |_ | (_| || || |\__ \ _ _ _
// \__,_| \___| \__| \__,_||_||_||___/(_)(_)(_)
//
// Code beyond this point is implementation detail...
//
//==============================================================================
#if defined (_WIN32) || defined (_WIN64)
#include <vector>
#include <unordered_map>
#undef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#undef NOMINMAX
#define NOMINMAX
#define Rectangle Rectangle_renamed_to_avoid_name_collisions
#include <windows.h>
#undef Rectangle
namespace choc::memory
{
struct MemoryDLL::Pimpl
{
Pimpl() = default;
~Pimpl()
{
if (entryFunction != nullptr)
(*reinterpret_cast<DLLEntryFn> (entryFunction)) ((HINSTANCE) imageData, DLL_PROCESS_DETACH, nullptr);
for (auto& m : loadedModules)
FreeLibrary (m);
if (imageData != nullptr)
VirtualFree (imageData, 0, MEM_RELEASE);
for (auto m : virtualBlocks)
VirtualFree (m, 0, MEM_RELEASE);
}
bool initialise (const void* data, size_t size)
{
if (size < sizeof (IMAGE_DOS_HEADER))
return false;
auto dosHeader = static_cast<const IMAGE_DOS_HEADER*> (data);
if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE
|| size < static_cast<size_t> (dosHeader->e_lfanew) + sizeof (IMAGE_NT_HEADERS))
return false;
const auto& headers = *getOffsetAs<IMAGE_NT_HEADERS> (data, dosHeader->e_lfanew);
if (headers.Signature != IMAGE_NT_SIGNATURE
|| (headers.OptionalHeader.SectionAlignment & 1) != 0)
return false;
#ifdef _M_ARM64
if (headers.FileHeader.Machine != IMAGE_FILE_MACHINE_ARM64) return false;
#elif defined (_WIN64)
if (headers.FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64) return false;
#else
if (headers.FileHeader.Machine != IMAGE_FILE_MACHINE_I386) return false;
#endif
SYSTEM_INFO systemInfo;
GetNativeSystemInfo (std::addressof (systemInfo));
auto alignedImageSize = roundUp (headers.OptionalHeader.SizeOfImage, systemInfo.dwPageSize);
if (alignedImageSize != roundUp (getLastSectionEnd (headers), systemInfo.dwPageSize))
return false;
imageData = VirtualAlloc (reinterpret_cast<void*> (headers.OptionalHeader.ImageBase),
alignedImageSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (imageData == nullptr)
{
imageData = VirtualAlloc (nullptr, alignedImageSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (imageData == nullptr)
return false;
}
while ((((uint64_t) imageData) >> 32) < (((uint64_t) imageData + alignedImageSize) >> 32))
{
virtualBlocks.push_back (imageData);
imageData = VirtualAlloc (nullptr, alignedImageSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (imageData == nullptr)
return false;
}
isDLL = (headers.FileHeader.Characteristics & IMAGE_FILE_DLL) != 0;
pageSize = systemInfo.dwPageSize;
if (size < headers.OptionalHeader.SizeOfHeaders)
return false;
auto newHeaders = VirtualAlloc (imageData, headers.OptionalHeader.SizeOfHeaders, MEM_COMMIT, PAGE_READWRITE);
memcpy (newHeaders, dosHeader, headers.OptionalHeader.SizeOfHeaders);
imageHeaders = getOffsetAs<IMAGE_NT_HEADERS> (newHeaders, dosHeader->e_lfanew);
imageHeaders->OptionalHeader.ImageBase = reinterpret_cast<uintptr_t> (imageData);
if (copySections (data, size, headers.OptionalHeader.SectionAlignment))
{
if (auto locationDelta = (ptrdiff_t) (imageHeaders->OptionalHeader.ImageBase - headers.OptionalHeader.ImageBase))
performRelocation (locationDelta);
if (loadImports() && prepareSections())
{
executeTLS();
loadNameTable();
if (imageHeaders->OptionalHeader.AddressOfEntryPoint != 0)
{
entryFunction = getOffsetAs<char> (imageData, imageHeaders->OptionalHeader.AddressOfEntryPoint);
if (isDLL)
return (*reinterpret_cast<DLLEntryFn> (entryFunction)) ((HINSTANCE) imageData, DLL_PROCESS_ATTACH, nullptr);
return true;
}
}
}
return false;
}
void* findFunction (std::string_view name)
{
if (auto found = exportedFunctionOffsets.find (std::string (name)); found != exportedFunctionOffsets.end())
return getOffsetAs<char> (imageData, found->second);
return {};
}
private:
PIMAGE_NT_HEADERS imageHeaders = {};
void* imageData = nullptr;
std::vector<HMODULE> loadedModules;
uint32_t pageSize = 0;
bool isDLL = false;
std::vector<void*> virtualBlocks;
std::unordered_map<std::string, size_t> exportedFunctionOffsets;
using DLLEntryFn = BOOL(WINAPI*)(HINSTANCE, DWORD, void*);
void* entryFunction = {};
template <typename Type, typename Diff>
static const Type* getOffsetAs (const void* address, Diff offset)
{
return reinterpret_cast<const Type*> (static_cast<const char*> (address) + offset);
}
template <typename Type, typename Diff>
static Type* getOffsetAs (void* address, Diff offset)
{
return reinterpret_cast<Type*> (static_cast<char*> (address) + offset);
}
template <typename Type>
Type* getDataDirectoryAddress (int type) const
{
auto& dd = imageHeaders->OptionalHeader.DataDirectory[type];
if (dd.Size > 0)
return getOffsetAs<Type> (imageData, dd.VirtualAddress);
return {};
}
static size_t getLastSectionEnd (const IMAGE_NT_HEADERS& headers)
{
auto section = IMAGE_FIRST_SECTION (&headers);
auto optionalSectionSize = headers.OptionalHeader.SectionAlignment;
size_t lastSectionEnd = 0;
for (uint32_t i = 0; i < headers.FileHeader.NumberOfSections; ++i, ++section)
{
auto end = section->VirtualAddress + (section->SizeOfRawData == 0 ? optionalSectionSize
: section->SizeOfRawData);
if (end > lastSectionEnd)
lastSectionEnd = end;
}
return lastSectionEnd;
}
void loadNameTable()
{
if (auto exports = getDataDirectoryAddress<IMAGE_EXPORT_DIRECTORY> (IMAGE_DIRECTORY_ENTRY_EXPORT))
{
if (exports->NumberOfNames > 0 && exports->NumberOfFunctions > 0)
{
auto name = getOffsetAs<const DWORD> (imageData, exports->AddressOfNames);
auto ordinal = getOffsetAs<const WORD> (imageData, exports->AddressOfNameOrdinals);
exportedFunctionOffsets.reserve (exports->NumberOfNames);
for (size_t i = 0; i < exports->NumberOfNames; ++i, ++name, ++ordinal)
if (*ordinal <= exports->NumberOfFunctions)
exportedFunctionOffsets[std::string (getOffsetAs<const char> (imageData, *name))]
= getOffsetAs<DWORD> (imageData, exports->AddressOfFunctions)[*ordinal];
}
}
}
void executeTLS()
{
if (auto tls = getDataDirectoryAddress<IMAGE_TLS_DIRECTORY> (IMAGE_DIRECTORY_ENTRY_TLS))
if (auto callback = reinterpret_cast<PIMAGE_TLS_CALLBACK*> (tls->AddressOfCallBacks))
while (*callback != nullptr)
(*callback++) ((void*) imageData, DLL_PROCESS_ATTACH, nullptr);
}
bool prepareSections()
{
auto section = IMAGE_FIRST_SECTION (imageHeaders);
auto size = getSectionSize (*section);
auto address = getSectionAddress (*section);
auto addressPage = getPageBase (address);
auto characteristics = section->Characteristics;
for (WORD i = 1; i < imageHeaders->FileHeader.NumberOfSections; ++i)
{
++section;
auto nextSize = getSectionSize (*section);
auto nextAddress = getSectionAddress (*section);
auto nextAddressPage = getPageBase (nextAddress);
if (addressPage == nextAddressPage || address + size > nextAddressPage)
{
if ((section->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) == 0 || (characteristics & IMAGE_SCN_MEM_DISCARDABLE) == 0)
characteristics = (characteristics | section->Characteristics) & ~static_cast<DWORD> (IMAGE_SCN_MEM_DISCARDABLE);
else
characteristics |= section->Characteristics;
size = static_cast<size_t> ((nextAddress + nextSize) - address);
continue;
}
if (! setProtectionFlags (size, characteristics, address, addressPage, false))
return false;
size = nextSize;
address = nextAddress;
addressPage = nextAddressPage;
characteristics = section->Characteristics;
}
return setProtectionFlags (size, characteristics, address, addressPage, true);
}
bool setProtectionFlags (size_t sectionSize, DWORD sectionCharacteristics, void* sectionAddress, void* addressPage, bool isLast)
{
if (sectionSize == 0)
return true;
if ((sectionCharacteristics & IMAGE_SCN_MEM_DISCARDABLE) != 0)
{
if (sectionAddress == addressPage
&& (isLast || imageHeaders->OptionalHeader.SectionAlignment == pageSize || (sectionSize % pageSize) == 0))
VirtualFree (sectionAddress, sectionSize, MEM_DECOMMIT);
return true;
}
auto getProtectionFlags = [] (DWORD type)
{
return ((type & IMAGE_SCN_MEM_NOT_CACHED) ? PAGE_NOCACHE : 0)
| ((type & IMAGE_SCN_MEM_EXECUTE)
? ((type & IMAGE_SCN_MEM_READ)
? ((type & IMAGE_SCN_MEM_WRITE) ? PAGE_EXECUTE_READWRITE : PAGE_EXECUTE_READ)
: ((type & IMAGE_SCN_MEM_WRITE) ? PAGE_EXECUTE_WRITECOPY : PAGE_EXECUTE))
: ((type & IMAGE_SCN_MEM_READ)
? ((type & IMAGE_SCN_MEM_WRITE) ? PAGE_READWRITE : PAGE_READONLY)
: ((type & IMAGE_SCN_MEM_WRITE) ? PAGE_WRITECOPY : PAGE_NOACCESS)));
};
DWORD oldProtectValue;
return VirtualProtect (sectionAddress, sectionSize,
static_cast<DWORD> (getProtectionFlags (sectionCharacteristics)),
std::addressof (oldProtectValue)) != 0;
}
bool loadImports()
{
auto imp = getDataDirectoryAddress<IMAGE_IMPORT_DESCRIPTOR> (IMAGE_DIRECTORY_ENTRY_IMPORT);
if (imp == nullptr)
return false;
while (! IsBadReadPtr (imp, sizeof (IMAGE_IMPORT_DESCRIPTOR)) && imp->Name != 0)
{
auto handle = LoadLibraryA (getOffsetAs<const char> (imageData, imp->Name));
if (handle == nullptr)
return false;
loadedModules.push_back (handle);
auto thunkRef = getOffsetAs<uintptr_t> (imageData, imp->OriginalFirstThunk ? imp->OriginalFirstThunk
: imp->FirstThunk);
auto funcRef = getOffsetAs<FARPROC> (imageData, imp->FirstThunk);
for (; *thunkRef != 0; ++thunkRef, ++funcRef)
{
auto name = IMAGE_SNAP_BY_ORDINAL(*thunkRef)
? (LPCSTR) IMAGE_ORDINAL(*thunkRef)
: (LPCSTR) std::addressof (getOffsetAs<IMAGE_IMPORT_BY_NAME> (imageData, *thunkRef)->Name);
*funcRef = GetProcAddress (handle, name);
if (*funcRef == 0)
return false;
}
++imp;
}
return true;
}
size_t getSectionSize (const IMAGE_SECTION_HEADER& section) const
{
if (auto size = section.SizeOfRawData)
return size;
if (section.Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
return imageHeaders->OptionalHeader.SizeOfInitializedData;
if (section.Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
return imageHeaders->OptionalHeader.SizeOfUninitializedData;
return 0;
}
static size_t roundUp (size_t value, size_t alignment) { return (value + alignment - 1) & ~(alignment - 1); }
char* getPageBase (void* address) const { return (char*) (reinterpret_cast<uintptr_t> (address) & ~static_cast<uintptr_t> (pageSize - 1)); }
char* getSectionAddress (const IMAGE_SECTION_HEADER& section) const
{
#ifdef _WIN64
return reinterpret_cast<char*> (static_cast<uintptr_t> (section.Misc.PhysicalAddress)
| (static_cast<uintptr_t> (imageHeaders->OptionalHeader.ImageBase & 0xffffffff00000000)));
#else
return reinterpret_cast<char*> (section.Misc.PhysicalAddress);
#endif
}
bool copySections (const void* data, size_t size, size_t sectionAlignment) const
{
auto section = IMAGE_FIRST_SECTION (imageHeaders);
for (int i = 0; i < imageHeaders->FileHeader.NumberOfSections; ++i, ++section)
{
if (section->SizeOfRawData == 0)
{
if (sectionAlignment == 0)
continue;
if (auto dest = VirtualAlloc (getOffsetAs<char> (imageData, section->VirtualAddress),
sectionAlignment, MEM_COMMIT, PAGE_READWRITE))
{
dest = getOffsetAs<char> (imageData, section->VirtualAddress);
section->Misc.PhysicalAddress = static_cast<uint32_t> (reinterpret_cast<uintptr_t> (dest));
memset (dest, 0, sectionAlignment);
continue;
}
return false;
}
if (size < section->PointerToRawData + section->SizeOfRawData)
return false;
if (auto dest = VirtualAlloc (getOffsetAs<char> (imageData, section->VirtualAddress),
section->SizeOfRawData, MEM_COMMIT, PAGE_READWRITE))
{
dest = getOffsetAs<char> (imageData, section->VirtualAddress);
memcpy (dest, static_cast<const char*> (data) + section->PointerToRawData, section->SizeOfRawData);
section->Misc.PhysicalAddress = static_cast<uint32_t> (reinterpret_cast<uintptr_t> (dest));
continue;
}
return false;
}
return true;
}
void performRelocation (ptrdiff_t delta)
{
auto directory = imageHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
if (directory.Size != 0)
{
auto relocation = getOffsetAs<IMAGE_BASE_RELOCATION> (imageData, directory.VirtualAddress);
while (relocation->VirtualAddress > 0)
{
auto dest = getOffsetAs<char> (imageData, relocation->VirtualAddress);
auto offset = getOffsetAs<uint16_t> (relocation, sizeof (IMAGE_BASE_RELOCATION));
for (uint32_t i = 0; i < (relocation->SizeOfBlock - sizeof (IMAGE_BASE_RELOCATION)) / 2; ++i, ++offset)
{
switch (*offset >> 12)
{
case IMAGE_REL_BASED_HIGHLOW: addDelta<uint32_t> (dest + (*offset & 0xfff), delta); break;
case IMAGE_REL_BASED_DIR64: addDelta<uint64_t> (dest + (*offset & 0xfff), delta); break;
case IMAGE_REL_BASED_ABSOLUTE:
default: break;
}
}
relocation = getOffsetAs<IMAGE_BASE_RELOCATION> (relocation, relocation->SizeOfBlock);
}
}
}
template <typename Type>
static void addDelta (char* addr, ptrdiff_t delta)
{
*reinterpret_cast<Type*> (addr) = static_cast<Type> (static_cast<ptrdiff_t> (*reinterpret_cast<Type*> (addr)) + delta);
}
};
#else
#include "choc_Assert.h"
namespace choc::memory
{
struct MemoryDLL::Pimpl
{
bool initialise (const void*, size_t) { CHOC_ASSERT (false); return {}; } // Only available on Windows!
void* findFunction (std::string_view) { CHOC_ASSERT (false); return {}; } // Only available on Windows!
};
#endif
inline MemoryDLL::~MemoryDLL() = default;
inline MemoryDLL::MemoryDLL (const void* data, size_t size) : pimpl (std::make_unique<Pimpl>())
{
if (! pimpl->initialise (data, size))
pimpl.reset();
}
inline void* MemoryDLL::findFunction (std::string_view name)
{
return pimpl != nullptr ? pimpl->findFunction (name) : nullptr;
}
} // namespace choc::memory
#endif // CHOC_MEMORYDLL_HEADER_INCLUDED