diff options
-rw-r--r-- | projects/openttd_vs80.vcproj | 8 | ||||
-rw-r--r-- | projects/openttd_vs90.vcproj | 8 | ||||
-rw-r--r-- | source.list | 2 | ||||
-rw-r--r-- | src/crashlog.cpp | 270 | ||||
-rw-r--r-- | src/crashlog.h | 185 | ||||
-rw-r--r-- | src/openttd.cpp | 8 | ||||
-rw-r--r-- | src/os/windows/crashlog_win.cpp | 552 | ||||
-rw-r--r-- | src/os/windows/win32.cpp | 16 | ||||
-rw-r--r-- | src/stdafx.h | 9 |
9 files changed, 766 insertions, 292 deletions
diff --git a/projects/openttd_vs80.vcproj b/projects/openttd_vs80.vcproj index da8fcbc1a..11691d53a 100644 --- a/projects/openttd_vs80.vcproj +++ b/projects/openttd_vs80.vcproj @@ -496,6 +496,10 @@ > </File> <File + RelativePath=".\..\src\crashlog.cpp" + > + </File> + <File RelativePath=".\..\src\command.cpp" > </File> @@ -856,6 +860,10 @@ > </File> <File + RelativePath=".\..\src\crashlog.h" + > + </File> + <File RelativePath=".\..\src\command_func.h" > </File> diff --git a/projects/openttd_vs90.vcproj b/projects/openttd_vs90.vcproj index 7dd93d550..6843c1aa6 100644 --- a/projects/openttd_vs90.vcproj +++ b/projects/openttd_vs90.vcproj @@ -493,6 +493,10 @@ > </File> <File + RelativePath=".\..\src\crashlog.cpp" + > + </File> + <File RelativePath=".\..\src\command.cpp" > </File> @@ -853,6 +857,10 @@ > </File> <File + RelativePath=".\..\src\crashlog.h" + > + </File> + <File RelativePath=".\..\src\command_func.h" > </File> diff --git a/source.list b/source.list index 87b1ff0f3..c782ccfcf 100644 --- a/source.list +++ b/source.list @@ -9,6 +9,7 @@ callback_table.cpp cargopacket.cpp cargotype.cpp cheat.cpp +crashlog.cpp command.cpp console.cpp console_cmds.cpp @@ -118,6 +119,7 @@ cargotype.h cheat_func.h cheat_type.h cmd_helper.h +crashlog.h command_func.h command_type.h company_base.h diff --git a/src/crashlog.cpp b/src/crashlog.cpp new file mode 100644 index 000000000..01678bea3 --- /dev/null +++ b/src/crashlog.cpp @@ -0,0 +1,270 @@ +/* $Id$ */ + +/* + * This file is part of OpenTTD. + * 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. + * 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. + * 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/>. + */ + +/** @file crashlog.cpp Implementation of generic function to be called to log a crash */ + +#include "stdafx.h" +#include "crashlog.h" +#include "gamelog.h" +#include "map_func.h" +#include "rev.h" +#include "string_func.h" +#include "strings_func.h" +#include "network/network.h" +#include "blitter/factory.hpp" +#include "base_media_base.h" +#include "music/music_driver.hpp" +#include "sound/sound_driver.hpp" +#include "video/video_driver.hpp" +#include "saveload/saveload.h" + +#include <time.h> + +/* static */ const char *CrashLog::message = NULL; +/* static */ char *CrashLog::gamelog_buffer = NULL; +/* static */ const char *CrashLog::gamelog_last = NULL; + +/* virtual */ char *CrashLog::LogRegisters(char *buffer, const char *last) const +{ + /* Stub implementation; not all OSes support this. */ + return buffer; +} + +/* virtual */ char *CrashLog::LogModules(char *buffer, const char *last) const +{ + /* Stub implementation; not all OSes support this. */ + return buffer; +} + +char *CrashLog::LogOpenTTDVersion(char *buffer, const char *last) const +{ + return buffer + seprintf(buffer, last, + "OpenTTD version:\n" + " Version: %s (%d)\n" + " NewGRF ver: %08x\n" + " Bits: %d\n" + " Endian: %s\n" + " Dedicated: %s\n" + " Build date: %s\n\n", + _openttd_revision, + _openttd_revision_modified, + _openttd_newgrf_version, +#ifdef _SQ64 + 64, +#else + 32, +#endif +#if (TTD_ENDIAN == TTD_LITTLE_ENDIAN) + "little", +#else + "big", +#endif +#ifdef DEDICATED + "yes", +#else + "no", +#endif + _openttd_build_date + ); +} + +char *CrashLog::LogConfiguration(char *buffer, const char *last) const +{ + buffer += seprintf(buffer, last, + "Configuration:\n" + " Blitter: %s\n" + " Graphics set: %s\n" + " Language: %s\n" + " Music driver: %s\n" + " Sound driver: %s\n" + " Sound set: %s\n" + " Video driver: %s\n\n", + BlitterFactoryBase::GetCurrentBlitter() == NULL ? "none" : BlitterFactoryBase::GetCurrentBlitter()->GetName(), + BaseGraphics::GetUsedSet() == NULL ? "none" : BaseGraphics::GetUsedSet()->name, + StrEmpty(_dynlang.curr_file) ? "none" : _dynlang.curr_file, + _music_driver == NULL ? "none" : _music_driver->GetName(), + _sound_driver == NULL ? "none" : _sound_driver->GetName(), + BaseSounds::GetUsedSet() == NULL ? "none" : BaseSounds::GetUsedSet()->name, + _video_driver == NULL ? "none" : _video_driver->GetName() + ); + + return buffer; +} + +/* Include these here so it's close to where it's actually used. */ +#ifdef WITH_ALLEGRO +# include <allegro.h> +#endif /* WITH_ALLEGRO */ +#ifdef WITH_FONTCONFIG +#include <fontconfig/fontconfig.h> +#endif /* WITH_FONTCONFIG */ +#ifdef WITH_FREETYPE +#include <ft2build.h> +#include FT_FREETYPE_H +#endif /* WITH_FREETYPE */ +#ifdef WITH_ICU +# include <unicode/uversion.h> +#endif /* WITH_ICU */ +#ifdef WITH_SDL +# include <SDL.h> +#endif /* WITH_SDL */ + +char *CrashLog::LogLibraries(char *buffer, const char *last) const +{ + buffer += seprintf(buffer, last, "Libraries:\n"); +#ifdef WITH_ALLEGRO + buffer += seprintf(buffer, last, " Allegro: %s\n", ALLEGRO_VERSION_STR); +#endif /* WITH_ALLEGRO */ +#ifdef WITH_FONTCONFIG + buffer += seprintf(buffer, last, " FontConfig: %d.%d.%d\n", FC_MAJOR, FC_MINOR, FC_REVISION); +#endif /* WITH_FONTCONFIG */ +#ifdef WITH_FREETYPE + buffer += seprintf(buffer, last, " FreeType: %d.%d.%d\n", FREETYPE_MAJOR, FREETYPE_MINOR, FREETYPE_PATCH); +#endif /* WITH_FREETYPE */ +#ifdef WITH_ICU + buffer += seprintf(buffer, last, " ICU: %s\n", U_ICU_VERSION); +#endif /* WITH_ICU */ +#ifdef WITH_SDL + buffer += seprintf(buffer, last, " SDL: %d.%d.%d\n", SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL); +#endif /* WITH_SDL */ + buffer += seprintf(buffer, last, "\n"); + return buffer; +} + +/* static */ void CrashLog::GamelogFillCrashLog(const char *s) +{ + CrashLog::gamelog_buffer += seprintf(CrashLog::gamelog_buffer, CrashLog::gamelog_last, "%s\n", s); +} + +char *CrashLog::LogGamelog(char *buffer, const char *last) const +{ + CrashLog::gamelog_buffer = buffer; + CrashLog::gamelog_last = last; + GamelogPrint(&CrashLog::GamelogFillCrashLog); + return CrashLog::gamelog_buffer + seprintf(CrashLog::gamelog_buffer, last, "\n"); +} + +char *CrashLog::FillCrashLog(char *buffer, const char *last) const +{ + time_t cur_time = time(NULL); + buffer += seprintf(buffer, last, "*** OpenTTD Crash Report ***\n\n"); + buffer += seprintf(buffer, last, "Crash at: %s\n", asctime(gmtime(&cur_time))); + + buffer = this->LogError(buffer, last, CrashLog::message); + buffer = this->LogOpenTTDVersion(buffer, last); + buffer = this->LogRegisters(buffer, last); + buffer = this->LogStacktrace(buffer, last); + buffer = this->LogOSVersion(buffer, last); + buffer = this->LogConfiguration(buffer, last); + buffer = this->LogLibraries(buffer, last); + buffer = this->LogModules(buffer, last); + buffer = this->LogGamelog(buffer, last); + + buffer += seprintf(buffer, last, "*** End of OpenTTD Crash Report ***\n"); + return buffer; +} + +bool CrashLog::WriteCrashLog(const char *buffer, char *filename, const char *filename_last) const +{ + seprintf(filename, filename_last, "%scrash.log", _personal_dir); + + FILE *file = FioFOpenFile(filename, "w", NO_DIRECTORY); + if (file == NULL) return false; + + size_t len = strlen(buffer); + size_t written = fwrite(buffer, 1, len, file); + + FioFCloseFile(file); + return len == written; +} + +/* virtual */ int CrashLog::WriteCrashDump(char *filename, const char *filename_last) const +{ + /* Stub implementation; not all OSes support this. */ + return 0; +} + +bool CrashLog::WriteSavegame(char *filename, const char *filename_last) const +{ + /* If the map array doesn't exist, saving will fail too. If the map got + * initialised, there is a big chance the rest is initialised too. */ + if (_m == NULL) return false; + + try { + GamelogStartAction(GLAT_EMERGENCY); + GamelogEmergency(); + GamelogStopAction(); + + seprintf(filename, filename_last, "%scrash.sav", _personal_dir); + + /* Fake ourselves to be a network server so we don't get threaded saving */ + _network_server = true; + return SaveOrLoad(filename, SL_SAVE, NO_DIRECTORY) == SL_OK; + } catch (...) { + return false; + } +} + +bool CrashLog::MakeCrashLog() const +{ + /* Don't keep looping logging crashes. */ + static bool crashlogged = false; + if (crashlogged) return false; + crashlogged = true; + + char filename[MAX_PATH]; + char buffer[65536]; + bool ret = true; + + printf("Crash encountered, generating crash log...\n"); + this->FillCrashLog(buffer, lastof(buffer)); + printf("%s\n", buffer); + printf("Crash log generated.\n\n"); + + printf("Writing crash log to disk...\n"); + bool bret = this->WriteCrashLog(buffer, filename, lastof(filename)); + if (bret) { + printf("Crash log written to %s. Please add this file to any bug reports.\n\n", filename); + } else { + printf("Writing crash log failed. Please attach the output above to any bug reports.\n\n"); + ret = false; + } + + /* Don't mention writing crash dumps because not all platforms support it. */ + int dret = this->WriteCrashDump(filename, lastof(filename)); + if (dret < 0) { + printf("Writing crash dump failed.\n\n"); + ret = false; + } else if (dret > 0) { + printf("Crash dump written to %s. Please add this file to any bug reports.\n\n", filename); + } + + printf("Writing crash savegame...\n"); + bret = this->WriteSavegame(filename, lastof(filename)); + if (bret) { + printf("Crash savegame written to %s. Please add this file and the last (auto)save to any bug reports.\n\n", filename); + } else { + ret = false; + printf("Writing crash savegame failed. Please attach the last (auto)save to any bug reports.\n\n"); + } + + return ret; +} + +/* static */ void CrashLog::SetErrorMessage(const char *message) +{ + CrashLog::message = message; +} + +/* static */ void CrashLog::AfterCrashLogCleanup() +{ + if (_music_driver != NULL) _music_driver->Stop(); + if (_sound_driver != NULL) _sound_driver->Stop(); + if (_video_driver != NULL) _video_driver->Stop(); +} diff --git a/src/crashlog.h b/src/crashlog.h new file mode 100644 index 000000000..4bdbf0230 --- /dev/null +++ b/src/crashlog.h @@ -0,0 +1,185 @@ +/* $Id$ */ + +/* + * This file is part of OpenTTD. + * 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. + * 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. + * 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/>. + */ + +/** @file crashlog.h Functions to be called to log a crash */ + +#ifndef CRASHLOG_H +#define CRASHLOG_H + +/** + * Helper class for creating crash logs. + */ +class CrashLog { +private: + /** Pointer to the error message. */ + static const char *message; + + /** Temporary 'local' location of the buffer. */ + static char *gamelog_buffer; + + /** Temporary 'local' location of the end of the buffer. */ + static const char *gamelog_last; + + /** + * Helper function for printing the gamelog. + * @param s the string to print. + */ + static void GamelogFillCrashLog(const char *s); +protected: + /** + * Writes OS' version to the buffer. + * @param buffer The begin where to write at. + * @param last The last position in the buffer to write to. + * @return the position of the \c '\0' character after the buffer. + */ + virtual char *LogOSVersion(char *buffer, const char *last) const = 0; + + /** + * Writes actually encountered error to the buffer. + * @param buffer The begin where to write at. + * @param last The last position in the buffer to write to. + * @param messege Message passed to use for possible errors. Can be NULL. + * @return the position of the \c '\0' character after the buffer. + */ + virtual char *LogError(char *buffer, const char *last, const char *message) const = 0; + + /** + * Writes the stack trace to the buffer, if there is information about it + * available. + * @param buffer The begin where to write at. + * @param last The last position in the buffer to write to. + * @return the position of the \c '\0' character after the buffer. + */ + virtual char *LogStacktrace(char *buffer, const char *last) const = 0; + + /** + * Writes information about the data in the registers, if there is + * information about it available. + * @param buffer The begin where to write at. + * @param last The last position in the buffer to write to. + * @return the position of the \c '\0' character after the buffer. + */ + virtual char *LogRegisters(char *buffer, const char *last) const; + + /** + * Writes the dynamically linked libaries/modules to the buffer, if there + * is information about it available. + * @param buffer The begin where to write at. + * @param last The last position in the buffer to write to. + * @return the position of the \c '\0' character after the buffer. + */ + virtual char *LogModules(char *buffer, const char *last) const; + + + /** + * Writes OpenTTD's version to the buffer. + * @param buffer The begin where to write at. + * @param last The last position in the buffer to write to. + * @return the position of the \c '\0' character after the buffer. + */ + char *LogOpenTTDVersion(char *buffer, const char *last) const; + + /** + * Writes the (important) configuration settings to the buffer. + * E.g. graphics set, sound set, blitter and AIs. + * @param buffer The begin where to write at. + * @param last The last position in the buffer to write to. + * @return the position of the \c '\0' character after the buffer. + */ + char *LogConfiguration(char *buffer, const char *last) const; + + /** + * Writes information (versions) of the used libraries. + * @param buffer The begin where to write at. + * @param last The last position in the buffer to write to. + * @return the position of the \c '\0' character after the buffer. + */ + char *LogLibraries(char *buffer, const char *last) const; + + /** + * Writes the gamelog data to the buffer. + * @param buffer The begin where to write at. + * @param last The last position in the buffer to write to. + * @return the position of the \c '\0' character after the buffer. + */ + char *LogGamelog(char *buffer, const char *last) const; + +public: + /** Stub destructor to silence some compilers. */ + virtual ~CrashLog() {} + + /** + * Fill the crash log buffer with all data of a crash log. + * @param buffer The begin where to write at. + * @param last The last position in the buffer to write to. + * @return the position of the \c '\0' character after the buffer. + */ + char *FillCrashLog(char *buffer, const char *last) const; + + /** + * Write the crash log to a file. + * @note On success the filename will be filled with the full path of the + * crash log file. Make sure filename is at least \c MAX_PATH big. + * @param buffer The begin of the buffer to write to the disk. + * @param filename Output for the filename of the written file. + * @param filename_last The last position in the filename buffer. + * @return true when the crash log was successfully written. + */ + bool WriteCrashLog(const char *buffer, char *filename, const char *filename_last) const; + + /** + * Write the (crash) dump to a file. + * @note On success the filename will be filled with the full path of the + * crash dump file. Make sure filename is at least \c MAX_PATH big. + * @param filename Output for the filename of the written file. + * @param filename_last The last position in the filename buffer. + * @return if less than 0, error. If 0 no dump is made, otherwise the dump + * was successfull (not all OSes support dumping files). + */ + virtual int WriteCrashDump(char *filename, const char *filename_last) const; + + /** + * Write the (crash) savegame to a file. + * @note On success the filename will be filled with the full path of the + * crash save file. Make sure filename is at least \c MAX_PATH big. + * @param filename Output for the filename of the written file. + * @param filename_last The last position in the filename buffer. + * @return true when the crash save was successfully made. + */ + bool WriteSavegame(char *filename, const char *filename_last) const; + + /** + * Makes the crash log, writes it to a file and then subsequently tries + * to make a crash dump and crash savegame. It uses DEBUG to write + * information like paths to the console. + * @return true when everything is made successfully. + */ + bool MakeCrashLog() const; + + /** + * Initialiser for crash logs; do the appropriate things so crashes are + * handled by our crash handler instead of returning straight to the OS. + * @note must be implemented by all implementers of CrashLog. + */ + static void InitialiseCrashLog(); + + /** + * Sets a message for the error message handler. + * @param message The error message of the error. + */ + static void SetErrorMessage(const char *message); + + /** + * Try to close the sound/video stuff so it doesn't keep lingering around + * incorrect video states or so, e.g. keeping dpmi disabled. + */ + static void AfterCrashLogCleanup(); +}; + +#endif /* CRASHLOG_H */ diff --git a/src/openttd.cpp b/src/openttd.cpp index a46a7a734..6297edacf 100644 --- a/src/openttd.cpp +++ b/src/openttd.cpp @@ -62,6 +62,7 @@ #include "highscore.h" #include "thread/thread.h" #include "station_base.h" +#include "crashlog.h" #include "newgrf_commons.h" @@ -124,10 +125,9 @@ void CDECL error(const char *s, ...) ShowOSErrorBox(buf, true); if (_video_driver != NULL) _video_driver->Stop(); - /* Don't go into NOT_REACHED here; NOT_REACHED is using error, so - * using it would result in an infinite loop instead of errors. */ - assert(0); - exit(1); + /* Set the error message for the crash log and then invoke it. */ + CrashLog::SetErrorMessage(buf); + abort(); } /** diff --git a/src/os/windows/crashlog_win.cpp b/src/os/windows/crashlog_win.cpp index cf622fc52..4919fa683 100644 --- a/src/os/windows/crashlog_win.cpp +++ b/src/os/windows/crashlog_win.cpp @@ -9,38 +9,101 @@ /** @file crashlog_win.cpp Implementation of a crashlogger for Windows */ -#if defined(WIN32_EXCEPTION_TRACKER) - #include "../../stdafx.h" +#include "../../crashlog.h" #include "win32.h" #include "../../core/alloc_func.hpp" +#include "../../core/math_func.hpp" #include "../../string_func.h" -#include "../../gamelog.h" -#include "../../saveload/saveload.h" #include "../../fileio_func.h" -#include "../../rev.h" #include "../../strings_func.h" #include <windows.h> -#include <dbghelp.h> -static const char *_exception_string = NULL; -void SetExceptionString(const char *s, ...) -{ - va_list va; - char buf[512]; +/** + * Windows implementation for the crash logger. + */ +class CrashLogWindows : public CrashLog { + /** Information about the encountered exception */ + EXCEPTION_POINTERS *ep; + + /* virtual */ char *LogOSVersion(char *buffer, const char *last) const; + /* virtual */ char *LogError(char *buffer, const char *last, const char *message) const; + /* virtual */ char *LogStacktrace(char *buffer, const char *last) const; + /* virtual */ char *LogRegisters(char *buffer, const char *last) const; + /* virtual */ char *LogModules(char *buffer, const char *last) const; +public: +#if defined(_MSC_VER) + /* virtual */ int WriteCrashDump(char *filename, const char *filename_last) const; +#endif /* _MSC_VER */ + + /** Buffer for the generated crash log */ + char crashlog[65536]; + /** Buffer for the filename of the crash log */ + char crashlog_filename[MAX_PATH]; + /** Buffer for the filename of the crash dump */ + char crashdump_filename[MAX_PATH]; + + /** + * A crash log is always generated when it's generated. + * @param ep the data related to the exception. + */ + CrashLogWindows(EXCEPTION_POINTERS *ep = NULL) : + ep(ep) + { + this->crashlog[0] = '\0'; + this->crashlog_filename[0] = '\0'; + this->crashdump_filename[0] = '\0'; + } + + /** + * Points to the current crash log. + */ + static CrashLogWindows *current; +}; - va_start(va, s); - vsnprintf(buf, lengthof(buf), s, va); - va_end(va); +/* static */ CrashLogWindows *CrashLogWindows::current = NULL; + +/* virtual */ char *CrashLogWindows::LogOSVersion(char *buffer, const char *last) const +{ + _OSVERSIONINFOA os; + os.dwOSVersionInfoSize = sizeof(os); + GetVersionExA(&os); + + return buffer + seprintf(buffer, last, + "Operating system:\n" + " Name: Windows\n" + " Release: %d.%d.%d (%s)\n" + " MSVC: %s\n\n", + (int)os.dwMajorVersion, + (int)os.dwMinorVersion, + (int)os.dwBuildNumber, + os.szCSDVersion, +#if defined(_MSC_VER) + "Yes" +#else + "No" +#endif + ); - _exception_string = strdup(buf); } -static void *_safe_esp; -static char *_crash_msg; -static bool _expanded; -static bool _did_emerg_save; +/* virtual */ char *CrashLogWindows::LogError(char *buffer, const char *last, const char *message) const +{ + return buffer + seprintf(buffer, last, + "Crash reason:\n" + " Exception: %.8X\n" +#ifdef _M_AMD64 + " Location: %.16IX\n" +#else + " Location: %.8X\n" +#endif + " Message: %s\n\n", + (int)ep->ExceptionRecord->ExceptionCode, + (size_t)ep->ExceptionRecord->ExceptionAddress, + message == NULL ? "<none>" : message + ); +} struct DebugFileInfo { uint32 size; @@ -112,7 +175,7 @@ static char *PrintModuleInfo(char *output, const char *last, HMODULE mod) GetModuleFileName(mod, buffer, MAX_PATH); GetFileInfo(&dfi, buffer); - output += seprintf(output, last, " %-20s handle: %p size: %d crc: %.8X date: %d-%.2d-%.2d %.2d:%.2d:%.2d\r\n", + output += seprintf(output, last, " %-20s handle: %p size: %d crc: %.8X date: %d-%.2d-%.2d %.2d:%.2d:%.2d\n", WIDE_TO_MB(buffer), mod, dfi.size, @@ -127,10 +190,13 @@ static char *PrintModuleInfo(char *output, const char *last, HMODULE mod) return output; } -static char *PrintModuleList(char *output, const char *last) +/* virtual */ char *CrashLogWindows::LogModules(char *output, const char *last) const { + MakeCRCTable(AllocaM(uint32, 256)); BOOL (WINAPI *EnumProcessModules)(HANDLE, HMODULE*, DWORD, LPDWORD); + output += seprintf(output, last, "Module information:\n"); + if (LoadLibraryList((Function*)&EnumProcessModules, "psapi.dll\0EnumProcessModules\0\0")) { HMODULE modules[100]; DWORD needed; @@ -144,183 +210,25 @@ static char *PrintModuleList(char *output, const char *last) size_t count = min(needed / sizeof(HMODULE), lengthof(modules)); for (size_t i = 0; i != count; i++) output = PrintModuleInfo(output, last, modules[i]); - return output; + return output + seprintf(output, last, "\n"); } } } output = PrintModuleInfo(output, last, NULL); - return output; -} - -static const TCHAR _crash_desc[] = - _T("A serious fault condition occured in the game. The game will shut down.\n") - _T("Please send the crash information and the crash.dmp file (if any) to the developers.\n") - _T("This will greatly help debugging. The correct place to do this is http://bugs.openttd.org. ") - _T("The information contained in the report is displayed below.\n") - _T("Press \"Emergency save\" to attempt saving the game."); - -static const TCHAR _save_succeeded[] = - _T("Emergency save succeeded.\n") - _T("Be aware that critical parts of the internal game state may have become ") - _T("corrupted. The saved game is not guaranteed to work."); - -static const TCHAR _emergency_crash[] = - _T("A serious fault condition occured in the game. The game will shut down.\n") - _T("As you loaded an emergency savegame no crash information will be generated.\n"); - -static bool EmergencySave() -{ - GamelogStartAction(GLAT_EMERGENCY); - GamelogEmergency(); - GamelogStopAction(); - SaveOrLoad("crash.sav", SL_SAVE, BASE_DIR); - return true; + return output + seprintf(output, last, "\n"); } -static const TCHAR * const _expand_texts[] = {_T("S&how report >>"), _T("&Hide report <<") }; - -static void SetWndSize(HWND wnd, int mode) +/* virtual */ char *CrashLogWindows::LogRegisters(char *buffer, const char *last) const { - RECT r, r2; - - GetWindowRect(wnd, &r); - SetDlgItemText(wnd, 15, _expand_texts[mode == 1]); - - if (mode >= 0) { - GetWindowRect(GetDlgItem(wnd, 11), &r2); - int offs = r2.bottom - r2.top + 10; - if (!mode) offs = -offs; - SetWindowPos(wnd, HWND_TOPMOST, 0, 0, - r.right - r.left, r.bottom - r.top + offs, SWP_NOMOVE | SWP_NOZORDER); - } else { - SetWindowPos(wnd, HWND_TOPMOST, - (GetSystemMetrics(SM_CXSCREEN) - (r.right - r.left)) / 2, - (GetSystemMetrics(SM_CYSCREEN) - (r.bottom - r.top)) / 2, - 0, 0, SWP_NOSIZE); - } -} - -static bool DoEmergencySave(HWND wnd) -{ - bool b = false; - - EnableWindow(GetDlgItem(wnd, 13), FALSE); - _did_emerg_save = true; - __try { - b = EmergencySave(); - } __except (1) {} - return b; -} - -static INT_PTR CALLBACK CrashDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) -{ - switch (msg) { - case WM_INITDIALOG: { -#if defined(UNICODE) - /* We need to put the crash-log in a seperate buffer because the default - * buffer in MB_TO_WIDE is not large enough (512 chars) */ - wchar_t crash_msgW[8096]; -#endif - SetDlgItemText(wnd, 10, _crash_desc); - SetDlgItemText(wnd, 11, MB_TO_WIDE_BUFFER(_crash_msg, crash_msgW, lengthof(crash_msgW))); - SendDlgItemMessage(wnd, 11, WM_SETFONT, (WPARAM)GetStockObject(ANSI_FIXED_FONT), FALSE); - SetWndSize(wnd, -1); - } return TRUE; - case WM_COMMAND: - switch (wParam) { - case 12: // Close - ExitProcess(0); - case 13: // Emergency save - if (DoEmergencySave(wnd)) { - MessageBox(wnd, _save_succeeded, _T("Save successful"), MB_ICONINFORMATION); - } else { - MessageBox(wnd, _T("Save failed"), _T("Save failed"), MB_ICONINFORMATION); - } - break; - case 15: // Expand window to show crash-message - _expanded ^= 1; - SetWndSize(wnd, _expanded); - break; - } - return TRUE; - case WM_CLOSE: ExitProcess(0); - } - - return FALSE; -} - -static void Handler2() -{ - ShowCursor(TRUE); - ShowWindow(GetActiveWindow(), FALSE); - DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(100), NULL, CrashDialogFunc); -} - -extern bool CloseConsoleLogIfActive(); - -static HANDLE _file_crash_log; - -static void GamelogPrintCrashLogProc(const char *s) -{ - DWORD num_written; - WriteFile(_file_crash_log, s, (DWORD)strlen(s), &num_written, NULL); - WriteFile(_file_crash_log, "\r\n", (DWORD)strlen("\r\n"), &num_written, NULL); -} - -/** Amount of output for the execption handler. */ -static const int EXCEPTION_OUTPUT_SIZE = 8192; - -static LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep) -{ - char *output; - static bool had_exception = false; - - if (had_exception) ExitProcess(0); - if (GamelogTestEmergency()) { - MessageBox(NULL, _emergency_crash, _T("Fatal Application Failure"), MB_ICONERROR); - ExitProcess(0); - } - had_exception = true; - - MakeCRCTable(AllocaM(uint32, 256)); - _crash_msg = output = (char*)LocalAlloc(LMEM_FIXED, EXCEPTION_OUTPUT_SIZE); - const char *last = output + EXCEPTION_OUTPUT_SIZE - 1; - - { - SYSTEMTIME time; - GetLocalTime(&time); - output += seprintf(output, last, - "*** OpenTTD Crash Report ***\r\n" - "Date: %d-%.2d-%.2d %.2d:%.2d:%.2d\r\n" - "Build: %s (%d) built on %s\r\n", - time.wYear, - time.wMonth, - time.wDay, - time.wHour, - time.wMinute, - time.wSecond, - _openttd_revision, - _openttd_revision_modified, - _openttd_build_date - ); - } - - if (_exception_string) - output += seprintf(output, last, "Reason: %s\r\n", _exception_string); - - output += seprintf(output, last, "Language: %s\r\n", _dynlang.curr_file); - + buffer += seprintf(buffer, last, "Registers:\n"); #ifdef _M_AMD64 - output += seprintf(output, last, "Exception %.8X at %.16IX\r\n" - "Registers:\r\n" - "RAX: %.16llX RBX: %.16llX RCX: %.16llX RDX: %.16llX\r\n" - "RSI: %.16llX RDI: %.16llX RBP: %.16llX RSP: %.16llX\r\n" - "R8: %.16llX R9: %.16llX R10: %.16llX R11: %.16llX\r\n" - "R12: %.16llX R13: %.16llX R14: %.16llX R15: %.16llX\r\n" - "RIP: %.16llX EFLAGS: %.8X\r\n" - "\r\nBytes at CS:RIP:\r\n", - ep->ExceptionRecord->ExceptionCode, - ep->ExceptionRecord->ExceptionAddress, + buffer += seprintf(buffer, last, + "Registers:\n" + " RAX: %.16llX RBX: %.16llX RCX: %.16llX RDX: %.16llX\n" + " RSI: %.16llX RDI: %.16llX RBP: %.16llX RSP: %.16llX\n" + " R8: %.16llX R9: %.16llX R10: %.16llX R11: %.16llX\n" + " R12: %.16llX R13: %.16llX R14: %.16llX R15: %.16llX\n" + " RIP: %.16llX EFLAGS: %.8X\n", ep->ContextRecord->Rax, ep->ContextRecord->Rbx, ep->ContextRecord->Rcx, @@ -341,88 +249,68 @@ static LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep) ep->ContextRecord->EFlags ); #else - output += seprintf(output, last, "Exception %.8X at %.8p\r\n" - "Registers:\r\n" - " EAX: %.8X EBX: %.8X ECX: %.8X EDX: %.8X\r\n" - " ESI: %.8X EDI: %.8X EBP: %.8X ESP: %.8X\r\n" - " EIP: %.8X EFLAGS: %.8X\r\n" - "\r\nBytes at CS:EIP:\r\n", - ep->ExceptionRecord->ExceptionCode, - ep->ExceptionRecord->ExceptionAddress, - ep->ContextRecord->Eax, - ep->ContextRecord->Ebx, - ep->ContextRecord->Ecx, - ep->ContextRecord->Edx, - ep->ContextRecord->Esi, - ep->ContextRecord->Edi, - ep->ContextRecord->Ebp, - ep->ContextRecord->Esp, - ep->ContextRecord->Eip, - ep->ContextRecord->EFlags + buffer += seprintf(buffer, last, + " EAX: %.8X EBX: %.8X ECX: %.8X EDX: %.8X\n" + " ESI: %.8X EDI: %.8X EBP: %.8X ESP: %.8X\n" + " EIP: %.8X EFLAGS: %.8X\n", + (int)ep->ContextRecord->Eax, + (int)ep->ContextRecord->Ebx, + (int)ep->ContextRecord->Ecx, + (int)ep->ContextRecord->Edx, + (int)ep->ContextRecord->Esi, + (int)ep->ContextRecord->Edi, + (int)ep->ContextRecord->Ebp, + (int)ep->ContextRecord->Esp, + (int)ep->ContextRecord->Eip, + (int)ep->ContextRecord->EFlags ); #endif - { + buffer += seprintf(buffer, last, "\n Bytes at instruction pointer:\n"); #ifdef _M_AMD64 - byte *b = (byte*)ep->ContextRecord->Rip; + byte *b = (byte*)ep->ContextRecord->Rip; #else - byte *b = (byte*)ep->ContextRecord->Eip; + byte *b = (byte*)ep->ContextRecord->Eip; #endif - int i; - for (i = 0; i != 24; i++) { - if (IsBadReadPtr(b, 1)) { - output += seprintf(output, last, " ??"); // OCR: WAS: , 0); - } else { - output += seprintf(output, last, " %.2X", *b); - } - b++; + for (int i = 0; i != 24; i++) { + if (IsBadReadPtr(b, 1)) { + buffer += seprintf(buffer, last, " ??"); // OCR: WAS: , 0); + } else { + buffer += seprintf(buffer, last, " %.2X", *b); } - output += seprintf(output, last, - "\r\n" - "\r\nStack trace: \r\n" - ); + b++; } + return buffer + seprintf(buffer, last, "\n\n"); +} - { - int i, j; +/* virtual */ char *CrashLogWindows::LogStacktrace(char *buffer, const char *last) const +{ + buffer += seprintf(buffer, last, "Stack trace:\n"); #ifdef _M_AMD64 - uint32 *b = (uint32*)ep->ContextRecord->Rsp; + uint32 *b = (uint32*)ep->ContextRecord->Rsp; #else - uint32 *b = (uint32*)ep->ContextRecord->Esp; + uint32 *b = (uint32*)ep->ContextRecord->Esp; #endif - for (j = 0; j != 24; j++) { - for (i = 0; i != 8; i++) { - if (IsBadReadPtr(b, sizeof(uint32))) { - output += seprintf(output, last, " ????????"); // OCR: WAS - , 0); - } else { - output += seprintf(output, last, " %.8X", *b); - } - b++; + for (int j = 0; j != 24; j++) { + for (int i = 0; i != 8; i++) { + if (IsBadReadPtr(b, sizeof(uint32))) { + buffer += seprintf(buffer, last, " ????????"); // OCR: WAS - , 0); + } else { + buffer += seprintf(buffer, last, " %.8X", *b); } - output += seprintf(output, last, "\r\n"); + b++; } + buffer += seprintf(buffer, last, "\n"); } + return buffer + seprintf(buffer, last, "\n"); +} - output += seprintf(output, last, "\r\nModule information:\r\n"); - output = PrintModuleList(output, last); - - { - _OSVERSIONINFOA os; - os.dwOSVersionInfoSize = sizeof(os); - GetVersionExA(&os); - output += seprintf(output, last, "\r\nSystem information:\r\n" - " Windows version %d.%d %d %s\r\n\r\n", - os.dwMajorVersion, os.dwMinorVersion, os.dwBuildNumber, os.szCSDVersion); - } - - _file_crash_log = CreateFile(_T("crash.log"), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0); - - if (_file_crash_log != INVALID_HANDLE_VALUE) { - DWORD num_written; - WriteFile(_file_crash_log, _crash_msg, output - _crash_msg, &num_written, NULL); - } +#if defined(_MSC_VER) +#include <dbghelp.h> -#if !defined(_DEBUG) +/* virtual */ int CrashLogWindows::WriteCrashDump(char *filename, const char *filename_last) const +{ + int ret = 0; HMODULE dbghelp = LoadLibrary(_T("dbghelp.dll")); if (dbghelp != NULL) { typedef BOOL (WINAPI *MiniDumpWriteDump_t)(HANDLE, DWORD, HANDLE, @@ -432,18 +320,17 @@ static LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep) CONST PMINIDUMP_CALLBACK_INFORMATION); MiniDumpWriteDump_t funcMiniDumpWriteDump = (MiniDumpWriteDump_t)GetProcAddress(dbghelp, "MiniDumpWriteDump"); if (funcMiniDumpWriteDump != NULL) { - HANDLE file = CreateFile(_T("crash.dmp"), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0); + seprintf(filename, filename_last, "%scrash.dmp", _personal_dir); + HANDLE file = CreateFile(OTTD2FS(filename), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0); HANDLE proc = GetCurrentProcess(); DWORD procid = GetCurrentProcessId(); MINIDUMP_EXCEPTION_INFORMATION mdei; MINIDUMP_USER_STREAM userstream; MINIDUMP_USER_STREAM_INFORMATION musi; - char msg[64]; - seprintf(msg, lastof(msg), "****** Built on %s. ******", _openttd_build_date); userstream.Type = LastReservedStream + 1; - userstream.Buffer = msg; - userstream.BufferSize = sizeof(msg); + userstream.Buffer = (void*)this->crashlog; + userstream.BufferSize = (ULONG)strlen(this->crashlog) + 1; musi.UserStreamCount = 1; musi.UserStreamArray = &userstream; @@ -453,31 +340,53 @@ static LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep) mdei.ClientPointers = false; funcMiniDumpWriteDump(proc, procid, file, MiniDumpWithDataSegs, &mdei, &musi, NULL); + ret = 1; + } else { + ret = -1; } FreeLibrary(dbghelp); } -#endif + return ret; +} +#endif /* _MSC_VER */ + +extern bool CloseConsoleLogIfActive(); +static void ShowCrashlogWindow(); + +/** + * Stack pointer for use when 'starting' the crash handler. + * Not static as gcc's inline assembly needs it that way. + */ +void *_safe_esp = NULL; - if (_file_crash_log != INVALID_HANDLE_VALUE) { - GamelogPrint(&GamelogPrintCrashLogProc); - CloseHandle(_file_crash_log); +static LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep) +{ + if (CrashLogWindows::current != NULL) { + CrashLog::AfterCrashLogCleanup(); + ExitProcess(2); } + CrashLogWindows *log = new CrashLogWindows(ep); + CrashLogWindows::current = log; + log->FillCrashLog(log->crashlog, lastof(log->crashlog)); + log->WriteCrashLog(log->crashlog, log->crashlog_filename, lastof(log->crashlog_filename)); + log->WriteCrashDump(log->crashdump_filename, lastof(log->crashdump_filename)); + /* Close any possible log files */ CloseConsoleLogIfActive(); if (_safe_esp) { #ifdef _M_AMD64 - ep->ContextRecord->Rip = (DWORD64)Handler2; + ep->ContextRecord->Rip = (DWORD64)ShowCrashlogWindow; ep->ContextRecord->Rsp = (DWORD64)_safe_esp; #else - ep->ContextRecord->Eip = (DWORD)Handler2; + ep->ContextRecord->Eip = (DWORD)ShowCrashlogWindow; ep->ContextRecord->Esp = (DWORD)_safe_esp; #endif return EXCEPTION_CONTINUE_EXECUTION; } - + CrashLog::AfterCrashLogCleanup(); return EXCEPTION_EXECUTE_HANDLER; } @@ -485,8 +394,9 @@ static LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep) extern "C" void *_get_safe_esp(); #endif -void Win32InitializeExceptions() +/* static */ void CrashLog::InitialiseCrashLog() { +#if defined(_MSC_VER) #ifdef _M_AMD64 _safe_esp = _get_safe_esp(); #else @@ -494,7 +404,111 @@ void Win32InitializeExceptions() mov _safe_esp, esp } #endif +#else + asm("movl %esp, __safe_esp"); +#endif SetUnhandledExceptionFilter(ExceptionHandler); } -#endif /* WIN32_EXCEPTION_TRACKER */ + +/* The crash log GUI */ + +static bool _expanded; + +static const TCHAR _crash_desc[] = + _T("A serious fault condition occured in the game. The game will shut down.\n") + _T("Please send the crash information and the crash.dmp file (if any) to the developers.\n") + _T("This will greatly help debugging. The correct place to do this is http://bugs.openttd.org. ") + _T("The information contained in the report is displayed below.\n") + _T("Press \"Emergency save\" to attempt saving the game."); + +static const TCHAR _save_succeeded[] = + _T("Emergency save succeeded.\n") + _T("Be aware that critical parts of the internal game state may have become ") + _T("corrupted. The saved game is not guaranteed to work."); + +static const TCHAR _emergency_crash[] = + _T("A serious fault condition occured in the game. The game will shut down.\n") + _T("As you loaded an emergency savegame no crash information will be generated.\n"); + +static const TCHAR * const _expand_texts[] = {_T("S&how report >>"), _T("&Hide report <<") }; + +static void SetWndSize(HWND wnd, int mode) +{ + RECT r, r2; + + GetWindowRect(wnd, &r); + SetDlgItemText(wnd, 15, _expand_texts[mode == 1]); + + if (mode >= 0) { + GetWindowRect(GetDlgItem(wnd, 11), &r2); + int offs = r2.bottom - r2.top + 10; + if (!mode) offs = -offs; + SetWindowPos(wnd, HWND_TOPMOST, 0, 0, + r.right - r.left, r.bottom - r.top + offs, SWP_NOMOVE | SWP_NOZORDER); + } else { + SetWindowPos(wnd, HWND_TOPMOST, + (GetSystemMetrics(SM_CXSCREEN) - (r.right - r.left)) / 2, + (GetSystemMetrics(SM_CYSCREEN) - (r.bottom - r.top)) / 2, + 0, 0, SWP_NOSIZE); + } +} + +static INT_PTR CALLBACK CrashDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + switch (msg) { + case WM_INITDIALOG: { +#if defined(UNICODE) + /* We need to put the crash-log in a seperate buffer because the default + * buffer in MB_TO_WIDE is not large enough (512 chars) */ + wchar_t crash_msgW[lengthof(CrashLogWindows::current->crashlog)]; +#endif + /* Convert unix -> dos newlines because the edit box only supports that properly :( */ + const char *unix_nl = CrashLogWindows::current->crashlog; + char dos_nl[lengthof(CrashLogWindows::current->crashlog)]; + char *p = dos_nl; + WChar c; + while ((c = Utf8Consume(&unix_nl)) && p < lastof(dos_nl) - 4) { // 4 is max number of bytes per character + if (c == '\n') p += Utf8Encode(p, '\r'); + p += Utf8Encode(p, c); + } + *p = '\0'; + + SetDlgItemText(wnd, 10, _crash_desc); + SetDlgItemText(wnd, 11, MB_TO_WIDE_BUFFER(dos_nl, crash_msgW, lengthof(crash_msgW))); + SendDlgItemMessage(wnd, 11, WM_SETFONT, (WPARAM)GetStockObject(ANSI_FIXED_FONT), FALSE); + SetWndSize(wnd, -1); + } return TRUE; + case WM_COMMAND: + switch (wParam) { + case 12: // Close + CrashLog::AfterCrashLogCleanup(); + ExitProcess(2); + case 13: // Emergency save + char filename[MAX_PATH]; + if (CrashLogWindows::current->WriteSavegame(filename, lastof(filename))) { + MessageBox(wnd, _save_succeeded, _T("Save successful"), MB_ICONINFORMATION); + } else { + MessageBox(wnd, _T("Save failed"), _T("Save failed"), MB_ICONINFORMATION); + } + break; + case 15: // Expand window to show crash-message + _expanded ^= 1; + SetWndSize(wnd, _expanded); + break; + } + return TRUE; + case WM_CLOSE: + CrashLog::AfterCrashLogCleanup(); + ExitProcess(2); + } + + return FALSE; +} + +static void ShowCrashlogWindow() +{ + ShowCursor(TRUE); + ShowWindow(GetActiveWindow(), FALSE); + DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(100), NULL, CrashDialogFunc); +} diff --git a/src/os/windows/win32.cpp b/src/os/windows/win32.cpp index 985a7a343..6ca970149 100644 --- a/src/os/windows/win32.cpp +++ b/src/os/windows/win32.cpp @@ -23,6 +23,7 @@ #include "../../functions.h" #include "../../core/random_func.hpp" #include "../../string_func.h" +#include "../../crashlog.h" #include <errno.h> #include <sys/stat.h> @@ -72,14 +73,6 @@ void ShowOSErrorBox(const char *buf, bool system) { MyShowCursor(true); MessageBox(GetActiveWindow(), MB_TO_WIDE(buf), _T("Error!"), MB_ICONSTOP); - - /* If exception tracker is enabled, we crash here to let the exception handler handle it. */ -#if defined(WIN32_EXCEPTION_TRACKER) && defined(NDEBUG) - if (system) { - SetExceptionString("%s", buf); - *(byte*)0 = 0; - } -#endif } /* Code below for windows version of opendir/readdir/closedir copied and @@ -354,6 +347,8 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLi _codepage = GetACP(); // get system codepage as some kind of a default #endif /* UNICODE */ + CrashLog::InitialiseCrashLog(); + #if defined(UNICODE) #if !defined(WINCE) @@ -382,11 +377,6 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLi argc = ParseCommandLine(cmdline, argv, lengthof(argv)); -#if defined(WIN32_EXCEPTION_TRACKER) - void Win32InitializeExceptions(); - Win32InitializeExceptions(); -#endif - ttd_main(argc, argv); return 0; } diff --git a/src/stdafx.h b/src/stdafx.h index bd9caf0fa..35cbc8b1b 100644 --- a/src/stdafx.h +++ b/src/stdafx.h @@ -230,12 +230,9 @@ #endif - #if defined(WIN32_EXCEPTION_TRACKER) - void SetExceptionString(const char *s, ...) WARN_FORMAT(1, 2); - #if defined(NDEBUG) && defined(WITH_ASSERT) - #undef assert - #define assert(expression) if (!(expression)) { SetExceptionString("Assertion failed at %s:%d: %s", __FILE__, __LINE__, #expression); *(byte*)0 = 0; } - #endif + #if defined(NDEBUG) && defined(WITH_ASSERT) + #undef assert + #define assert(expression) if (!(expression)) error("Assertion failed at line %i of %s: %s", __LINE__, __FILE__, #expression); #endif /* MSVC doesn't have these :( */ |