tron@2186: /* $Id$ */ tron@2186: truelight@0: #include "stdafx.h" Darkvater@1891: #include "openttd.h" tron@1302: #include "debug.h" tron@2163: #include "functions.h" tron@2171: #include "macros.h" tron@2162: #include "saveload.h" tron@1317: #include "string.h" truelight@0: #include "gfx.h" truelight@0: #include "window.h" truelight@0: #include truelight@0: #include truelight@0: #include truelight@0: #include truelight@0: #include Darkvater@5304: #include // SHGetFolderPath tron@2160: #include "variables.h" tron@2183: #include "win32.h" Darkvater@4218: #include "fios.h" // opendir/readdir/closedir Darkvater@4210: #include Darkvater@5168: #include Darkvater@4218: #include Darkvater@4218: #include Darkvater@4218: #include tron@2171: truelight@0: static bool _has_console; truelight@0: orudge@3394: #if defined(__MINGW32__) orudge@3394: #include orudge@3394: #endif truelight@0: tron@2208: static bool cursor_visible = true; tron@2208: tron@2207: bool MyShowCursor(bool show) tron@2207: { tron@2209: if (cursor_visible == show) return show; tron@2207: tron@2209: cursor_visible = show; tron@2207: ShowCursor(show); tron@2207: tron@2207: return !show; tron@2207: } tron@2207: Darkvater@5168: /** Helper function needed by dynamically loading libraries Darkvater@5168: * XXX: Hurray for MS only having an ANSI GetProcAddress function Darkvater@5168: * on normal windows and no Wide version except for in Windows Mobile/CE */ Darkvater@5168: bool LoadLibraryList(Function proc[], const char *dll) truelight@0: { tron@1468: while (*dll != '\0') { Darkvater@5168: HMODULE lib; Darkvater@5168: lib = LoadLibrary(MB_TO_WIDE(dll)); tron@2183: tron@2183: if (lib == NULL) return false; tron@4077: for (;;) { tron@4077: FARPROC p; tron@2183: tron@2183: while (*dll++ != '\0'); tron@2183: if (*dll == '\0') break; Darkvater@5168: #if defined(WINCE) Darkvater@5168: p = GetProcAddress(lib, MB_TO_WIDE(dll); Darkvater@5168: #else truelight@0: p = GetProcAddress(lib, dll); Darkvater@5168: #endif tron@2183: if (p == NULL) return false; tron@2183: *proc++ = (Function)p; truelight@0: } truelight@0: dll++; truelight@0: } truelight@0: return true; truelight@0: } truelight@0: darkvater@796: #ifdef _MSC_VER Darkvater@5168: static const char *_exception_string = NULL; Darkvater@2428: #endif truelight@0: truelight@0: void ShowOSErrorBox(const char *buf) truelight@0: { truelight@0: MyShowCursor(true); Darkvater@5168: MessageBox(GetActiveWindow(), MB_TO_WIDE(buf), _T("Error!"), MB_ICONSTOP); truelight@0: truelight@0: // if exception tracker is enabled, we crash here to let the exception handler handle it. truelight@0: #if defined(WIN32_EXCEPTION_TRACKER) && !defined(_DEBUG) truelight@0: if (*buf == '!') { truelight@0: _exception_string = buf; truelight@0: *(byte*)0 = 0; truelight@0: } truelight@0: #endif truelight@0: } truelight@0: Darkvater@2428: #ifdef _MSC_VER Darkvater@2428: Darkvater@2428: static void *_safe_esp; Darkvater@2428: static char *_crash_msg; Darkvater@2428: static bool _expanded; Darkvater@2428: static bool _did_emerg_save; Darkvater@2428: static int _ident; Darkvater@2428: truelight@0: typedef struct DebugFileInfo { truelight@0: uint32 size; truelight@0: uint32 crc32; truelight@0: SYSTEMTIME file_time; truelight@0: } DebugFileInfo; truelight@0: truelight@0: static uint32 *_crc_table; truelight@0: truelight@0: static void MakeCRCTable(uint32 *table) { truelight@0: uint32 crc, poly = 0xEDB88320L; tron@2026: int i; tron@2026: int j; truelight@193: truelight@0: _crc_table = table; truelight@0: tron@1468: for (i = 0; i != 256; i++) { truelight@0: crc = i; tron@1468: for (j = 8; j != 0; j--) { belugas@4078: crc = (crc & 1 ? (crc >> 1) ^ poly : crc >> 1); truelight@0: } truelight@0: table[i] = crc; truelight@0: } truelight@0: } truelight@0: truelight@0: static uint32 CalcCRC(byte *data, uint size, uint32 crc) { tron@1468: for (; size > 0; size--) { tron@1468: crc = ((crc >> 8) & 0x00FFFFFF) ^ _crc_table[(crc ^ *data++) & 0xFF]; tron@1468: } truelight@0: return crc; truelight@0: } truelight@0: Darkvater@5168: static void GetFileInfo(DebugFileInfo *dfi, const TCHAR *filename) truelight@0: { Darkvater@5310: HANDLE file; truelight@0: memset(dfi, 0, sizeof(dfi)); truelight@0: Darkvater@5310: file = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0); Darkvater@5310: if (file != INVALID_HANDLE_VALUE) { truelight@0: byte buffer[1024]; truelight@0: DWORD numread; truelight@0: uint32 filesize = 0; truelight@0: FILETIME write_time; truelight@0: uint32 crc = (uint32)-1; truelight@0: Darkvater@5310: for (;;) { Darkvater@5310: if (ReadFile(file, buffer, sizeof(buffer), &numread, NULL) == 0 || numread == 0) Darkvater@5310: break; Darkvater@5310: filesize += numread; Darkvater@5310: crc = CalcCRC(buffer, numread, crc); Darkvater@5310: } Darkvater@5310: dfi->size = filesize; Darkvater@5310: dfi->crc32 = crc ^ (uint32)-1; truelight@193: Darkvater@5310: if (GetFileTime(file, NULL, NULL, &write_time)) { Darkvater@5310: FileTimeToSystemTime(&write_time, &dfi->file_time); truelight@0: } Darkvater@5310: CloseHandle(file); truelight@0: } truelight@0: } truelight@0: truelight@0: truelight@0: static char *PrintModuleInfo(char *output, HMODULE mod) truelight@0: { Darkvater@5168: TCHAR buffer[MAX_PATH]; truelight@0: DebugFileInfo dfi; tron@1468: truelight@0: GetModuleFileName(mod, buffer, MAX_PATH); truelight@0: GetFileInfo(&dfi, buffer); tron@2458: output += sprintf(output, " %-20s handle: %p size: %d crc: %.8X date: %d-%.2d-%.2d %.2d:%.2d:%.2d\r\n", Darkvater@5168: WIDE_TO_MB(buffer), truelight@0: mod, truelight@0: dfi.size, truelight@0: dfi.crc32, truelight@0: dfi.file_time.wYear, truelight@0: dfi.file_time.wMonth, truelight@0: dfi.file_time.wDay, truelight@0: dfi.file_time.wHour, truelight@0: dfi.file_time.wMinute, truelight@0: dfi.file_time.wSecond truelight@0: ); truelight@0: return output; truelight@0: } truelight@0: truelight@0: static char *PrintModuleList(char *output) truelight@0: { Darkvater@5310: BOOL (WINAPI *EnumProcessModules)(HANDLE, HMODULE*, DWORD, LPDWORD); truelight@0: Darkvater@5168: if (LoadLibraryList((Function*)&EnumProcessModules, "psapi.dll\0EnumProcessModules\0\0")) { Darkvater@5310: HMODULE modules[100]; Darkvater@5310: DWORD needed; Darkvater@5310: BOOL res; Darkvater@5310: int count, i; Darkvater@5310: Darkvater@5310: HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId()); Darkvater@5310: if (proc != NULL) { truelight@0: res = EnumProcessModules(proc, modules, sizeof(modules), &needed); truelight@0: CloseHandle(proc); truelight@0: if (res) { Darkvater@5310: count = min(needed / sizeof(HMODULE), lengthof(modules)); Darkvater@5310: Darkvater@5310: for (i = 0; i != count; i++) output = PrintModuleInfo(output, modules[i]); truelight@0: return output; truelight@0: } truelight@0: } truelight@0: } truelight@0: output = PrintModuleInfo(output, NULL); truelight@0: return output; truelight@0: } truelight@0: Darkvater@5168: static const TCHAR _crash_desc[] = Darkvater@5168: _T("A serious fault condition occured in the game. The game will shut down.\n") celestar@5648: _T("Please send the crash information and the crash.dmp file (if any) to the developers.\n") celestar@5648: _T("This will greatly help debugging. The correct place to do this is http://bugs.openttd.org. ") Darkvater@5168: _T("The information contained in the report is displayed below.\n") Darkvater@5168: _T("Press \"Emergency save\" to attempt saving the game."); truelight@0: Darkvater@5168: static const TCHAR _save_succeeded[] = Darkvater@5168: _T("Emergency save succeeded.\n") Darkvater@5168: _T("Be aware that critical parts of the internal game state may have become ") Darkvater@5168: _T("corrupted. The saved game is not guaranteed to work."); truelight@0: Darkvater@1881: static bool EmergencySave(void) Darkvater@1881: { Darkvater@1881: SaveOrLoad("crash.sav", SL_SAVE); Darkvater@1881: return true; Darkvater@1881: } truelight@0: Darkvater@5311: /* Disable the crash-save submit code as it's not used */ Darkvater@5311: #if 0 Darkvater@5311: truelight@0: typedef struct { Darkvater@5168: HINTERNET (WINAPI *InternetOpen)(LPCTSTR,DWORD, LPCTSTR, LPCTSTR, DWORD); Darkvater@5168: HINTERNET (WINAPI *InternetConnect)(HINTERNET, LPCTSTR, INTERNET_PORT, LPCTSTR, LPCTSTR, DWORD, DWORD, DWORD); Darkvater@5168: HINTERNET (WINAPI *HttpOpenRequest)(HINTERNET, LPCTSTR, LPCTSTR, LPCTSTR, LPCTSTR, LPCTSTR *, DWORD, DWORD); Darkvater@5168: BOOL (WINAPI *HttpSendRequest)(HINTERNET, LPCTSTR, DWORD, LPVOID, DWORD); truelight@0: BOOL (WINAPI *InternetCloseHandle)(HINTERNET); truelight@0: BOOL (WINAPI *HttpQueryInfo)(HINTERNET, DWORD, LPVOID, LPDWORD, LPDWORD); truelight@0: } WinInetProcs; truelight@0: truelight@0: #define M(x) x "\0" Darkvater@5168: #if defined(UNICODE) Darkvater@5168: # define W(x) x "W" Darkvater@5168: #else Darkvater@5168: # define W(x) x "A" Darkvater@5168: #endif truelight@193: static const char wininet_files[] = truelight@0: M("wininet.dll") Darkvater@5168: M(W("InternetOpen")) Darkvater@5168: M(W("InternetConnect")) Darkvater@5168: M(W("HttpOpenRequest")) Darkvater@5168: M(W("HttpSendRequest")) truelight@0: M("InternetCloseHandle") Darkvater@5168: M(W("HttpQueryInfo")) truelight@0: M(""); Darkvater@5168: #undef W truelight@0: #undef M truelight@0: truelight@0: static WinInetProcs _wininet; truelight@0: Darkvater@5168: static const TCHAR *SubmitCrashReport(HWND wnd, void *msg, size_t msglen, const TCHAR *arg) truelight@0: { truelight@0: HINTERNET inet, conn, http; Darkvater@5168: const TCHAR *err = NULL; truelight@0: DWORD code, len; Darkvater@5168: static TCHAR buf[100]; Darkvater@5168: TCHAR buff[100]; truelight@0: Darkvater@5168: if (_wininet.InternetOpen == NULL && !LoadLibraryList((Function*)&_wininet, wininet_files)) return _T("can't load wininet.dll"); truelight@0: Darkvater@5168: inet = _wininet.InternetOpen(_T("OTTD"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 ); Darkvater@5168: if (inet == NULL) { err = _T("internetopen failed"); goto error1; } truelight@0: Darkvater@5168: conn = _wininet.InternetConnect(inet, _T("www.openttd.org"), INTERNET_DEFAULT_HTTP_PORT, _T(""), _T(""), INTERNET_SERVICE_HTTP, 0, 0); Darkvater@5168: if (conn == NULL) { err = _T("internetconnect failed"); goto error2; } truelight@0: Darkvater@5168: _sntprintf(buff, lengthof(buff), _T("/crash.php?file=%s&ident=%d"), arg, _ident); Darkvater@5168: Darkvater@5168: http = _wininet.HttpOpenRequest(conn, _T("POST"), buff, NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE , 0); Darkvater@5168: if (http == NULL) { err = _T("httpopenrequest failed"); goto error3; } Darkvater@5168: Darkvater@5168: if (!_wininet.HttpSendRequest(http, _T("Content-type: application/binary"), -1, msg, (DWORD)msglen)) { err = _T("httpsendrequest failed"); goto error4; } truelight@0: truelight@0: len = sizeof(code); Darkvater@5168: if (!_wininet.HttpQueryInfo(http, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &code, &len, 0)) { err = _T("httpqueryinfo failed"); goto error4; } truelight@193: truelight@0: if (code != 200) { Darkvater@5168: int l = _sntprintf(buf, lengthof(buf), _T("Server said: %d "), code); truelight@0: len = sizeof(buf) - l; truelight@0: _wininet.HttpQueryInfo(http, HTTP_QUERY_STATUS_TEXT, buf + l, &len, 0); truelight@0: err = buf; truelight@0: } truelight@0: truelight@0: error4: truelight@0: _wininet.InternetCloseHandle(http); truelight@0: error3: truelight@0: _wininet.InternetCloseHandle(conn); truelight@0: error2: truelight@0: _wininet.InternetCloseHandle(inet); truelight@0: error1: truelight@0: return err; truelight@0: } truelight@0: Darkvater@5168: static void SubmitFile(HWND wnd, const TCHAR *file) truelight@0: { truelight@0: HANDLE h; truelight@0: unsigned long size; truelight@0: unsigned long read; truelight@0: void *mem; truelight@0: truelight@0: h = CreateFile(file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); truelight@0: if (h == NULL) return; truelight@0: truelight@0: size = GetFileSize(h, NULL); truelight@0: if (size > 500000) goto error1; truelight@193: truelight@0: mem = malloc(size); truelight@0: if (mem == NULL) goto error1; truelight@0: truelight@0: if (!ReadFile(h, mem, size, &read, NULL) || read != size) goto error2; truelight@0: truelight@193: SubmitCrashReport(wnd, mem, size, file); truelight@0: truelight@0: error2: truelight@0: free(mem); truelight@0: error1: truelight@0: CloseHandle(h); truelight@0: } truelight@0: Darkvater@5311: #endif /* Disabled crash-submit procedures */ Darkvater@5311: Darkvater@5168: static const TCHAR * const _expand_texts[] = {_T("S&how report >>"), _T("&Hide report <<") }; truelight@0: truelight@0: static void SetWndSize(HWND wnd, int mode) truelight@0: { truelight@0: RECT r,r2; truelight@0: int offs; truelight@0: truelight@0: GetWindowRect(wnd, &r); truelight@193: truelight@0: SetDlgItemText(wnd, 15, _expand_texts[mode == 1]); truelight@193: truelight@0: if (mode >= 0) { truelight@0: GetWindowRect(GetDlgItem(wnd, 11), &r2); truelight@0: offs = r2.bottom - r2.top + 10; tron@1468: if (!mode) offs = -offs; tron@1468: SetWindowPos(wnd, HWND_TOPMOST, 0, 0, tron@1468: r.right - r.left, r.bottom - r.top + offs, SWP_NOMOVE | SWP_NOZORDER); truelight@0: } else { truelight@193: SetWindowPos(wnd, HWND_TOPMOST, tron@1468: (GetSystemMetrics(SM_CXSCREEN) - (r.right - r.left)) / 2, tron@1468: (GetSystemMetrics(SM_CYSCREEN) - (r.bottom - r.top)) / 2, truelight@0: 0, 0, SWP_NOSIZE); truelight@0: } truelight@0: } truelight@0: truelight@0: static bool DoEmergencySave(HWND wnd) truelight@0: { truelight@0: bool b = false; truelight@0: truelight@0: EnableWindow(GetDlgItem(wnd, 13), FALSE); truelight@0: _did_emerg_save = true; truelight@0: __try { truelight@0: b = EmergencySave(); truelight@0: } __except (1) {} truelight@0: return b; truelight@0: } truelight@0: tron@2458: static INT_PTR CALLBACK CrashDialogFunc(HWND wnd,UINT msg,WPARAM wParam,LPARAM lParam) truelight@0: { tron@2952: switch (msg) { Darkvater@5310: case WM_INITDIALOG: { Darkvater@5168: #if defined(UNICODE) Darkvater@5312: /* We need to put the crash-log in a seperate buffer because the default Darkvater@5312: * buffer in MB_TO_WIDE is not large enough (256 chars) */ Darkvater@5310: wchar_t crash_msgW[8096]; Darkvater@5168: #endif Darkvater@5310: SetDlgItemText(wnd, 10, _crash_desc); Darkvater@5310: SetDlgItemText(wnd, 11, MB_TO_WIDE_BUFFER(_crash_msg, crash_msgW, lengthof(crash_msgW))); Darkvater@5310: SendDlgItemMessage(wnd, 11, WM_SETFONT, (WPARAM)GetStockObject(ANSI_FIXED_FONT), FALSE); Darkvater@5310: SetWndSize(wnd, -1); Darkvater@5310: } return TRUE; Darkvater@5310: case WM_COMMAND: Darkvater@5310: switch (wParam) { Darkvater@5310: case 12: /* Close */ Darkvater@5310: ExitProcess(0); Darkvater@5310: case 13: /* Emergency save */ Darkvater@5310: if (DoEmergencySave(wnd)) { Darkvater@5310: MessageBox(wnd, _save_succeeded, _T("Save successful"), MB_ICONINFORMATION); Darkvater@5310: } else { Darkvater@5310: MessageBox(wnd, _T("Save failed"), _T("Save failed"), MB_ICONINFORMATION); Darkvater@5310: } Darkvater@5310: break; Darkvater@5311: /* Disable the crash-save submit code as it's not used */ Darkvater@5311: #if 0 Darkvater@5310: case 14: { /* Submit crash report */ Darkvater@5310: const TCHAR *s; truelight@0: Darkvater@5310: SetCursor(LoadCursor(NULL, IDC_WAIT)); Darkvater@5168: Darkvater@5310: s = SubmitCrashReport(wnd, _crash_msg, strlen(_crash_msg), _T("")); Darkvater@5310: if (s != NULL) { Darkvater@5310: MessageBox(wnd, s, _T("Error"), MB_ICONSTOP); Darkvater@5310: break; Darkvater@5310: } Darkvater@5310: Darkvater@5310: // try to submit emergency savegame Darkvater@5310: if (_did_emerg_save || DoEmergencySave(wnd)) SubmitFile(wnd, _T("crash.sav")); Darkvater@5310: Darkvater@5310: // try to submit the autosaved game Darkvater@5310: if (_opt.autosave) { Darkvater@5310: TCHAR buf[40]; Darkvater@5310: _sntprintf(buf, lengthof(buf), _T("autosave%d.sav"), (_autosave_ctr - 1) & 3); Darkvater@5310: SubmitFile(wnd, buf); Darkvater@5310: } Darkvater@5310: EnableWindow(GetDlgItem(wnd, 14), FALSE); Darkvater@5310: SetCursor(LoadCursor(NULL, IDC_ARROW)); Darkvater@5310: MessageBox(wnd, _T("Crash report submitted. Thank you."), _T("Crash Report"), MB_ICONINFORMATION); Darkvater@5310: } break; Darkvater@5311: #endif /* Disabled crash-submit procedures */ Darkvater@5310: case 15: /* Expand window to show crash-message */ Darkvater@5310: _expanded ^= 1; Darkvater@5310: SetWndSize(wnd, _expanded); Darkvater@5310: break; truelight@0: } Darkvater@5310: return TRUE; Darkvater@5310: case WM_CLOSE: ExitProcess(0); truelight@0: } truelight@0: truelight@0: return FALSE; truelight@0: } truelight@0: darkvater@1102: static void Handler2(void) truelight@0: { truelight@0: ShowCursor(TRUE); truelight@0: ShowWindow(GetActiveWindow(), FALSE); truelight@0: DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(100), NULL, CrashDialogFunc); truelight@0: } truelight@0: darkvater@1102: extern bool CloseConsoleLogIfActive(void); darkvater@1023: truelight@0: static LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep) truelight@0: { Darkvater@3204: extern const char _openttd_revision[]; truelight@0: char *output; Darkvater@5168: static bool had_exception = false; truelight@0: tron@1468: if (had_exception) ExitProcess(0); truelight@0: had_exception = true; truelight@193: truelight@0: _ident = GetTickCount(); // something pretty unique truelight@0: truelight@0: MakeCRCTable(alloca(256 * sizeof(uint32))); truelight@0: _crash_msg = output = LocalAlloc(LMEM_FIXED, 8192); truelight@0: truelight@0: { truelight@0: SYSTEMTIME time; truelight@0: GetLocalTime(&time); Darkvater@5168: output += sprintf(output, truelight@0: "*** OpenTTD Crash Report ***\r\n" truelight@0: "Date: %d-%.2d-%.2d %.2d:%.2d:%.2d\r\n" Darkvater@4236: "Build: %s built on " __DATE__ " " __TIME__ "\r\n", truelight@0: time.wYear, truelight@0: time.wMonth, truelight@0: time.wDay, truelight@0: time.wHour, truelight@0: time.wMinute, truelight@0: time.wSecond, Darkvater@3204: _openttd_revision truelight@0: ); truelight@0: } truelight@0: tron@1468: if (_exception_string) tron@1468: output += sprintf(output, "Reason: %s\r\n", _exception_string); truelight@0: Darkvater@2482: #ifdef _M_AMD64 Darkvater@2482: output += sprintf(output, "Exception %.8X at %.16IX\r\n" Darkvater@2482: "Registers:\r\n" Darkvater@2482: "RAX: %.16llX RBX: %.16llX RCX: %.16llX RDX: %.16llX\r\n" Darkvater@2482: "RSI: %.16llX RDI: %.16llX RBP: %.16llX RSP: %.16llX\r\n" Darkvater@2482: "R8: %.16llX R9: %.16llX R10: %.16llX R11: %.16llX\r\n" Darkvater@2482: "R12: %.16llX R13: %.16llX R14: %.16llX R15: %.16llX\r\n" Darkvater@2482: "RIP: %.16llX EFLAGS: %.8X\r\n" Darkvater@2482: "\r\nBytes at CS:RIP:\r\n", Darkvater@2482: ep->ExceptionRecord->ExceptionCode, Darkvater@2482: ep->ExceptionRecord->ExceptionAddress, Darkvater@2482: ep->ContextRecord->Rax, Darkvater@2482: ep->ContextRecord->Rbx, Darkvater@2482: ep->ContextRecord->Rcx, Darkvater@2482: ep->ContextRecord->Rdx, Darkvater@2482: ep->ContextRecord->Rsi, Darkvater@2482: ep->ContextRecord->Rdi, Darkvater@2482: ep->ContextRecord->Rbp, Darkvater@2482: ep->ContextRecord->Rsp, Darkvater@2482: ep->ContextRecord->R8, Darkvater@2482: ep->ContextRecord->R9, Darkvater@2482: ep->ContextRecord->R10, Darkvater@2482: ep->ContextRecord->R11, Darkvater@2482: ep->ContextRecord->R12, Darkvater@2482: ep->ContextRecord->R13, Darkvater@2482: ep->ContextRecord->R14, Darkvater@2482: ep->ContextRecord->R15, Darkvater@2482: ep->ContextRecord->Rip, Darkvater@2482: ep->ContextRecord->EFlags Darkvater@2482: ); Darkvater@2482: #else truelight@0: output += sprintf(output, "Exception %.8X at %.8X\r\n" truelight@0: "Registers:\r\n" truelight@0: " EAX: %.8X EBX: %.8X ECX: %.8X EDX: %.8X\r\n" truelight@0: " ESI: %.8X EDI: %.8X EBP: %.8X ESP: %.8X\r\n" truelight@0: " EIP: %.8X EFLAGS: %.8X\r\n" truelight@0: "\r\nBytes at CS:EIP:\r\n", truelight@0: ep->ExceptionRecord->ExceptionCode, truelight@0: ep->ExceptionRecord->ExceptionAddress, truelight@0: ep->ContextRecord->Eax, truelight@0: ep->ContextRecord->Ebx, truelight@0: ep->ContextRecord->Ecx, truelight@0: ep->ContextRecord->Edx, truelight@0: ep->ContextRecord->Esi, truelight@0: ep->ContextRecord->Edi, truelight@0: ep->ContextRecord->Ebp, truelight@0: ep->ContextRecord->Esp, truelight@0: ep->ContextRecord->Eip, truelight@0: ep->ContextRecord->EFlags truelight@0: ); Darkvater@2482: #endif truelight@0: truelight@0: { Darkvater@2482: #ifdef _M_AMD64 Darkvater@2482: byte *b = (byte*)ep->ContextRecord->Rip; Darkvater@2482: #else truelight@0: byte *b = (byte*)ep->ContextRecord->Eip; Darkvater@2482: #endif truelight@0: int i; tron@1468: for (i = 0; i != 24; i++) { truelight@0: if (IsBadReadPtr(b, 1)) { truelight@0: output += sprintf(output, " ??"); // OCR: WAS: , 0); truelight@0: } else { truelight@0: output += sprintf(output, " %.2X", *b); truelight@0: } truelight@0: b++; truelight@0: } truelight@0: output += sprintf(output, truelight@0: "\r\n" truelight@0: "\r\nStack trace: \r\n" truelight@0: ); truelight@0: } truelight@0: truelight@0: { truelight@0: int i,j; Darkvater@2482: #ifdef _M_AMD64 Darkvater@2482: uint32 *b = (uint32*)ep->ContextRecord->Rsp; Darkvater@2482: #else truelight@0: uint32 *b = (uint32*)ep->ContextRecord->Esp; Darkvater@2482: #endif tron@1468: for (j = 0; j != 24; j++) { tron@1468: for (i = 0; i != 8; i++) { truelight@0: if (IsBadReadPtr(b,sizeof(uint32))) { truelight@0: output += sprintf(output, " ????????"); //OCR: WAS - , 0); truelight@0: } else { truelight@0: output += sprintf(output, " %.8X", *b); truelight@0: } truelight@0: b++; truelight@0: } truelight@0: output += sprintf(output, "\r\n"); truelight@0: } truelight@0: } truelight@0: truelight@0: output += sprintf(output, "\r\nModule information:\r\n"); truelight@0: output = PrintModuleList(output); truelight@0: truelight@0: { truelight@0: OSVERSIONINFO os; truelight@0: os.dwOSVersionInfoSize = sizeof(os); truelight@0: GetVersionEx(&os); truelight@0: output += sprintf(output, "\r\nSystem information:\r\n" tron@1468: " Windows version %d.%d %d %s\r\n", tron@1468: os.dwMajorVersion, os.dwMinorVersion, os.dwBuildNumber, os.szCSDVersion); truelight@0: } truelight@0: truelight@0: { Darkvater@5168: HANDLE file = CreateFile(_T("crash.log"), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0); truelight@0: DWORD num_written; truelight@0: if (file != INVALID_HANDLE_VALUE) { truelight@0: WriteFile(file, _crash_msg, output - _crash_msg, &num_written, NULL); truelight@0: CloseHandle(file); truelight@0: } truelight@0: } truelight@0: darkvater@1023: /* Close any possible log files */ darkvater@1023: CloseConsoleLogIfActive(); darkvater@1023: truelight@0: if (_safe_esp) { Darkvater@2482: #ifdef _M_AMD64 Darkvater@2482: ep->ContextRecord->Rip = (DWORD64)Handler2; Darkvater@2482: ep->ContextRecord->Rsp = (DWORD64)_safe_esp; Darkvater@2482: #else truelight@0: ep->ContextRecord->Eip = (DWORD)Handler2; truelight@0: ep->ContextRecord->Esp = (DWORD)_safe_esp; Darkvater@2482: #endif truelight@0: return EXCEPTION_CONTINUE_EXECUTION; truelight@0: } darkvater@1023: darkvater@1023: darkvater@1023: return EXCEPTION_EXECUTE_HANDLER; truelight@0: } truelight@0: darkvater@1102: static void Win32InitializeExceptions(void) truelight@0: { Darkvater@2482: #ifdef _M_AMD64 Darkvater@3341: extern void *_get_save_esp(void); Darkvater@2482: _safe_esp = _get_save_esp(); Darkvater@2482: #else truelight@0: _asm { tron@1468: mov _safe_esp, esp truelight@0: } Darkvater@2482: #endif truelight@193: truelight@0: SetUnhandledExceptionFilter(ExceptionHandler); truelight@0: } Darkvater@3341: #endif /* _MSC_VER */ truelight@0: Darkvater@4218: /* Code below for windows version of opendir/readdir/closedir copied and Darkvater@4218: * modified from Jan Wassenberg's GPL implementation posted over at Darkvater@4218: * http://www.gamedev.net/community/forums/topic.asp?topic_id=364584&whichpage=1� */ Darkvater@4218: Darkvater@4218: /* suballocator - satisfies most requests with a reusable static instance. Darkvater@4218: * this avoids hundreds of alloc/free which would fragment the heap. Darkvater@4224: * To guarantee reentrancy, we fall back to malloc if the instance is Darkvater@4218: * already in use (it's important to avoid suprises since this is such a Darkvater@4218: * low-level routine). */ Darkvater@4218: static DIR _global_dir; Darkvater@4218: static bool _global_dir_is_in_use = false; Darkvater@4218: Darkvater@4218: static inline DIR *dir_calloc(void) Darkvater@4218: { Darkvater@4218: DIR *d; Darkvater@4218: Darkvater@4218: if (_global_dir_is_in_use) { Darkvater@4224: d = calloc(1, sizeof(*d)); Darkvater@4218: } else { Darkvater@4218: _global_dir_is_in_use = true; Darkvater@4218: d = &_global_dir; Darkvater@4224: memset(d, 0, sizeof(*d)); Darkvater@4218: } Darkvater@4218: return d; Darkvater@4218: } Darkvater@4218: Darkvater@4218: static inline void dir_free(DIR *d) Darkvater@4218: { Darkvater@4218: if (d == &_global_dir) { Darkvater@4218: _global_dir_is_in_use = false; Darkvater@4218: } else { Darkvater@4218: free(d); Darkvater@4218: } Darkvater@4218: } Darkvater@4218: Darkvater@4218: DIR *opendir(const char *path) Darkvater@4218: { Darkvater@4218: DIR *d; Darkvater@4218: UINT sem = SetErrorMode(SEM_FAILCRITICALERRORS); // disable 'no-disk' message box Darkvater@5167: DWORD fa = GetFileAttributesW(OTTD2FS(path)); Darkvater@4218: Darkvater@4224: if ((fa != INVALID_FILE_ATTRIBUTES) && (fa & FILE_ATTRIBUTE_DIRECTORY)) { Darkvater@4224: d = dir_calloc(); Darkvater@4224: if (d != NULL) { Darkvater@5120: char search_path[MAX_PATH]; Darkvater@4224: /* build search path for FindFirstFile */ Darkvater@4224: snprintf(search_path, lengthof(search_path), "%s" PATHSEP "*", path); Darkvater@5167: d->hFind = FindFirstFileW(OTTD2FS(search_path), &d->fd); Darkvater@4224: Darkvater@4224: if (d->hFind != INVALID_HANDLE_VALUE || Darkvater@4224: GetLastError() == ERROR_NO_MORE_FILES) { // the directory is empty Darkvater@4224: d->ent.dir = d; Darkvater@4224: d->at_first_entry = true; Darkvater@4224: } else { Darkvater@4224: dir_free(d); Darkvater@4224: d = NULL; Darkvater@4224: } Darkvater@4224: } else { Darkvater@4224: errno = ENOMEM; Darkvater@4224: } Darkvater@4224: } else { Darkvater@4224: /* path not found or not a directory */ Darkvater@4224: d = NULL; Darkvater@4218: errno = ENOENT; Darkvater@4218: } Darkvater@4218: Darkvater@4218: SetErrorMode(sem); // restore previous setting Darkvater@4218: return d; Darkvater@4218: } Darkvater@4218: Darkvater@4218: struct dirent *readdir(DIR *d) Darkvater@4218: { Darkvater@4218: DWORD prev_err = GetLastError(); // avoid polluting last error Darkvater@4218: Darkvater@4218: if (d->at_first_entry) { Darkvater@4218: /* the directory was empty when opened */ Darkvater@4218: if (d->hFind == INVALID_HANDLE_VALUE) return NULL; Darkvater@4218: d->at_first_entry = false; Darkvater@5167: } else if (!FindNextFileW(d->hFind, &d->fd)) { // determine cause and bail Darkvater@4218: if (GetLastError() == ERROR_NO_MORE_FILES) SetLastError(prev_err); Darkvater@4218: return NULL; Darkvater@4218: } Darkvater@4218: Darkvater@4218: /* This entry has passed all checks; return information about it. Darkvater@4218: * (note: d_name is a pointer; see struct dirent definition) */ Darkvater@4218: d->ent.d_name = d->fd.cFileName; Darkvater@4218: return &d->ent; Darkvater@4218: } Darkvater@4218: Darkvater@4218: int closedir(DIR *d) Darkvater@4218: { Darkvater@4218: FindClose(d->hFind); Darkvater@4218: dir_free(d); Darkvater@4218: return 0; Darkvater@4218: } Darkvater@4218: Darkvater@4221: bool FiosIsRoot(const char *file) truelight@0: { Darkvater@4221: return file[3] == '\0'; // C:\... truelight@0: } truelight@0: Darkvater@4221: void FiosGetDrives(void) truelight@0: { Darkvater@5168: TCHAR drives[256]; Darkvater@5168: const TCHAR *s; truelight@0: Darkvater@4221: GetLogicalDriveStrings(sizeof(drives), drives); Darkvater@4221: for (s = drives; *s != '\0';) { Darkvater@4221: FiosItem *fios = FiosAlloc(); Darkvater@4221: fios->type = FIOS_TYPE_DRIVE; Darkvater@4221: fios->mtime = 0; Darkvater@5168: snprintf(fios->name, lengthof(fios->name), "%c:", s[0] & 0xFF); Darkvater@4221: ttd_strlcpy(fios->title, fios->name, lengthof(fios->title)); Darkvater@4221: while (*s++ != '\0'); truelight@0: } truelight@0: } truelight@0: Darkvater@4221: bool FiosIsValidFile(const char *path, const struct dirent *ent, struct stat *sb) truelight@0: { Darkvater@4245: // hectonanoseconds between Windows and POSIX epoch Darkvater@4247: static const int64 posix_epoch_hns = 0x019DB1DED53E8000LL; Darkvater@5167: const WIN32_FIND_DATAW *fd = &ent->dir->fd; Darkvater@4224: if (fd->dwFileAttributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) return false; truelight@0: Darkvater@4224: sb->st_size = ((uint64) fd->nFileSizeHigh << 32) + fd->nFileSizeLow; Darkvater@4245: /* UTC FILETIME to seconds-since-1970 UTC Darkvater@4245: * we just have to subtract POSIX epoch and scale down to units of seconds. Darkvater@4245: * http://www.gamedev.net/community/forums/topic.asp?topic_id=294070&whichpage=1� Darkvater@4245: * XXX - not entirely correct, since filetimes on FAT aren't UTC but local, Darkvater@4245: * this won't entirely be correct, but we use the time only for comparsion. */ Darkvater@4245: sb->st_mtime = (time_t)((*(uint64*)&fd->ftLastWriteTime - posix_epoch_hns) / 1E7); Darkvater@4221: sb->st_mode = (fd->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)? S_IFDIR : S_IFREG; Darkvater@4224: Darkvater@4221: return true; truelight@0: } truelight@0: Darkvater@4222: bool FiosGetDiskFreeSpace(const char *path, uint32 *tot) truelight@0: { darkvater@1596: UINT sem = SetErrorMode(SEM_FAILCRITICALERRORS); // disable 'no-disk' message box Darkvater@4222: bool retval = false; Darkvater@5168: TCHAR root[4]; truelight@0: DWORD spc, bps, nfc, tnc; darkvater@1596: Darkvater@5168: _sntprintf(root, lengthof(root), _T("%c:") _T(PATHSEP), path[0]); darkvater@1596: if (tot != NULL && GetDiskFreeSpace(root, &spc, &bps, &nfc, &tnc)) { darkvater@1596: *tot = ((spc * bps) * (uint64)nfc) >> 20; Darkvater@4222: retval = true; tron@4077: } darkvater@1596: darkvater@1596: SetErrorMode(sem); // reset previous setting Darkvater@4222: return retval; truelight@0: } truelight@0: truelight@0: static int ParseCommandLine(char *line, char **argv, int max_argc) truelight@0: { truelight@0: int n = 0; truelight@0: truelight@0: do { truelight@0: // skip whitespace Darkvater@5310: while (*line == ' ' || *line == '\t') line++; truelight@0: truelight@0: // end? Darkvater@5310: if (*line == '\0') break; truelight@193: truelight@0: // special handling when quoted truelight@0: if (*line == '"') { truelight@0: argv[n++] = ++line; truelight@0: while (*line != '"') { tron@1468: if (*line == '\0') return n; truelight@0: line++; truelight@0: } truelight@0: } else { truelight@0: argv[n++] = line; truelight@0: while (*line != ' ' && *line != '\t') { tron@1468: if (*line == '\0') return n; truelight@0: line++; truelight@0: } truelight@0: } tron@1468: *line++ = '\0'; truelight@0: } while (n != max_argc); truelight@0: truelight@0: return n; truelight@0: } truelight@0: darkvater@1102: void CreateConsole(void) truelight@0: { truelight@0: HANDLE hand; truelight@0: CONSOLE_SCREEN_BUFFER_INFO coninfo; truelight@0: truelight@0: if (_has_console) return; truelight@0: _has_console = true; truelight@0: Darkvater@4572: AllocConsole(); truelight@193: truelight@0: hand = GetStdHandle(STD_OUTPUT_HANDLE); truelight@0: GetConsoleScreenBufferInfo(hand, &coninfo); truelight@0: coninfo.dwSize.Y = 500; truelight@0: SetConsoleScreenBufferSize(hand, coninfo.dwSize); truelight@193: truelight@0: // redirect unbuffered STDIN, STDOUT, STDERR to the console tron@2172: #if !defined(__CYGWIN__) Darkvater@2482: *stdout = *_fdopen( _open_osfhandle((intptr_t)hand, _O_TEXT), "w" ); Darkvater@2482: *stdin = *_fdopen(_open_osfhandle((intptr_t)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT), "r" ); Darkvater@2482: *stderr = *_fdopen(_open_osfhandle((intptr_t)GetStdHandle(STD_ERROR_HANDLE), _O_TEXT), "w" ); truelight@0: #else truelight@0: // open_osfhandle is not in cygwin truelight@0: *stdout = *fdopen(1, "w" ); truelight@543: *stdin = *fdopen(0, "r" ); truelight@193: *stderr = *fdopen(2, "w" ); truelight@0: #endif truelight@193: tron@1468: setvbuf(stdin, NULL, _IONBF, 0); tron@1468: setvbuf(stdout, NULL, _IONBF, 0); tron@1468: setvbuf(stderr, NULL, _IONBF, 0); truelight@0: } truelight@0: truelight@0: void ShowInfo(const char *str) truelight@0: { tron@4077: if (_has_console) { celestar@5648: fprintf(stderr, str); tron@4077: } else { truelight@0: bool old; truelight@193: truelight@0: ReleaseCapture(); truelight@0: _left_button_clicked =_left_button_down = false; truelight@193: truelight@0: old = MyShowCursor(true); Darkvater@5168: if (MessageBox(GetActiveWindow(), MB_TO_WIDE(str), _T("OpenTTD"), MB_ICONINFORMATION | MB_OKCANCEL) == IDCANCEL) { truelight@0: CreateConsole(); truelight@0: } truelight@0: MyShowCursor(old); truelight@0: } truelight@0: } truelight@0: Darkvater@2428: #ifdef __MINGW32__ Darkvater@2428: /* _set_error_mode() constants&function (do not exist in mingw headers) */ Darkvater@2428: #define _OUT_TO_DEFAULT 0 Darkvater@2428: #define _OUT_TO_STDERR 1 Darkvater@2428: #define _OUT_TO_MSGBOX 2 Darkvater@2428: #define _REPORT_ERRMODE 3 Darkvater@2428: int _set_error_mode(int); Darkvater@2428: #endif truelight@0: Darkvater@5168: int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, tron@1468: LPTSTR lpCmdLine, int nCmdShow) truelight@0: { truelight@0: int argc; truelight@0: char *argv[64]; // max 64 command line arguments Darkvater@5312: char *cmdline; truelight@0: Darkvater@5168: #if defined(UNICODE) Darkvater@5312: /* For UNICODE we need to convert the commandline to char* _AND_ Darkvater@5312: * save it because argv[] points into this buffer and thus needs to Darkvater@5312: * be available between subsequent calls to FS2OTTD() */ Darkvater@5312: char cmdlinebuf[MAX_PATH]; Darkvater@5168: #endif Darkvater@5168: Darkvater@5312: cmdline = WIDE_TO_MB_BUFFER(GetCommandLine(), cmdlinebuf, lengthof(cmdlinebuf)); Darkvater@5312: truelight@0: #if defined(_DEBUG) truelight@0: CreateConsole(); truelight@0: #endif truelight@0: Darkvater@2428: _set_error_mode(_OUT_TO_MSGBOX); // force assertion output to messagebox truelight@0: Darkvater@5310: /* setup random seed to something quite random */ rubidium@4369: _random_seeds[1][0] = _random_seeds[0][0] = GetTickCount(); rubidium@4369: _random_seeds[1][1] = _random_seeds[0][1] = _random_seeds[0][0] * 0x1234567; ludde@2073: SeedMT(_random_seeds[0][0]); truelight@0: Darkvater@5168: argc = ParseCommandLine(cmdline, argv, lengthof(argv)); truelight@0: truelight@0: #if defined(WIN32_EXCEPTION_TRACKER) Darkvater@5168: Win32InitializeExceptions(); truelight@0: #endif truelight@0: truelight@0: #if defined(WIN32_EXCEPTION_TRACKER_DEBUG) truelight@0: _try { Darkvater@5168: LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep); truelight@0: #endif truelight@0: ttd_main(argc, argv); truelight@0: truelight@0: #if defined(WIN32_EXCEPTION_TRACKER_DEBUG) truelight@0: } _except (ExceptionHandler(_exception_info())) {} truelight@0: #endif truelight@0: truelight@0: return 0; truelight@0: } truelight@0: Darkvater@1390: void DeterminePaths(void) truelight@0: { Darkvater@5167: char *s, *cfg; Darkvater@5167: wchar_t path[MAX_PATH]; truelight@0: Darkvater@5296: _paths.personal_dir = _paths.game_data_dir = cfg = malloc(MAX_PATH); Darkvater@5167: GetCurrentDirectoryW(MAX_PATH - 1, path); Darkvater@5218: convert_from_fs(path, cfg, MAX_PATH); truelight@193: Darkvater@2559: cfg[0] = toupper(cfg[0]); Darkvater@5120: s = strchr(cfg, '\0'); tron@1468: if (s[-1] != '\\') strcpy(s, "\\"); truelight@0: Darkvater@5296: _paths.save_dir = str_fmt("%ssave", cfg); Darkvater@5296: _paths.autosave_dir = str_fmt("%s\\autosave", _paths.save_dir); Darkvater@5296: _paths.scenario_dir = str_fmt("%sscenario", cfg); Darkvater@5296: _paths.heightmap_dir = str_fmt("%sscenario\\heightmap", cfg); Darkvater@5296: _paths.gm_dir = str_fmt("%sgm\\", cfg); Darkvater@5296: _paths.data_dir = str_fmt("%sdata\\", cfg); Darkvater@5296: _paths.lang_dir = str_fmt("%slang\\", cfg); truelight@0: Darkvater@1482: if (_config_file == NULL) Darkvater@5296: _config_file = str_fmt("%sopenttd.cfg", _paths.personal_dir); Darkvater@1482: Darkvater@5296: _highscore_file = str_fmt("%shs.dat", _paths.personal_dir); Darkvater@5296: _log_file = str_fmt("%sopenttd.log", _paths.personal_dir); truelight@0: truelight@0: // make (auto)save and scenario folder Darkvater@5296: CreateDirectoryW(OTTD2FS(_paths.save_dir), NULL); Darkvater@5296: CreateDirectoryW(OTTD2FS(_paths.autosave_dir), NULL); Darkvater@5296: CreateDirectoryW(OTTD2FS(_paths.scenario_dir), NULL); Darkvater@5296: CreateDirectoryW(OTTD2FS(_paths.heightmap_dir), NULL); truelight@0: } truelight@0: Darkvater@1390: /** Darkvater@1390: * Insert a chunk of text from the clipboard onto the textbuffer. Get TEXT clipboard Darkvater@1390: * and append this up to the maximum length (either absolute or screenlength). If maxlength Darkvater@1390: * is zero, we don't care about the screenlength but only about the physical length of the string Darkvater@1390: * @param tb @Textbuf type to be changed Darkvater@1390: * @return Return true on successfull change of Textbuf, or false otherwise Darkvater@1390: */ Darkvater@1390: bool InsertTextBufferClipboard(Textbuf *tb) Darkvater@1390: { peter1138@5108: HGLOBAL cbuf; peter1138@5108: char utf8_buf[512]; peter1138@5108: const char *ptr; Darkvater@1390: peter1138@5108: WChar c; peter1138@5108: uint16 width, length; peter1138@5108: peter1138@5108: if (IsClipboardFormatAvailable(CF_UNICODETEXT)) { Darkvater@5312: const char *ret; peter1138@5108: peter1138@5108: OpenClipboard(NULL); peter1138@5108: cbuf = GetClipboardData(CF_UNICODETEXT); peter1138@5108: peter1138@5108: ptr = GlobalLock(cbuf); Darkvater@5312: ret = convert_from_fs((wchar_t*)ptr, utf8_buf, lengthof(utf8_buf)); peter1138@5108: GlobalUnlock(cbuf); peter1138@5108: CloseClipboard(); peter1138@5108: Darkvater@5312: if (*ret == '\0') return false; peter1138@5108: } else if (IsClipboardFormatAvailable(CF_TEXT)) { Darkvater@1390: OpenClipboard(NULL); Darkvater@1390: cbuf = GetClipboardData(CF_TEXT); Darkvater@1390: peter1138@5108: ptr = GlobalLock(cbuf); peter1138@5108: ttd_strlcpy(utf8_buf, ptr, lengthof(utf8_buf)); Darkvater@1390: GlobalUnlock(cbuf); Darkvater@1390: CloseClipboard(); peter1138@5108: } else { peter1138@5108: return false; Darkvater@1390: } peter1138@5108: peter1138@5108: width = length = 0; peter1138@5108: peter1138@5108: for (ptr = utf8_buf; (c = Utf8Consume(&ptr)) != '\0';) { peter1138@5108: byte charwidth; peter1138@5108: peter1138@5108: if (!IsPrintable(c)) break; peter1138@5108: if (tb->length + length >= tb->maxlength - 1) break; peter1138@5108: charwidth = GetCharacterWidth(FS_NORMAL, c); peter1138@5108: peter1138@5108: if (tb->maxwidth != 0 && width + tb->width + charwidth > tb->maxwidth) break; peter1138@5108: peter1138@5108: width += charwidth; peter1138@5108: length += Utf8CharLen(c); peter1138@5108: } peter1138@5108: peter1138@5108: if (length == 0) return false; peter1138@5108: peter1138@5108: memmove(tb->buf + tb->caretpos + length, tb->buf + tb->caretpos, tb->length - tb->caretpos); peter1138@5108: memcpy(tb->buf + tb->caretpos, utf8_buf, length); peter1138@5108: tb->width += width; peter1138@5108: tb->caretxoffs += width; peter1138@5108: peter1138@5108: tb->length += length; peter1138@5108: tb->caretpos += length; peter1138@5108: tb->buf[tb->length] = '\0'; // terminating zero peter1138@5108: peter1138@5108: return true; Darkvater@1390: } Darkvater@1885: ludde@2073: ludde@2073: void CSleep(int milliseconds) ludde@2073: { ludde@2073: Sleep(milliseconds); Darkvater@2099: } ludde@2125: ludde@2125: ludde@2125: // Utility function to get the current timestamp in milliseconds ludde@2125: // Useful for profiling ludde@2139: int64 GetTS(void) ludde@2125: { ludde@2125: static double freq; ludde@2125: __int64 value; ludde@2125: if (!freq) { ludde@2125: QueryPerformanceFrequency((LARGE_INTEGER*)&value); ludde@2125: freq = (double)1000000 / value; ludde@2125: } ludde@2125: QueryPerformanceCounter((LARGE_INTEGER*)&value); ludde@2125: return (__int64)(value * freq); ludde@2139: } Darkvater@5167: Darkvater@5218: /** Convert from OpenTTD's encoding to that of the local environment in Darkvater@5218: * UNICODE. OpenTTD encoding is UTF8, local is wide-char Darkvater@5167: * @param name pointer to a valid string that will be converted Darkvater@5218: * @param utf16_buf pointer to a valid wide-char buffer that will receive the Darkvater@5218: * converted string Darkvater@5218: * @param buflen length in wide characters of the receiving buffer Darkvater@5218: * @return pointer to utf16_buf. If conversion fails the string is of zero-length */ Darkvater@5218: wchar_t *convert_to_fs(const char *name, wchar_t *utf16_buf, size_t buflen) Darkvater@5218: { Darkvater@5218: int len = MultiByteToWideChar(CP_UTF8, 0, name, -1, utf16_buf, buflen); Darkvater@5218: if (len == 0) { Darkvater@5568: DEBUG(misc, 0, "[utf8] error converting '%s'. Errno %d", name, GetLastError()); Darkvater@5218: utf16_buf[0] = '\0'; Darkvater@5218: } Darkvater@5218: Darkvater@5218: return utf16_buf; Darkvater@5218: } Darkvater@5218: Darkvater@5218: /** Convert from OpenTTD's encoding to that of the local environment in Darkvater@5218: * UNICODE. OpenTTD encoding is UTF8, local is wide-char. Darkvater@5218: * The returned value's contents can only be guaranteed until the next call to Darkvater@5218: * this function. So if the value is needed for anything else, use convert_from_fs Darkvater@5218: * @param name pointer to a valid string that will be converted Darkvater@5218: * @return pointer to the converted string; if failed string is of zero-length */ Darkvater@5167: const wchar_t *OTTD2FS(const char *name) Darkvater@5167: { Darkvater@5312: static wchar_t utf16_buf[512]; Darkvater@5218: return convert_to_fs(name, utf16_buf, lengthof(utf16_buf)); Darkvater@5218: } Darkvater@5167: Darkvater@5218: Darkvater@5218: /** Convert to OpenTTD's encoding from that of the local environment in Darkvater@5218: * UNICODE. OpenTTD encoding is UTF8, local is wide-char Darkvater@5218: * @param name pointer to a valid string that will be converted Darkvater@5218: * @param utf8_buf pointer to a valid buffer that will receive the converted string Darkvater@5218: * @param buflen length in characters of the receiving buffer Darkvater@5218: * @return pointer to utf8_buf. If conversion fails the string is of zero-length */ Darkvater@5218: char *convert_from_fs(const wchar_t *name, char *utf8_buf, size_t buflen) Darkvater@5218: { Darkvater@5218: int len = WideCharToMultiByte(CP_UTF8, 0, name, -1, utf8_buf, buflen, NULL, NULL); Darkvater@5167: if (len == 0) { Darkvater@5568: DEBUG(misc, 0, "[utf8] error converting wide-string. Errno %d", GetLastError()); Darkvater@5218: utf8_buf[0] = '\0'; Darkvater@5167: } Darkvater@5167: Darkvater@5218: return utf8_buf; Darkvater@5167: } Darkvater@5167: Darkvater@5218: /** Convert to OpenTTD's encoding from that of the local environment in Darkvater@5218: * UNICODE. OpenTTD encoding is UTF8, local is wide-char. Darkvater@5218: * The returned value's contents can only be guaranteed until the next call to Darkvater@5218: * this function. So if the value is needed for anything else, use convert_from_fs Darkvater@5167: * @param name pointer to a valid string that will be converted Darkvater@5218: * @return pointer to the converted string; if failed string is of zero-length */ Darkvater@5167: const char *FS2OTTD(const wchar_t *name) Darkvater@5167: { Darkvater@5167: static char utf8_buf[512]; Darkvater@5218: return convert_from_fs(name, utf8_buf, lengthof(utf8_buf)); Darkvater@5167: } Darkvater@5304: Darkvater@5304: /** Our very own SHGetFolderPath function for support of windows operating Darkvater@5304: * systems that don't have this function (eg Win9x, etc.). We try using the Darkvater@5304: * native function, and if that doesn't exist we will try a more crude approach Darkvater@5304: * of environment variables and hope for the best */ Darkvater@5304: HRESULT OTTDSHGetFolderPath(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, LPTSTR pszPath) Darkvater@5304: { Darkvater@5304: static HRESULT (WINAPI *SHGetFolderPath)(HWND, int, HANDLE, DWORD, LPTSTR) = NULL; Darkvater@5304: static bool first_time = true; Darkvater@5304: Darkvater@5304: /* We only try to load the library one time; if it fails, it fails */ Darkvater@5304: if (first_time) { Darkvater@5304: #if defined(UNICODE) Darkvater@5304: # define W(x) x "W" Darkvater@5304: #else Darkvater@5304: # define W(x) x "A" Darkvater@5304: #endif Darkvater@5304: if (!LoadLibraryList((Function*)&SHGetFolderPath, "SHFolder.dll\0" W("SHGetFolderPath") "\0\0")) { Darkvater@5568: DEBUG(misc, 0, "Unable to load " W("SHGetFolderPath") "from SHFolder.dll"); Darkvater@5304: } Darkvater@5304: #undef W Darkvater@5304: first_time = false; Darkvater@5304: } Darkvater@5304: Darkvater@5304: if (SHGetFolderPath != NULL) return SHGetFolderPath(hwnd, csidl, hToken, dwFlags, pszPath); Darkvater@5304: Darkvater@5304: /* SHGetFolderPath doesn't exist, try a more conservative approach, Darkvater@5304: * eg environment variables. This is only included for legacy modes Darkvater@5304: * MSDN says: that 'pszPath' is a "Pointer to a null-terminated string of Darkvater@5304: * length MAX_PATH which will receive the path" so let's assume that Darkvater@5304: * Windows 95 with Internet Explorer 5.0, Windows 98 with Internet Explorer 5.0, Darkvater@5304: * Windows 98 Second Edition (SE), Windows NT 4.0 with Internet Explorer 5.0, Darkvater@5304: * Windows NT 4.0 with Service Pack 4 (SP4) */ Darkvater@5304: { Darkvater@5304: DWORD ret; Darkvater@5304: switch (csidl) { Darkvater@5304: case CSIDL_FONTS: /* Get the system font path, eg %WINDIR%\Fonts */ Darkvater@5336: ret = GetEnvironmentVariable(_T("WINDIR"), pszPath, MAX_PATH); Darkvater@5304: if (ret == 0) break; Darkvater@5336: _tcsncat(pszPath, _T("\\Fonts"), MAX_PATH); Darkvater@5304: Darkvater@5304: return (HRESULT)0; Darkvater@5304: break; Darkvater@5304: /* XXX - other types to go here when needed... */ Darkvater@5304: } Darkvater@5304: } Darkvater@5304: Darkvater@5304: return E_INVALIDARG; Darkvater@5304: }