OpenTTD Source  1.11.0-beta1
crashlog_win.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
10 #include "../../stdafx.h"
11 #include "../../crashlog.h"
12 #include "win32.h"
13 #include "../../core/alloc_func.hpp"
14 #include "../../core/math_func.hpp"
15 #include "../../string_func.h"
16 #include "../../fileio_func.h"
17 #include "../../strings_func.h"
18 #include "../../gamelog.h"
19 #include "../../saveload/saveload.h"
20 #include "../../video/video_driver.hpp"
21 
22 #include <windows.h>
23 #include <signal.h>
24 
25 #include "../../safeguards.h"
26 
27 /* printf format specification for 32/64-bit addresses. */
28 #ifdef _M_AMD64
29 #define PRINTF_PTR "0x%016IX"
30 #else
31 #define PRINTF_PTR "0x%08X"
32 #endif
33 
37 class CrashLogWindows : public CrashLog {
39  EXCEPTION_POINTERS *ep;
40 
41  char *LogOSVersion(char *buffer, const char *last) const override;
42  char *LogError(char *buffer, const char *last, const char *message) const override;
43  char *LogStacktrace(char *buffer, const char *last) const override;
44  char *LogRegisters(char *buffer, const char *last) const override;
45  char *LogModules(char *buffer, const char *last) const override;
46 public:
47 #if defined(_MSC_VER)
48  int WriteCrashDump(char *filename, const char *filename_last) const override;
49  char *AppendDecodedStacktrace(char *buffer, const char *last) const;
50 #else
51  char *AppendDecodedStacktrace(char *buffer, const char *last) const { return buffer; }
52 #endif /* _MSC_VER */
53 
55  char crashlog[65536];
57  char crashlog_filename[MAX_PATH];
59  char crashdump_filename[MAX_PATH];
61  char screenshot_filename[MAX_PATH];
62 
67  CrashLogWindows(EXCEPTION_POINTERS *ep = nullptr) :
68  ep(ep)
69  {
70  this->crashlog[0] = '\0';
71  this->crashlog_filename[0] = '\0';
72  this->crashdump_filename[0] = '\0';
73  this->screenshot_filename[0] = '\0';
74  }
75 
80 };
81 
82 /* static */ CrashLogWindows *CrashLogWindows::current = nullptr;
83 
84 /* virtual */ char *CrashLogWindows::LogOSVersion(char *buffer, const char *last) const
85 {
86  _OSVERSIONINFOA os;
87  os.dwOSVersionInfoSize = sizeof(os);
88  GetVersionExA(&os);
89 
90  return buffer + seprintf(buffer, last,
91  "Operating system:\n"
92  " Name: Windows\n"
93  " Release: %d.%d.%d (%s)\n",
94  (int)os.dwMajorVersion,
95  (int)os.dwMinorVersion,
96  (int)os.dwBuildNumber,
97  os.szCSDVersion
98  );
99 
100 }
101 
102 /* virtual */ char *CrashLogWindows::LogError(char *buffer, const char *last, const char *message) const
103 {
104  return buffer + seprintf(buffer, last,
105  "Crash reason:\n"
106  " Exception: %.8X\n"
107 #ifdef _M_AMD64
108  " Location: %.16IX\n"
109 #else
110  " Location: %.8X\n"
111 #endif
112  " Message: %s\n\n",
113  (int)ep->ExceptionRecord->ExceptionCode,
114  (size_t)ep->ExceptionRecord->ExceptionAddress,
115  message == nullptr ? "<none>" : message
116  );
117 }
118 
120  uint32 size;
121  uint32 crc32;
122  SYSTEMTIME file_time;
123 };
124 
125 static uint32 *_crc_table;
126 
127 static void MakeCRCTable(uint32 *table)
128 {
129  uint32 crc, poly = 0xEDB88320L;
130  int i;
131  int j;
132 
133  _crc_table = table;
134 
135  for (i = 0; i != 256; i++) {
136  crc = i;
137  for (j = 8; j != 0; j--) {
138  crc = (crc & 1 ? (crc >> 1) ^ poly : crc >> 1);
139  }
140  table[i] = crc;
141  }
142 }
143 
144 static uint32 CalcCRC(byte *data, uint size, uint32 crc)
145 {
146  for (; size > 0; size--) {
147  crc = ((crc >> 8) & 0x00FFFFFF) ^ _crc_table[(crc ^ *data++) & 0xFF];
148  }
149  return crc;
150 }
151 
152 static void GetFileInfo(DebugFileInfo *dfi, const TCHAR *filename)
153 {
154  HANDLE file;
155  memset(dfi, 0, sizeof(*dfi));
156 
157  file = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, 0);
158  if (file != INVALID_HANDLE_VALUE) {
159  byte buffer[1024];
160  DWORD numread;
161  uint32 filesize = 0;
162  FILETIME write_time;
163  uint32 crc = (uint32)-1;
164 
165  for (;;) {
166  if (ReadFile(file, buffer, sizeof(buffer), &numread, nullptr) == 0 || numread == 0) {
167  break;
168  }
169  filesize += numread;
170  crc = CalcCRC(buffer, numread, crc);
171  }
172  dfi->size = filesize;
173  dfi->crc32 = crc ^ (uint32)-1;
174 
175  if (GetFileTime(file, nullptr, nullptr, &write_time)) {
176  FileTimeToSystemTime(&write_time, &dfi->file_time);
177  }
178  CloseHandle(file);
179  }
180 }
181 
182 
183 static char *PrintModuleInfo(char *output, const char *last, HMODULE mod)
184 {
185  TCHAR buffer[MAX_PATH];
186  DebugFileInfo dfi;
187 
188  GetModuleFileName(mod, buffer, MAX_PATH);
189  GetFileInfo(&dfi, buffer);
190  output += seprintf(output, last, " %-20s handle: %p size: %d crc: %.8X date: %d-%.2d-%.2d %.2d:%.2d:%.2d\n",
191  FS2OTTD(buffer),
192  mod,
193  dfi.size,
194  dfi.crc32,
195  dfi.file_time.wYear,
196  dfi.file_time.wMonth,
197  dfi.file_time.wDay,
198  dfi.file_time.wHour,
199  dfi.file_time.wMinute,
200  dfi.file_time.wSecond
201  );
202  return output;
203 }
204 
205 /* virtual */ char *CrashLogWindows::LogModules(char *output, const char *last) const
206 {
207  MakeCRCTable(AllocaM(uint32, 256));
208  BOOL (WINAPI *EnumProcessModules)(HANDLE, HMODULE*, DWORD, LPDWORD);
209 
210  output += seprintf(output, last, "Module information:\n");
211 
212  if (LoadLibraryList((Function*)&EnumProcessModules, "psapi.dll\0EnumProcessModules\0\0")) {
213  HMODULE modules[100];
214  DWORD needed;
215  BOOL res;
216 
217  HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());
218  if (proc != nullptr) {
219  res = EnumProcessModules(proc, modules, sizeof(modules), &needed);
220  CloseHandle(proc);
221  if (res) {
222  size_t count = std::min<DWORD>(needed / sizeof(HMODULE), lengthof(modules));
223 
224  for (size_t i = 0; i != count; i++) output = PrintModuleInfo(output, last, modules[i]);
225  return output + seprintf(output, last, "\n");
226  }
227  }
228  }
229  output = PrintModuleInfo(output, last, nullptr);
230  return output + seprintf(output, last, "\n");
231 }
232 
233 /* virtual */ char *CrashLogWindows::LogRegisters(char *buffer, const char *last) const
234 {
235  buffer += seprintf(buffer, last, "Registers:\n");
236 #ifdef _M_AMD64
237  buffer += seprintf(buffer, last,
238  " RAX: %.16I64X RBX: %.16I64X RCX: %.16I64X RDX: %.16I64X\n"
239  " RSI: %.16I64X RDI: %.16I64X RBP: %.16I64X RSP: %.16I64X\n"
240  " R8: %.16I64X R9: %.16I64X R10: %.16I64X R11: %.16I64X\n"
241  " R12: %.16I64X R13: %.16I64X R14: %.16I64X R15: %.16I64X\n"
242  " RIP: %.16I64X EFLAGS: %.8lX\n",
243  ep->ContextRecord->Rax,
244  ep->ContextRecord->Rbx,
245  ep->ContextRecord->Rcx,
246  ep->ContextRecord->Rdx,
247  ep->ContextRecord->Rsi,
248  ep->ContextRecord->Rdi,
249  ep->ContextRecord->Rbp,
250  ep->ContextRecord->Rsp,
251  ep->ContextRecord->R8,
252  ep->ContextRecord->R9,
253  ep->ContextRecord->R10,
254  ep->ContextRecord->R11,
255  ep->ContextRecord->R12,
256  ep->ContextRecord->R13,
257  ep->ContextRecord->R14,
258  ep->ContextRecord->R15,
259  ep->ContextRecord->Rip,
260  ep->ContextRecord->EFlags
261  );
262 #elif defined(_M_IX86)
263  buffer += seprintf(buffer, last,
264  " EAX: %.8X EBX: %.8X ECX: %.8X EDX: %.8X\n"
265  " ESI: %.8X EDI: %.8X EBP: %.8X ESP: %.8X\n"
266  " EIP: %.8X EFLAGS: %.8X\n",
267  (int)ep->ContextRecord->Eax,
268  (int)ep->ContextRecord->Ebx,
269  (int)ep->ContextRecord->Ecx,
270  (int)ep->ContextRecord->Edx,
271  (int)ep->ContextRecord->Esi,
272  (int)ep->ContextRecord->Edi,
273  (int)ep->ContextRecord->Ebp,
274  (int)ep->ContextRecord->Esp,
275  (int)ep->ContextRecord->Eip,
276  (int)ep->ContextRecord->EFlags
277  );
278 #elif defined(_M_ARM64)
279  buffer += seprintf(buffer, last,
280  " X0: %.16I64X X1: %.16I64X X2: %.16I64X X3: %.16I64X\n"
281  " X4: %.16I64X X5: %.16I64X X6: %.16I64X X7: %.16I64X\n"
282  " X8: %.16I64X X9: %.16I64X X10: %.16I64X X11: %.16I64X\n"
283  " X12: %.16I64X X13: %.16I64X X14: %.16I64X X15: %.16I64X\n"
284  " X16: %.16I64X X17: %.16I64X X18: %.16I64X X19: %.16I64X\n"
285  " X20: %.16I64X X21: %.16I64X X22: %.16I64X X23: %.16I64X\n"
286  " X24: %.16I64X X25: %.16I64X X26: %.16I64X X27: %.16I64X\n"
287  " X28: %.16I64X Fp: %.16I64X Lr: %.16I64X\n",
288  ep->ContextRecord->X0,
289  ep->ContextRecord->X1,
290  ep->ContextRecord->X2,
291  ep->ContextRecord->X3,
292  ep->ContextRecord->X4,
293  ep->ContextRecord->X5,
294  ep->ContextRecord->X6,
295  ep->ContextRecord->X7,
296  ep->ContextRecord->X8,
297  ep->ContextRecord->X9,
298  ep->ContextRecord->X10,
299  ep->ContextRecord->X11,
300  ep->ContextRecord->X12,
301  ep->ContextRecord->X13,
302  ep->ContextRecord->X14,
303  ep->ContextRecord->X15,
304  ep->ContextRecord->X16,
305  ep->ContextRecord->X17,
306  ep->ContextRecord->X18,
307  ep->ContextRecord->X19,
308  ep->ContextRecord->X20,
309  ep->ContextRecord->X21,
310  ep->ContextRecord->X22,
311  ep->ContextRecord->X23,
312  ep->ContextRecord->X24,
313  ep->ContextRecord->X25,
314  ep->ContextRecord->X26,
315  ep->ContextRecord->X27,
316  ep->ContextRecord->X28,
317  ep->ContextRecord->Fp,
318  ep->ContextRecord->Lr
319  );
320 #endif
321 
322  buffer += seprintf(buffer, last, "\n Bytes at instruction pointer:\n");
323 #ifdef _M_AMD64
324  byte *b = (byte*)ep->ContextRecord->Rip;
325 #elif defined(_M_IX86)
326  byte *b = (byte*)ep->ContextRecord->Eip;
327 #elif defined(_M_ARM64)
328  byte *b = (byte*)ep->ContextRecord->Pc;
329 #endif
330  for (int i = 0; i != 24; i++) {
331  if (IsBadReadPtr(b, 1)) {
332  buffer += seprintf(buffer, last, " ??"); // OCR: WAS: , 0);
333  } else {
334  buffer += seprintf(buffer, last, " %.2X", *b);
335  }
336  b++;
337  }
338  return buffer + seprintf(buffer, last, "\n\n");
339 }
340 
341 /* virtual */ char *CrashLogWindows::LogStacktrace(char *buffer, const char *last) const
342 {
343  buffer += seprintf(buffer, last, "Stack trace:\n");
344 #ifdef _M_AMD64
345  uint32 *b = (uint32*)ep->ContextRecord->Rsp;
346 #elif defined(_M_IX86)
347  uint32 *b = (uint32*)ep->ContextRecord->Esp;
348 #elif defined(_M_ARM64)
349  uint32 *b = (uint32*)ep->ContextRecord->Sp;
350 #endif
351  for (int j = 0; j != 24; j++) {
352  for (int i = 0; i != 8; i++) {
353  if (IsBadReadPtr(b, sizeof(uint32))) {
354  buffer += seprintf(buffer, last, " ????????"); // OCR: WAS - , 0);
355  } else {
356  buffer += seprintf(buffer, last, " %.8X", *b);
357  }
358  b++;
359  }
360  buffer += seprintf(buffer, last, "\n");
361  }
362  return buffer + seprintf(buffer, last, "\n");
363 }
364 
365 #if defined(_MSC_VER)
366 static const uint MAX_SYMBOL_LEN = 512;
367 static const uint MAX_FRAMES = 64;
368 
369 #pragma warning(disable:4091)
370 #include <dbghelp.h>
371 #pragma warning(default:4091)
372 
373 char *CrashLogWindows::AppendDecodedStacktrace(char *buffer, const char *last) const
374 {
375 #define M(x) x "\0"
376  static const char dbg_import[] =
377  M("dbghelp.dll")
378  M("SymInitialize")
379  M("SymSetOptions")
380  M("SymCleanup")
381  M("StackWalk64")
382  M("SymFunctionTableAccess64")
383  M("SymGetModuleBase64")
384  M("SymGetModuleInfo64")
385  M("SymGetSymFromAddr64")
386  M("SymGetLineFromAddr64")
387  M("")
388  ;
389 #undef M
390 
391  struct ProcPtrs {
392  BOOL (WINAPI * pSymInitialize)(HANDLE, PCSTR, BOOL);
393  BOOL (WINAPI * pSymSetOptions)(DWORD);
394  BOOL (WINAPI * pSymCleanup)(HANDLE);
395  BOOL (WINAPI * pStackWalk64)(DWORD, HANDLE, HANDLE, LPSTACKFRAME64, PVOID, PREAD_PROCESS_MEMORY_ROUTINE64, PFUNCTION_TABLE_ACCESS_ROUTINE64, PGET_MODULE_BASE_ROUTINE64, PTRANSLATE_ADDRESS_ROUTINE64);
396  PVOID (WINAPI * pSymFunctionTableAccess64)(HANDLE, DWORD64);
397  DWORD64 (WINAPI * pSymGetModuleBase64)(HANDLE, DWORD64);
398  BOOL (WINAPI * pSymGetModuleInfo64)(HANDLE, DWORD64, PIMAGEHLP_MODULE64);
399  BOOL (WINAPI * pSymGetSymFromAddr64)(HANDLE, DWORD64, PDWORD64, PIMAGEHLP_SYMBOL64);
400  BOOL (WINAPI * pSymGetLineFromAddr64)(HANDLE, DWORD64, PDWORD, PIMAGEHLP_LINE64);
401  } proc;
402 
403  buffer += seprintf(buffer, last, "\nDecoded stack trace:\n");
404 
405  /* Try to load the functions from the DLL, if that fails because of a too old dbghelp.dll, just skip it. */
406  if (LoadLibraryList((Function*)&proc, dbg_import)) {
407  /* Initialize symbol handler. */
408  HANDLE hCur = GetCurrentProcess();
409  proc.pSymInitialize(hCur, nullptr, TRUE);
410  /* Load symbols only when needed, fail silently on errors, demangle symbol names. */
411  proc.pSymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_FAIL_CRITICAL_ERRORS | SYMOPT_UNDNAME);
412 
413  /* Initialize starting stack frame from context record. */
414  STACKFRAME64 frame;
415  memset(&frame, 0, sizeof(frame));
416 #ifdef _M_AMD64
417  frame.AddrPC.Offset = ep->ContextRecord->Rip;
418  frame.AddrFrame.Offset = ep->ContextRecord->Rbp;
419  frame.AddrStack.Offset = ep->ContextRecord->Rsp;
420 #elif defined(_M_IX86)
421  frame.AddrPC.Offset = ep->ContextRecord->Eip;
422  frame.AddrFrame.Offset = ep->ContextRecord->Ebp;
423  frame.AddrStack.Offset = ep->ContextRecord->Esp;
424 #elif defined(_M_ARM64)
425  frame.AddrPC.Offset = ep->ContextRecord->Pc;
426  frame.AddrFrame.Offset = ep->ContextRecord->Fp;
427  frame.AddrStack.Offset = ep->ContextRecord->Sp;
428 #endif
429  frame.AddrPC.Mode = AddrModeFlat;
430  frame.AddrFrame.Mode = AddrModeFlat;
431  frame.AddrStack.Mode = AddrModeFlat;
432 
433  /* Copy context record as StackWalk64 may modify it. */
434  CONTEXT ctx;
435  memcpy(&ctx, ep->ContextRecord, sizeof(ctx));
436 
437  /* Allocate space for symbol info. */
438  IMAGEHLP_SYMBOL64 *sym_info = (IMAGEHLP_SYMBOL64*)alloca(sizeof(IMAGEHLP_SYMBOL64) + MAX_SYMBOL_LEN - 1);
439  sym_info->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
440  sym_info->MaxNameLength = MAX_SYMBOL_LEN;
441 
442  /* Walk stack at most MAX_FRAMES deep in case the stack is corrupt. */
443  for (uint num = 0; num < MAX_FRAMES; num++) {
444  if (!proc.pStackWalk64(
445 #ifdef _M_AMD64
446  IMAGE_FILE_MACHINE_AMD64,
447 #else
448  IMAGE_FILE_MACHINE_I386,
449 #endif
450  hCur, GetCurrentThread(), &frame, &ctx, nullptr, proc.pSymFunctionTableAccess64, proc.pSymGetModuleBase64, nullptr)) break;
451 
452  if (frame.AddrPC.Offset == frame.AddrReturn.Offset) {
453  buffer += seprintf(buffer, last, " <infinite loop>\n");
454  break;
455  }
456 
457  /* Get module name. */
458  const char *mod_name = "???";
459 
460  IMAGEHLP_MODULE64 module;
461  module.SizeOfStruct = sizeof(module);
462  if (proc.pSymGetModuleInfo64(hCur, frame.AddrPC.Offset, &module)) {
463  mod_name = module.ModuleName;
464  }
465 
466  /* Print module and instruction pointer. */
467  buffer += seprintf(buffer, last, "[%02d] %-20s " PRINTF_PTR, num, mod_name, frame.AddrPC.Offset);
468 
469  /* Get symbol name and line info if possible. */
470  DWORD64 offset;
471  if (proc.pSymGetSymFromAddr64(hCur, frame.AddrPC.Offset, &offset, sym_info)) {
472  buffer += seprintf(buffer, last, " %s + %I64u", sym_info->Name, offset);
473 
474  DWORD line_offs;
475  IMAGEHLP_LINE64 line;
476  line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
477  if (proc.pSymGetLineFromAddr64(hCur, frame.AddrPC.Offset, &line_offs, &line)) {
478  buffer += seprintf(buffer, last, " (%s:%d)", line.FileName, line.LineNumber);
479  }
480  }
481  buffer += seprintf(buffer, last, "\n");
482  }
483 
484  proc.pSymCleanup(hCur);
485  }
486 
487  return buffer + seprintf(buffer, last, "\n*** End of additional info ***\n");
488 }
489 
490 /* virtual */ int CrashLogWindows::WriteCrashDump(char *filename, const char *filename_last) const
491 {
492  int ret = 0;
493  HMODULE dbghelp = LoadLibrary(_T("dbghelp.dll"));
494  if (dbghelp != nullptr) {
495  typedef BOOL (WINAPI *MiniDumpWriteDump_t)(HANDLE, DWORD, HANDLE,
496  MINIDUMP_TYPE,
497  CONST PMINIDUMP_EXCEPTION_INFORMATION,
498  CONST PMINIDUMP_USER_STREAM_INFORMATION,
499  CONST PMINIDUMP_CALLBACK_INFORMATION);
500  MiniDumpWriteDump_t funcMiniDumpWriteDump = (MiniDumpWriteDump_t)GetProcAddress(dbghelp, "MiniDumpWriteDump");
501  if (funcMiniDumpWriteDump != nullptr) {
502  seprintf(filename, filename_last, "%scrash.dmp", _personal_dir.c_str());
503  HANDLE file = CreateFile(OTTD2FS(filename), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, 0);
504  HANDLE proc = GetCurrentProcess();
505  DWORD procid = GetCurrentProcessId();
506  MINIDUMP_EXCEPTION_INFORMATION mdei;
507  MINIDUMP_USER_STREAM userstream;
508  MINIDUMP_USER_STREAM_INFORMATION musi;
509 
510  userstream.Type = LastReservedStream + 1;
511  userstream.Buffer = (void*)this->crashlog;
512  userstream.BufferSize = (ULONG)strlen(this->crashlog) + 1;
513 
514  musi.UserStreamCount = 1;
515  musi.UserStreamArray = &userstream;
516 
517  mdei.ThreadId = GetCurrentThreadId();
518  mdei.ExceptionPointers = ep;
519  mdei.ClientPointers = false;
520 
521  funcMiniDumpWriteDump(proc, procid, file, MiniDumpWithDataSegs, &mdei, &musi, nullptr);
522  ret = 1;
523  } else {
524  ret = -1;
525  }
526  FreeLibrary(dbghelp);
527  }
528  return ret;
529 }
530 #endif /* _MSC_VER */
531 
532 extern bool CloseConsoleLogIfActive();
533 static void ShowCrashlogWindow();
534 
539 void *_safe_esp = nullptr;
540 
541 static LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep)
542 {
543  /* Disable our event loop. */
544  SetWindowLongPtr(GetActiveWindow(), GWLP_WNDPROC, (LONG_PTR)&DefWindowProc);
545 
546  if (CrashLogWindows::current != nullptr) {
548  ExitProcess(2);
549  }
550 
551  if (GamelogTestEmergency()) {
552  static const TCHAR _emergency_crash[] =
553  _T("A serious fault condition occurred in the game. The game will shut down.\n")
554  _T("As you loaded an emergency savegame no crash information will be generated.\n");
555  MessageBox(nullptr, _emergency_crash, _T("Fatal Application Failure"), MB_ICONERROR);
556  ExitProcess(3);
557  }
558 
560  static const TCHAR _saveload_crash[] =
561  _T("A serious fault condition occurred in the game. The game will shut down.\n")
562  _T("As you loaded an savegame for which you do not have the required NewGRFs\n")
563  _T("no crash information will be generated.\n");
564  MessageBox(nullptr, _saveload_crash, _T("Fatal Application Failure"), MB_ICONERROR);
565  ExitProcess(3);
566  }
567 
568  CrashLogWindows *log = new CrashLogWindows(ep);
570  char *buf = log->FillCrashLog(log->crashlog, lastof(log->crashlog));
572  log->AppendDecodedStacktrace(buf, lastof(log->crashlog));
575 
576  /* Close any possible log files */
577  CloseConsoleLogIfActive();
578 
579  if ((VideoDriver::GetInstance() == nullptr || VideoDriver::GetInstance()->HasGUI()) && _safe_esp != nullptr) {
580 #ifdef _M_AMD64
581  ep->ContextRecord->Rip = (DWORD64)ShowCrashlogWindow;
582  ep->ContextRecord->Rsp = (DWORD64)_safe_esp;
583 #elif defined(_M_IX86)
584  ep->ContextRecord->Eip = (DWORD)ShowCrashlogWindow;
585  ep->ContextRecord->Esp = (DWORD)_safe_esp;
586 #elif defined(_M_ARM64)
587  ep->ContextRecord->Pc = (DWORD64)ShowCrashlogWindow;
588  ep->ContextRecord->Sp = (DWORD64)_safe_esp;
589 #endif
590  return EXCEPTION_CONTINUE_EXECUTION;
591  }
592 
594  return EXCEPTION_EXECUTE_HANDLER;
595 }
596 
597 static void CDECL CustomAbort(int signal)
598 {
599  RaiseException(0xE1212012, 0, 0, nullptr);
600 }
601 
602 /* static */ void CrashLog::InitialiseCrashLog()
603 {
604 #if defined(_M_AMD64) || defined(_M_ARM64)
605  CONTEXT ctx;
606  RtlCaptureContext(&ctx);
607 
608  /* The stack pointer for AMD64 must always be 16-byte aligned inside a
609  * function. As we are simulating a function call with the safe ESP value,
610  * we need to subtract 8 for the imaginary return address otherwise stack
611  * alignment would be wrong in the called function. */
612 #if defined(_M_ARM64)
613  _safe_esp = (void *)(ctx.Sp - 8);
614 #else
615  _safe_esp = (void *)(ctx.Rsp - 8);
616 #endif
617 #else
618 #if defined(_MSC_VER)
619  _asm {
620  mov _safe_esp, esp
621  }
622 #else
623  asm("movl %esp, __safe_esp");
624 #endif
625 #endif
626 
627  /* SIGABRT is not an unhandled exception, so we need to intercept it. */
628  signal(SIGABRT, CustomAbort);
629 #if defined(_MSC_VER)
630  /* Don't show abort message as we will get the crashlog window anyway. */
631  _set_abort_behavior(0, _WRITE_ABORT_MSG);
632 #endif
633  SetUnhandledExceptionFilter(ExceptionHandler);
634 }
635 
636 /* The crash log GUI */
637 
638 static bool _expanded;
639 
640 static const TCHAR _crash_desc[] =
641  _T("A serious fault condition occurred in the game. The game will shut down.\n")
642  _T("Please send the crash information and the crash.dmp file (if any) to the developers.\n")
643  _T("This will greatly help debugging. The correct place to do this is https://github.com/OpenTTD/OpenTTD/issues. ")
644  _T("The information contained in the report is displayed below.\n")
645  _T("Press \"Emergency save\" to attempt saving the game. Generated file(s):\n")
646  _T("%s");
647 
648 static const TCHAR _save_succeeded[] =
649  _T("Emergency save succeeded.\nIts location is '%s'.\n")
650  _T("Be aware that critical parts of the internal game state may have become ")
651  _T("corrupted. The saved game is not guaranteed to work.");
652 
653 static const TCHAR * const _expand_texts[] = {_T("S&how report >>"), _T("&Hide report <<") };
654 
655 static void SetWndSize(HWND wnd, int mode)
656 {
657  RECT r, r2;
658 
659  GetWindowRect(wnd, &r);
660  SetDlgItemText(wnd, 15, _expand_texts[mode == 1]);
661 
662  if (mode >= 0) {
663  GetWindowRect(GetDlgItem(wnd, 11), &r2);
664  int offs = r2.bottom - r2.top + 10;
665  if (mode == 0) offs = -offs;
666  SetWindowPos(wnd, HWND_TOPMOST, 0, 0,
667  r.right - r.left, r.bottom - r.top + offs, SWP_NOMOVE | SWP_NOZORDER);
668  } else {
669  SetWindowPos(wnd, HWND_TOPMOST,
670  (GetSystemMetrics(SM_CXSCREEN) - (r.right - r.left)) / 2,
671  (GetSystemMetrics(SM_CYSCREEN) - (r.bottom - r.top)) / 2,
672  0, 0, SWP_NOSIZE);
673  }
674 }
675 
676 /* When TCHAR is char, then _sntprintf becomes snprintf. When TCHAR is wchar it doesn't. Likewise for strcat. */
677 #undef snprintf
678 #undef strcat
679 
680 static INT_PTR CALLBACK CrashDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)
681 {
682  switch (msg) {
683  case WM_INITDIALOG: {
684  /* We need to put the crash-log in a separate buffer because the default
685  * buffer in MB_TO_WIDE is not large enough (512 chars) */
686  TCHAR crash_msgW[lengthof(CrashLogWindows::current->crashlog)];
687  /* Convert unix -> dos newlines because the edit box only supports that properly :( */
688  const char *unix_nl = CrashLogWindows::current->crashlog;
689  char dos_nl[lengthof(CrashLogWindows::current->crashlog)];
690  char *p = dos_nl;
691  WChar c;
692  while ((c = Utf8Consume(&unix_nl)) && p < lastof(dos_nl) - 4) { // 4 is max number of bytes per character
693  if (c == '\n') p += Utf8Encode(p, '\r');
694  p += Utf8Encode(p, c);
695  }
696  *p = '\0';
697 
698  /* Add path to crash.log and crash.dmp (if any) to the crash window text */
699  size_t len = _tcslen(_crash_desc) + 2;
700  len += _tcslen(OTTD2FS(CrashLogWindows::current->crashlog_filename)) + 2;
701  len += _tcslen(OTTD2FS(CrashLogWindows::current->crashdump_filename)) + 2;
702  len += _tcslen(OTTD2FS(CrashLogWindows::current->screenshot_filename)) + 1;
703 
704  TCHAR *text = AllocaM(TCHAR, len);
705  _sntprintf(text, len, _crash_desc, OTTD2FS(CrashLogWindows::current->crashlog_filename));
706  if (OTTD2FS(CrashLogWindows::current->crashdump_filename)[0] != _T('\0')) {
707  _tcscat(text, _T("\n"));
708  _tcscat(text, OTTD2FS(CrashLogWindows::current->crashdump_filename));
709  }
710  if (OTTD2FS(CrashLogWindows::current->screenshot_filename)[0] != _T('\0')) {
711  _tcscat(text, _T("\n"));
712  _tcscat(text, OTTD2FS(CrashLogWindows::current->screenshot_filename));
713  }
714 
715  SetDlgItemText(wnd, 10, text);
716  SetDlgItemText(wnd, 11, convert_to_fs(dos_nl, crash_msgW, lengthof(crash_msgW)));
717  SendDlgItemMessage(wnd, 11, WM_SETFONT, (WPARAM)GetStockObject(ANSI_FIXED_FONT), FALSE);
718  SetWndSize(wnd, -1);
719  } return TRUE;
720  case WM_COMMAND:
721  switch (wParam) {
722  case 12: // Close
724  ExitProcess(2);
725  case 13: // Emergency save
726  char filename[MAX_PATH];
727  if (CrashLogWindows::current->WriteSavegame(filename, lastof(filename))) {
728  size_t len = _tcslen(_save_succeeded) + _tcslen(OTTD2FS(filename)) + 1;
729  TCHAR *text = AllocaM(TCHAR, len);
730  _sntprintf(text, len, _save_succeeded, OTTD2FS(filename));
731  MessageBox(wnd, text, _T("Save successful"), MB_ICONINFORMATION);
732  } else {
733  MessageBox(wnd, _T("Save failed"), _T("Save failed"), MB_ICONINFORMATION);
734  }
735  break;
736  case 15: // Expand window to show crash-message
737  _expanded ^= 1;
738  SetWndSize(wnd, _expanded);
739  break;
740  }
741  return TRUE;
742  case WM_CLOSE:
744  ExitProcess(2);
745  }
746 
747  return FALSE;
748 }
749 
750 static void ShowCrashlogWindow()
751 {
752  ShowCursor(TRUE);
753  ShowWindow(GetActiveWindow(), FALSE);
754  DialogBox(GetModuleHandle(nullptr), MAKEINTRESOURCE(100), nullptr, CrashDialogFunc);
755 }
WChar
char32_t WChar
Type for wide characters, i.e.
Definition: string_type.h:35
_personal_dir
std::string _personal_dir
custom directory for personal settings, saves, newgrf, etc.
Definition: fileio.cpp:1119
CrashLog::AfterCrashLogCleanup
static void AfterCrashLogCleanup()
Try to close the sound/video stuff so it doesn't keep lingering around incorrect video states or so,...
Definition: crashlog.cpp:507
win32.h
CrashLog::WriteScreenshot
bool WriteScreenshot(char *filename, const char *filename_last) const
Write the (crash) screenshot to a file.
Definition: crashlog.cpp:423
CrashLogWindows
Windows implementation for the crash logger.
Definition: crashlog_win.cpp:37
CrashLogWindows::CrashLogWindows
CrashLogWindows(EXCEPTION_POINTERS *ep=nullptr)
A crash log is always generated when it's generated.
Definition: crashlog_win.cpp:67
_safe_esp
void * _safe_esp
Stack pointer for use when 'starting' the crash handler.
Definition: crashlog_win.cpp:539
LoadLibraryList
bool LoadLibraryList(Function proc[], const char *dll)
Helper function needed by dynamically loading libraries XXX: Hurray for MS only having an ANSI GetPro...
Definition: win32.cpp:57
DebugFileInfo
Definition: crashlog_win.cpp:119
Utf8Encode
size_t Utf8Encode(T buf, WChar c)
Encode a unicode character and place it in the buffer.
Definition: string.cpp:523
CrashLogWindows::crashlog_filename
char crashlog_filename[MAX_PATH]
Buffer for the filename of the crash log.
Definition: crashlog_win.cpp:57
CrashLogWindows::LogOSVersion
char * LogOSVersion(char *buffer, const char *last) const override
Writes OS' version to the buffer.
Definition: crashlog_win.cpp:84
CrashLogWindows::LogStacktrace
char * LogStacktrace(char *buffer, const char *last) const override
Writes the stack trace to the buffer, if there is information about it available.
Definition: crashlog_win.cpp:341
OTTD2FS
const TCHAR * OTTD2FS(const char *name, bool console_cp)
Convert from OpenTTD's encoding to that of the local environment.
Definition: win32.cpp:601
CrashLogWindows::ep
EXCEPTION_POINTERS * ep
Information about the encountered exception.
Definition: crashlog_win.cpp:39
CrashLogWindows::current
static CrashLogWindows * current
Points to the current crash log.
Definition: crashlog_win.cpp:79
GamelogTestEmergency
bool GamelogTestEmergency()
Finds out if current game is a loaded emergency savegame.
Definition: gamelog.cpp:420
SaveloadCrashWithMissingNewGRFs
bool SaveloadCrashWithMissingNewGRFs()
Did loading the savegame cause a crash? If so, were NewGRFs missing?
Definition: afterload.cpp:364
CrashLog::message
static const char * message
Pointer to the error message.
Definition: crashlog.h:19
CrashLog
Helper class for creating crash logs.
Definition: crashlog.h:16
CrashLog::WriteCrashDump
virtual int WriteCrashDump(char *filename, const char *filename_last) const
Write the (crash) dump to a file.
Definition: crashlog.cpp:383
CrashLogWindows::crashdump_filename
char crashdump_filename[MAX_PATH]
Buffer for the filename of the crash dump.
Definition: crashlog_win.cpp:59
VideoDriver::GetInstance
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
Definition: video_driver.hpp:111
CrashLogWindows::crashlog
char crashlog[65536]
Buffer for the generated crash log.
Definition: crashlog_win.cpp:55
CrashLog::InitialiseCrashLog
static void InitialiseCrashLog()
Initialiser for crash logs; do the appropriate things so crashes are handled by our crash handler ins...
Definition: crashlog_osx.cpp:254
seprintf
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:442
CrashLogWindows::LogModules
char * LogModules(char *buffer, const char *last) const override
Writes the dynamically linked libraries/modules to the buffer, if there is information about it avail...
Definition: crashlog_win.cpp:205
CrashLogWindows::screenshot_filename
char screenshot_filename[MAX_PATH]
Buffer for the filename of the crash screenshot.
Definition: crashlog_win.cpp:61
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:377
CrashLog::FillCrashLog
char * FillCrashLog(char *buffer, const char *last) const
Fill the crash log buffer with all data of a crash log.
Definition: crashlog.cpp:334
CrashLog::WriteCrashLog
bool WriteCrashLog(const char *buffer, char *filename, const char *filename_last) const
Write the crash log to a file.
Definition: crashlog.cpp:369
FS2OTTD
const char * FS2OTTD(const TCHAR *name)
Convert to OpenTTD's encoding from that of the local environment.
Definition: win32.cpp:583
convert_to_fs
TCHAR * convert_to_fs(const char *name, TCHAR *system_buf, size_t buflen, bool console_cp)
Convert from OpenTTD's encoding to that of the environment in UNICODE.
Definition: win32.cpp:650
CrashLogWindows::LogError
char * LogError(char *buffer, const char *last, const char *message) const override
Writes actually encountered error to the buffer.
Definition: crashlog_win.cpp:102
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:393
CrashLogWindows::LogRegisters
char * LogRegisters(char *buffer, const char *last) const override
Writes information about the data in the registers, if there is information about it available.
Definition: crashlog_win.cpp:233
AllocaM
#define AllocaM(T, num_elements)
alloca() has to be called in the parent function, so define AllocaM() as a macro
Definition: alloc_func.hpp:132