Форум программистов, компьютерный форум CyberForum.ru

Ошибка LNK2019 - C++

Восстановить пароль Регистрация
 
Progers
New to C++
 Аватар для Progers
83 / 44 / 5
Регистрация: 14.01.2013
Сообщений: 258
18.01.2014, 19:06     Ошибка LNK2019 #1
Здравствуйте! Скачал игру WarZ точнее исходники, и HackShield(Защита от читеров).
Пытаюсь защиту встроить в игру, но потом у меня начали появляться проблемы типа:
Кликните здесь для просмотра всего текста

Ошибка 94 error LNK2019: ссылка на неразрешенный внешний символ _GetFileVersionInfoA@16 в функции "unsigned long __cdecl GetFileVersion(char *,unsigned long *,unsigned long *)" (?GetFileVersion@@YAKPADPAK1@Z) r3dlibd_statcrt.lib
Ошибка 95 error LNK2019: ссылка на неразрешенный внешний символ _GetFileVersionInfoSizeA@8 в функции "unsigned long __cdecl GetFileVersion(char *,unsigned long *,unsigned long *)" (?GetFileVersion@@YAKPADPAK1@Z) r3dlibd_statcrt.lib
Ошибка 93 error LNK2019: ссылка на неразрешенный внешний символ _VerQueryValueA@16 в функции "unsigned long __cdecl GetFileVersion(char *,unsigned long *,unsigned long *)" (?GetFileVersion@@YAKPADPAK1@Z) r3dlibd_statcrt.lib
Ошибка 96 fatal error LNK1120: 3 неразрешенных внешних элементов D:\Other\WarZ\bin\Studio_d.exe


Уже всё попробовал сделать, пытался добавить
C++
1
#pragma comment(lib, "Version.lib")
Но без результатно.
Использую Visual Studio 2008.
Similar
Эксперт
41792 / 34177 / 6122
Регистрация: 12.04.2006
Сообщений: 57,940
18.01.2014, 19:06     Ошибка LNK2019
Посмотрите здесь:

C++ Ошибка LNK2019
Ошибка LNK2019 C++
C++ Ошибка LNK2019
Ошибка LNK2019 C++
Ошибка LNK2019 C++
Ошибка LNK2019 C++
Ошибка LNK2019 C++
Ошибка LNK2019 C++
Ошибка 2 error LNK2019, не пойму в чем ошибка C++
C++ LNK2019 ошибка
C++ ошибка LNK2019
C++ Ошибка LNK2019

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
После регистрации реклама в сообщениях будет скрыта и будут доступны все возможности форума.
Ev_Hyper
Заблокирован
18.01.2014, 19:18     Ошибка LNK2019 #2
Progers, код выложите
Progers
New to C++
 Аватар для Progers
83 / 44 / 5
Регистрация: 14.01.2013
Сообщений: 258
18.01.2014, 19:30  [ТС]     Ошибка LNK2019 #3
Ev_Hyper, Исходник весит полтора гега

Добавлено через 9 минут
Не знаю если эти проблемные места, но вот пример 2 файла:
Кликните здесь для просмотра всего текста

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
#pragma comment(lib, "HShield.lib") 
#pragma comment(lib, "HsCryptLib.lib") 
#pragma comment(lib, "HSUpChk.lib") 
#pragma comment(lib, "HsUserUtil.lib") 
#pragma comment(lib, "HsUserUtilDll.lib") 
#pragma comment(lib, "AntiCpXSvr.lib") 
#pragma comment(lib, "Version.lib") 
#pragma comment(lib, "version.lib") 
#include <winver.h>
#include "r3dPCH.h"
#include "r3d.h"
#include "r3dDebug.h"
#include "Shield/HShield.h"
#include "../SF/Console/EngineConsole.h"
#include <WINDOWS.h>
//Project shield
 
////////////////
//Start
int __stdcall HS_CallbackProc ( long lCode, long lParamSize, void* pParam )
{
TCHAR szMsg[MAX_PATH];
switch ( lCode )
{
    case AHNHS_ENGINE_DETECT_GAME_HACK:
wsprintf( szMsg, "You cannot run the following program and game simultaneously. (%x) \n [%s]",
lCode, (LPTSTR)pParam );
MessageBox( NULL, szMsg, "Error", MB_OK );
break;
case AHNHS_ACTAPC_DETECT_AUTOMACRO:
wsprintf(szMsg, _T("Suspected macro operation has been detected. (Code = %x"),
lCode);
MessageBox( NULL, szMsg, " Error", MB_OK );
break;
case AHNHS_ACTAPC_DETECT_AUTOMOUSE:
case AHNHS_ACTAPC_DETECT_ALREADYHOOKED:
break;
case AHNHS_ACTAPC_DETECT_SPEEDHACK:
wsprintf( szMsg, "Suspected speed hack operation has been detected. (%x)", lCode );
MessageBox( NULL, szMsg, "Error", MB_OK );
break;
case AHNHS_ACTAPC_DETECT_KDTRACE:
case AHNHS_ACTAPC_DETECT_KDTRACE_CHANGED:
    wsprintf( szMsg, "Attempt of game debugging has been detected. (%x)", lCode );
MessageBox( NULL, szMsg, "Error", MB_OK );
break;
case AHNHS_ACTAPC_DETECT_DRIVERFAILED:
case AHNHS_ACTAPC_DETECT_HOOKFUNCTION:
case AHNHS_ACTAPC_DETECT_MODULE_CHANGE:
case AHNHS_ACTAPC_DETECT_LMP_FAILED:
case AHNHS_ACTAPC_DETECT_MEM_MODIFY_FROM_LMP:
case AHNHS_ACTAPC_DETECT_ENGINEFAILED:
case AHNHS_ACTAPC_DETECT_CODEMISMATCH:
case AHNHS_ACTAPC_DETECT_ANTIFREESERVER:
case AHNHS_ACTAPC_DETECT_ABNORMAL_HACKSHIELD_STATUS:
wsprintf( szMsg, "There is a problem in the hack detection feature. (%x)", lCode );
MessageBox( NULL, szMsg, "Error", MB_OK );
break;
}
return 1;
}
//End
// First
BOOL HS_Init()
{
int nRet = HS_ERR_OK;
TCHAR szFullFilePath[MAX_PATH];
TCHAR szMsg[MAX_PATH];
DWORD dwOption = 0;
lstrcat ( szFullFilePath, _T( "D:\\Other\\hack sheild\\Bin\\Win\\x86\\HShield\\EhSvc.dll" ) );
dwOption = AHNHS_CHKOPT_ALL;
nRet = _AhnHS_Initialize ( szFullFilePath, HS_CallbackProc,1000,"B228F291B7D7FAD361D7A4B7",dwOption,AHNHS_SPEEDHACK_SENSING_RATIO_NORMAL );
if ( nRet != HS_ERR_OK ) 
{
switch ( nRet )
{
case HS_ERR_COMPATIBILITY_MODE_RUNNING:
case HS_ERR_NEED_ADMIN_RIGHTS:
case HS_ERR_INVALID_FILES:
case HS_ERR_INIT_DRV_FAILED:
case HS_ERR_DEBUGGER_DETECT:
case HS_ERR_NOT_INITIALIZED:
default:
wsprintf( szMsg, "An error occurred in the hack prevention feature.(%x)", nRet );
break;
}
MessageBox( NULL, szMsg, "Error", MB_OK );
return FALSE;
}
return TRUE;
}
//Second
BOOL HS_StartService()
{
int nRet = HS_ERR_OK;
TCHAR szMsg[MAX_PATH];
nRet = _AhnHS_StartService();
if ( nRet != HS_ERR_OK )
{
switch ( nRet )
{
case HS_ERR_START_ENGINE_FAILED:
case HS_ERR_DRV_FILE_CREATE_FAILED:
case HS_ERR_REG_DRV_FILE_FAILED:
case HS_ERR_START_DRV_FAILED:
default:
wsprintf ( szMsg, "An error occurred in the anti-hacking feature.(%x)", nRet );
break;
}
MessageBox( NULL, szMsg, "Error", MB_OK );
return FALSE;
}
return TRUE;
}
//Third
BOOL HS_StopService()
{
int nRet = HS_ERR_OK;
nRet = _AhnHS_StopService();
if ( nRet != HS_ERR_OK )
{
return FALSE;
}
return TRUE;
}
//Fourth
BOOL HS_UnInit()
{
int nRet = HS_ERR_OK;
nRet = _AhnHS_Uninitialize();
if ( nRet != HS_ERR_OK )
{
return FALSE;
}
return TRUE;
}
////END                           END                                    END
char __r3dCmdLine[1024];
 
typedef bool (*Win32MsgProc_fn)(UINT uMsg, WPARAM wParam, LPARAM lParam);
 
//hack: add temp handler for external message processing
 
namespace
{
    const int       NUM_MSG_PROC_MAX = 8;
    Win32MsgProc_fn r3dApp_MsgProc3[NUM_MSG_PROC_MAX] = {0};
}
 
static  int     StartWinHeight = 300;
static  int     StartWinWidth  = 300;
static  int     curDispWidth   = 0;
static  int     curDispHeight  = 0;
 
namespace win
{
    HINSTANCE   hInstance  = NULL;
    HWND        hWnd       = NULL;
    const char  *szWinName = "$o, yeah!$";
    HICON       hWinIcon   = 0;
    int     bSuspended  = 0;
    int     bNeedRender = 1;
    
    void        HandleActivate();
    void        HandleDeactivate();
    void        HandleMinimize();
    void        HandleRestore();
 
    int     Init();
}
 
void RegisterMsgProc (Win32MsgProc_fn proc)
{
    for (int i = 0; i<NUM_MSG_PROC_MAX; i++ )
    {
        if (!r3dApp_MsgProc3[i])
        {
            r3dApp_MsgProc3[i] = proc;
            return;
        }
    }
    r3d_assert ( 0 && "RegisterMsgProc error; register more than NUM_MSG_PROC_MAX MsgProc." );
}
 
void UnregisterMsgProc (Win32MsgProc_fn proc)
{
    for (int i = 0; i<NUM_MSG_PROC_MAX; i++ )
    {
        if (r3dApp_MsgProc3[i] == proc)
        {
            r3dApp_MsgProc3[i] = NULL;
            return;
        }
    }
    r3d_assert ( 0 && "UnregisterMsgProc error." );
}
 
#define INPUT_KBD_STACK 32
volatile static  int   input_ScanStack[INPUT_KBD_STACK + 2];
volatile static  int   * volatile input_StackHead = input_ScanStack;
volatile static  int   * volatile input_StackTail = input_ScanStack;
 
 
bool g_bExit = false;
 
bool IsNeedExit()
{
    return g_bExit;
}
 
int win::input_Flush()
{
  input_StackHead = input_ScanStack;
  input_StackTail = input_ScanStack;
 
  return 1;
}
 
int win::kbhit()
{
  if(input_StackHead == input_StackTail)
    return 0;
  else
    return 1;
}
 
int win::getch( bool bPop )
{
    int ch;
 
  if(!win::kbhit())
    return 0;
 
  ch = *input_StackTail;
  if ( bPop )
      input_StackTail++;
 
  if(input_StackTail >= input_ScanStack + INPUT_KBD_STACK)
    input_StackTail = input_ScanStack;
 
  return ch;
}
 
 
static 
void wnd__DrawLogo()
{
#if TSG_BITMAP
    HDC     hDC;
    HANDLE      hBmp;
 
  // load background image and center our window
  hBmp = LoadImage(
    GetModuleHandle(NULL), 
    MAKEINTRESOURCE(TSG_BITMAP),
    IMAGE_BITMAP,
    win__Width,
    win__Height,
    LR_DEFAULTCOLOR
    );
  if(hBmp == NULL) return;
 
  if(hDC = GetDC(win::hWnd))
  {
    HDC dc;
 
    dc = CreateCompatibleDC(hDC);
    SelectObject(dc, hBmp);
    BitBlt(hDC, 0, 0, win__Width, win__Height, dc, 0, 0, SRCCOPY);
    DeleteDC(dc);
 
    ReleaseDC(win::hWnd, hDC);
  }
 
  DeleteObject(hBmp);
 
#endif
 
  return;
}
 
bool winMouseWasVisible = true;
extern bool r3dMouse_visible;
void win::HandleActivate()
{
    //  if(!win::bSuspended)
    //      return;
 
    win::bSuspended = 0;
    win::bNeedRender = 1;
 
    if(Mouse)    Mouse->SetCapture();
    if(Keyboard) Keyboard->ClearPressed();
 
    if( winMouseWasVisible || g_cursor_mode->GetInt() )
        r3dMouse::Show(true);
    else 
        r3dMouse::Hide(true);
}
 
void win::HandleDeactivate()
{
    //  if(win::bSuspended)
    //    return;
    win::bSuspended = 1;
 
    if( !(r_render_on_deactivation && r_render_on_deactivation->GetInt()) )
        win::bNeedRender = 0;
    else
        win::bNeedRender = 1;
 
    winMouseWasVisible = r3dMouse_visible;
 
    if(Mouse)    Mouse->ReleaseCapture();
    if(Keyboard) Keyboard->ClearPressed();
}
 
void win::HandleMinimize()
{
    win::bNeedRender = 0;
}
 
void win::HandleRestore()
{
    win::bNeedRender = 1;
}
 
 
//
//
//
// main Callback function
//
//
 
/*
namespace 
{
  //
  // some vars to simulate move moving by ourselves.
  //
  
  static bool bOnCaption = false;   // true if we're on caption
  static bool bDragging  = true;    // true if we're dragging our window
  static int  dragX      = 0;       // offset of drag point, relative to window origin
  static int  dragY      = 0;       // offset of drag point, relative to window origin
  
  static void dragDisable()
  {
    if(!bDragging) return;
  
    ReleaseCapture();
    bDragging = false;
 
    return;
  }  
};
*/
 
void (*OnDblClick)() = 0;
 
static 
LRESULT CALLBACK win__WndFunc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
  static int userProcActive = 0;
 
  if(userProcActive) {
    // in very rare occasions we can reenter this function
    // one of cases is that when error is thrown from processing user or UI functions
    // so, in this case we'll enter to never ending loop
    return DefWindowProc(hWnd, uMsg, wParam, lParam);
  }
 
  userProcActive = true;
  bool bAnyCompleted = false;
  for(int i = 0; i < NUM_MSG_PROC_MAX; i++ )
  {
      if ( r3dApp_MsgProc3 [i] )
          bAnyCompleted |= r3dApp_MsgProc3[i](uMsg, wParam, lParam);
  }
  userProcActive = false;
  if ( bAnyCompleted ) return 0;
 
 
  //r3dOutToLog("uMsg %x\n", uMsg);
  switch(uMsg) 
  {
    case WM_CLOSE:
    {
      r3dOutToLog("alt-f4 pressed\n");
      r3dOutToLog("...terminating application\n");
 
      ClipCursor(NULL);
      
      //HRESULT res = TerminateProcess(r3d_CurrentProcess, 0);
 
      g_bExit = true;
      return 0;
    }
    
    case WM_CONTEXTMENU:
      // disable context menu
      return 0;
      
    case WM_ENTERMENULOOP:
      r3dOutToLog("!!!warning!!! r3dApp entered to modal menu loop\n");
      break;
      
    case WM_ENTERSIZEMOVE:
      //r3d_assert(0 && "WM_ENTERSIZEMOVE");
      win::HandleDeactivate();
      return 0;
      
    case WM_EXITSIZEMOVE:
      r3dOutToLog("WM_EXITSIZEMOVE: %d\n", win::bSuspended);
      win::HandleActivate();
      break;
 
/*
    case WM_CAPTURECHANGED:
      // if we lose capture from our window - disable dragging
      if(bDragging && (HWND)lParam != hWnd) {
        // note: do not call dragDisable(), because it will call ReleaseCapture()
        bDragging = false;
        break;
      }
      break;
 
    case WM_LBUTTONUP:
    {
      if(bDragging) {
        dragDisable();
      }
      break;
    }
 
    case WM_LBUTTONDOWN:
    {
      if(bOnCaption) {
        // start dragging our window, calc drag anchor point, relative to window corner
        POINT pp;        
        GetCursorPos(&pp);
        RECT rr;
        GetWindowRect(hWnd, &rr);
 
        dragX = pp.x - rr.left;
        dragY = pp.y - rr.top;
        
        ::SetCapture(hWnd);
        bDragging = true;
      }
      
      break;
    }
    
    case WM_MOUSEMOVE:
    {
      if(bDragging) {
        POINT pp;        
        GetCursorPos(&pp);
        SetWindowPos(hWnd, 0, pp.x - dragX, pp.y - dragY, 0, 0, SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOZORDER);
      }
 
      break;
    }
 
    case WM_NCHITTEST:
    {
      if(!r3dRenderer || !r3dRenderer->d3dpp.Windowed) 
        break;
      if(win::bSuspended)
        break;
        
      // if cursor is clipped somewhere, don't allow this window dragging at all.
      RECT clipRect;
      ::GetClipCursor(&clipRect);
      if(clipRect.left != 0 || clipRect.top != 0 || clipRect.right != curDispWidth || clipRect.bottom != curDispHeight) {
        return HTCLIENT;
      }
        
      LONG hitTest = DefWindowProc(hWnd, uMsg, wParam, lParam);
      if(hitTest == HTCLIENT && bOnCaption) {
        if(Mouse) Mouse->Hide(); 
        if(Mouse) Mouse->SetCapture();
        
        bOnCaption = false;
        return hitTest;
      }
      
      if(hitTest == HTCAPTION && bOnCaption) {
        // return that we still in client area - so windows will not start windows moving by itself
        return HTCLIENT;
      }
      
      if(hitTest == HTCAPTION && !bOnCaption) {
        if(Mouse) Mouse->Show(); 
        if(Mouse) Mouse->ReleaseCapture();
 
        // we will simuate dragging by ourselves, otherwise game will be in modal dragging loop!
        bOnCaption = true;
        return HTCLIENT;
      }
 
      return hitTest;
    }
*/    
    
    // disable menu calling when ALT pressed
    case WM_SYSCOMMAND:
    {
      // disable those system commands
      switch(wParam & 0xFFFF) {
        case 0xF093:        // system menu on caption bar
        case SC_KEYMENU:
        case SC_MOVE:
          return 0;
        case SC_MINIMIZE:
          win::HandleMinimize();
          break;
        case SC_RESTORE:
          win::HandleRestore();
          break;
 
      }
 
      r3dOutToLog("r3dapp: SysCmd: %x\n", wParam & 0xFFFF);
      break;
    }
 
    case WM_NCACTIVATE: 
      //dragDisable();
 
      if((wParam & 0xFFFF) == TRUE) 
        win::HandleActivate();
      break;
 
    case WM_ACTIVATE:
      //dragDisable();
 
      if((wParam & 0xFFFF) == WA_INACTIVE) {
        win::HandleDeactivate();
      } else {
        win::HandleActivate();
      }
      break;
 
    case WM_KEYDOWN:
    {
        EngineConsole::ProcessKey( wParam );
        break;
    }
 
    case WM_LBUTTONDBLCLK:
        if( OnDblClick )
            OnDblClick() ;
        break;
 
    // store char to input stream
    case WM_CHAR:
    {
        EngineConsole::ProcessChar( wParam );
 
        int ch;
 
      ch              = (TCHAR)wParam;
      *(input_StackHead++) = ch;
      if(input_StackHead >= input_ScanStack + INPUT_KBD_STACK)
    input_StackHead = input_ScanStack;
      break;
    }
 
    case WM_PAINT:
    {
    HDC         hDC;
    PAINTSTRUCT ps;
 
      hDC = BeginPaint(hWnd,&ps);
      wnd__DrawLogo();
      EndPaint(hWnd,&ps);
      break;
    }
 
    case WM_DESTROY:
      //PostQuitMessage (0);
        g_bExit = true;
      break;
  }
 
  return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
 
void r3dWinStyleModify(HWND hWnd, int add, DWORD style)
{
  if(add)
    SetWindowLong(hWnd, GWL_STYLE, GetWindowLong(win::hWnd, GWL_STYLE) | style);
  else
    SetWindowLong(hWnd, GWL_STYLE, GetWindowLong(win::hWnd, GWL_STYLE) & ~style);
}
 
 
BOOL win::Init()
{
  static const char* szWinClassName = "r3dWin";
 
  r3d_assert(hInstance != NULL);
 
  WNDCLASS  wndclass;
  wndclass.style         = CS_DBLCLKS | CS_GLOBALCLASS;
  wndclass.lpfnWndProc   = win__WndFunc;        // window function
  wndclass.cbClsExtra    = 0;               // no extra count of bytes
  wndclass.cbWndExtra    = 0;               // no extra count of bytes
  wndclass.hInstance     = GetModuleHandle(NULL);   // this instance
  wndclass.hIcon         = (hWinIcon) ? hWinIcon : LoadIcon(NULL, IDI_APPLICATION);
  wndclass.hCursor       = LoadCursor(NULL, IDC_ARROW);
  wndclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
  wndclass.lpszMenuName  = NULL;
  wndclass.lpszClassName = szWinClassName;
  RegisterClass(&wndclass);
 
    HDC     disp_dc;
 
  disp_dc  = CreateIC("DISPLAY", NULL, NULL, NULL);
  curDispWidth  = GetDeviceCaps(disp_dc, HORZRES);
  curDispHeight = GetDeviceCaps(disp_dc, VERTRES);
  //disp_bpp = GetDeviceCaps(disp_dc, BITSPIXEL);
  DeleteDC(disp_dc);
 
  hWnd = CreateWindow(
    /* window class name */       szWinClassName,                       
    /* window caption*/           szWinName,                    
    /* window style */            WS_VISIBLE | WS_OVERLAPPEDWINDOW,
    /* initial x position */      (curDispWidth - StartWinWidth) / 2,       
    /* initial y position */      (curDispHeight - StartWinHeight) / 2,     
    /* initial x size */          StartWinWidth,                
    /* initial y size */          StartWinHeight,               
    /* parent window handle */    NULL,                             
    /* window menu handle*/       NULL,                             
    /* program instance handle */ GetModuleHandle(NULL),            
    /* creation parameters */     NULL);                            
 
  if(!hWnd) {
    MessageBox(GetActiveWindow(), "Window Creation Failed", "Error", MB_OK);
    return FALSE;
  }
 
/*
  //WinStyleModify(0, WS_SYSMENU);
  WinStyleModify(0, WS_BORDER);
  WinStyleModify(0, WS_CAPTION);
  WinStyleModify(1, WS_DLGFRAME);
*/
 
  // set icon
  ::SendMessage(hWnd, WM_SETICON, TRUE,  (LPARAM)wndclass.hIcon);
  ::SendMessage(hWnd, WM_SETICON, FALSE, (LPARAM)wndclass.hIcon);
  
  r3dWinStyleModify(hWnd, 0, WS_THICKFRAME);    // prevent resize
  r3dWinStyleModify(hWnd, 0, WS_MAXIMIZEBOX);   // prevent maximize
  //r3dWinStyleModify(hWnd, 0, WS_MINIMIZEBOX); // prevent minimize
  
 
  ShowWindow(win::hWnd, FALSE);
  wnd__DrawLogo();
  InvalidateRect(win::hWnd, NULL, FALSE);
  UpdateWindow(win::hWnd);
  SetFocus(win::hWnd);
 
  return TRUE;
}
 
 
 
int win::ProcessSuspended()
{
  if(!bSuspended)
    return FALSE;
 
  MSG msg;
  while(PeekMessage(&msg, NULL,0,0,PM_NOREMOVE))
  {
    if(!GetMessage (&msg, NULL, 0, 0)) 
      return 1;
 
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }
 
  return TRUE;
}
 
 
static void startupFunc(DWORD in)
{
//  in = in;
 
 
  game::PreInit();  
  win::Init();
  
  game::Init();
 
  game::MainLoop();
 
  game::Shutdown();    
 
}
 
//
//
// the One And Only - WinMain!
//
//
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
      HS_Init();
      HS_StartService();
#ifdef _DEBUG
#ifdef ENABLE_MEMORY_DEBUG
    //_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
    //_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
 
    _CrtMemState _ms;
    _CrtMemCheckpoint(&_ms);
#endif
#endif
 
#if 0
    char* __internal_gnrt_lkey(const char* name, int exp_year, int exp_month, int exp_day);
    void r3dLibraryInit(char* license);
    void checkLicenseKey();
 
    char* lic = __internal_gnrt_lkey("testing", 2010, 7, 10);
    r3dLibraryInit(lic);
    checkLicenseKey();
#endif
 
    // set our game to run only one processor (we're not using multithreading)
    // that will help with timer
    //DWORD_PTR oldmask = ::SetThreadAffinityMask(::GetCurrentThread(), 0);
 
 
  r3dscpy(__r3dCmdLine, lpCmdLine);
  
#ifdef _DEBUG
  //DWORD NewMask = ~(_EM_ZERODIVIDE | _EM_OVERFLOW | _EM_INVALID);
  //_controlfp(NewMask, _MCW_EM);
#endif 
 
  win::hInstance = hInstance;
 
  r3dThreadEntryHelper(startupFunc, 0);
 
  PostQuitMessage(0);
 
#ifdef _DEBUG
#ifdef ENABLE_MEMORY_DEBUG
   _CrtMemDumpAllObjectsSince(&_ms);
#endif
#endif
   HS_StopService();
   HS_UnInit();
  return 0;
}

Кликните здесь для просмотра всего текста

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
/**********************************************************************
 * 
 * StackWalker.cpp
 *
 *
 * History:
 *  2005-07-27   v1    - First public release on [url]http://www.codeproject.com/[/url]
 *                       [url]http://www.codeproject.com/threads/StackWalker.asp[/url]
 *  2005-07-28   v2    - Changed the params of the constructor and ShowCallstack
 *                       (to simplify the usage)
 *  2005-08-01   v3    - Changed to use 'CONTEXT_FULL' instead of CONTEXT_ALL 
 *                       (should also be enough)
 *                     - Changed to compile correctly with the PSDK of VC7.0
 *                       (GetFileVersionInfoSizeA and GetFileVersionInfoA is wrongly defined:
 *                        it uses LPSTR instead of LPCSTR as first paremeter)
 *                     - Added declarations to support VC5/6 without using 'dbghelp.h'
 *                     - Added a 'pUserData' member to the ShowCallstack function and the 
 *                       PReadProcessMemoryRoutine declaration (to pass some user-defined data, 
 *                       which can be used in the readMemoryFunction-callback)
 *  2005-08-02   v4    - OnSymInit now also outputs the OS-Version by default
 *                     - Added example for doing an exception-callstack-walking in main.cpp
 *                       (thanks to owillebo: [url]http://www.codeproject.com/script/profile/whos_who.asp?id=536268[/url])
 *  2005-08-05   v5    - Removed most Lint ([url]http://www.gimpel.com/[/url]) errors... thanks to Okko Willeboordse!
 *
 **********************************************************************/
#include "r3dPCH.h"
 
#pragma comment(lib, "version.lib")  // for "VerQueryValue"
#pragma comment(lib, "Version.lib")
#include "StackWalker.h"
#include <windows.h>
 
// If VC7 and later, then use the shipped 'dbghelp.h'-file
#if _MSC_VER >= 1300
#include <dbghelp.h>
#else
// inline the important dbghelp.h-declarations...
typedef enum {
    SymNone = 0,
    SymCoff,
    SymCv,
    SymPdb,
    SymExport,
    SymDeferred,
    SymSym,
    SymDia,
    SymVirtual,
    NumSymTypes
} SYM_TYPE;
typedef struct _IMAGEHLP_LINE64 {
    DWORD                       SizeOfStruct;           // set to sizeof(IMAGEHLP_LINE64)
    PVOID                       Key;                    // internal
    DWORD                       LineNumber;             // line number in file
    PCHAR                       FileName;               // full filename
    DWORD64                     Address;                // first instruction of line
} IMAGEHLP_LINE64, *PIMAGEHLP_LINE64;
typedef struct _IMAGEHLP_MODULE64 {
    DWORD                       SizeOfStruct;           // set to sizeof(IMAGEHLP_MODULE64)
    DWORD64                     BaseOfImage;            // base load address of module
    DWORD                       ImageSize;              // virtual size of the loaded module
    DWORD                       TimeDateStamp;          // date/time stamp from pe header
    DWORD                       CheckSum;               // checksum from the pe header
    DWORD                       NumSyms;                // number of symbols in the symbol table
    SYM_TYPE                    SymType;                // type of symbols loaded
    CHAR                        ModuleName[32];         // module name
    CHAR                        ImageName[256];         // image name
    CHAR                        LoadedImageName[256];   // symbol file name
} IMAGEHLP_MODULE64, *PIMAGEHLP_MODULE64;
typedef struct _IMAGEHLP_SYMBOL64 {
    DWORD                       SizeOfStruct;           // set to sizeof(IMAGEHLP_SYMBOL64)
    DWORD64                     Address;                // virtual address including dll base address
    DWORD                       Size;                   // estimated size of symbol, can be zero
    DWORD                       Flags;                  // info about the symbols, see the SYMF defines
    DWORD                       MaxNameLength;          // maximum size of symbol name in 'Name'
    CHAR                        Name[1];                // symbol name (null terminated string)
} IMAGEHLP_SYMBOL64, *PIMAGEHLP_SYMBOL64;
typedef enum {
    AddrMode1616,
    AddrMode1632,
    AddrModeReal,
    AddrModeFlat
} ADDRESS_MODE;
typedef struct _tagADDRESS64 {
    DWORD64       Offset;
    WORD          Segment;
    ADDRESS_MODE  Mode;
} ADDRESS64, *LPADDRESS64;
typedef struct _KDHELP64 {
    DWORD64   Thread;
    DWORD   ThCallbackStack;
    DWORD   ThCallbackBStore;
    DWORD   NextCallback;
    DWORD   FramePointer;
    DWORD64   KiCallUserMode;
    DWORD64   KeUserCallbackDispatcher;
    DWORD64   SystemRangeStart;
    DWORD64  Reserved[8];
} KDHELP64, *PKDHELP64;
typedef struct _tagSTACKFRAME64 {
    ADDRESS64   AddrPC;               // program counter
    ADDRESS64   AddrReturn;           // return address
    ADDRESS64   AddrFrame;            // frame pointer
    ADDRESS64   AddrStack;            // stack pointer
    ADDRESS64   AddrBStore;           // backing store pointer
    PVOID       FuncTableEntry;       // pointer to pdata/fpo or NULL
    DWORD64     Params[4];            // possible arguments to the function
    BOOL        Far;                  // WOW far call
    BOOL        Virtual;              // is this a virtual frame?
    DWORD64     Reserved[3];
    KDHELP64    KdHelp;
} STACKFRAME64, *LPSTACKFRAME64;
typedef
BOOL
(__stdcall *PREAD_PROCESS_MEMORY_ROUTINE64)(
    HANDLE      hProcess,
    DWORD64     qwBaseAddress,
    PVOID       lpBuffer,
    DWORD       nSize,
    LPDWORD     lpNumberOfBytesRead
    );
typedef
PVOID
(__stdcall *PFUNCTION_TABLE_ACCESS_ROUTINE64)(
    HANDLE  hProcess,
    DWORD64 AddrBase
    );
typedef
DWORD64
(__stdcall *PGET_MODULE_BASE_ROUTINE64)(
    HANDLE  hProcess,
    DWORD64 Address
    );
typedef
DWORD64
(__stdcall *PTRANSLATE_ADDRESS_ROUTINE64)(
    HANDLE    hProcess,
    HANDLE    hThread,
    LPADDRESS64 lpaddr
    );
#define SYMOPT_CASE_INSENSITIVE         0x00000001
#define SYMOPT_UNDNAME                  0x00000002
#define SYMOPT_DEFERRED_LOADS           0x00000004
#define SYMOPT_NO_CPP                   0x00000008
#define SYMOPT_LOAD_LINES               0x00000010
#define SYMOPT_OMAP_FIND_NEAREST        0x00000020
#define SYMOPT_LOAD_ANYTHING            0x00000040
#define SYMOPT_IGNORE_CVREC             0x00000080
#define SYMOPT_NO_UNQUALIFIED_LOADS     0x00000100
#define SYMOPT_FAIL_CRITICAL_ERRORS     0x00000200
#define SYMOPT_EXACT_SYMBOLS            0x00000400
#define SYMOPT_ALLOW_ABSOLUTE_SYMBOLS   0x00000800
#define SYMOPT_IGNORE_NT_SYMPATH        0x00001000
#define SYMOPT_INCLUDE_32BIT_MODULES    0x00002000
#define SYMOPT_PUBLICS_ONLY             0x00004000
#define SYMOPT_NO_PUBLICS               0x00008000
#define SYMOPT_AUTO_PUBLICS             0x00010000
#define SYMOPT_NO_IMAGE_SEARCH          0x00020000
#define SYMOPT_SECURE                   0x00040000
#define SYMOPT_DEBUG                    0x80000000
#define UNDNAME_COMPLETE                 (0x0000)  // Enable full undecoration
#define UNDNAME_NAME_ONLY                (0x1000)  // Crack only the name for primary declaration;
#endif  // _MSC_VER < 1300
 
// Some missing defines (for VC5/6):
#ifndef INVALID_FILE_ATTRIBUTES
#define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
#endif  
 
 
// secure-CRT_functions are only available starting with VC8
#if _MSC_VER < 1400
#define strcpy_s strcpy
#define strcat_s(dst, len, src) strcat(dst, src)
#define _snprintf_s _snprintf
#define _tcscat_s _tcscat
#endif
 
// Normally it should be enough to use 'CONTEXT_FULL' (better would be 'CONTEXT_ALL')
#define USED_CONTEXT_FLAGS CONTEXT_FULL
 
 
class StackWalkerInternal
{
public:
  StackWalkerInternal(StackWalker *parent, HANDLE hProcess)
  {
    m_parent = parent;
    m_hDbhHelp = NULL;
    pSC = NULL;
    m_hProcess = hProcess;
    m_szSymPath = NULL;
    pSFTA = NULL;
    pSGLFA = NULL;
    pSGMB = NULL;
    pSGMI = NULL;
    pSGO = NULL;
    pSGSFA = NULL;
    pSI = NULL;
    pSLM = NULL;
    pSSO = NULL;
    pSW = NULL;
    pUDSN = NULL;
    pSGSP = NULL;
  }
  ~StackWalkerInternal()
  {
    if (pSC != NULL)
      pSC(m_hProcess);  // SymCleanup
    if (m_hDbhHelp != NULL)
      FreeLibrary(m_hDbhHelp);
    m_hDbhHelp = NULL;
    m_parent = NULL;
    if(m_szSymPath != NULL)
      free(m_szSymPath);
    m_szSymPath = NULL;
  }
  BOOL Init(LPCSTR szSymPath)
  {
    if (m_parent == NULL)
      return FALSE;
    // Dynamically load the Entry-Points for dbghelp.dll:
    // First try to load the newsest one from
    TCHAR szTemp[4096];
    // But before wqe do this, we first check if the ".local" file exists
    if (GetModuleFileName(NULL, szTemp, 4096) > 0)
    {
      _tcscat_s(szTemp, _T(".local"));
      if (GetFileAttributes(szTemp) == INVALID_FILE_ATTRIBUTES)
      {
        // ".local" file does not exist, so we can try to load the dbghelp.dll from the "Debugging Tools for Windows"
        if (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, 4096) > 0)
        {
          _tcscat_s(szTemp, _T("\\Debugging Tools for Windows\\dbghelp.dll"));
          // now check if the file exists:
          if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
          {
            m_hDbhHelp = LoadLibrary(szTemp);
          }
        }
          // Still not found? Then try to load the 64-Bit version:
        if ( (m_hDbhHelp == NULL) && (GetEnvironmentVariable(_T("ProgramFiles"), szTemp, 4096) > 0) )
        {
          _tcscat_s(szTemp, _T("\\Debugging Tools for Windows 64-Bit\\dbghelp.dll"));
          if (GetFileAttributes(szTemp) != INVALID_FILE_ATTRIBUTES)
          {
            m_hDbhHelp = LoadLibrary(szTemp);
          }
        }
      }
    }
    if (m_hDbhHelp == NULL)  // if not already loaded, try to load a default-one
      m_hDbhHelp = LoadLibrary( _T("dbghelp.dll") );
    if (m_hDbhHelp == NULL)
      return FALSE;
    pSI = (tSI) GetProcAddress(m_hDbhHelp, "SymInitialize" );
    pSC = (tSC) GetProcAddress(m_hDbhHelp, "SymCleanup" );
 
    pSW = (tSW) GetProcAddress(m_hDbhHelp, "StackWalk64" );
    pSGO = (tSGO) GetProcAddress(m_hDbhHelp, "SymGetOptions" );
    pSSO = (tSSO) GetProcAddress(m_hDbhHelp, "SymSetOptions" );
 
    pSFTA = (tSFTA) GetProcAddress(m_hDbhHelp, "SymFunctionTableAccess64" );
    pSGLFA = (tSGLFA) GetProcAddress(m_hDbhHelp, "SymGetLineFromAddr64" );
    pSGMB = (tSGMB) GetProcAddress(m_hDbhHelp, "SymGetModuleBase64" );
    pSGMI = (tSGMI) GetProcAddress(m_hDbhHelp, "SymGetModuleInfo64" );
    //pSGMI_V3 = (tSGMI_V3) GetProcAddress(m_hDbhHelp, "SymGetModuleInfo64" );
    pSGSFA = (tSGSFA) GetProcAddress(m_hDbhHelp, "SymGetSymFromAddr64" );
    pUDSN = (tUDSN) GetProcAddress(m_hDbhHelp, "UnDecorateSymbolName" );
    pSLM = (tSLM) GetProcAddress(m_hDbhHelp, "SymLoadModule64" );
    pSGSP =(tSGSP) GetProcAddress(m_hDbhHelp, "SymGetSearchPath" );
 
    if ( pSC == NULL || pSFTA == NULL || pSGMB == NULL || pSGMI == NULL ||
      pSGO == NULL || pSGSFA == NULL || pSI == NULL || pSSO == NULL ||
      pSW == NULL || pUDSN == NULL || pSLM == NULL )
    {
      FreeLibrary(m_hDbhHelp);
      m_hDbhHelp = NULL;
      pSC = NULL;
      return FALSE;
    }
 
    // SymInitialize
    if (szSymPath != NULL)
      m_szSymPath = _strdup(szSymPath);
    if (this->pSI(m_hProcess, m_szSymPath, FALSE) == FALSE)
      this->m_parent->OnDbgHelpErr("SymInitialize", GetLastError(), 0);
      
    DWORD symOptions = this->pSGO();  // SymGetOptions
    symOptions |= SYMOPT_LOAD_LINES;
    symOptions |= SYMOPT_FAIL_CRITICAL_ERRORS;
    //symOptions |= SYMOPT_NO_PROMPTS;
    // SymSetOptions
    symOptions = this->pSSO(symOptions);
 
    char buf[StackWalker::STACKWALK_MAX_NAMELEN] = {0};
    if (this->pSGSP != NULL)
    {
      if (this->pSGSP(m_hProcess, buf, StackWalker::STACKWALK_MAX_NAMELEN) == FALSE)
        this->m_parent->OnDbgHelpErr("SymGetSearchPath", GetLastError(), 0);
    }
    char szUserName[1024] = {0};
    DWORD dwSize = 1024;
    GetUserNameA(szUserName, &dwSize);
    this->m_parent->OnSymInit(buf, symOptions, szUserName);
 
    return TRUE;
  }
 
  StackWalker *m_parent;
 
  HMODULE m_hDbhHelp;
  HANDLE m_hProcess;
  LPSTR m_szSymPath;
 
/*typedef struct IMAGEHLP_MODULE64_V3 {
    DWORD    SizeOfStruct;           // set to sizeof(IMAGEHLP_MODULE64)
    DWORD64  BaseOfImage;            // base load address of module
    DWORD    ImageSize;              // virtual size of the loaded module
    DWORD    TimeDateStamp;          // date/time stamp from pe header
    DWORD    CheckSum;               // checksum from the pe header
    DWORD    NumSyms;                // number of symbols in the symbol table
    SYM_TYPE SymType;                // type of symbols loaded
    CHAR     ModuleName[32];         // module name
    CHAR     ImageName[256];         // image name
    // new elements: 07-Jun-2002
    CHAR     LoadedImageName[256];   // symbol file name
    CHAR     LoadedPdbName[256];     // pdb file name
    DWORD    CVSig;                  // Signature of the CV record in the debug directories
    CHAR         CVData[MAX_PATH * 3];   // Contents of the CV record
    DWORD    PdbSig;                 // Signature of PDB
    GUID     PdbSig70;               // Signature of PDB (VC 7 and up)
    DWORD    PdbAge;                 // DBI age of pdb
    BOOL     PdbUnmatched;           // loaded an unmatched pdb
    BOOL     DbgUnmatched;           // loaded an unmatched dbg
    BOOL     LineNumbers;            // we have line number information
    BOOL     GlobalSymbols;          // we have internal symbol information
    BOOL     TypeInfo;               // we have type information
    // new elements: 17-Dec-2003
    BOOL     SourceIndexed;          // pdb supports source server
    BOOL     Publics;                // contains public symbols
};
*/
typedef struct IMAGEHLP_MODULE64_V2 {
    DWORD    SizeOfStruct;           // set to sizeof(IMAGEHLP_MODULE64)
    DWORD64  BaseOfImage;            // base load address of module
    DWORD    ImageSize;              // virtual size of the loaded module
    DWORD    TimeDateStamp;          // date/time stamp from pe header
    DWORD    CheckSum;               // checksum from the pe header
    DWORD    NumSyms;                // number of symbols in the symbol table
    SYM_TYPE SymType;                // type of symbols loaded
    CHAR     ModuleName[32];         // module name
    CHAR     ImageName[256];         // image name
    CHAR     LoadedImageName[256];   // symbol file name
};
 
 
  // SymCleanup()
  typedef BOOL (__stdcall *tSC)( IN HANDLE hProcess );
  tSC pSC;
 
  // SymFunctionTableAccess64()
  typedef PVOID (__stdcall *tSFTA)( HANDLE hProcess, DWORD64 AddrBase );
  tSFTA pSFTA;
 
  // SymGetLineFromAddr64()
  typedef BOOL (__stdcall *tSGLFA)( IN HANDLE hProcess, IN DWORD64 dwAddr,
    OUT PDWORD pdwDisplacement, OUT PIMAGEHLP_LINE64 Line );
  tSGLFA pSGLFA;
 
  // SymGetModuleBase64()
  typedef DWORD64 (__stdcall *tSGMB)( IN HANDLE hProcess, IN DWORD64 dwAddr );
  tSGMB pSGMB;
 
  // SymGetModuleInfo64()
  typedef BOOL (__stdcall *tSGMI)( IN HANDLE hProcess, IN DWORD64 dwAddr, OUT IMAGEHLP_MODULE64_V2 *ModuleInfo );
  tSGMI pSGMI;
 
//  // SymGetModuleInfo64()
//  typedef BOOL (__stdcall *tSGMI_V3)( IN HANDLE hProcess, IN DWORD64 dwAddr, OUT IMAGEHLP_MODULE64_V3 *ModuleInfo );
//  tSGMI_V3 pSGMI_V3;
 
  // SymGetOptions()
  typedef DWORD (__stdcall *tSGO)( VOID );
  tSGO pSGO;
 
  // SymGetSymFromAddr64()
  typedef BOOL (__stdcall *tSGSFA)( IN HANDLE hProcess, IN DWORD64 dwAddr,
    OUT PDWORD64 pdwDisplacement, OUT PIMAGEHLP_SYMBOL64 Symbol );
  tSGSFA pSGSFA;
 
  // SymInitialize()
  typedef BOOL (__stdcall *tSI)( IN HANDLE hProcess, IN PSTR UserSearchPath, IN BOOL fInvadeProcess );
  tSI pSI;
 
  // SymLoadModule64()
  typedef DWORD64 (__stdcall *tSLM)( IN HANDLE hProcess, IN HANDLE hFile,
    IN PSTR ImageName, IN PSTR ModuleName, IN DWORD64 BaseOfDll, IN DWORD SizeOfDll );
  tSLM pSLM;
 
  // SymSetOptions()
  typedef DWORD (__stdcall *tSSO)( IN DWORD SymOptions );
  tSSO pSSO;
 
  // StackWalk64()
  typedef BOOL (__stdcall *tSW)( 
    DWORD MachineType, 
    HANDLE hProcess,
    HANDLE hThread, 
    LPSTACKFRAME64 StackFrame, 
    PVOID ContextRecord,
    PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
    PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
    PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
    PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress );
  tSW pSW;
 
  // UnDecorateSymbolName()
  typedef DWORD (__stdcall WINAPI *tUDSN)( PCSTR DecoratedName, PSTR UnDecoratedName,
    DWORD UndecoratedLength, DWORD Flags );
  tUDSN pUDSN;
 
  typedef BOOL (__stdcall WINAPI *tSGSP)(HANDLE hProcess, PSTR SearchPath, DWORD SearchPathLength);
  tSGSP pSGSP;
 
 
private:
  // **************************************** ToolHelp32 ************************
  #define MAX_MODULE_NAME32 255
  #define TH32CS_SNAPMODULE   0x00000008
  #pragma pack( push, 8 )
  typedef struct tagMODULEENTRY32
  {
      DWORD   dwSize;
      DWORD   th32ModuleID;       // This module
      DWORD   th32ProcessID;      // owning process
      DWORD   GlblcntUsage;       // Global usage count on the module
      DWORD   ProccntUsage;       // Module usage count in th32ProcessID's context
      BYTE  * modBaseAddr;        // Base address of module in th32ProcessID's context
      DWORD   modBaseSize;        // Size in bytes of module starting at modBaseAddr
      HMODULE hModule;            // The hModule of this module in th32ProcessID's context
      char    szModule[MAX_MODULE_NAME32 + 1];
      char    szExePath[MAX_PATH];
  } MODULEENTRY32;
  typedef MODULEENTRY32 *  PMODULEENTRY32;
  typedef MODULEENTRY32 *  LPMODULEENTRY32;
  #pragma pack( pop )
 
  BOOL GetModuleListTH32(HANDLE hProcess, DWORD pid)
  {
    // CreateToolhelp32Snapshot()
    typedef HANDLE (__stdcall *tCT32S)(DWORD dwFlags, DWORD th32ProcessID);
    // Module32First()
    typedef BOOL (__stdcall *tM32F)(HANDLE hSnapshot, LPMODULEENTRY32 lpme);
    // Module32Next()
    typedef BOOL (__stdcall *tM32N)(HANDLE hSnapshot, LPMODULEENTRY32 lpme);
 
    // try both dlls...
    const TCHAR *dllname[] = { _T("kernel32.dll"), _T("tlhelp32.dll") };
    HINSTANCE hToolhelp = NULL;
    tCT32S pCT32S = NULL;
    tM32F pM32F = NULL;
    tM32N pM32N = NULL;
 
    HANDLE hSnap;
    MODULEENTRY32 me;
    me.dwSize = sizeof(me);
    BOOL keepGoing;
    size_t i;
 
    for (i = 0; i<(sizeof(dllname) / sizeof(dllname[0])); i++ )
    {
      hToolhelp = LoadLibrary( dllname[i] );
      if (hToolhelp == NULL)
        continue;
      pCT32S = (tCT32S) GetProcAddress(hToolhelp, "CreateToolhelp32Snapshot");
      pM32F = (tM32F) GetProcAddress(hToolhelp, "Module32First");
      pM32N = (tM32N) GetProcAddress(hToolhelp, "Module32Next");
      if ( (pCT32S != NULL) && (pM32F != NULL) && (pM32N != NULL) )
        break; // found the functions!
      FreeLibrary(hToolhelp);
      hToolhelp = NULL;
    }
 
    if (hToolhelp == NULL)
      return FALSE;
 
    hSnap = pCT32S( TH32CS_SNAPMODULE, pid );
    if (hSnap == (HANDLE) -1)
      return FALSE;
 
    keepGoing = !!pM32F( hSnap, &me );
    int cnt = 0;
    while (keepGoing)
    {
      this->LoadModule(hProcess, me.szExePath, me.szModule, (DWORD64) me.modBaseAddr, me.modBaseSize);
      cnt++;
      keepGoing = !!pM32N( hSnap, &me );
    }
    CloseHandle(hSnap);
    FreeLibrary(hToolhelp);
    if (cnt <= 0)
      return FALSE;
    return TRUE;
  }  // GetModuleListTH32
 
  // **************************************** PSAPI ************************
  typedef struct _MODULEINFO {
      LPVOID lpBaseOfDll;
      DWORD SizeOfImage;
      LPVOID EntryPoint;
  } MODULEINFO, *LPMODULEINFO;
 
  BOOL GetModuleListPSAPI(HANDLE hProcess)
  {
    // EnumProcessModules()
    typedef BOOL (__stdcall *tEPM)(HANDLE hProcess, HMODULE *lphModule, DWORD cb, LPDWORD lpcbNeeded );
    // GetModuleFileNameEx()
    typedef DWORD (__stdcall *tGMFNE)(HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize );
    // GetModuleBaseName()
    typedef DWORD (__stdcall *tGMBN)(HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize );
    // GetModuleInformation()
    typedef BOOL (__stdcall *tGMI)(HANDLE hProcess, HMODULE hModule, LPMODULEINFO pmi, DWORD nSize );
 
    HINSTANCE hPsapi;
    tEPM pEPM;
    tGMFNE pGMFNE;
    tGMBN pGMBN;
    tGMI pGMI;
 
    DWORD i;
    //ModuleEntry e;
    DWORD cbNeeded;
    MODULEINFO mi;
    HMODULE *hMods = 0;
    char *tt = NULL;
    char *tt2 = NULL;
    const SIZE_T TTBUFLEN = 8096;
    int cnt = 0;
 
    hPsapi = LoadLibrary( _T("psapi.dll") );
    if (hPsapi == NULL)
      return FALSE;
 
    pEPM = (tEPM) GetProcAddress( hPsapi, "EnumProcessModules" );
    pGMFNE = (tGMFNE) GetProcAddress( hPsapi, "GetModuleFileNameExA" );
    pGMBN = (tGMFNE) GetProcAddress( hPsapi, "GetModuleBaseNameA" );
    pGMI = (tGMI) GetProcAddress( hPsapi, "GetModuleInformation" );
    if ( (pEPM == NULL) || (pGMFNE == NULL) || (pGMBN == NULL) || (pGMI == NULL) )
    {
      // we couldnґt find all functions
      FreeLibrary(hPsapi);
      return FALSE;
    }
 
    hMods = (HMODULE*) malloc(sizeof(HMODULE) * (TTBUFLEN / sizeof HMODULE));
    tt = (char*) malloc(sizeof(char) * TTBUFLEN);
    tt2 = (char*) malloc(sizeof(char) * TTBUFLEN);
    if ( (hMods == NULL) || (tt == NULL) || (tt2 == NULL) )
      goto cleanup;
 
    if ( ! pEPM( hProcess, hMods, TTBUFLEN, &cbNeeded ) )
    {
      //_ftprintf(fLogFile, _T("%lu: EPM failed, GetLastError = %lu\n"), g_dwShowCount, gle );
      goto cleanup;
    }
 
    if ( cbNeeded > TTBUFLEN )
    {
      //_ftprintf(fLogFile, _T("%lu: More than %lu module handles. Huh?\n"), g_dwShowCount, lenof( hMods ) );
      goto cleanup;
    }
 
    for ( i = 0; i < cbNeeded / sizeof hMods[0]; i++ )
    {
      // base address, size
      pGMI(hProcess, hMods[i], &mi, sizeof mi );
      // image file name
      tt[0] = 0;
      pGMFNE(hProcess, hMods[i], tt, TTBUFLEN );
      // module name
      tt2[0] = 0;
      pGMBN(hProcess, hMods[i], tt2, TTBUFLEN );
 
      DWORD dwRes = this->LoadModule(hProcess, tt, tt2, (DWORD64) mi.lpBaseOfDll, mi.SizeOfImage);
      if (dwRes != ERROR_SUCCESS)
        this->m_parent->OnDbgHelpErr("LoadModule", dwRes, 0);
      cnt++;
    }
 
  cleanup:
    if (hPsapi != NULL) FreeLibrary(hPsapi);
    if (tt2 != NULL) free(tt2);
    if (tt != NULL) free(tt);
    if (hMods != NULL) free(hMods);
 
    return cnt != 0;
  }  // GetModuleListPSAPI
 
  DWORD LoadModule(HANDLE hProcess, LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size)
  {
    CHAR *szImg = _strdup(img);
    CHAR *szMod = _strdup(mod);
    DWORD result = ERROR_SUCCESS;
    if ( (szImg == NULL) || (szMod == NULL) )
      result = ERROR_NOT_ENOUGH_MEMORY;
    else
    {
      if (pSLM(hProcess, 0, szImg, szMod, baseAddr, size) == 0)
        result = GetLastError();
    }
    ULONGLONG fileVersion = 0;
    if ( (m_parent != NULL) && (szImg != NULL) )
    {
      // try to retrive the file-version:
      if ( (this->m_parent->m_options & StackWalker::RetrieveFileVersion) != 0)
      {
        VS_FIXEDFILEINFO *fInfo = NULL;
        DWORD dwHandle;
        DWORD dwSize = GetFileVersionInfoSizeA(szImg, &dwHandle);
        if (dwSize > 0)
        {
          LPVOID vData = malloc(dwSize);
          if (vData != NULL)
          {
            if (GetFileVersionInfoA(szImg, dwHandle, dwSize, vData) != 0)
            {
              UINT len;
              TCHAR szSubBlock[] = _T("\\");
              if (VerQueryValue(vData, szSubBlock, (LPVOID*) &fInfo, &len) == 0)
                fInfo = NULL;
              else
              {
                fileVersion = ((ULONGLONG)fInfo->dwFileVersionLS) + ((ULONGLONG)fInfo->dwFileVersionMS << 32);
              }
            }
            free(vData);
          }
        }
      }
 
      // Retrive some additional-infos about the module
      IMAGEHLP_MODULE64_V2 Module;
      const char *szSymType = "-unknown-";
      if (this->GetModuleInfo(hProcess, baseAddr, &Module) != FALSE)
      {
        switch(Module.SymType)
        {
          case SymNone:
            szSymType = "-nosymbols-";
            break;
          case SymCoff:
            szSymType = "COFF";
            break;
          case SymCv:
            szSymType = "CV";
            break;
          case SymPdb:
            szSymType = "PDB";
            break;
          case SymExport:
            szSymType = "-exported-";
            break;
          case SymDeferred:
            szSymType = "-deferred-";
            break;
          case SymSym:
            szSymType = "SYM";
            break;
          case 8: //SymVirtual:
            szSymType = "Virtual";
            break;
          case 9: // SymDia:
            szSymType = "DIA";
            break;
        }
      }
      this->m_parent->OnLoadModule(img, mod, baseAddr, size, result, szSymType, Module.LoadedImageName, fileVersion);
    }
    if (szImg != NULL) free(szImg);
    if (szMod != NULL) free(szMod);
    return result;
  }
public:
  BOOL LoadModules(HANDLE hProcess, DWORD dwProcessId)
  {
    // first try toolhelp32
    if (GetModuleListTH32(hProcess, dwProcessId))
      return true;
    // then try psapi
    return GetModuleListPSAPI(hProcess);
  }
 
 
  BOOL GetModuleInfo(HANDLE hProcess, DWORD64 baseAddr, IMAGEHLP_MODULE64_V2 *pModuleInfo)
  {
    if(this->pSGMI == NULL)
    {
      SetLastError(ERROR_DLL_INIT_FAILED);
      return FALSE;
    }
    // First try to use the larger ModuleInfo-Structure
//    memset(pModuleInfo, 0, sizeof(IMAGEHLP_MODULE64_V3));
//    pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64_V3);
//    if (this->pSGMI_V3 != NULL)
//    {
//      if (this->pSGMI_V3(hProcess, baseAddr, pModuleInfo) != FALSE)
//        return TRUE;
//      // check if the parameter was wrong (size is bad...)
//      if (GetLastError() != ERROR_INVALID_PARAMETER)
//        return FALSE;
//    }
    // could not retrive the bigger structure, try with the smaller one (as defined in VC7.1)...
    pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64_V2);
    void *pData = malloc(4096); // reserve enough memory, so the bug in v6.3.5.1 does not lead to memory-overwrites...
    if (pData == NULL)
    {
      SetLastError(ERROR_NOT_ENOUGH_MEMORY);
      return FALSE;
    }
    memcpy(pData, pModuleInfo, sizeof(IMAGEHLP_MODULE64_V2));
    if (this->pSGMI(hProcess, baseAddr, (IMAGEHLP_MODULE64_V2*) pData) != FALSE)
    {
      // only copy as much memory as is reserved...
      memcpy(pModuleInfo, pData, sizeof(IMAGEHLP_MODULE64_V2));
      pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64_V2);
      free(pData);
      return TRUE;
    }
    free(pData);
    SetLastError(ERROR_DLL_INIT_FAILED);
    return FALSE;
  }
};
 
// #############################################################
StackWalker::StackWalker(DWORD dwProcessId, HANDLE hProcess)
{
  this->m_options = OptionsAll;
  this->m_modulesLoaded = FALSE;
  this->m_hProcess = hProcess;
  this->m_sw = new StackWalkerInternal(this, this->m_hProcess);
  this->m_dwProcessId = dwProcessId;
  this->m_szSymPath = NULL;
}
StackWalker::StackWalker(int options, LPCSTR szSymPath, DWORD dwProcessId, HANDLE hProcess)
{
  this->m_options = options;
  this->m_modulesLoaded = FALSE;
  this->m_hProcess = hProcess;
  this->m_sw = new StackWalkerInternal(this, this->m_hProcess);
  this->m_dwProcessId = dwProcessId;
  if (szSymPath != NULL)
  {
    this->m_szSymPath = _strdup(szSymPath);
    this->m_options |= SymBuildPath;
  }
  else
    this->m_szSymPath = NULL;
}
 
StackWalker::~StackWalker()
{
  if (m_szSymPath != NULL)
    free(m_szSymPath);
  m_szSymPath = NULL;
  if (this->m_sw != NULL)
    delete this->m_sw;
  this->m_sw = NULL;
}
 
BOOL StackWalker::LoadModules()
{
  if (this->m_sw == NULL)
  {
    SetLastError(ERROR_DLL_INIT_FAILED);
    return FALSE;
  }
  if (m_modulesLoaded != FALSE)
    return TRUE;
 
  // Build the sym-path:
  char *szSymPath = NULL;
  if ( (this->m_options & SymBuildPath) != 0)
  {
    const size_t nSymPathLen = 4096;
    szSymPath = (char*) malloc(nSymPathLen);
    if (szSymPath == NULL)
    {
      SetLastError(ERROR_NOT_ENOUGH_MEMORY);
      return FALSE;
    }
    szSymPath[0] = 0;
    // Now first add the (optional) provided sympath:
    if (this->m_szSymPath != NULL)
    {
      strcat_s(szSymPath, nSymPathLen, this->m_szSymPath);
      strcat_s(szSymPath, nSymPathLen, ";");
    }
 
    strcat_s(szSymPath, nSymPathLen, ".;");
 
    const size_t nTempLen = 1024;
    char szTemp[nTempLen];
    // Now add the current directory:
    if (GetCurrentDirectoryA(nTempLen, szTemp) > 0)
    {
      szTemp[nTempLen-1] = 0;
      strcat_s(szSymPath, nSymPathLen, szTemp);
      strcat_s(szSymPath, nSymPathLen, ";");
    }
 
    // Now add the path for the main-module:
    if (GetModuleFileNameA(NULL, szTemp, nTempLen) > 0)
    {
      szTemp[nTempLen-1] = 0;
      for (char *p = (szTemp+strlen(szTemp)-1); p >= szTemp; --p)
      {
        // locate the rightmost path separator
        if ( (*p == '\\') || (*p == '/') || (*p == ':') )
        {
          *p = 0;
          break;
        }
      }  // for (search for path separator...)
      if (szTemp[0]!='\0')
      {
        strcat_s(szSymPath, nSymPathLen, szTemp);
        strcat_s(szSymPath, nSymPathLen, ";");
      }
    }
    if (GetEnvironmentVariableA("_NT_SYMBOL_PATH", szTemp, nTempLen) > 0)
    {
      szTemp[nTempLen-1] = 0;
      strcat_s(szSymPath, nSymPathLen, szTemp);
      strcat_s(szSymPath, nSymPathLen, ";");
    }
    if (GetEnvironmentVariableA("_NT_ALTERNATE_SYMBOL_PATH", szTemp, nTempLen) > 0)
    {
      szTemp[nTempLen-1] = 0;
      strcat_s(szSymPath, nSymPathLen, szTemp);
      strcat_s(szSymPath, nSymPathLen, ";");
    }
    if (GetEnvironmentVariableA("SYSTEMROOT", szTemp, nTempLen) > 0)
    {
      szTemp[nTempLen-1] = 0;
      strcat_s(szSymPath, nSymPathLen, szTemp);
      strcat_s(szSymPath, nSymPathLen, ";");
      // also add the "system32"-directory:
      strcat_s(szTemp, nTempLen, "\\system32");
      strcat_s(szSymPath, nSymPathLen, szTemp);
      strcat_s(szSymPath, nSymPathLen, ";");
    }
 
    if ( (this->m_options & SymBuildPath) != 0)
    {
      if (GetEnvironmentVariableA("SYSTEMDRIVE", szTemp, nTempLen) > 0)
      {
        szTemp[nTempLen-1] = 0;
        strcat_s(szSymPath, nSymPathLen, "SRV*");
        strcat_s(szSymPath, nSymPathLen, szTemp);
        strcat_s(szSymPath, nSymPathLen, "\\websymbols");
        strcat_s(szSymPath, nSymPathLen, "*http://msdl.microsoft.com/download/symbols;");
      }
      else
        strcat_s(szSymPath, nSymPathLen, "SRV*c:\\websymbols*http://msdl.microsoft.com/download/symbols;");
    }
  }
 
  // First Init the whole stuff...
  BOOL bRet = this->m_sw->Init(szSymPath);
  if (szSymPath != NULL) free(szSymPath); szSymPath = NULL;
  if (bRet == FALSE)
  {
    this->OnDbgHelpErr("Error while initializing dbghelp.dll", 0, 0);
    SetLastError(ERROR_DLL_INIT_FAILED);
    return FALSE;
  }
 
  bRet = this->m_sw->LoadModules(this->m_hProcess, this->m_dwProcessId);
  if (bRet != FALSE)
    m_modulesLoaded = TRUE;
  return bRet;
}
 
 
// The following is used to pass the "userData"-Pointer to the user-provided readMemoryFunction
// This has to be done due to a problem with the "hProcess"-parameter in x64...
// Because this class is in no case multi-threading-enabled (because of the limitations 
// of dbghelp.dll) it is "safe" to use a static-variable
static StackWalker::PReadProcessMemoryRoutine s_readMemoryFunction = NULL;
static LPVOID s_readMemoryFunction_UserData = NULL;
 
BOOL StackWalker::ShowCallstack(HANDLE hThread, const CONTEXT *context, PReadProcessMemoryRoutine readMemoryFunction, LPVOID pUserData)
{
  CONTEXT c;;
  CallstackEntry csEntry;
  IMAGEHLP_SYMBOL64 *pSym = NULL;
  StackWalkerInternal::IMAGEHLP_MODULE64_V2 Module;
  IMAGEHLP_LINE64 Line;
  int frameNum;
 
  if (m_modulesLoaded == FALSE)
    this->LoadModules();  // ignore the result...
 
  if (this->m_sw->m_hDbhHelp == NULL)
  {
    SetLastError(ERROR_DLL_INIT_FAILED);
    return FALSE;
  }
 
  m_StackDepth = 0;
 
  s_readMemoryFunction = readMemoryFunction;
  s_readMemoryFunction_UserData = pUserData;
 
  if (context == NULL)
  {
    // If no context is provided, capture the context
    if (hThread == GetCurrentThread())
    {
      GET_CURRENT_CONTEXT(c, USED_CONTEXT_FLAGS);
    }
    else
    {
      SuspendThread(hThread);
      memset(&c, 0, sizeof(CONTEXT));
      c.ContextFlags = USED_CONTEXT_FLAGS;
      if (GetThreadContext(hThread, &c) == FALSE)
      {
        ResumeThread(hThread);
        return FALSE;
      }
    }
  }
  else
    c = *context;
 
  // init STACKFRAME for first call
  STACKFRAME64 s; // in/out stackframe
  memset(&s, 0, sizeof(s));
  DWORD imageType;
#ifdef _M_IX86
  // normally, call ImageNtHeader() and use machine info from PE header
  imageType = IMAGE_FILE_MACHINE_I386;
  s.AddrPC.Offset = c.Eip;
  s.AddrPC.Mode = AddrModeFlat;
  s.AddrFrame.Offset = c.Ebp;
  s.AddrFrame.Mode = AddrModeFlat;
  s.AddrStack.Offset = c.Esp;
  s.AddrStack.Mode = AddrModeFlat;
#elif _M_X64
  imageType = IMAGE_FILE_MACHINE_AMD64;
  s.AddrPC.Offset = c.Rip;
  s.AddrPC.Mode = AddrModeFlat;
  s.AddrFrame.Offset = c.Rsp;
  s.AddrFrame.Mode = AddrModeFlat;
  s.AddrStack.Offset = c.Rsp;
  s.AddrStack.Mode = AddrModeFlat;
#elif _M_IA64
  imageType = IMAGE_FILE_MACHINE_IA64;
  s.AddrPC.Offset = c.StIIP;
  s.AddrPC.Mode = AddrModeFlat;
  s.AddrFrame.Offset = c.IntSp;
  s.AddrFrame.Mode = AddrModeFlat;
  s.AddrBStore.Offset = c.RsBSP;
  s.AddrBStore.Mode = AddrModeFlat;
  s.AddrStack.Offset = c.IntSp;
  s.AddrStack.Mode = AddrModeFlat;
#else
#error "Platform not supported!"
#endif
 
  pSym = (IMAGEHLP_SYMBOL64 *) malloc(sizeof(IMAGEHLP_SYMBOL64) + STACKWALK_MAX_NAMELEN);
  if (!pSym) goto cleanup;  // not enough memory...
  memset(pSym, 0, sizeof(IMAGEHLP_SYMBOL64) + STACKWALK_MAX_NAMELEN);
  pSym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
  pSym->MaxNameLength = STACKWALK_MAX_NAMELEN;
 
  memset(&Line, 0, sizeof(Line));
  Line.SizeOfStruct = sizeof(Line);
 
  memset(&Module, 0, sizeof(Module));
  Module.SizeOfStruct = sizeof(Module);
 
  for (frameNum = 0; ; ++frameNum )
  {
    // get next stack frame (StackWalk64(), SymFunctionTableAccess64(), SymGetModuleBase64())
    // if this returns ERROR_INVALID_ADDRESS (487) or ERROR_NOACCESS (998), you can
    // assume that either you are done, or that the stack is so hosed that the next
    // deeper frame could not be found.
    // CONTEXT need not to be suplied if imageTyp is IMAGE_FILE_MACHINE_I386!
    if ( ! this->m_sw->pSW(imageType, this->m_hProcess, hThread, &s, &c, myReadProcMem, this->m_sw->pSFTA, this->m_sw->pSGMB, NULL) )
    {
      this->OnDbgHelpErr("StackWalk64", GetLastError(), s.AddrPC.Offset);
      break;
    }
 
    csEntry.offset = s.AddrPC.Offset;
    csEntry.name[0] = 0;
    csEntry.undName[0] = 0;
    csEntry.undFullName[0] = 0;
    csEntry.offsetFromSmybol = 0;
    csEntry.offsetFromLine = 0;
    csEntry.lineFileName[0] = 0;
    csEntry.lineNumber = 0;
    csEntry.loadedImageName[0] = 0;
    csEntry.moduleName[0] = 0;
    if (s.AddrPC.Offset == s.AddrReturn.Offset)
    {
      this->OnDbgHelpErr("StackWalk64-Endless-Callstack!", 0, s.AddrPC.Offset);
      break;
    }
    if (s.AddrPC.Offset != 0)
    {
      // we seem to have a valid PC
      // show procedure info (SymGetSymFromAddr64())
      if (this->m_sw->pSGSFA(this->m_hProcess, s.AddrPC.Offset, &(csEntry.offsetFromSmybol), pSym) != FALSE)
      {
        // TODO: Mache dies sicher...!
        strcpy_s(csEntry.name, pSym->Name);
        // UnDecorateSymbolName()
        this->m_sw->pUDSN( pSym->Name, csEntry.undName, STACKWALK_MAX_NAMELEN, UNDNAME_NAME_ONLY );
        this->m_sw->pUDSN( pSym->Name, csEntry.undFullName, STACKWALK_MAX_NAMELEN, UNDNAME_COMPLETE );
      }
      else
      {
        this->OnDbgHelpErr("SymGetSymFromAddr64", GetLastError(), s.AddrPC.Offset);
      }
 
      // show line number info, NT5.0-method (SymGetLineFromAddr64())
      if (this->m_sw->pSGLFA != NULL )
      { // yes, we have SymGetLineFromAddr64()
        if (this->m_sw->pSGLFA(this->m_hProcess, s.AddrPC.Offset, &(csEntry.offsetFromLine), &Line) != FALSE)
        {
          csEntry.lineNumber = Line.LineNumber;
          // TODO: Mache dies sicher...!
          strcpy_s(csEntry.lineFileName, Line.FileName);
        }
        else
        {
          this->OnDbgHelpErr("SymGetLineFromAddr64", GetLastError(), s.AddrPC.Offset);
        }
      } // yes, we have SymGetLineFromAddr64()
 
      // show module info (SymGetModuleInfo64())
      if (this->m_sw->GetModuleInfo(this->m_hProcess, s.AddrPC.Offset, &Module ) != FALSE)
      { // got module info OK
        switch ( Module.SymType )
        {
        case SymNone:
          csEntry.symTypeString = "-nosymbols-";
          break;
        case SymCoff:
          csEntry.symTypeString = "COFF";
          break;
        case SymCv:
          csEntry.symTypeString = "CV";
          break;
        case SymPdb:
          csEntry.symTypeString = "PDB";
          break;
        case SymExport:
          csEntry.symTypeString = "-exported-";
          break;
        case SymDeferred:
          csEntry.symTypeString = "-deferred-";
          break;
        case SymSym:
          csEntry.symTypeString = "SYM";
          break;
#if API_VERSION_NUMBER >= 9
        case SymDia:
          csEntry.symTypeString = "DIA";
          break;
#endif
        case 8: //SymVirtual:
          csEntry.symTypeString = "Virtual";
          break;
        default:
          //_snprintf( ty, sizeof ty, "symtype=%ld", (long) Module.SymType );
          csEntry.symTypeString = NULL;
          break;
        }
 
        // TODO: Mache dies sicher...!
        strcpy_s(csEntry.moduleName, Module.ModuleName);
        csEntry.baseOfImage = Module.BaseOfImage;
        strcpy_s(csEntry.loadedImageName, Module.LoadedImageName);
      } // got module info OK
      else
      {
        this->OnDbgHelpErr("SymGetModuleInfo64", GetLastError(), s.AddrPC.Offset);
      }
    } // we seem to have a valid PC
 
    CallstackEntryType et = nextEntry;
    if (frameNum == 0)
      et = firstEntry;
    this->OnCallstackEntry(et, csEntry);
    m_StackDepth++;
    
    if (s.AddrReturn.Offset == 0)
    {
      this->OnCallstackEntry(lastEntry, csEntry);
      SetLastError(ERROR_SUCCESS);
      break;
    }
  } // for ( frameNum )
 
  cleanup:
    if (pSym) free( pSym );
 
  if (context == NULL)
    ResumeThread(hThread);
 
  return TRUE;
}
 
BOOL __stdcall StackWalker::myReadProcMem(
    HANDLE      hProcess,
    DWORD64     qwBaseAddress,
    PVOID       lpBuffer,
    DWORD       nSize,
    LPDWORD     lpNumberOfBytesRead
    )
{
  if (s_readMemoryFunction == NULL)
  {
    SIZE_T st;
    BOOL bRet = ReadProcessMemory(hProcess, (LPVOID) qwBaseAddress, lpBuffer, nSize, &st);
    *lpNumberOfBytesRead = (DWORD) st;
    //printf("ReadMemory: hProcess: %p, baseAddr: %p, buffer: %p, size: %d, read: %d, result: %d\n", hProcess, (LPVOID) qwBaseAddress, lpBuffer, nSize, (DWORD) st, (DWORD) bRet);
    return bRet;
  }
  else
  {
    return s_readMemoryFunction(hProcess, qwBaseAddress, lpBuffer, nSize, lpNumberOfBytesRead, s_readMemoryFunction_UserData);
  }
}
 
void StackWalker::OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion)
{
  CHAR buffer[STACKWALK_MAX_NAMELEN];
  if (fileVersion == 0)
    _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "%s:%s (%p), size: %d (result: %d), SymType: '%s', PDB: '%s'\n", img, mod, (LPVOID) baseAddr, size, result, symType, pdbName);
  else
  {
    DWORD v4 = (DWORD) fileVersion & 0xFFFF;
    DWORD v3 = (DWORD) (fileVersion>>16) & 0xFFFF;
    DWORD v2 = (DWORD) (fileVersion>>32) & 0xFFFF;
    DWORD v1 = (DWORD) (fileVersion>>48) & 0xFFFF;
    _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "%s:%s (%p), size: %d (result: %d), SymType: '%s', PDB: '%s', fileVersion: %d.%d.%d.%d\n", img, mod, (LPVOID) baseAddr, size, result, symType, pdbName, v1, v2, v3, v4);
  }
  OnOutput(buffer);
}
 
void StackWalker::OnCallstackEntry(CallstackEntryType eType, CallstackEntry &entry)
{
  // skip ignored calls stack frame
  if(m_StackDepth <= m_IgnoreDepth)
    return;
 
  CHAR buffer[STACKWALK_MAX_NAMELEN];
  if ( (eType != lastEntry) && (entry.offset != 0) )
  {
    if (entry.name[0] == 0)
      sprintf_s(entry.name, sizeof(entry.name), "0x%08X", (unsigned int)entry.offset); // convert to uint32_t, as our callstack cannot really have 64bit addresses
    if (entry.undName[0] != 0)
      strcpy_s(entry.name, entry.undName);
    if (entry.undFullName[0] != 0)
      strcpy_s(entry.name, entry.undFullName);
 
    if(entry.lineFileName[0] == 0) 
      _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "%s!%s\n", entry.moduleName, entry.name);
    else
      _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "%s!%s (%s:%d)\n", entry.moduleName, entry.name, entry.lineFileName, entry.lineNumber);
 
    OnOutput(buffer);
  }
}
 
void StackWalker::OnDbgHelpErr(LPCSTR szFuncName, DWORD gle, DWORD64 addr)
{
  CHAR buffer[STACKWALK_MAX_NAMELEN];
  _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "ERROR: %s, GetLastError: %d (Address: %p)\n", szFuncName, gle, (LPVOID) addr);
  OnOutput(buffer);
}
 
void StackWalker::OnSymInit(LPCSTR szSearchPath, DWORD symOptions, LPCSTR szUserName)
{
  CHAR buffer[STACKWALK_MAX_NAMELEN];
  _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "SymInit: Symbol-SearchPath: '%s', symOptions: %d, UserName: '%s'\n", szSearchPath, symOptions, szUserName);
  OnOutput(buffer);
  // Also display the OS-version
#if _MSC_VER <= 1200
  OSVERSIONINFOA ver;
  ZeroMemory(&ver, sizeof(OSVERSIONINFOA));
  ver.dwOSVersionInfoSize = sizeof(ver);
  if (GetVersionExA(&ver) != FALSE)
  {
    _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "OS-Version: %d.%d.%d (%s)\n", 
      ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber,
      ver.szCSDVersion);
    OnOutput(buffer);
  }
#else
  OSVERSIONINFOEXA ver;
  ZeroMemory(&ver, sizeof(OSVERSIONINFOEXA));
  ver.dwOSVersionInfoSize = sizeof(ver);
  if (GetVersionExA( (OSVERSIONINFOA*) &ver) != FALSE)
  {
    _snprintf_s(buffer, STACKWALK_MAX_NAMELEN, "OS-Version: %d.%d.%d (%s) 0x%x-0x%x\n", 
      ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber,
      ver.szCSDVersion, ver.wSuiteMask, ver.wProductType);
    OnOutput(buffer);
  }
#endif
}
 
void StackWalker::OnOutput(LPCSTR buffer)
{
  OutputDebugStringA(buffer);
}

Первая winmain.cpp
Вторая StackWalker.cpp
mustimur
268 / 222 / 57
Регистрация: 22.11.2013
Сообщений: 832
Записей в блоге: 1
18.01.2014, 21:50     Ошибка LNK2019 #4
У меня такое было: причина возможная ошибок - отличие платформы (Win32/x64) или типов и набора переменных функции библиотеки (описанных в файле .lib) и объявленных в твоем коде.
Даже если ты библиотеку писал сам и перекомпилировал, то тут может следующая проблема быть: lib файл остался у нее старый (по дате посмотри, он возможно до последний компиляции). У меня в VS2012 так было: решал удалением его перед компиляцией.
Yandex
Объявления
18.01.2014, 21:50     Ошибка LNK2019
Ответ Создать тему
Опции темы

Текущее время: 15:01. Часовой пояс GMT +3.
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin® Version 3.8.9
Copyright ©2000 - 2017, vBulletin Solutions, Inc.
Рейтинг@Mail.ru