aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/common/extended_trace.cpp
blob: bf61ac1d1665f35c3235bce7575b311351c335ad (plain)
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
// --------------------------------------------------------------------------------------
//
// Written by Zoltan Csizmadia, zoltan_csizmadia@yahoo.com
// For companies(Austin,TX): If you would like to get my resume, send an email.
//
// The source is free, but if you want to use it, mention my name and e-mail address
//
// History:
//    1.0      Initial version                  Zoltan Csizmadia
//    1.1      WhineCube version                Masken
//    1.2      Dolphin version                  Masken
//
// --------------------------------------------------------------------------------------

#if defined(WIN32)
#include <cstdio>
#include <windows.h>
#include "common/extended_trace.h"
#include "common/string_util.h"
using namespace std;

#include <tchar.h>
#include <ImageHlp.h>

#define BUFFERSIZE   0x200
#pragma warning(disable:4996)

// Unicode safe char* -> TCHAR* conversion
void PCSTR2LPTSTR( PCSTR lpszIn, LPTSTR lpszOut )
{
#if defined(UNICODE)||defined(_UNICODE)
    ULONG index = 0;
    PCSTR lpAct = lpszIn;

    for( ; ; lpAct++ )
    {
        lpszOut[index++] = (TCHAR)(*lpAct);
        if ( *lpAct == 0 )
            break;
    }
#else
    // This is trivial :)
    strcpy( lpszOut, lpszIn );
#endif
}

// Let's figure out the path for the symbol files
// Search path= ".;%_NT_SYMBOL_PATH%;%_NT_ALTERNATE_SYMBOL_PATH%;%SYSTEMROOT%;%SYSTEMROOT%\System32;" + lpszIniPath
// Note: There is no size check for lpszSymbolPath!
static void InitSymbolPath( PSTR lpszSymbolPath, PCSTR lpszIniPath )
{
    CHAR lpszPath[BUFFERSIZE];

    // Creating the default path
    // ".;%_NT_SYMBOL_PATH%;%_NT_ALTERNATE_SYMBOL_PATH%;%SYSTEMROOT%;%SYSTEMROOT%\System32;"
    strcpy( lpszSymbolPath, "." );

    // environment variable _NT_SYMBOL_PATH
    if ( GetEnvironmentVariableA( "_NT_SYMBOL_PATH", lpszPath, BUFFERSIZE ) )
    {
        strcat( lpszSymbolPath, ";" );
        strcat( lpszSymbolPath, lpszPath );
    }

    // environment variable _NT_ALTERNATE_SYMBOL_PATH
    if ( GetEnvironmentVariableA( "_NT_ALTERNATE_SYMBOL_PATH", lpszPath, BUFFERSIZE ) )
    {
        strcat( lpszSymbolPath, ";" );
        strcat( lpszSymbolPath, lpszPath );
    }

    // environment variable SYSTEMROOT
    if ( GetEnvironmentVariableA( "SYSTEMROOT", lpszPath, BUFFERSIZE ) )
    {
        strcat( lpszSymbolPath, ";" );
        strcat( lpszSymbolPath, lpszPath );
        strcat( lpszSymbolPath, ";" );

        // SYSTEMROOT\System32
        strcat( lpszSymbolPath, lpszPath );
        strcat( lpszSymbolPath, "\\System32" );
    }

    // Add user defined path
    if ( lpszIniPath != NULL )
        if ( lpszIniPath[0] != '\0' )
        {
            strcat( lpszSymbolPath, ";" );
            strcat( lpszSymbolPath, lpszIniPath );
        }
}

// Uninitialize the loaded symbol files
BOOL UninitSymInfo() {
    return SymCleanup( GetCurrentProcess() );
}

// Initializes the symbol files
BOOL InitSymInfo( PCSTR lpszInitialSymbolPath )
{
    CHAR     lpszSymbolPath[BUFFERSIZE];
    DWORD    symOptions = SymGetOptions();

    symOptions |= SYMOPT_LOAD_LINES;
    symOptions &= ~SYMOPT_UNDNAME;
    SymSetOptions( symOptions );
    InitSymbolPath( lpszSymbolPath, lpszInitialSymbolPath );

    return SymInitialize( GetCurrentProcess(), lpszSymbolPath, TRUE);
}

// Get the module name from a given address
static BOOL GetModuleNameFromAddress( UINT address, LPTSTR lpszModule )
{
    BOOL              ret = FALSE;
    IMAGEHLP_MODULE   moduleInfo;

    ::ZeroMemory( &moduleInfo, sizeof(moduleInfo) );
    moduleInfo.SizeOfStruct = sizeof(moduleInfo);

    if ( SymGetModuleInfo( GetCurrentProcess(), (DWORD)address, &moduleInfo ) )
    {
        // Got it!
        PCSTR2LPTSTR( moduleInfo.ModuleName, lpszModule );
        ret = TRUE;
    }
    else
        // Not found :(
        _tcscpy( lpszModule, _T("?") );

    return ret;
}

// Get function prototype and parameter info from ip address and stack address
static BOOL GetFunctionInfoFromAddresses( ULONG fnAddress, ULONG stackAddress, LPTSTR lpszSymbol )
{
    BOOL              ret = FALSE;
    DWORD             dwSymSize = 10000;
    TCHAR             lpszUnDSymbol[BUFFERSIZE]=_T("?");
    CHAR              lpszNonUnicodeUnDSymbol[BUFFERSIZE]="?";
    LPTSTR            lpszParamSep = NULL;
    LPTSTR            lpszParsed = lpszUnDSymbol;
    PIMAGEHLP_SYMBOL  pSym = (PIMAGEHLP_SYMBOL)GlobalAlloc( GMEM_FIXED, dwSymSize );

    ::ZeroMemory( pSym, dwSymSize );
    pSym->SizeOfStruct = dwSymSize;
    pSym->MaxNameLength = dwSymSize - sizeof(IMAGEHLP_SYMBOL);

    // Set the default to unknown
    _tcscpy( lpszSymbol, _T("?") );

    // Get symbol info for IP
#ifndef _M_X64
    DWORD             dwDisp = 0;
    if ( SymGetSymFromAddr( GetCurrentProcess(), (ULONG)fnAddress, &dwDisp, pSym ) )
#else
    //makes it compile but hell im not sure if this works...
    DWORD64           dwDisp = 0;
    if ( SymGetSymFromAddr( GetCurrentProcess(), (ULONG)fnAddress, (PDWORD64)&dwDisp, pSym ) )
#endif
    {
        // Make the symbol readable for humans
        UnDecorateSymbolName( pSym->Name, lpszNonUnicodeUnDSymbol, BUFFERSIZE,
            UNDNAME_COMPLETE |
            UNDNAME_NO_THISTYPE |
            UNDNAME_NO_SPECIAL_SYMS |
            UNDNAME_NO_MEMBER_TYPE |
            UNDNAME_NO_MS_KEYWORDS |
            UNDNAME_NO_ACCESS_SPECIFIERS );

        // Symbol information is ANSI string
        PCSTR2LPTSTR( lpszNonUnicodeUnDSymbol, lpszUnDSymbol );

        // I am just smarter than the symbol file :)
        if (_tcscmp(lpszUnDSymbol, _T("_WinMain@16")) == 0)
            _tcscpy(lpszUnDSymbol, _T("WinMain(HINSTANCE,HINSTANCE,LPCTSTR,int)"));
        else if (_tcscmp(lpszUnDSymbol, _T("_main")) == 0)
            _tcscpy(lpszUnDSymbol, _T("main(int,TCHAR * *)"));
        else if (_tcscmp(lpszUnDSymbol, _T("_mainCRTStartup")) == 0)
            _tcscpy(lpszUnDSymbol, _T("mainCRTStartup()"));
        else if (_tcscmp(lpszUnDSymbol, _T("_wmain")) == 0)
            _tcscpy(lpszUnDSymbol, _T("wmain(int,TCHAR * *,TCHAR * *)"));
        else if (_tcscmp(lpszUnDSymbol, _T("_wmainCRTStartup")) == 0)
            _tcscpy(lpszUnDSymbol, _T("wmainCRTStartup()"));

        lpszSymbol[0] = _T('\0');

        // Let's go through the stack, and modify the function prototype, and insert the actual
        // parameter values from the stack
        if ( _tcsstr( lpszUnDSymbol, _T("(void)") ) == NULL && _tcsstr( lpszUnDSymbol, _T("()") ) == NULL)
        {
            ULONG index = 0;
            for( ; ; index++ )
            {
                lpszParamSep = _tcschr( lpszParsed, _T(',') );
                if ( lpszParamSep == NULL )
                    break;

                *lpszParamSep = _T('\0');

                _tcscat( lpszSymbol, lpszParsed );
                _stprintf( lpszSymbol + _tcslen(lpszSymbol), _T("=0x%08X,"), *((ULONG*)(stackAddress) + 2 + index) );

                lpszParsed = lpszParamSep + 1;
            }

            lpszParamSep = _tcschr( lpszParsed, _T(')') );
            if ( lpszParamSep != NULL )
            {
                *lpszParamSep = _T('\0');

                _tcscat( lpszSymbol, lpszParsed );
                _stprintf( lpszSymbol + _tcslen(lpszSymbol), _T("=0x%08X)"), *((ULONG*)(stackAddress) + 2 + index) );

                lpszParsed = lpszParamSep + 1;
            }
        }

        _tcscat( lpszSymbol, lpszParsed );

        ret = TRUE;
    }
    GlobalFree( pSym );

    return ret;
}

// Get source file name and line number from IP address
// The output format is: "sourcefile(linenumber)" or
//                       "modulename!address" or
//                       "address"
static BOOL GetSourceInfoFromAddress( UINT address, LPTSTR lpszSourceInfo )
{
    BOOL           ret = FALSE;
    IMAGEHLP_LINE  lineInfo;
    DWORD          dwDisp;
    TCHAR          lpszFileName[BUFFERSIZE] = _T("");
    TCHAR          lpModuleInfo[BUFFERSIZE] = _T("");

    _tcscpy( lpszSourceInfo, _T("?(?)") );

    ::ZeroMemory( &lineInfo, sizeof( lineInfo ) );
    lineInfo.SizeOfStruct = sizeof( lineInfo );

    if ( SymGetLineFromAddr( GetCurrentProcess(), address, &dwDisp, &lineInfo ) )
    {
        // Got it. Let's use "sourcefile(linenumber)" format
        PCSTR2LPTSTR( lineInfo.FileName, lpszFileName );
        TCHAR fname[_MAX_FNAME];
        TCHAR ext[_MAX_EXT];
        _tsplitpath(lpszFileName, NULL, NULL, fname, ext);
        _stprintf( lpszSourceInfo, _T("%s%s(%d)"), fname, ext, lineInfo.LineNumber );
        ret = TRUE;
    }
    else
    {
        // There is no source file information. :(
        // Let's use the "modulename!address" format
        GetModuleNameFromAddress( address, lpModuleInfo );

        if ( lpModuleInfo[0] == _T('?') || lpModuleInfo[0] == _T('\0'))
            // There is no modulename information. :((
            // Let's use the "address" format
            _stprintf( lpszSourceInfo, _T("0x%08X"), address );
        else
            _stprintf( lpszSourceInfo, _T("%s!0x%08X"), lpModuleInfo, address );

        ret = FALSE;
    }

    return ret;
}

void PrintFunctionAndSourceInfo(FILE* file, const STACKFRAME& callstack)
{
    TCHAR symInfo[BUFFERSIZE] = _T("?");
    TCHAR srcInfo[BUFFERSIZE] = _T("?");

    GetFunctionInfoFromAddresses((ULONG)callstack.AddrPC.Offset, (ULONG)callstack.AddrFrame.Offset, symInfo);
    GetSourceInfoFromAddress((ULONG)callstack.AddrPC.Offset, srcInfo);
    etfprint(file, "     " + Common::TStrToUTF8(srcInfo) + " : " + Common::TStrToUTF8(symInfo) + "\n");
}

void StackTrace( HANDLE hThread, const char* lpszMessage, FILE *file )
{
    STACKFRAME     callStack;
    BOOL           bResult;
    CONTEXT        context;
    HANDLE         hProcess = GetCurrentProcess();

    // If it's not this thread, let's suspend it, and resume it at the end
    if ( hThread != GetCurrentThread() )
        if ( SuspendThread( hThread ) == -1 )
        {
            // whaaat ?!
            etfprint(file, "Call stack info failed\n");
            return;
        }

        ::ZeroMemory( &context, sizeof(context) );
        context.ContextFlags = CONTEXT_FULL;

        if ( !GetThreadContext( hThread, &context ) )
        {
            etfprint(file, "Call stack info failed\n");
            return;
        }

        ::ZeroMemory( &callStack, sizeof(callStack) );
#ifndef _M_X64
        callStack.AddrPC.Offset    = context.Eip;
        callStack.AddrStack.Offset = context.Esp;
        callStack.AddrFrame.Offset = context.Ebp;
#else
        callStack.AddrPC.Offset    = context.Rip;
        callStack.AddrStack.Offset = context.Rsp;
        callStack.AddrFrame.Offset = context.Rbp;
#endif
        callStack.AddrPC.Mode      = AddrModeFlat;
        callStack.AddrStack.Mode   = AddrModeFlat;
        callStack.AddrFrame.Mode   = AddrModeFlat;

        etfprint(file, "Call stack info: \n");
        etfprint(file, lpszMessage);

        PrintFunctionAndSourceInfo(file, callStack);

        for( ULONG index = 0; ; index++ )
        {
            bResult = StackWalk(
                IMAGE_FILE_MACHINE_I386,
                hProcess,
                hThread,
                &callStack,
                NULL,
                NULL,
                SymFunctionTableAccess,
                SymGetModuleBase,
                NULL);

            if ( index == 0 )
                continue;

            if( !bResult || callStack.AddrFrame.Offset == 0 )
                break;

            PrintFunctionAndSourceInfo(file, callStack);

        }

        if ( hThread != GetCurrentThread() )
            ResumeThread( hThread );
}

void StackTrace(HANDLE hThread, const char* lpszMessage, FILE *file, DWORD eip, DWORD esp, DWORD ebp )
{
    STACKFRAME     callStack;
    BOOL           bResult;
    TCHAR          symInfo[BUFFERSIZE] = _T("?");
    TCHAR          srcInfo[BUFFERSIZE] = _T("?");
    HANDLE         hProcess = GetCurrentProcess();

    // If it's not this thread, let's suspend it, and resume it at the end
    if ( hThread != GetCurrentThread() )
        if ( SuspendThread( hThread ) == -1 )
        {
            // whaaat ?!
            etfprint(file, "Call stack info failed\n");
            return;
        }

        ::ZeroMemory( &callStack, sizeof(callStack) );
        callStack.AddrPC.Offset    = eip;
        callStack.AddrStack.Offset = esp;
        callStack.AddrFrame.Offset = ebp;
        callStack.AddrPC.Mode      = AddrModeFlat;
        callStack.AddrStack.Mode   = AddrModeFlat;
        callStack.AddrFrame.Mode   = AddrModeFlat;

        etfprint(file, "Call stack info: \n");
        etfprint(file, lpszMessage);

        PrintFunctionAndSourceInfo(file, callStack);

        for( ULONG index = 0; ; index++ )
        {
            bResult = StackWalk(
                IMAGE_FILE_MACHINE_I386,
                hProcess,
                hThread,
                &callStack,
                NULL,
                NULL,
                SymFunctionTableAccess,
                SymGetModuleBase,
                NULL);

            if ( index == 0 )
                continue;

            if( !bResult || callStack.AddrFrame.Offset == 0 )
                break;

            PrintFunctionAndSourceInfo(file, callStack);
        }

        if ( hThread != GetCurrentThread() )
            ResumeThread( hThread );
}

char g_uefbuf[2048];

void etfprintf(FILE *file, const char *format, ...)
{
    va_list ap;
    va_start(ap, format);
    int len = vsprintf(g_uefbuf, format, ap);
    fwrite(g_uefbuf, 1, len, file);
    va_end(ap);
}

void etfprint(FILE *file, const std::string &text)
{
    size_t len = text.length();
    fwrite(text.data(), 1, len, file);
}

#endif //WIN32