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