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