This repository has been archived by the owner on Mar 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 76
/
winpatcher.c
1107 lines (1038 loc) · 40.5 KB
/
winpatcher.c
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Generic Windows Process Patcher. Intended for patching nedmalloc in to
replace the MSVCRT allocator but could be used for anything.
(C) 2009-2010 Niall Douglas
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/*#define _DEBUG
#define USE_DEBUGGER_OUTPUT
#pragma optimize("g", off)*/
#ifdef NEDMALLOC_DLL_EXPORTS /* Building patcher with nedmalloc */
#include "nedmalloc.h"
extern void *(*sysmalloc)(size_t);
extern void *(*syscalloc)(size_t, size_t);
extern void *(*sysrealloc)(void *, size_t);
extern void (*sysfree)(void *);
extern size_t (*sysblksize)(void *);
#else /* Else building patcher with dlmalloc */
#ifndef NEDMALLOCEXTSPEC
#if defined(NEDMALLOC_DLL_EXPORTS) || defined(USERMODEPAGEALLOCATOR_DLL_EXPORTS)
#ifdef WIN32
#define NEDMALLOCEXTSPEC extern __declspec(dllexport)
#elif defined(__GNUC__)
#define NEDMALLOCEXTSPEC extern __attribute__ ((visibility("default")))
#endif
#ifndef ENABLE_TOLERANT_NEDMALLOC
#define ENABLE_TOLERANT_NEDMALLOC 1
#endif
#else
#define NEDMALLOCEXTSPEC extern
#endif
#endif
#define nedpmalloc(a, v) HeapAlloc(GetProcessHeap(), 0, (v))
#define nedpcalloc(a, v, s) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (v)*(s))
#define nedprealloc(a, p, v) HeapReAlloc(GetProcessHeap(), 0, (p), (v))
#define nedpfree(a, p) HeapFree(GetProcessHeap(), 0, (p))
#endif
#include "embedded_printf.h"
#include <stdlib.h>
#include <assert.h>
#ifdef WIN32
#include <tchar.h>
#include <process.h>
#include <malloc.h>
#ifdef USERMODEPAGEALLOCATOR_DLL_EXPORTS
#define ENABLE_USERMODEPAGEALLOCATOR 1
#define THROWSPEC
#define ONLY_MSPACES 1
#define MMAP_CLEARS 0
#include "malloc.c.h"
#include "usermodepageallocator.c"
#else
#define WIN32_LEAN_AND_MEAN 1
#define _WIN32_WINNT 0x0501 /* Minimum of Windows XP required */
#include <windows.h>
#endif
#include "Dbghelp.h"
#pragma comment(lib, "dbghelp.lib")
#include <psapi.h>
#include "nedtries/uthash/src/uthash.h"
#include "winpatcher_errorh.h"
#pragma warning(disable: 4100) /* Unreferenced formal parameter */
#pragma warning(disable: 4127) /* conditional expression is constant */
#pragma warning(disable: 4706) /* Assignment within conditional expression */
/* TODO list:
* Patch GetProcAddress to return the patched address
*/
/* Set uthash to use nedmalloc */
#undef uthash_malloc
#undef uthash_free
#define uthash_malloc(sz) nedpmalloc(0, sz)
#define uthash_free(ptr, sz) nedpfree(0, ptr)
#define HASH_FIND_PTR(head,findptr,out) \
HASH_FIND(hh,head,findptr,sizeof(void *),out)
#define HASH_ADD_PTR(head,ptrfield,add) \
HASH_ADD(hh,head,ptrfield,sizeof(void *),add)
#if defined(__cplusplus)
#if !defined(NO_WINPATCHER_NAMESPACE)
namespace winpatcher {
#else
extern "C" {
#endif
#endif
/* If you want to learn lots more about the vagueries of Win32 PE dynamic linking,
see http://msdn.microsoft.com/en-us/magazine/cc301808.aspx. Excerpt from that:
The anchor of the imports data is the IMAGE_IMPORT_DESCRIPTOR structure. The DataDirectory
entry for imports points to an array of these structures. There's one IMAGE_IMPORT_DESCRIPTOR
for each imported executable. The end of the IMAGE_IMPORT_DESCRIPTOR array is indicated by an
entry with fields all set to 0. Figure 5 shows the contents of an IMAGE_IMPORT_DESCRIPTOR.
Each IMAGE_IMPORT_DESCRIPTOR typically points to two essentially identical arrays. These
arrays have been called by several names, but the two most common names are the Import Address
Table (IAT) and the Import Name Table (INT).
Both arrays have elements of type IMAGE_THUNK_DATA, which is a pointer-sized union. Each
IMAGE_THUNK_DATA element corresponds to one imported function from the executable. The ends of
both arrays are indicated by an IMAGE_THUNK_DATA element with a value of zero. The
IMAGE_THUNK_DATA union is a DWORD with these interpretations:
DWORD Function; // Memory address of the imported function
DWORD Ordinal; // Ordinal value of imported API
DWORD AddressOfData; // RVA to an IMAGE_IMPORT_BY_NAME with
// the imported API name
DWORD ForwarderString;// RVA to a forwarder string
The IMAGE_THUNK_DATA structures within the IAT lead a dual-purpose life. In the executable
file, they contain either the ordinal of the imported API or an RVA to an IMAGE_IMPORT_BY_NAME
structure. The IMAGE_IMPORT_BY_NAME structure is just a WORD, followed by a string naming the
imported API. The WORD value is a "hint" to the loader as to what the ordinal of the imported
API might be. When the loader brings in the executable, it overwrites each IAT entry with the
actual address of the imported function. This a key point to understand before proceeding. I
highly recommend reading Russell Osterlund's article in this issue which describes the steps
that the Windows loader takes.
Before the executable is loaded, is there a way you can tell if an IMAGE_THUNK_DATA structure
contains an import ordinal, as opposed to an RVA to an IMAGE_IMPORT_BY_NAME structure? The key
is the high bit of the IMAGE_THUNK_DATA value. If set, the bottom 31 bits (or 63 bits for a 64-bit
executable) is treated as an ordinal value. If the high bit isn't set, the IMAGE_THUNK_ DATA value
is an RVA to the IMAGE_IMPORT_BY_NAME.
The other array, the INT, is essentially identical to the IAT. It's also an array of
IMAGE_THUNK_DATA structures. The key difference is that the INT isn't overwritten by the loader
when brought into memory. Why have two parallel arrays for each set of APIs imported from a DLL?
The answer is in a concept called binding. When the binding process rewrites the IAT in the file
(I'll describe this process later), some way of getting the original information needs to remain.
The INT, which is a duplicate copy of the information, is just the ticket.
*/
typedef struct ModuleListItem_t
{
const char *into;
HMODULE intoAddr;
const char *from; /* zero means this module */
} ModuleListItem;
typedef struct SymbolListItem_t
{
struct Replace_t
{
const char *name; /* Replace this symbol */
HMODULE moduleBase; /* In this DLL */
char moduleName[_MAX_PATH+2]; /* Where the DLL is named this */
PROC addr; /* Where the symbol has this address in the DLL (=0 for use GetProcAddress()) */
} replace;
ModuleListItem *modules; /* zero means wherever the replace symbol lives */
struct With_t
{
const char *name;
PROC addr;
} with;
} SymbolListItem;
/* Little helper function to return the module base (a HMODULE)
given some address within that module. Assumes that the NT kernel
maps an entire module at once with one TLB entry */
static HMODULE ModuleFromAddress(void *addr) THROWSPEC
{
MEMORY_BASIC_INFORMATION mbi={0};
return ((VirtualQuery(addr, &mbi, sizeof(mbi)) != 0) ? (HMODULE) mbi.AllocationBase : NULL);
}
/* Little helper function to deindirect the PE DLL linking mechanism
This is architecture dependent */
static PROC DeindirectAddress(PROC _addr) THROWSPEC
{
unsigned char *addr=(unsigned char *)((size_t) _addr);
#if defined(_M_IX86)
if(0xe9==addr[0])
{ /* We're seeing a jmp rel32 inserted under Edit & Continue */
unsigned int offset=*(unsigned int *)(addr+1);
addr+=offset+5;
}
if(0xff==addr[0] && 0x25==addr[1])
{ /* This is a jmp ptr, so dword[2:6] is where to load the address from */
addr=(unsigned char *)(**(unsigned int **)(addr+2));
}
#elif defined(_M_X64)
if(0xff==addr[0] && 0x25==addr[1])
{ /* This is a jmp qword ptr, so dword[2:6] is the offset to where to load the address from */
unsigned int offset=*(unsigned int *)(addr+2);
addr+=offset+6;
addr=(unsigned char *)(*(size_t *)(addr));
}
#endif
return (PROC)(size_t) addr;
}
/* Little helper function for sending stuff to the debugger output
seeing as fprintf et al are completely unavailable to us */
#if defined(_DEBUG) && defined(USE_DEBUGGER_OUTPUT)
#include "embedded_printf.c"
#endif
static void putc_(void *p, char c) THROWSPEC { *(*((char **)p))++ = c; }
static HANDLE debugfile=INVALID_HANDLE_VALUE;
extern void DebugPrint(const char *fmt, ...) THROWSPEC
{
#if defined(_DEBUG) && defined(USE_DEBUGGER_OUTPUT)
char buffer[16384];
char *s=buffer;
HANDLE stdouth=GetStdHandle(STD_OUTPUT_HANDLE);
DWORD len;
DWORD written=0;
va_list va;
va_start(va,fmt);
tfp_format(&s,putc_,fmt,va);
putc_(&s,0);
va_end(va);
len=(DWORD)(strchr(buffer, 0)-buffer);
OutputDebugStringA(buffer);
if(stdouth && stdouth!=INVALID_HANDLE_VALUE)
WriteFile(stdouth, buffer, len, &written, NULL);
#if 1 /* Enable this if you want it to write the log to C:\nedmalloc.log */
if(INVALID_HANDLE_VALUE==debugfile)
{
debugfile=CreateFile(__T("C:\\nedmalloc.log"), GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ,
NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
}
if(INVALID_HANDLE_VALUE!=debugfile)
WriteFile(debugfile, buffer, len, &written, NULL);
#endif
#endif
}
/* Traps win32 structured exceptions and converts to Status */
static int ExceptionToStatus(Status *ret, unsigned int code, EXCEPTION_POINTERS *ep)
{
#if defined(_DEBUG)
DebugPrint("Winpatcher: Win32 Exception %u at %p\n", code, ep->ExceptionRecord ? ep->ExceptionRecord->ExceptionAddress : 0);
#endif
ret->code=-(int)code;
_stprintf_s(ret->msg, sizeof(ret->msg)/sizeof(TCHAR), __T("Win32 Exception %u at %p"), code, ep->ExceptionRecord ? ep->ExceptionRecord->ExceptionAddress : 0);
return EXCEPTION_EXECUTE_HANDLER;
}
/* Our own implementation of DbgHelp's ImageDirectoryEntryToData()
DbgHelp unfortunately calls malloc() during its DllMain which is a
big no-no in our situation */
PVOID MyImageDirectoryEntryToData(PVOID Base, BOOLEAN MappedAsImage, USHORT DirectoryEntry, PULONG Size )
{
IMAGE_DOS_HEADER *dosheader=(IMAGE_DOS_HEADER *) Base;
IMAGE_NT_HEADERS *peheader=0;
void *ret=0;
size_t offset=0;
if(Size) *Size=0;
if(dosheader->e_magic==*(USHORT *)"MZ")
peheader=(IMAGE_NT_HEADERS *)((char *)dosheader+dosheader->e_lfanew);
else
peheader=(IMAGE_NT_HEADERS *) dosheader;
if(peheader->Signature!=IMAGE_NT_SIGNATURE)
{
SetLastError(ERROR_INVALID_DATA);
return 0;
}
offset=peheader->OptionalHeader.DataDirectory[DirectoryEntry].VirtualAddress;
if(offset)
{
ret=(void *)((char *) Base+offset);
if(Size) *Size=peheader->OptionalHeader.DataDirectory[DirectoryEntry].Size;
}
return ret;
}
/* Modifies the import table of a loaded module
Returns: The number of entries modified
moduleBase: Where the PE module is living in memory
importModuleName: Name of the PE module whose exports we wish to modify
fnToReplace: Address of function to replace
fnNew: Replacement address
*/
static Status ModifyModuleImportTableForI(HMODULE moduleBase, const char *importModuleName, SymbolListItem *sli, int patchin) THROWSPEC
{
Status ret = { SUCCESS };
ULONG size;
PIMAGE_THUNK_DATA thunk = 0;
PIMAGE_IMPORT_DESCRIPTOR desc = 0;
PROC replaceaddr = patchin ? sli->replace.addr : sli->with.addr, withaddr = patchin ? sli->with.addr : sli->replace.addr;
int replaced = 0;
/* Find the import table of the module loaded at hmodCaller */
desc = (PIMAGE_IMPORT_DESCRIPTOR) MyImageDirectoryEntryToData(moduleBase, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &size);
if (!desc)
return MKSTATUS(ret, SUCCESS); /* This module has no import section */
/* Find all import descriptors containing references to the module we want. */
for (; desc->Name; desc++) {
PSTR modname = (PSTR)((PBYTE) moduleBase + desc->Name);
int modnamecmp = lstrcmpiA(modname, importModuleName);
/*if (modnamecmp>0)
break;*/
if (0==modnamecmp) {
/* Get the import address table (IAT) for the functions imported from our wanted module */
thunk = (PIMAGE_THUNK_DATA)((PBYTE) moduleBase + desc->FirstThunk);
/* Find and replace current function address with new function address */
for (; thunk->u1.Function; thunk++) {
/* Get the address of the function address */
PROC *fn = (PROC *) &thunk->u1.Function;
/* Is this the function we're looking for? */
BOOL found = (*fn == replaceaddr);
if (found) {
/* The addresses match; change the import section address. */
MEMORY_BASIC_INFORMATION mbi={0};
#if defined(_DEBUG)
{
char moduleBaseName[_MAX_PATH+2];
GetModuleBaseNameA(GetCurrentProcess(), moduleBase, moduleBaseName, sizeof(moduleBaseName)-1);
DebugPrint("Winpatcher: Replacing function pointer %p (%s:%s) with %p (%s) at %p in module %p (%s)\n",
*fn, importModuleName, sli->replace.name, withaddr, sli->with.name, fn, moduleBase, moduleBaseName);
}
#endif
/*if(!WriteProcessMemory(GetCurrentProcess(), fn, &withaddr, sizeof(withaddr), NULL))
return MKSTATUSWIN(ret);*/
if(!VirtualQuery(fn, &mbi, sizeof(mbi)))
return MKSTATUSWIN(ret);
if(!(mbi.Protect & PAGE_EXECUTE_READWRITE))
{
#if defined(_DEBUG)
DebugPrint("Winpatcher: Setting PAGE_WRITECOPY on module %p, region %p length %u\n", moduleBase, mbi.BaseAddress, mbi.RegionSize);
#endif
if(!VirtualProtect(mbi.BaseAddress, mbi.RegionSize, PAGE_EXECUTE_WRITECOPY, &mbi.Protect))
return MKSTATUSWIN(ret);
}
*fn=withaddr;
FlushInstructionCache(GetCurrentProcess(), mbi.BaseAddress, mbi.RegionSize);
if(!VirtualProtect(mbi.BaseAddress, mbi.RegionSize, PAGE_EXECUTE_READ, &mbi.Protect))
return MKSTATUSWIN(ret);
replaced++;
}
}
}
}
return MKSTATUS(ret, SUCCESS+replaced);
}
/* Modifies all symbols in the import table of a loaded module
Returns: The number of entries modified
moduleBase: The PE module to patch
*/
static Status ModifyModuleImportTableFor(HMODULE moduleBase, SymbolListItem *sli, int patchin, int *usingreleaseMSVCRT, int *usingdebugMSVCRT) THROWSPEC
{
Status ret={SUCCESS};
int count=0;
for(; sli->replace.name; sli++, count++)
{
if(sli->modules)
{
ModuleListItem *module;
int moduleidx=0;
for(module=sli->modules; module->into; module++, moduleidx++)
{
if(!module->intoAddr && (HMODULE)(size_t)-1!=module->intoAddr)
{
if(!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module->into, &module->intoAddr))
module->intoAddr=(HMODULE)(size_t)-1;
}
if((HMODULE)(size_t)-1==module->intoAddr)
{ /* Not loaded so move to next one */
ret=MKSTATUSWIN(ret);
continue;
}
sli->replace.moduleBase=module->intoAddr;
if(!(sli->replace.addr=GetProcAddress(sli->replace.moduleBase, sli->replace.name)))
return MKSTATUS(ret, SUCCESS); /* Some symbols may not always be found */
if(!module->from)
{
if(!sli->with.addr)
abort(); /* If we are not specifying the module it must be a local symbol */
}
else
{
HMODULE withBase=0;
if(!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module->from, &withBase))
return MKSTATUSWIN(ret);
if(!(sli->with.addr=GetProcAddress(withBase, sli->with.name)))
return MKSTATUSWIN(ret);
}
if((ret=ModifyModuleImportTableForI(moduleBase, module->into, sli, patchin), ret.code)<0)
return ret;
if(ret.code && !strncmp(module->into, "MSVCR", 5))
{
if(usingdebugMSVCRT && (moduleidx & 1)) (*usingdebugMSVCRT)++;
else (*usingreleaseMSVCRT)++;
}
}
}
else
{
if(!sli->replace.moduleBase)
{
if(!sli->replace.addr || !sli->with.addr)
abort(); /* If you are not specifying modules you must specify symbols */
sli->replace.addr=DeindirectAddress(sli->replace.addr);
sli->replace.moduleBase=ModuleFromAddress((void *)(size_t) sli->replace.addr);
if(!GetModuleBaseNameA(GetCurrentProcess(), sli->replace.moduleBase, sli->replace.moduleName, sizeof(sli->replace.moduleName)-1))
return MKSTATUSWIN(ret);
}
if((ret=ModifyModuleImportTableForI(moduleBase, sli->replace.moduleName, sli, patchin), ret.code)<0)
return ret;
}
}
return MKSTATUS(ret, count);
}
/* ARA are suffering from slow process init times due to the patcher. Let's see what we can
do through the magic of caching! */
static HMODULE MyModuleBase, skipModules[3], lastModuleList[4096];
static DWORD lastModuleListLen;
typedef struct PatchedModule_t
{
HMODULE moduleBaseAddr;
char moduleBaseName[_MAX_PATH+2];
UT_hash_handle hh;
} PatchedModule;
static PatchedModule *patchedmodules;
/* Modifies all symbols in all loaded modules
Returns: The number of entries modified, plus how many are using release vs. debug versions of MSVCRT
*/
NEDMALLOCEXTSPEC Status WinPatcher(SymbolListItem *symbollist, int patchin, int *usingreleaseMSVCRT, int *usingdebugMSVCRT) THROWSPEC;
Status WinPatcher(SymbolListItem *symbollist, int patchin, int *usingreleaseMSVCRT, int *usingdebugMSVCRT) THROWSPEC
{
int count=0;
Status ret={SUCCESS};
__try
{
HMODULE *module=0, modulelist[4096];
DWORD modulelistlen=sizeof(modulelist), modulelistlenneeded=0;
if(!skipModules[0])
{
assert(MyModuleBase);
skipModules[0]=ModuleFromAddress((void *)(size_t) StackWalk64); /* Not DbgHelp.dll as it calls malloc during its own operation which causes recursion */
}
/* This is not a fast call, but sadly there is no choice */
if(!EnumProcessModules(GetCurrentProcess(), modulelist, modulelistlen, &modulelistlenneeded))
return MKSTATUSWIN(ret);
if(!patchin || lastModuleListLen!=modulelistlenneeded || memcmp(lastModuleList, modulelist, modulelistlenneeded))
{
for(module=modulelist; module<modulelist+(modulelistlenneeded/sizeof(HMODULE)); module++)
{
PatchedModule *pm=0;
HMODULE *m;
HASH_FIND_PTR(patchedmodules, module, pm);
if(pm)
{ /* Already patched */
assert(pm->moduleBaseAddr==*module);
#if defined(_DEBUG)
DebugPrint("Winpatcher: Module %p (%s) already patched\n", pm->moduleBaseAddr, pm->moduleBaseName, patchin ? "patch" : "depatch");
#endif
if(patchin)
{
count+=SUCCESS;
continue;
}
}
else
{
if(!(pm=nedpcalloc(0, 1, sizeof(PatchedModule))))
return MKSTATUS(ret, ERROR);
pm->moduleBaseAddr=*module;
#if defined(_DEBUG)
/* This is an extremely slow call, so absolutely avoid if possible */
GetModuleBaseNameA(GetCurrentProcess(), pm->moduleBaseAddr, pm->moduleBaseName, sizeof(pm->moduleBaseName)-1);
#endif
HASH_ADD_PTR(patchedmodules, moduleBaseAddr, pm);
}
if(*module==MyModuleBase || *module==skipModules[0])
continue; /* Not us or we'd break our patch table */
#if defined(_DEBUG)
DebugPrint("Winpatcher: Scanning module %p (%s) for things to %s ...\n", pm->moduleBaseAddr, pm->moduleBaseName, patchin ? "patch" : "depatch");
#endif
if((ret=ModifyModuleImportTableFor(*module, symbollist, patchin, usingreleaseMSVCRT, usingdebugMSVCRT), ret.code)<0)
return ret;
count+=ret.code;
}
memcpy(lastModuleList, modulelist, modulelistlenneeded);
lastModuleListLen=modulelistlenneeded;
}
else
{
#if defined(_DEBUG)
DebugPrint("Winpatcher: Loaded module list hasn't changed, so exiting\n");
#endif
}
}
__except(ExceptionToStatus(&ret, GetExceptionCode(), GetExceptionInformation()))
{
return ret;
}
return MKSTATUS(ret, count);
}
NEDMALLOCEXTSPEC int PatchInNedmallocDLL(void) THROWSPEC;
NEDMALLOCEXTSPEC int DepatchInNedmallocDLL(void) THROWSPEC;
/* A LoadLibrary() wrapper. It's important to patch before
as well as after as one DLL load can trigger other DLL loads */
static HMODULE WINAPI LoadLibraryA_winpatcher(LPCSTR lpLibFileName)
{
HMODULE ret=0;
#ifdef REPLACE_SYSTEM_ALLOCATOR
/*if(!PatchInNedmallocDLL()) abort();*/
#endif
#if defined(_DEBUG)
DebugPrint("Winpatcher: LoadLibraryA intercepted\n");
#endif
ret=LoadLibraryA(lpLibFileName);
#ifdef REPLACE_SYSTEM_ALLOCATOR
if(!PatchInNedmallocDLL()) abort();
#endif
return ret;
}
static HMODULE WINAPI LoadLibraryW_winpatcher(LPCWSTR lpLibFileName)
{
HMODULE ret=0;
#ifdef REPLACE_SYSTEM_ALLOCATOR
/*if(!PatchInNedmallocDLL()) abort();*/
#endif
#if defined(_DEBUG)
DebugPrint("Winpatcher: LoadLibraryW intercepted\n");
#endif
ret=LoadLibraryW(lpLibFileName);
#ifdef REPLACE_SYSTEM_ALLOCATOR
if(!PatchInNedmallocDLL()) abort();
#endif
return ret;
}
#if ENABLE_USERMODEPAGEALLOCATOR
#define M2_CUSTOM_FLAGS_BEGIN (1<<16)
#define USERPAGE_TOPDOWN (M2_CUSTOM_FLAGS_BEGIN<<0)
#define USERPAGE_NOCOMMIT (M2_CUSTOM_FLAGS_BEGIN<<1)
extern int OSHavePhysicalPageSupport(void);
extern void *userpage_malloc(size_t toallocate, unsigned flags);
extern int userpage_free(void *mem, size_t size);
extern void *userpage_realloc(void *mem, size_t oldsize, size_t newsize, int flags, unsigned flags2);
extern void *userpage_commit(void *mem, size_t size);
extern int userpage_release(void *mem, size_t size);
static LPVOID WINAPI VirtualAlloc_winpatcher(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect)
{
LPVOID ret=0;
dwSize=(dwSize+4095) & ~4095;
#if defined(_DEBUG)
DebugPrint("Winpatcher: VirtualAlloc(%p, %u, %x, %x) intercepted\n", lpAddress, dwSize, flAllocationType, flProtect);
#endif
if(OSHavePhysicalPageSupport())
{
if(!lpAddress && flAllocationType&MEM_RESERVE)
{
ret=userpage_malloc(dwSize, (flAllocationType&MEM_COMMIT) ? 0 : USERPAGE_NOCOMMIT);
#if defined(_DEBUG)
DebugPrint("Winpatcher: userpage_malloc returns %p\n", ret);
if(flAllocationType&MEM_COMMIT)
{
volatile char *p, *pend=(char *) ret + dwSize;
for(p=(char *) ret; p<pend; p+=4096)
*p;
}
#endif
}
else if(lpAddress && (flAllocationType&(MEM_COMMIT|MEM_RESERVE))==(MEM_COMMIT))
{
ret=userpage_commit(lpAddress, dwSize);
#if defined(_DEBUG)
DebugPrint("Winpatcher: userpage_commit returns %p\n", ret);
#endif
}
}
if(!ret || (void *)-1==ret)
{
ret=VirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect);
#if defined(_DEBUG)
DebugPrint("Winpatcher: VirtualAlloc returns %p\n", ret);
#endif
}
return (void *)-1==ret ? 0 : ret;
}
static BOOL WINAPI VirtualFree_winpatcher(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType)
{
dwSize=(dwSize+4095) & ~4095;
#if defined(_DEBUG)
DebugPrint("Winpatcher: VirtualFree(%p, %u, %x) intercepted\n", lpAddress, dwSize, dwFreeType);
#endif
if(OSHavePhysicalPageSupport())
{
if(dwFreeType==MEM_DECOMMIT)
{
if(-1!=userpage_release(lpAddress, dwSize)) return 1;
}
else if(dwFreeType==MEM_RELEASE)
{
if(-1!=userpage_free(lpAddress, dwSize)) return 1;
}
}
return VirtualFree(lpAddress, dwSize, dwFreeType);
}
static SIZE_T WINAPI VirtualQuery_winpatcher(LPVOID lpAddress, PMEMORY_BASIC_INFORMATION lpBuffer, SIZE_T dwSize)
{
#if defined(_DEBUG)
DebugPrint("Winpatcher: VirtualQuery(%p, %p, %u) intercepted\n", lpAddress, lpBuffer, dwSize);
#endif
return VirtualQuery(lpAddress, lpBuffer, dwSize);
}
#endif /* ENABLE_USERMODEPAGEALLOCATOR */
/* The patch table: replace the specified symbols in the specified modules with the
specified replacements. Format is:
<-- what to replace --> <-- in what --> <-- replacements -->
{{ "<linker symbol>", 0, "", 0|<function addr> }, 0|<which modules>, { "<linker symbol>", <function addr> } },
If you specify <which modules> then <function addr> is overwritten with whatever
GetProcAddress() returns for <linker symbol>. On the hand, and usually much more
usefully, leaving <which modules> at zero and writing in whatever the dynamic
linker resolves for <function addr> lets the patcher look up which modules the
dynamic linker used and to patch that instead. This helps when the implementing
module is not constant, but it does require that the enclosing DLL is using the
same version as everything else in the process.
Note that not specifying modules introduces x86 or x64 dependent code and specific
assumptions about how MSVC implements the PE image spec. The only fully portable
method is to specify modules, plus specifying modules covers executables not built
using the same version of MSVCRT.
*/
static ModuleListItem modules[]={
/* NOTE: Keep these release/debug format as this is used above! */
#if 0
/* Release and Debug MSVC6 CRTs */
{ "MSVCRT.DLL", 0, 0 }, { "MSVCRTD.DLL", 0, 0 },
#endif
/* Release and Debug MSVC7.0 CRTs */
{ "MSVCR70.DLL", 0, 0 }, { "MSVCR70D.DLL", 0, 0 },
/* Release and Debug MSVC7.1 CRTs */
{ "MSVCR71.DLL", 0, 0 }, { "MSVCR71D.DLL", 0, 0 },
/* Release and Debug MSVC8 CRTs */
{ "MSVCR80.DLL", 0, 0 }, { "MSVCR80D.DLL", 0, 0 },
/* Release and Debug MSVC9 CRTs */
{ "MSVCR90.DLL", 0, 0 }, { "MSVCR90D.DLL", 0, 0 },
/* Release and Debug MSVC10 CRTs */
{ "MSVCR100.DLL", 0, 0 }, { "MSVCR100D.DLL", 0, 0 },
{ 0, 0, 0 }
};
static ModuleListItem kernelmodule[]={
{ "KERNEL32.DLL", 0, 0 },
{ 0, 0, 0 }
};
static SymbolListItem nedmallocpatchtable[]={
#ifdef NEDMALLOC_H
{ { "malloc", 0, "", 0/*(PROC) malloc */ }, modules, { "nedmalloc", (PROC) nedmalloc } },
{ { "calloc", 0, "", 0/*(PROC) calloc */ }, modules, { "nedcalloc", (PROC) nedcalloc } },
{ { "realloc", 0, "", 0/*(PROC) realloc*/ }, modules, { "nedrealloc", (PROC) nedrealloc } },
{ { "free", 0, "", 0/*(PROC) free */ }, modules, { "nedfree", (PROC) nedfree } },
{ { "_msize", 0, "", 0/*(PROC) _msize */ }, modules, { "nedblksize", (PROC) nedmemsize } },
#endif
#if 0 /* Usually it's best to leave these off */
{ { "_malloc_dbg", 0, "", 0/*(PROC) malloc */ }, modules, { "nedmalloc_dbg", (PROC) nedmalloc_dbg } },
{ { "_calloc_dbg", 0, "", 0/*(PROC) calloc */ }, modules, { "nedcalloc_dbg", (PROC) nedcalloc_dbg } },
{ { "_realloc_dbg", 0, "", 0/*(PROC) realloc*/ }, modules, { "nedrealloc_dbg", (PROC) nedrealloc_dbg } },
{ { "_free_dbg", 0, "", 0/*(PROC) free */ }, modules, { "nedfree_dbg", (PROC) nedfree_dbg } },
{ { "_msize_dbg", 0, "", 0/*(PROC) free */ }, modules, { "nedblksize_dbg", (PROC) nedblksize_dbg } },
#endif
{ { "LoadLibraryA", 0, "", 0 }, kernelmodule, { "LoadLibraryA_winpatcher", (PROC) LoadLibraryA_winpatcher } },
{ { "LoadLibraryW", 0, "", 0 }, kernelmodule, { "LoadLibraryW_winpatcher", (PROC) LoadLibraryW_winpatcher } },
#ifdef REPLACE_SYSTEM_ALLOCATOR
#if ENABLE_USERMODEPAGEALLOCATOR
{ { "VirtualAlloc", 0, "", 0 }, kernelmodule, { "VirtualAlloc_winpatcher", (PROC) VirtualAlloc_winpatcher } },
{ { "VirtualFree", 0, "", 0 }, kernelmodule, { "VirtualFree_winpatcher", (PROC) VirtualFree_winpatcher } },
{ { "VirtualQuery", 0, "", 0 }, kernelmodule, { "VirtualQuery_winpatcher", (PROC) VirtualQuery_winpatcher } },
#endif
#endif
{ { 0, 0, "", 0 }, 0, { 0, 0 } }
};
#ifdef NEDMALLOC_H
/* Thunks for nedmalloc */
static void *nedmalloc_dbg(size_t size, int type, const char *filename, int lineno) { return nedmalloc(size); }
static void *nedcalloc_dbg(size_t no, size_t size, int type, const char *filename, int lineno) { return nedcalloc(no, size); }
static void *nedrealloc_dbg(void *ptr, size_t size, int type, const char *filename, int lineno) { return nedrealloc(ptr, size); }
static void nedfree_dbg(void *ptr, int type) { nedfree(ptr); }
static size_t nedblksize_dbg(void *ptr, int type) { return nedmemsize(ptr); }
/* Here come some fun! Windows is unusual in that various DLLs loaded by processes may be
linked to any one of the MSVCRTs listed in the patch table above - which is twelve different
options. Each MSVCRT runs its own separate CRT heap and is generally incapable of handling
blocks from a MSVCRT not its own, so we need to figure out specifically which system allocator
function to call based on what is doing the call. Painful, but not much choice! */
extern HANDLE sym_myprocess;
extern VOID (WINAPI *RtlCaptureContextAddr)(PCONTEXT);
extern void DeinitSym(void) THROWSPEC;
HANDLE sym_myprocess;
VOID (WINAPI *RtlCaptureContextAddr)(PCONTEXT)=(VOID (WINAPI *)(PCONTEXT)) -1;
void DeinitSym(void) THROWSPEC
{
if(sym_myprocess)
{
SymCleanup(sym_myprocess);
CloseHandle(sym_myprocess);
sym_myprocess=0;
}
}
#pragma optimize("g", off)
static int ExceptionFilter(unsigned int code, struct _EXCEPTION_POINTERS *ep, CONTEXT *ct) THROWSPEC
{
*ct=*ep->ContextRecord;
return EXCEPTION_EXECUTE_HANDLER;
}
static DWORD64 __stdcall GetModBase(HANDLE hProcess, DWORD64 dwAddr) THROWSPEC
{
DWORD64 modulebase;
// Try to get the module base if already loaded, otherwise load the module
modulebase=SymGetModuleBase64(hProcess, dwAddr);
if(modulebase)
return modulebase;
else
{
MEMORY_BASIC_INFORMATION stMBI ;
if ( 0 != VirtualQueryEx ( hProcess, (LPCVOID)(size_t)dwAddr, &stMBI, sizeof(stMBI)))
{
int n;
DWORD dwPathLen=0, dwNameLen=0 ;
TCHAR szFile[ MAX_PATH ], szModuleName[ MAX_PATH ] ;
MODULEINFO mi={0};
dwPathLen = GetModuleFileName ( (HMODULE) stMBI.AllocationBase , szFile, MAX_PATH );
dwNameLen = GetModuleBaseName (hProcess, (HMODULE) stMBI.AllocationBase , szModuleName, MAX_PATH );
for(n=dwNameLen; n>0; n--)
{
if(szModuleName[n]=='.')
{
szModuleName[n]=0;
break;
}
}
if(!GetModuleInformation(hProcess, (HMODULE) stMBI.AllocationBase, &mi, sizeof(mi)))
{
//fxmessage("WARNING: GetModuleInformation() returned error code %d\n", GetLastError());
}
if(!SymLoadModule64 ( hProcess, NULL, (PSTR)( (dwPathLen) ? szFile : 0), (PSTR)( (dwNameLen) ? szModuleName : 0),
(DWORD64) mi.lpBaseOfDll, mi.SizeOfImage))
{
//fxmessage("WARNING: SymLoadModule64() returned error code %d\n", GetLastError());
}
//fxmessage("%s, %p, %x, %x\n", szFile, mi.lpBaseOfDll, mi.SizeOfImage, (DWORD) mi.lpBaseOfDll+mi.SizeOfImage);
modulebase=SymGetModuleBase64(hProcess, dwAddr);
return modulebase;
}
}
return 0;
}
static HMODULE DoFindMSVCRTForCaller(void)
{
int i;
HANDLE mythread=(HANDLE) GetCurrentThread();
STACKFRAME64 sf={ 0 };
CONTEXT ct={ 0 };
if(!sym_myprocess)
{
DWORD symopts;
DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(), &sym_myprocess, 0, FALSE, DUPLICATE_SAME_ACCESS);
symopts=SymGetOptions();
SymSetOptions(symopts /*| SYMOPT_DEFERRED_LOADS*/ | SYMOPT_LOAD_LINES);
SymInitialize(sym_myprocess, NULL, TRUE);
atexit(DeinitSym);
}
ct.ContextFlags=CONTEXT_FULL;
// Use RtlCaptureContext() if we have it as it saves an exception throw
if((VOID (WINAPI *)(PCONTEXT)) -1==RtlCaptureContextAddr)
RtlCaptureContextAddr=(VOID (WINAPI *)(PCONTEXT)) GetProcAddress(GetModuleHandle(L"kernel32"), "RtlCaptureContext");
if(RtlCaptureContextAddr)
RtlCaptureContextAddr(&ct);
else
{ // This is nasty, but it works
__try
{
int *foo=0;
*foo=78;
}
__except (ExceptionFilter(GetExceptionCode(), GetExceptionInformation(), &ct))
{
}
}
sf.AddrPC.Mode=sf.AddrStack.Mode=sf.AddrFrame.Mode=AddrModeFlat;
#if !(defined(_M_AMD64) || defined(_M_X64))
sf.AddrPC.Offset =ct.Eip;
sf.AddrStack.Offset=ct.Esp;
sf.AddrFrame.Offset=ct.Ebp;
#else
sf.AddrPC.Offset =ct.Rip;
sf.AddrStack.Offset=ct.Rsp;
sf.AddrFrame.Offset=ct.Rbp; // maybe Rdi?
#endif
for(;;)
{
IMAGEHLP_MODULE64 ihm={ sizeof(IMAGEHLP_MODULE64) };
if(!StackWalk64(
#if !(defined(_M_AMD64) || defined(_M_X64))
IMAGE_FILE_MACHINE_I386,
#else
IMAGE_FILE_MACHINE_AMD64,
#endif
sym_myprocess, mythread, &sf, &ct, NULL, SymFunctionTableAccess64, GetModBase, NULL))
break;
if(0==sf.AddrPC.Offset)
break;
if(SymGetModuleInfo64(sym_myprocess, sf.AddrPC.Offset, &ihm))
{ // Is this me? If so keep going up the stack until it isn't
ModuleListItem *module;
if((HMODULE) ihm.BaseOfImage==MyModuleBase)
continue;
DebugPrint("Found caller of malloc function at %p (%s)\n", ihm.BaseOfImage, ihm.ModuleName);
for(module=modules; module->into; module++)
{
ULONG size;
PIMAGE_IMPORT_DESCRIPTOR desc = 0;
if((HMODULE)(size_t)-1==module->intoAddr)
continue;
desc = (PIMAGE_IMPORT_DESCRIPTOR) MyImageDirectoryEntryToData((PVOID) ihm.BaseOfImage, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &size);
if(!desc)
continue;
for (; desc->Name; desc++) {
PSTR modname = (PSTR)((PBYTE) ihm.BaseOfImage + desc->Name);
int modnamecmp = lstrcmpiA(modname, module->into);
if (modnamecmp>0)
break;
if (0==modnamecmp) {
DebugPrint("Module %p (%s) was originally linked to %s\n", ihm.BaseOfImage, ihm.ModuleName, module->into);
return (HMODULE) module->intoAddr;
}
}
}
}
}
DebugPrint("FATAL ERROR: Failed to walk up the stack of the caller!\n");
abort();
return (HMODULE) 0;
}
#pragma optimize("g", on)
static HMODULE FindMSVCRTForCaller(void)
{
/* If there is only one MSVCRT in this process, call that directly. Else do a stack backtrace to
find the MSVCRT we ought to use. */
ModuleListItem *module;
HMODULE ret=0;
for(module=modules; module->into; module++)
{
if(module->intoAddr && (void *)-1!=module->intoAddr)
{
if(ret) /* We have more than one MSVCRT, so search */
return DoFindMSVCRTForCaller();
ret=module->intoAddr;
}
}
if(ret) return ret;
DebugPrint("FATAL ERROR: Failed to find any patched MSVCRT at all!\n");
abort();
return (HMODULE) 0;
}
static void *sysmallocX(size_t size)
{
return ((void * (*)(size_t))GetProcAddress(FindMSVCRTForCaller(), "malloc"))(size);
}
static void *syscallocX(size_t no, size_t size)
{
return ((void * (*)(size_t, size_t))GetProcAddress(FindMSVCRTForCaller(), "calloc"))(no, size);
}
static void *sysreallocX(void *ptr, size_t size)
{
return ((void * (*)(void *, size_t))GetProcAddress(FindMSVCRTForCaller(), "realloc"))(ptr, size);
}
static void sysfreeX(void *ptr)
{
((void (*)(void *))GetProcAddress(FindMSVCRTForCaller(), "free"))(ptr);
}
static size_t sysblksizeX(void *ptr)
{
return ((size_t (*)(void *))GetProcAddress(FindMSVCRTForCaller(), "_msize"))(ptr);
}
#endif
int PatchInNedmallocDLL(void) THROWSPEC
{
static int UsingReleaseMSVCRT, UsingDebugMSVCRT;
Status ret={SUCCESS};
#ifdef NEDMALLOC_H
if(!UsingReleaseMSVCRT && !UsingDebugMSVCRT)
{
sysmalloc=sysmallocX;
syscalloc=syscallocX;
sysrealloc=sysreallocX;
sysfree=sysfreeX;
sysblksize=sysblksizeX;
}
#endif
ret=WinPatcher(nedmallocpatchtable, 1, &UsingReleaseMSVCRT, &UsingDebugMSVCRT);
#if defined(_DEBUG)
DebugPrint("Winpatcher: UsingReleaseMSVCRT=%d, UsingDebugMSVCRT=%d\n", UsingReleaseMSVCRT, UsingDebugMSVCRT);
#endif
if(ret.code<0)
{
TCHAR buffer[4096];
MakeReportFromStatus(buffer, sizeof(buffer)/sizeof(TCHAR), &ret);
#if defined(_DEBUG)
DebugPrint("Winpatcher: DLL Process Attach Failed with %s\n", buffer);
#endif
MessageBox(NULL, buffer, __T("Error"), MB_OK);
return FALSE;
}
return TRUE;
}
int DepatchInNedmallocDLL(void) THROWSPEC
{
Status ret={SUCCESS};
ret=WinPatcher(nedmallocpatchtable, 0, 0, 0);
if(ret.code<0)
{
TCHAR buffer[4096];
MakeReportFromStatus(buffer, sizeof(buffer)/sizeof(TCHAR), &ret);
#if defined(_DEBUG)
DebugPrint("Winpatcher: DLL Process Detach Failed with %s\n", buffer);
#endif
MessageBox(NULL, buffer, __T("Error"), MB_OK);
return FALSE;
}
return TRUE;
}
LONG CALLBACK ProcessExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo)
{
Status ret={SUCCESS};
ExceptionToStatus(&ret, ExceptionInfo->ExceptionRecord->ExceptionCode, ExceptionInfo);
return EXCEPTION_CONTINUE_SEARCH;
}
/* The DLL entry function for nedmalloc. This is called by the dynamic linker
before absolutely everything else - including the CRT */
BOOL WINAPI
_DllMainCRTStartup(
HANDLE hDllHandle,
DWORD dwReason,
LPVOID lpreserved
);
BOOL WINAPI _CRT_INIT(
HANDLE hDllHandle,
DWORD dwReason,
LPVOID lpreserved
);
//#pragma optimize("", off)
/* We split DllPreMainCRTStartup to avoid an annoying bug on the x64 compiler in /O2
whereby it inserts a security cookie check before we've initialised support for it, thus
provoking a failure */