-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathdebugger.cpp
1918 lines (1654 loc) · 54.8 KB
/
debugger.cpp
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
/*
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https ://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdbool.h>
#include <inttypes.h>
#include "windows.h"
#include "psapi.h"
#include "dbghelp.h"
#include "../common.h"
#include "debugger.h"
#define CALLCONV_MICROSOFT_X64 0
#define CALLCONV_THISCALL 1
#define CALLCONV_FASTCALL 2
#define CALLCONV_CDECL 3
#define CALLCONV_DEFAULT 4
#define BREAKPOINT_UNKNOWN 0
#define BREAKPOINT_ENTRYPOINT 1
#define BREAKPOINT_TARGET 2
#define PERSIST_END_EXCEPTION 0x0F22
// cleans up all breakpoint structures
// does not actually remove breakpoints in target process
void Debugger::DeleteBreakpoints() {
for (auto iter = breakpoints.begin(); iter != breakpoints.end(); iter++) {
delete *iter;
}
breakpoints.clear();
}
void Debugger::CreateException(EXCEPTION_RECORD *win_exception_record,
Exception *exception)
{
switch (win_exception_record->ExceptionCode) {
case EXCEPTION_BREAKPOINT:
case 0x4000001f:
exception->type = BREAKPOINT;
break;
case EXCEPTION_ACCESS_VIOLATION:
exception->type = ACCESS_VIOLATION;
break;
case EXCEPTION_ILLEGAL_INSTRUCTION:
exception->type = ILLEGAL_INSTRUCTION;
break;
case EXCEPTION_STACK_OVERFLOW:
exception->type = STACK_OVERFLOW;
break;
default:
exception->type = OTHER;
break;
}
exception->ip = win_exception_record->ExceptionAddress;
exception->maybe_execute_violation = false;
exception->maybe_write_violation = false;
exception->access_address = 0;
if (win_exception_record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
if (win_exception_record->ExceptionInformation[0] == 8) {
exception->maybe_execute_violation = true;
}
if (win_exception_record->ExceptionInformation[0] == 1) {
exception->maybe_write_violation = true;
}
exception->access_address = (void *)(win_exception_record->ExceptionInformation[1]);
}
}
void Debugger::RetrieveThreadContext() {
if (have_thread_context) return; // already done
lcContext.ContextFlags = CONTEXT_ALL;
HANDLE thread_handle = OpenThread(THREAD_ALL_ACCESS, FALSE, thread_id);
GetThreadContext(thread_handle, &lcContext);
CloseHandle(thread_handle);
have_thread_context = true;
}
void Debugger::SaveRegisters(SavedRegisters* registers) {
RetrieveThreadContext();
memcpy(®isters->saved_context, &lcContext, sizeof(registers->saved_context));
}
void Debugger::RestoreRegisters(SavedRegisters* registers) {
have_thread_context = false;
HANDLE thread_handle = OpenThread(THREAD_ALL_ACCESS, FALSE, thread_id);
if (!SetThreadContext(thread_handle, &lcContext)) {
FATAL("Error restoring registers");
}
CloseHandle(thread_handle);
}
size_t Debugger::GetRegister(Register r) {
RetrieveThreadContext();
#ifdef _WIN64
switch (r) {
case RAX:
return lcContext.Rax;
case RCX:
return lcContext.Rcx;
case RDX:
return lcContext.Rdx;
case RBX:
return lcContext.Rbx;
case RSP:
return lcContext.Rsp;
case RBP:
return lcContext.Rbp;
case RSI:
return lcContext.Rsi;
case RDI:
return lcContext.Rdi;
case R8:
return lcContext.R8;
case R9:
return lcContext.R9;
case R10:
return lcContext.R10;
case R11:
return lcContext.R11;
case R12:
return lcContext.R12;
case R13:
return lcContext.R13;
case R14:
return lcContext.R14;
case R15:
return lcContext.R15;
case RIP:
return lcContext.Rip;
default:
FATAL("Unimplemented");
}
#else
switch (r) {
case RAX:
return lcContext.Eax;
case RCX:
return lcContext.Ecx;
case RDX:
return lcContext.Edx;
case RBX:
return lcContext.Ebx;
case RSP:
return lcContext.Esp;
case RBP:
return lcContext.Ebp;
case RSI:
return lcContext.Esi;
case RDI:
return lcContext.Edi;
case RIP:
return lcContext.Eip;
default:
FATAL("Unimplemented");
}
#endif
}
void Debugger::SetRegister(Register r, size_t value) {
RetrieveThreadContext();
#ifdef _WIN64
switch (r) {
case RAX:
lcContext.Rax = value;
break;
case RCX:
lcContext.Rcx = value;
break;
case RDX:
lcContext.Rdx = value;
break;
case RBX:
lcContext.Rbx = value;
break;
case RSP:
lcContext.Rsp = value;
break;
case RBP:
lcContext.Rbp = value;
break;
case RSI:
lcContext.Rsi = value;
break;
case RDI:
lcContext.Rdi = value;
break;
case R8:
lcContext.R8 = value;
break;
case R9:
lcContext.R9 = value;
break;
case R10:
lcContext.R10 = value;
break;
case R11:
lcContext.R11 = value;
break;
case R12:
lcContext.R12 = value;
break;
case R13:
lcContext.R13 = value;
break;
case R14:
lcContext.R14 = value;
break;
case R15:
lcContext.R15 = value;
break;
case RIP:
lcContext.Rip = value;
break;
default:
FATAL("Unimplemented");
}
#else
switch (r) {
case RAX:
lcContext.Eax = value;
break;
case RCX:
lcContext.Ecx = value;
break;
case RDX:
lcContext.Edx = value;
break;
case RBX:
lcContext.Ebx = value;
break;
case RSP:
lcContext.Esp = value;
break;
case RBP:
lcContext.Ebp = value;
break;
case RSI:
lcContext.Esi = value;
break;
case RDI:
lcContext.Edi = value;
break;
case RIP:
lcContext.Eip = value;
break;
default:
FATAL("Unimplemented");
}
#endif
HANDLE thread_handle = OpenThread(THREAD_ALL_ACCESS, FALSE, thread_id);
SetThreadContext(thread_handle, &lcContext);
CloseHandle(thread_handle);
}
// converts between MemoryProtection and Windows protection flags
DWORD Debugger::WindowsProtectionFlags(MemoryProtection protection) {
switch (protection) {
case READONLY:
return PAGE_READONLY;
case READWRITE:
return PAGE_READWRITE;
case READEXECUTE:
return PAGE_EXECUTE_READ;
case READWRITEEXECUTE:
return PAGE_EXECUTE_READWRITE;
default:
FATAL("Unumplemented memory protection");
}
}
// allocates memory within 2GB of memory region
// between region_min and region_max
void *Debugger::RemoteAllocateNear(uint64_t region_min,
uint64_t region_max,
size_t size,
MemoryProtection protection,
bool use_shared_memory)
{
void *ret = NULL;
// try before first
uint64_t min_address = region_max;
if (min_address < 0x80000000) min_address = 0;
else min_address -= 0x80000000;
uint64_t max_address = region_min;
if (max_address < size) max_address = 0;
else max_address -= size;
ret = RemoteAllocateBefore(min_address,
max_address,
size,
protection);
if (ret) return ret;
min_address = region_max;
uint64_t address_range_max = 0xFFFFFFFFFFFFFFFFULL;
if (child_ptr_size == 4) {
address_range_max = 0xFFFFFFFFULL;
}
if ((address_range_max - 0x80000000) < region_min) {
max_address = address_range_max - size;
} else {
max_address = region_min + 0x80000000 - size;
}
ret = RemoteAllocateAfter(min_address,
max_address,
size,
protection);
return ret;
}
// allocates memory in target process as close as possible
// to max_address, but at address larger than min_address
void *Debugger::RemoteAllocateBefore(uint64_t min_address,
uint64_t max_address,
size_t size,
MemoryProtection protection)
{
DWORD protection_flags = WindowsProtectionFlags(protection);
MEMORY_BASIC_INFORMATION meminfobuf;
void *ret_address = NULL;
uint64_t cur_code = max_address;
while (cur_code > min_address) {
// Don't attempt allocating on the null page
if (cur_code < 0x1000) break;
size_t step = size;
size_t query_ret = VirtualQueryEx(child_handle,
(LPCVOID)cur_code,
&meminfobuf,
sizeof(MEMORY_BASIC_INFORMATION));
if (!query_ret) break;
if (meminfobuf.State == MEM_FREE) {
if (meminfobuf.RegionSize >= size) {
size_t address = (size_t)meminfobuf.BaseAddress +
(meminfobuf.RegionSize - size);
ret_address = VirtualAllocEx(child_handle,
(LPVOID)address,
size,
MEM_COMMIT | MEM_RESERVE,
protection_flags);
if (ret_address) {
if (((size_t)ret_address >= min_address) &&
((size_t)ret_address <= max_address)) {
return ret_address;
} else {
return NULL;
}
}
} else {
step = size - meminfobuf.RegionSize;
}
}
cur_code = (size_t)meminfobuf.BaseAddress;
if (cur_code < step) break;
else cur_code -= step;
}
return ret_address;
}
// allocates memory in target process as close as possible
// to min_address, but not higher than max_address
void *Debugger::RemoteAllocateAfter(uint64_t min_address,
uint64_t max_address,
size_t size,
MemoryProtection protection)
{
DWORD protection_flags = WindowsProtectionFlags(protection);
MEMORY_BASIC_INFORMATION meminfobuf;
void *ret_address = NULL;
uint64_t cur_code = min_address;
while (cur_code < max_address) {
size_t query_ret = VirtualQueryEx(child_handle,
(LPCVOID)cur_code,
&meminfobuf,
sizeof(MEMORY_BASIC_INFORMATION));
if (!query_ret) break;
if (meminfobuf.State == MEM_FREE) {
size_t region_address = (size_t)meminfobuf.BaseAddress;
size_t region_size = meminfobuf.RegionSize;
// make sure we are allocating on an address that
// is aligned according to allocation_granularity
size_t alignment = region_address & (allocation_granularity - 1);
if (alignment) {
size_t offset = (allocation_granularity - alignment);
region_address += offset;
if (region_size > offset) {
region_size -= offset;
} else {
region_size = 0;
}
}
if (region_size >= size) {
ret_address = VirtualAllocEx(child_handle,
(LPVOID)region_address,
size,
MEM_COMMIT | MEM_RESERVE,
protection_flags);
if (ret_address) {
if (((size_t)ret_address >= min_address) &&
((size_t)ret_address <= max_address)) {
return ret_address;
} else {
return NULL;
}
}
}
}
cur_code = (size_t)meminfobuf.BaseAddress + meminfobuf.RegionSize;
}
return ret_address;
}
void Debugger::RemoteFree(void *address, size_t size) {
if (!child_handle) return;
VirtualFreeEx(child_handle, address, 0, MEM_RELEASE);
}
void Debugger::RemoteWrite(void *address, void *buffer, size_t size) {
SIZE_T size_written;
if (WriteProcessMemory(
child_handle,
address,
buffer,
size,
&size_written))
{
return;
}
// we need to (a) read page permissions
// (b) make it writable, and (c) restore permissions
DWORD oldProtect;
if (!VirtualProtectEx(child_handle,
address,
size,
PAGE_READWRITE,
&oldProtect))
{
FATAL("Error in VirtualProtectEx");
}
if (!WriteProcessMemory(
child_handle,
address,
buffer,
size,
&size_written))
{
FATAL("Error writing target memory\n");
}
DWORD ignore;
if (!VirtualProtectEx(child_handle,
address,
size,
oldProtect,
&ignore))
{
FATAL("Error in VirtualProtectEx");
}
}
void Debugger::RemoteRead(void *address, void *buffer, size_t size) {
SIZE_T size_read;
if (!ReadProcessMemory(
child_handle,
address,
buffer,
size,
&size_read))
{
FATAL("Error reading target memory\n");
}
}
void Debugger::RemoteProtect(void *address, size_t size, MemoryProtection protect) {
DWORD protection_flags = WindowsProtectionFlags(protect);
DWORD old_protect;
if (!VirtualProtectEx(child_handle,
address,
size,
protection_flags,
&old_protect))
{
FATAL("Could not apply memory protection");
}
}
// detects executable memory regions in the module
// makes them non-executable
// and copies code out into this process
void Debugger::ExtractCodeRanges(void *module_base,
size_t min_address,
size_t max_address,
std::list<AddressRange> *executable_ranges,
size_t *code_size)
{
LPCVOID end_address = (char *)max_address;
LPCVOID cur_address = module_base;
MEMORY_BASIC_INFORMATION meminfobuf;
AddressRange newRange;
for (auto iter = executable_ranges->begin();
iter != executable_ranges->end(); iter++)
{
free(iter->data);
}
executable_ranges->clear();
*code_size = 0;
while (cur_address < end_address) {
size_t ret = VirtualQueryEx(child_handle,
cur_address,
&meminfobuf,
sizeof(MEMORY_BASIC_INFORMATION));
if (!ret) break;
if (meminfobuf.Protect & 0xF0) {
// printf("%p, %llx, %lx\n", meminfobuf.BaseAddress, meminfobuf.RegionSize, meminfobuf.Protect);
SIZE_T size_read;
newRange.data = (char *)malloc(meminfobuf.RegionSize);
if (!ReadProcessMemory(child_handle,
meminfobuf.BaseAddress,
newRange.data,
meminfobuf.RegionSize,
&size_read))
{
FATAL("Error in ReadProcessMemory");
}
if (size_read != meminfobuf.RegionSize) {
FATAL("Error in ReadProcessMemory");
}
uint8_t low = meminfobuf.Protect & 0xFF;
low = low >> 4;
DWORD newProtect = (meminfobuf.Protect & 0xFFFFFF00) + low;
DWORD oldProtect;
if (!VirtualProtectEx(child_handle,
meminfobuf.BaseAddress,
meminfobuf.RegionSize,
newProtect,
&oldProtect))
{
FATAL("Error in VirtualProtectEx");
}
newRange.from = (size_t)meminfobuf.BaseAddress;
newRange.to = (size_t)meminfobuf.BaseAddress + meminfobuf.RegionSize;
executable_ranges->push_back(newRange);
*code_size += newRange.to - newRange.from;
}
cur_address = (char *)meminfobuf.BaseAddress + meminfobuf.RegionSize;
}
}
// sets all pages containing (previously detected)
// code to non-executable
void Debugger::ProtectCodeRanges(std::list<AddressRange> *executable_ranges) {
MEMORY_BASIC_INFORMATION meminfobuf;
for (auto iter = executable_ranges->begin();
iter != executable_ranges->end(); iter++)
{
size_t ret = VirtualQueryEx(child_handle,
(void *)iter->from,
&meminfobuf,
sizeof(MEMORY_BASIC_INFORMATION));
// if the module was already instrumented, everything must be the same as before
if (!ret) {
FATAL("Error in ProtectCodeRanges."
"Target incompatible with persist_instrumentation_data");
}
if (iter->from != (size_t)meminfobuf.BaseAddress) {
FATAL("Error in ProtectCodeRanges."
"Target incompatible with persist_instrumentation_data");
}
if (iter->to != (size_t)meminfobuf.BaseAddress + meminfobuf.RegionSize) {
FATAL("Error in ProtectCodeRanges."
"Target incompatible with persist_instrumentation_data");
}
if (!(meminfobuf.Protect & 0xF0)) {
FATAL("Error in ProtectCodeRanges."
"Target incompatible with persist_instrumentation_data");
}
uint8_t low = meminfobuf.Protect & 0xFF;
low = low >> 4;
DWORD newProtect = (meminfobuf.Protect & 0xFFFFFF00) + low;
DWORD oldProtect;
if (!VirtualProtectEx(child_handle,
meminfobuf.BaseAddress,
meminfobuf.RegionSize,
newProtect,
&oldProtect))
{
FATAL("Error in VirtualProtectEx");
}
}
}
void Debugger::PatchPointersRemote(size_t min_address, size_t max_address, std::unordered_map<size_t, size_t>& search_replace) {
if (child_ptr_size == 4) {
PatchPointersRemoteT<uint32_t>(min_address, max_address, search_replace);
} else {
PatchPointersRemoteT<uint64_t>(min_address, max_address, search_replace);
}
}
template<typename T>
void Debugger::PatchPointersRemoteT(size_t min_address, size_t max_address, std::unordered_map<size_t, size_t>& search_replace) {
size_t module_size = max_address - min_address;
char* buf = (char *)malloc(module_size);
RemoteRead((void *)min_address, buf, module_size);
size_t remote_address = min_address;
for (size_t i = 0; i < (module_size - child_ptr_size + 1); i++) {
T ptr = *(T *)(buf + i);
auto iter = search_replace.find(ptr);
if (iter != search_replace.end()) {
// printf("patching entry %zx at address %zx\n", (size_t)ptr, remote_address);
T fixed_ptr = (T)iter->second;
RemoteWrite((void *)remote_address, &fixed_ptr, child_ptr_size);
}
remote_address += 1;
}
free(buf);
}
// returns an array of handles for all modules loaded in the target process
DWORD Debugger::GetLoadedModules(HMODULE **modules) {
DWORD module_handle_storage_size = 1024 * sizeof(HMODULE);
HMODULE *module_handles = (HMODULE *)malloc(module_handle_storage_size);
DWORD hmodules_size;
while (true) {
if (!EnumProcessModulesEx(child_handle,
module_handles,
module_handle_storage_size,
&hmodules_size,
LIST_MODULES_ALL))
{
FATAL("EnumProcessModules failed, %x\n", GetLastError());
}
if (hmodules_size <= module_handle_storage_size) break;
module_handle_storage_size *= 2;
module_handles = (HMODULE *)realloc(module_handles, module_handle_storage_size);
}
*modules = module_handles;
return hmodules_size / sizeof(HMODULE);
}
// parses PE headers and gets the module entypoint
void *Debugger::GetModuleEntrypoint(void *base_address) {
unsigned char headers[4096];
SIZE_T num_read = 0;
if (!ReadProcessMemory(child_handle, base_address, headers, 4096, &num_read) ||
(num_read != 4096))
{
FATAL("Error reading target memory\n");
}
DWORD pe_offset;
pe_offset = *((DWORD *)(headers + 0x3C));
unsigned char *pe = headers + pe_offset;
DWORD signature = *((DWORD *)pe);
if (signature != 0x00004550) {
FATAL("PE signature error\n");
}
pe = pe + 0x18;
WORD magic = *((WORD *)pe);
if ((magic != 0x10b) && (magic != 0x20b)) {
FATAL("Unknown PE magic value\n");
}
DWORD entrypoint_offset = *((DWORD *)(pe + 16));
if (entrypoint_offset == 0) return NULL;
return (char *)base_address + entrypoint_offset;
}
// parses PE headers and gets the image size
DWORD Debugger::GetImageSize(void *base_address) {
unsigned char headers[4096];
SIZE_T num_read = 0;
if (!ReadProcessMemory(child_handle, base_address, headers, 4096, &num_read) ||
(num_read != 4096))
{
FATAL("Error reading target memory\n");
}
DWORD pe_offset;
pe_offset = *((DWORD *)(headers + 0x3C));
unsigned char *pe = headers + pe_offset;
DWORD signature = *((DWORD *)pe);
if (signature != 0x00004550) {
FATAL("PE signature error\n");
}
pe = pe + 0x18;
WORD magic = *((WORD *)pe);
if ((magic != 0x10b) && (magic != 0x20b)) {
FATAL("Unknown PE magic value\n");
}
DWORD SizeOfImage = *((DWORD *)(pe + 56));
return SizeOfImage;
}
// parses PE headers and gets the image size
void Debugger::GetImageSize(void *base_address, size_t *min_address, size_t *max_address) {
*min_address = (size_t)base_address;
DWORD SizeOfImage = GetImageSize(base_address);
*max_address = *min_address + SizeOfImage;
}
// adds a one-time breakpoint at a specified address
// type, is an arbitrary int
// that can be accessed later when the breakpoint gets hit
void Debugger::AddBreakpoint(void *address, int type) {
Breakpoint *new_breakpoint = new Breakpoint;
SIZE_T rwsize = 0;
if (!ReadProcessMemory(child_handle, address, &(new_breakpoint->original_opcode), 1, &rwsize) ||
(rwsize != 1)) {
FATAL("Error reading target memory\n");
}
rwsize = 0;
unsigned char cc = 0xCC;
if (!WriteProcessMemory(child_handle, address, &cc, 1, &rwsize) || (rwsize != 1)) {
FATAL("Error writing target memory\n");
}
FlushInstructionCache(child_handle, address, 1);
new_breakpoint->address = address;
new_breakpoint->type = type;
breakpoints.push_back(new_breakpoint);
}
// damn it Windows, why don't you have a GetProcAddress
// that works on another process
DWORD Debugger::GetProcOffset(HMODULE module, const char *name) {
char* base_of_dll = (char*)module;
DWORD size_of_image = GetImageSize(base_of_dll);
// try the exported symbols next
char* modulebuf = (char*)malloc(size_of_image);
SIZE_T num_read;
if (!ReadProcessMemory(child_handle, base_of_dll, modulebuf, size_of_image, &num_read) ||
(num_read != size_of_image))
{
FATAL("Error reading target memory\n");
}
DWORD pe_offset;
pe_offset = *((DWORD *)(modulebuf + 0x3C));
char *pe = modulebuf + pe_offset;
DWORD signature = *((DWORD *)pe);
if (signature != 0x00004550) {
free(modulebuf);
return 0;
}
pe = pe + 0x18;
WORD magic = *((WORD *)pe);
DWORD exporttableoffset;
if (magic == 0x10b) {
exporttableoffset = *(DWORD *)(pe + 96);
} else if (magic == 0x20b) {
exporttableoffset = *(DWORD *)(pe + 112);
} else {
free(modulebuf);
return 0;
}
if (!exporttableoffset) {
free(modulebuf);
return 0;
}
char *exporttable = modulebuf + exporttableoffset;
DWORD numentries = *(DWORD *)(exporttable + 24);
DWORD addresstableoffset = *(DWORD *)(exporttable + 28);
DWORD nameptrtableoffset = *(DWORD *)(exporttable + 32);
DWORD ordinaltableoffset = *(DWORD *)(exporttable + 36);
DWORD *nameptrtable = (DWORD *)(modulebuf + nameptrtableoffset);
WORD *ordinaltable = (WORD *)(modulebuf + ordinaltableoffset);
DWORD *addresstable = (DWORD *)(modulebuf + addresstableoffset);
DWORD i;
for (i = 0; i < numentries; i++) {
char *nameptr = modulebuf + nameptrtable[i];
if (strcmp(name, nameptr) == 0) break;
}
if (i == numentries) {
free(modulebuf);
return 0;
}
WORD oridnal = ordinaltable[i];
DWORD offset = addresstable[oridnal];
free(modulebuf);
return offset;
}
// Gets the registered safe exception handlers for the module
void Debugger::GetExceptionHandlers(size_t module_haeder, std::unordered_set <size_t>& handlers) {
// only present on x86
if (child_ptr_size != 4) return;
DWORD size_of_image = GetImageSize((void *)module_haeder);
char* modulebuf = (char*)malloc(size_of_image);
SIZE_T num_read;
if (!ReadProcessMemory(child_handle, (void *)module_haeder, modulebuf, size_of_image, &num_read) ||
(num_read != size_of_image))
{
FATAL("Error reading target memory\n");
}
DWORD pe_offset;
pe_offset = *((DWORD*)(modulebuf + 0x3C));
char* pe = modulebuf + pe_offset;
DWORD signature = *((DWORD*)pe);
if (signature != 0x00004550) {
free(modulebuf);
return;
}
pe = pe + 0x18;
WORD magic = *((WORD*)pe);
DWORD lc_offset;
DWORD lc_size;
if (magic == 0x10b) {
lc_offset = *(DWORD*)(pe + 176);
lc_size = *(DWORD*)(pe + 180);
} else if (magic == 0x20b) {
lc_offset = *(DWORD*)(pe + 192);
lc_size = *(DWORD*)(pe + 196);
} else {
free(modulebuf);
return;
}
if (!lc_offset || (lc_size != 64)) {
free(modulebuf);
return;
}
char* lc = modulebuf + lc_offset;
size_t seh_table_address;
DWORD seh_count;
if (magic == 0x10b) {
seh_table_address = *(DWORD*)(lc + 64);
seh_count = *(DWORD*)(lc + 68);
} else if (magic == 0x20b) {
seh_table_address = *(uint64_t*)(lc + 96);
seh_count = *(DWORD*)(lc + 104);
} else {
free(modulebuf);
return;
}
size_t seh_table_offset = seh_table_address - module_haeder;
DWORD* seh_table = (DWORD *)(modulebuf + seh_table_offset);
for (DWORD i = 0; i < seh_count; i++) {
handlers.insert(module_haeder + seh_table[i]);
}
free(modulebuf);
}
// attempt to obtain the address of target function
// in various ways
char *Debugger::GetTargetAddress(HMODULE module) {
char* base_of_dll = (char *)module;
// if persist_offset is defined, use that
if (target_offset) {
return base_of_dll + target_offset;
}
DWORD offset = GetProcOffset(module, target_method.c_str());
if (offset) {
return (char *)module + offset;
}
// finally, try the debug symbols
char *method_address = NULL;
char base_name[MAX_PATH];
GetModuleBaseNameA(child_handle,
module,
(LPSTR)(&base_name),
sizeof(base_name));
char module_path[MAX_PATH];
if (!GetModuleFileNameExA(child_handle,
module,
module_path,
sizeof(module_path)))
return NULL;
ULONG64 buffer[(sizeof(SYMBOL_INFO) +
MAX_SYM_NAME * sizeof(TCHAR) +
sizeof(ULONG64) - 1) /
sizeof(ULONG64)];
PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)buffer;
pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO);
pSymbol->MaxNameLen = MAX_SYM_NAME;
SymInitialize(child_handle, NULL, false);
DWORD64 sym_base_address = SymLoadModuleEx(child_handle,
NULL,
module_path,
NULL,
0,
0,
NULL,
0);
if (SymFromName(child_handle, target_method.c_str(), pSymbol)) {
target_offset = (unsigned long)(pSymbol->Address - sym_base_address);
method_address = base_of_dll + target_offset;
}
SymCleanup(child_handle);
return method_address;
}
// called when a module gets loaded
void Debugger::OnModuleLoaded(void *module, char *module_name) {
// printf("In on_module_loaded, name: %s, base: %p\n", module_name, module_info.lpBaseOfDll);
if (target_function_defined && _stricmp(module_name, target_module.c_str()) == 0) {
target_address = GetTargetAddress((HMODULE)module);
if (!target_address) {
FATAL("Error determining target method address\n");
}
AddBreakpoint(target_address, BREAKPOINT_TARGET);
}
}
// called when a module gets unloaded
void Debugger::OnModuleUnloaded(void *module) { }
// reads numitems entries from stack in remote process
// from stack_addr
// into buffer