Debian Codegraph @

vendor/Heap-Layers/wrappers/winwrapper.cpp

raw
1 /* -*- C++ -*- */
2
3 /*
4 * @file winwrapper.cpp
5 * @brief Replaces malloc family on Windows with custom versions.
6 * @author Emery Berger <http://www.emeryberger.org>
7 * @note Copyright (C) 2011-2015 by Emery Berger, University of Massachusetts Amherst.
8 */
9
10 /*
11 To use this library,
12 you only need to define the following allocation functions:
13
14 - xxmalloc
15 - xxfree
16 - xxmalloc_usable_size
17 - xxmalloc_lock
18 - xxmalloc_unlock
19
20 See the extern "C" block below for function prototypes and more
21 details. YOU SHOULD NOT NEED TO MODIFY ANY OF THE CODE HERE TO
22 SUPPORT ANY ALLOCATOR.
23
24 LIMITATIONS:
25
26 - This wrapper assumes that the underlying allocator will do "the
27 right thing" when xxfree() is called with a pointer internal to an
28 allocated object. Header-based allocators, for example, need not
29 apply.
30
31 - This wrapper also assumes that there is some way to lock all the
32 heaps used by a given allocator; however, such support is only
33 required by programs that also call fork(). In case your program
34 does not, the lock and unlock calls given below can be no-ops.
35
36 */
37
38 #include <windows.h>
39 #include <errno.h>
40 #include <psapi.h>
41 #include <stdio.h>
42 #include <tchar.h>
43
44 #include "x86jump.h"
45
46 extern "C" {
47
48 void * xxmalloc (size_t);
49 void xxfree (void *);
50
51 // Takes a pointer and returns how much space it holds.
52 size_t xxmalloc_usable_size (void *);
53
54 // Locks the heap(s), used prior to any invocation of fork().
55 void xxmalloc_lock (void);
56
57 // Unlocks the heap(s), after fork().
58 void xxmalloc_unlock (void);
59
60 }
61
62
63 #ifdef _DEBUG
64 #error "This library must be compiled in release mode."
65 #endif
66
67 #define WIN32_LEAN_AND_MEAN
68
69 #if !defined(_M_IX86) && !defined(_M_X64)
70 #error "Hoard currently only supports x86-based architectures on Windows."
71 #endif
72
73 #if (_WIN32_WINNT < 0x0500)
74 #define _WIN32_WINNT 0x0500
75 #endif
76
77 #pragma inline_depth(255)
78
79 #pragma warning(disable: 4273)
80 #pragma warning(disable: 4098) // Library conflict.
81 #pragma warning(disable: 4355) // 'this' used in base member initializer list.
82 #pragma warning(disable: 4074) // initializers put in compiler reserved area.
83
84
85 #define WINWRAPPER_PREFIX(x) winwrapper_##x
86
87 class Patch {
88 public:
89 const char *import; // import name of patch routine
90 FARPROC replacement; // pointer to replacement function
91 FARPROC original; // pointer to original function
92 bool patched; // did we actually execute this patch?
93 unsigned char codebytes[sizeof(X86Jump)]; // original code storage
94 };
95
96 static bool PatchMe();
97 static void UnpatchMe();
98 extern "C" void executeRegisteredFunctions();
99
100 /// Initialize everything.
101 extern "C" void InitializeWinWrapper() {
102 // Allocate (and leak) something from the old Windows heap.
103 HeapAlloc (GetProcessHeap(), 0, 1);
104 PatchMe();
105 }
106
107 /// Mr. Gorbachev, tear down this process.
108 extern "C" void FinalizeWinWrapper() {
109 TerminateProcess(GetCurrentProcess(), 0);
110 }
111
112 extern "C" {
113
114 __declspec(dllexport) int ReferenceWinWrapperStub;
115
116 void * WINWRAPPER_PREFIX(_expand) (void * ptr) {
117 return nullptr;
118 }
119
120 void * WINWRAPPER_PREFIX(_expand_dbg)(void *userData,
121 size_t newSize,
122 int blockType,
123 const char *filename,
124 int linenumber)
125 {
126 return nullptr;
127 }
128
129 static void * WINWRAPPER_PREFIX(realloc) (void * ptr, size_t sz)
130 {
131 // null ptr = act like a malloc.
132 if (ptr == nullptr) {
133 return xxmalloc(sz);
134 }
135
136 // 0 size = free. We return a small object. This behavior is
137 // apparently required under Mac OS X and optional under POSIX.
138 if (sz == 0) {
139 xxfree (ptr);
140 return xxmalloc(1);
141 }
142
143 auto originalSize = xxmalloc_usable_size (ptr);
144 auto minSize = (originalSize < sz) ? originalSize : sz;
145
146 // Don't change size if the object is shrinking by less than half.
147 if ((originalSize / 2 < sz) && (sz <= originalSize)) {
148 // Do nothing.
149 return ptr;
150 }
151
152 auto * buf = xxmalloc (sz);
153
154 if (buf != nullptr) {
155 // Successful malloc.
156 // Copy the contents of the original object
157 // up to the size of the new block.
158 memcpy (buf, ptr, minSize);
159 xxfree (ptr);
160 }
161
162 // Return a pointer to the new one.
163 return buf;
164 }
165
166 static void * WINWRAPPER_PREFIX(_recalloc)(void * memblock, size_t num, size_t size) {
167 const auto requestedSize = num * size;
168 auto * ptr = WINWRAPPER_PREFIX(realloc)(memblock, requestedSize);
169 if (ptr != nullptr) {
170 const auto actualSize = xxmalloc_usable_size(ptr);
171 if (actualSize > requestedSize) {
172 // Clear out any memory after the end of the requested chunk.
173 memset (static_cast<char *>(ptr) + requestedSize, 0, actualSize - requestedSize);
174 }
175 }
176 return ptr;
177 }
178
179 static void * WINWRAPPER_PREFIX(calloc)(size_t num, size_t size) {
180 auto * ptr = xxmalloc (num * size);
181 if (ptr) {
182 memset (ptr, 0, num * size);
183 }
184 return ptr;
185 }
186
187 char * WINWRAPPER_PREFIX(strdup) (const char * s)
188 {
189 char * newString = nullptr;
190 if (s != nullptr) {
191 auto len = strlen(s) + 1;
192 if ((newString = (char *) xxmalloc(len))) {
193 memcpy (newString, s, len);
194 }
195 }
196 return newString;
197 }
198
199 //// Exit handling.
200
201 const int MAX_EXIT_FUNCTIONS = 2048;
202 _onexit_t exitFunctions[MAX_EXIT_FUNCTIONS];
203 static int exitFunctionsRegistered = 0;
204
205 void WINWRAPPER_PREFIX(exit)(int status) {
206 executeRegisteredFunctions();
207 TerminateProcess(GetCurrentProcess(), status);
208 }
209
210 void WINWRAPPER_PREFIX(_exit)(int status) {
211 TerminateProcess(GetCurrentProcess(), status);
212 }
213
214 _onexit_t WINWRAPPER_PREFIX(_onexit)(_onexit_t fn) {
215 if (exitFunctionsRegistered >= MAX_EXIT_FUNCTIONS) {
216 return nullptr;
217 } else {
218 exitFunctions[exitFunctionsRegistered] = fn;
219 exitFunctionsRegistered++;
220 return fn;
221 }
222 }
223
224 int WINWRAPPER_PREFIX(atexit)(void (*fn)(void)) {
225 if (WINWRAPPER_PREFIX(_onexit)((_onexit_t) fn) == nullptr) {
226 return ENOMEM;
227 } else {
228 return 0;
229 }
230 }
231
232 void WINWRAPPER_PREFIX(_cexit)() {
233 executeRegisteredFunctions();
234 }
235
236 void WINWRAPPER_PREFIX(_c_exit)() {
237 }
238
239 /// Execute all registered functions in LIFO order.
240 void executeRegisteredFunctions() {
241 for (int i = exitFunctionsRegistered; i > 0; i--) {
242 (*exitFunctions[i-1])();
243 }
244 exitFunctionsRegistered = 0;
245 }
246
247 void * WINWRAPPER_PREFIX(_calloc_dbg)(size_t num,
248 size_t size,
249 int blockType,
250 const char *filename,
251 int linenumber)
252 {
253 return WINWRAPPER_PREFIX(calloc)(num, size);
254 }
255
256 void * WINWRAPPER_PREFIX(_malloc_dbg)(size_t size,
257 int blockType,
258 const char *filename,
259 int linenumber)
260 {
261 return xxmalloc(size);
262 }
263
264 void * WINWRAPPER_PREFIX(_realloc_dbg)(void *userData,
265 size_t newSize,
266 int blockType,
267 const char *filename,
268 int linenumber)
269 {
270 return WINWRAPPER_PREFIX(realloc)(userData, newSize);
271 }
272
273 void WINWRAPPER_PREFIX(_free_dbg)(void *userData,
274 int blockType)
275 {
276 xxfree(userData);
277 }
278
279 size_t WINWRAPPER_PREFIX(_msize_dbg)(void *userData,
280 int blockType)
281 {
282 return xxmalloc_usable_size(userData);
283 }
284
285 LPVOID WINWRAPPER_PREFIX(HeapAlloc)(HANDLE hHeap,
286 DWORD dwFlags,
287 SIZE_T dwBytes)
288 {
289 if (hHeap == nullptr) {
290 return nullptr;
291 }
292 if (dwFlags & HEAP_ZERO_MEMORY) {
293 return WINWRAPPER_PREFIX(calloc)(1, dwBytes);
294 } else {
295 return xxmalloc(dwBytes);
296 }
297 }
298
299 SIZE_T WINAPI WINWRAPPER_PREFIX(HeapCompact)(HANDLE hHeap,
300 DWORD dwFlags)
301 {
302 // Stub: 4GB malloc should be enough for anyone :).
303 return (1UL << 31);
304 }
305
306 HANDLE WINAPI WINWRAPPER_PREFIX(HeapCreate)(DWORD flOptions,
307 SIZE_T dwInitialSize,
308 SIZE_T dwMaximumSize)
309 {
310 // Ignore all options and just return a bogus (non-null) handle.
311 return (HANDLE) 0x1;
312 }
313
314 BOOL WINAPI WINWRAPPER_PREFIX(HeapDestroy)(HANDLE hHeap)
315 {
316 // For now, do nothing and claim we destroyed the heap.
317 // NOTE: this potentially leaks memory if the user is creating
318 // and destroying heaps rather than explicitly freeing objects.
319 return TRUE;
320 }
321
322 BOOL WINWRAPPER_PREFIX(HeapFree)(HANDLE hHeap,
323 DWORD dwFlags,
324 LPVOID lpMem)
325 {
326 xxfree(lpMem);
327 return true;
328 }
329
330 LPVOID WINAPI WINWRAPPER_PREFIX(HeapReAlloc)(HANDLE hHeap,
331 DWORD dwFlags,
332 LPVOID lpMem,
333 SIZE_T dwBytes)
334 {
335 // Immediately fail if we are asked to realloc in place (since we can't guarantee it).
336 if (dwFlags & HEAP_REALLOC_IN_PLACE_ONLY) {
337 return nullptr;
338 }
339 // Use _recalloc to handle requests with HEAP_ZERO_MEMORY.
340 if (dwFlags & HEAP_ZERO_MEMORY) {
341 return WINWRAPPER_PREFIX(_recalloc)(lpMem, 1, dwBytes);
342 }
343 return WINWRAPPER_PREFIX(realloc)(lpMem, dwBytes);
344 }
345
346 BOOL WINAPI WINWRAPPER_PREFIX(HeapValidate)(HANDLE hHeap,
347 DWORD dwFlags,
348 LPCVOID lpMem)
349 {
350 // A stub that says the heap is fine.
351 return TRUE;
352 }
353
354 SIZE_T WINAPI WINWRAPPER_PREFIX(HeapSize)(HANDLE hHeap,
355 DWORD dwFlags,
356 LPCVOID lpMem)
357 {
358 return xxmalloc_usable_size((void *) lpMem);
359 }
360
361 BOOL WINAPI WINWRAPPER_PREFIX(HeapWalk)(HANDLE hHeap,
362 LPPROCESS_HEAP_ENTRY lpEntry)
363 {
364 // A stub that prevents actually walking the heap.
365 return FALSE;
366 }
367
368 PVOID WINWRAPPER_PREFIX(RtlAllocateHeap)(PVOID HeapHandle,
369 ULONG Flags,
370 SIZE_T Size)
371 {
372 DWORD fl = (DWORD) Flags;
373 return (PVOID) WINWRAPPER_PREFIX(HeapAlloc)(HeapHandle, fl, Size);
374 }
375
376 ULONG
377 WINWRAPPER_PREFIX(RtlSizeHeap)(PVOID HeapHandle,
378 ULONG Flags,
379 PVOID MemoryPointer )
380 {
381 return xxmalloc_usable_size(MemoryPointer);
382 }
383
384 PVOID WINWRAPPER_PREFIX(RtlCreateHeap)(ULONG Flags,
385 PVOID HeapBase,
386 SIZE_T ReserveSize,
387 SIZE_T CommitSize,
388 PVOID Lock,
389 PVOID /* PRTL_HEAP_PARAMETERS */ Parameters)
390 {
391 // FIX ME: right now, it's just a bogus number.
392 return (PVOID) 0x1;
393 }
394
395 BOOLEAN WINWRAPPER_PREFIX(RtlFreeHeap)(PVOID HeapHandle,
396 ULONG Flags,
397 PVOID HeapBase)
398 {
399 xxfree(HeapBase);
400 return TRUE;
401 }
402
403 PVOID WINWRAPPER_PREFIX(RtlDestroyHeap)(PVOID HeapHandle)
404 {
405 return nullptr;
406 }
407
408
409 }
410
411
412 /* ------------------------------------------------------------------------ */
413
414 #define INTERPOSE(x) {#x, (FARPROC) winwrapper_##x, false, 0}
415 #define INTERPOSE2(x,y) {x, (FARPROC) y, false, 0}
416
417 static Patch rls_patches[] =
418 {
419 // operator new, new[], delete, delete[].
420
421 // _WIN64
422
423 INTERPOSE2("??2@YAPEAX_K@Z", xxmalloc),
424 INTERPOSE2("??_U@YAPEAX_K@Z", xxmalloc),
425 INTERPOSE2("??3@YAXPEAX@Z", xxfree),
426 INTERPOSE2("??_V@YAXPEAX@Z", xxfree),
427
428 // non _WIN64
429
430 {"??2@YAPAXI@Z", (FARPROC) xxmalloc, false, 0},
431 {"??_U@YAPAXI@Z", (FARPROC) xxmalloc, false, 0},
432 {"??3@YAXPAX@Z", (FARPROC) xxfree, false, 0},
433 {"??_V@YAXPAX@Z", (FARPROC) xxfree, false, 0},
434
435 // Debug versions.
436
437 INTERPOSE(_calloc_dbg),
438 INTERPOSE(_expand_dbg),
439 INTERPOSE(_free_dbg),
440 INTERPOSE(_malloc_dbg),
441 INTERPOSE(_msize_dbg),
442 INTERPOSE(_realloc_dbg),
443
444 // the nothrow variants new, new[], delete, delete[]
445
446 {"??2@YAPAXIABUnothrow_t@std@@@Z", (FARPROC) xxmalloc, false, 0},
447 {"??_U@YAPAXIABUnothrow_t@std@@@Z", (FARPROC) xxmalloc, false, 0},
448 {"??3@YAXPAXABUnothrow_t@std@@@Z", (FARPROC) xxfree, false, 0},
449 {"??_V@YAXPAXABUnothrow_t@std@@@Z", (FARPROC) xxfree, false, 0},
450
451 // Other malloc API friends.
452
453 {"_msize", (FARPROC) xxmalloc_usable_size, false, 0},
454 INTERPOSE(calloc),
455 {"_calloc_base",(FARPROC) WINWRAPPER_PREFIX(calloc),false, 0},
456 {"_calloc_crt",(FARPROC) WINWRAPPER_PREFIX(calloc), false, 0},
457 {"_calloc_impl",(FARPROC) WINWRAPPER_PREFIX(calloc), false, 0},
458 INTERPOSE(_expand),
459 INTERPOSE2("malloc", xxmalloc),
460 INTERPOSE2("_malloc_base", xxmalloc),
461 INTERPOSE2("_malloc_crt", xxmalloc),
462 INTERPOSE2("_malloc_impl", xxmalloc),
463 INTERPOSE(realloc),
464 {"_realloc_base",(FARPROC) WINWRAPPER_PREFIX(realloc),false, 0},
465 {"_realloc_crt",(FARPROC) WINWRAPPER_PREFIX(realloc),false, 0},
466 {"_realloc_impl",(FARPROC) WINWRAPPER_PREFIX(realloc),false, 0},
467 INTERPOSE2("free", xxfree),
468 INTERPOSE2("_free_base", xxfree),
469 INTERPOSE2("_free_crt", xxfree),
470 INTERPOSE2("_free_impl", xxfree),
471 INTERPOSE(_recalloc),
472 {"_recalloc_base", (FARPROC) WINWRAPPER_PREFIX(_recalloc),false, 0},
473 {"_recalloc_crt", (FARPROC) WINWRAPPER_PREFIX(_recalloc),false, 0},
474 {"_recalloc_impl", (FARPROC) WINWRAPPER_PREFIX(_recalloc),false, 0},
475
476 #if 1
477 INTERPOSE(exit),
478 INTERPOSE(_exit),
479 INTERPOSE(_onexit),
480 INTERPOSE(atexit),
481 INTERPOSE(_cexit),
482 INTERPOSE(_c_exit),
483 #endif
484
485 INTERPOSE(strdup)
486
487 #if 1
488 // RTL Heap API
489
490 ,{"RtlAllocateHeap", (FARPROC) WINWRAPPER_PREFIX(RtlAllocateHeap), false, 0},
491 // {"RtlCreateHeap", (FARPROC) WINWRAPPER_PREFIX(RtlCreateHeap), false, 0},
492 // {"RtlDestroyHeap", (FARPROC) WINWRAPPER_PREFIX(RtlDestroyHeap), false, 0},
493 {"RtlFreeHeap", (FARPROC) WINWRAPPER_PREFIX(RtlFreeHeap), false, 0},
494 {"RtlSizeHeap", (FARPROC) WINWRAPPER_PREFIX(RtlSizeHeap), false, 0}
495 #endif
496
497 #if 1
498 // Windows Heap API
499
500 ,{"HeapAlloc", (FARPROC) WINWRAPPER_PREFIX(HeapAlloc),false, 0},
501 {"HeapCompact", (FARPROC) WINWRAPPER_PREFIX(HeapCompact),false, 0},
502 // {"HeapCreate", (FARPROC) WINWRAPPER_PREFIX(HeapWalk),false, 0},
503 // {"HeapDestroy", (FARPROC) WINWRAPPER_PREFIX(HeapWalk),false, 0},
504 {"HeapFree", (FARPROC) WINWRAPPER_PREFIX(HeapFree),false, 0},
505 // HeapLock
506 // HeapQueryInformation
507 {"HeapReAlloc", (FARPROC) WINWRAPPER_PREFIX(HeapReAlloc),false, 0},
508 // HeapSetInformation
509 {"HeapSize", (FARPROC) WINWRAPPER_PREFIX(HeapSize),false, 0},
510 // HeapUnlock
511 {"HeapValidate", (FARPROC) WINWRAPPER_PREFIX(HeapValidate),false, 0},
512 {"HeapWalk", (FARPROC) WINWRAPPER_PREFIX(HeapWalk),false, 0}
513 #endif
514
515 };
516
517
518
519 static void PatchIt (Patch *patch)
520 {
521 // Change rights on CRT Library module to execute/read/write.
522
523 MEMORY_BASIC_INFORMATION mbi_thunk;
524 VirtualQuery((void*)patch->original, &mbi_thunk,
525 sizeof(MEMORY_BASIC_INFORMATION));
526 VirtualProtect(mbi_thunk.BaseAddress, mbi_thunk.RegionSize,
527 PAGE_EXECUTE_READWRITE, &mbi_thunk.Protect);
528
529 // Patch CRT library original routine:
530 // save original code bytes for exit restoration
531 // write jmp <patch_routine> (at least 5 bytes long) to original.
532
533 memcpy (patch->codebytes, patch->original, sizeof(X86Jump));
534 auto * patchloc = (unsigned char*)patch->original;
535 new (patchloc) X86Jump (patch->replacement);
536
537 // Reset CRT library code to original page protection.
538
539 VirtualProtect(mbi_thunk.BaseAddress, mbi_thunk.RegionSize,
540 mbi_thunk.Protect, &mbi_thunk.Protect);
541
542 }
543
544 static void UnpatchIt (Patch *patch)
545 {
546 if (patch->patched) {
547
548 // Change rights on CRT Library module to execute/read/write.
549
550 MEMORY_BASIC_INFORMATION mbi_thunk;
551 VirtualQuery((void*)patch->original, &mbi_thunk,
552 sizeof(MEMORY_BASIC_INFORMATION));
553 VirtualProtect(mbi_thunk.BaseAddress, mbi_thunk.RegionSize,
554 PAGE_EXECUTE_READWRITE, &mbi_thunk.Protect);
555
556 // Restore original CRT routine.
557
558 memcpy (patch->original, patch->codebytes, sizeof(X86Jump));
559
560 // Reset CRT library code to original page protection.
561
562 VirtualProtect(mbi_thunk.BaseAddress, mbi_thunk.RegionSize,
563 mbi_thunk.Protect, &mbi_thunk.Protect);
564 }
565 }
566
567
568 static bool PatchMe()
569 {
570 bool patchedIn = false;
571
572 // We walk through all modules loaded by the process and patch the relevant entry points.
573 auto pid = GetCurrentProcessId();
574 auto hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
575 PROCESS_VM_READ,
576 FALSE, pid);
577 DWORD cbNeeded;
578 const auto MaxModules = 8192;
579 HMODULE hMods[MaxModules];
580 if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) {
581 for (auto i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) {
582 TCHAR szModName[MAX_PATH] = { 0 };
583 LPTSTR pszBuffer = szModName;
584 if (GetModuleFileName(hMods[i], pszBuffer,
585 sizeof(szModName) / sizeof(TCHAR)))
586 {
587
588 // Only patch CRT libraries.
589 if (!(_tcsstr(pszBuffer, _T("CRT")) ||
590 _tcsstr(pszBuffer, _T("crt")))) {
591 continue;
592 }
593
594 HMODULE RlsCRTLibrary = GetModuleHandle(pszBuffer);
595 // Patch all relevant release CRT Library entry points.
596 if (RlsCRTLibrary) {
597 for (auto j = 0; j < sizeof(rls_patches) / sizeof(*rls_patches); j++) {
598 if (rls_patches[j].original = GetProcAddress(RlsCRTLibrary, rls_patches[j].import)) {
599 // Got one: patch it.
600 PatchIt(&rls_patches[j]);
601 rls_patches[j].patched = true;
602 patchedIn = true;
603 }
604 }
605 }
606 }
607 }
608 }
609 return patchedIn;
610 }
611
612 static void UnpatchMe()
613 {
614 for (int i = 0; i < sizeof(rls_patches) / sizeof(*rls_patches); i++) {
615 UnpatchIt(&rls_patches[i]);
616 }
617 }
618