-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracewin.c
94 lines (81 loc) · 2.87 KB
/
tracewin.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
#include "carppriv.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <dbghelp.h>
List *
get_stack_trace () {
CONTEXT context = {0};
STACKFRAME64 stackframe = {0};
HANDLE process = GetCurrentProcess();
int i = 0;
List *stack = NULL;
/* fill in current context */
RtlCaptureContext(&context);
/* fill in current stackframe */
stackframe.AddrPC.Mode = AddrModeFlat;
stackframe.AddrFrame.Mode = AddrModeFlat;
stackframe.AddrStack.Mode = AddrModeFlat;
stackframe.AddrPC.Offset = context.Eip;
stackframe.AddrFrame.Offset = context.Ebp;
stackframe.AddrStack.Offset = context.Esp;
/* initialize the symbol handler */
if (!SymInitialize(process, NULL, TRUE)) {
fprintf(stderr, "SymInitialize() error %d\n", GetLastError());
exit(255);
}
/* walk the stack to get the symbols */
while (StackWalk64(
IMAGE_FILE_MACHINE_I386, /* machine type */
process, /* process */
GetCurrentThread(), /* thread */
&stackframe, /* stack frame */
&context, /* context */
NULL, /* read mem func */
NULL, /* func table access func */
NULL, /* get module base func */
NULL)) /* translate addr func */
{
FuncInfo *f;
DWORD64 pc = stackframe.AddrPC.Offset;
DWORD offset = 0;
size_t size;
SYMBOL_INFO *symbol;
IMAGEHLP_LINE64 *line;
IMAGEHLP_MODULE64 *module;
if (i++ > 200)
break;
/* symbol */
size = sizeof (SYMBOL_INFO) + (1000 - 1) * sizeof (TCHAR);
symbol = calloc(1, size);
symbol->MaxNameLen = 1000;
if (!SymFromAddr(process, pc, 0, symbol)) {
list_free(stack, func_info_free);
stack = NULL;
free(symbol);
break;
}
/* line */
line = calloc(1, sizeof *line);
line->SizeOfStruct = sizeof *line;
SymGetLineFromAddr64(process, pc, &offset, line);
/* module */
module = calloc(1, sizeof *module);
if (!SymGetModuleInfo64(process, pc, module)) {
fprintf(stderr, "SymGetModuleInfo64() error %d\n", GetLastError());
exit(255);
}
f = (FuncInfo *) calloc(sizeof (FuncInfo), 1);
f->func = strdup(symbol->Name);
f->file = strdup(line->FileName);
f->line = line->LineNumber;
f->lib = strdup(module->ModuleName);
stack = list_push(stack, f);
free(symbol);
free(line);
free(module);
}
SymCleanup(process);
return stack;
}