18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-11-21 06:14:58 +01:00
Files
maszyna/EU07.cpp
maj00r 201cae07e1 fix: a failed start says why and ends with an error code; a small crash dump by default (#425)
* fix: a failed start says why in the log and ends with an error code

When the window could not be made, the log only said "Bad init: failed to
create glfw window", without the reason glfw knows (no OpenGL driver, no
pixel format that fits, no EGL). Sometimes it did not even say that: the
log thread writes every 50 ms, and main() ended the process with
std::_Exit(0) without stopping it, so a start that failed within that time
left a log that ends at "// startup".

- glfw's errors go to the log and errors.txt through glfwSetErrorCallback,
  set before glfwInit(); each distinct message once.
- after a failed start (or an exception caught in main) the log thread is
  stopped and waited for, as the test runs already do, so nothing logged
  last is lost.
- a failed start ends with exit code 1 instead of 0, so the starter can
  tell it from a closing. A start that worked ends as before.

* fix: glfw's errors told during the start only, a closed crash dialog is no failed start

After review of the previous commit:

- the glfw error callback is taken off at the end of init(). Once the
  simulator runs, glfw would only repeat what the platform can't do
  (glfwSetCursorPos on Wayland, on every mouse-look) or what a scenery
  asks for in vain (launcher key codes below GLFW_KEY_SPACE, checked on
  every update), which would put new lines in errors.txt of existing
  sceneries and cost a format and a lock per call.
- closing the crash-report window ends the simulator as before, but
  init() now returns 1 for it (above 0: closed by the player), and only a
  result below 0 gives exit code 1.
- a start that throws from init() (bad_alloc, or a runtime_error on
  Windows) ends with exit code 1 too; an exception after a start that
  worked ends with 0 as before.

* feat: a small crash dump by default, the full one with "crashdump.full yes"

The dump written by the crash handler (Windows, WITHDUMPGEN) held all the
memory of the simulator (MiniDumpWithFullMemory), so it was as large as
the memory the simulator took: gigabytes on a large scenery, written to
the game folder at the moment of the crash, on machines with 8 GB of RAM
too.

By default it now holds the stacks with the memory they point to, the
threads, the modules, the handles, the memory map and the modules' data
segments (MiniDumpWithDataSegs in place of MiniDumpWithFullMemory, the
rest of the flags as before). The globals, Global among them, stay
readable. "crashdump.full yes" in eu07.ini writes the full dump as before.

Measured on td.scn with a ghostview camera (1.2 GB committed): the small
dump 44 MB in 2 s, the full one 1.6 GB in 19 s.

The key is new and optional: eu07.ini files without it read as before,
and the setting is listed in the log at start.

* fix: the small crash dump keeps the process and thread blocks

MiniDumpWithProcessThreadData adds the PEB and the TEBs, a few KB: the
command line (the scenery and the vehicle), the environment and the last
error of each thread, which the small dump otherwise lacks, since the heap
behind Global's longer strings is not in it.

* fix: an exception that ends the simulator says what it was in the log

After review of #425:

- the exceptions main() catches are logged ("Critical error: ..."): on
  Windows the runtime_error that only showed a message box, and on the
  other systems any std::exception, which used to end the simulator
  through std::terminate with no word in the log. On Windows the others
  are still left to CrashHandler, whose dump shows where they were
  thrown.
- every exception caught there ends with exit code 1, in the start or
  later, as a crash; it used to be 0 when caught, the abort code when not.
- closing the crash-report window logs "Crash report window closed,
  closing" instead of the error "Failed to run crash gui!", which stays
  for a result below 0.

* feat: the stack of a crash on Linux in the log and on the standard error

On Linux no dump is written (the crash handler is Windows only, crashpad
is off), so a crash left a log that just stopped.

A handler of SIGSEGV, SIGBUS, SIGFPE, SIGILL and SIGABRT (installed at
the start of main) now writes, with write() only:

  Crash: signal 11 (SIGSEGV) at address 0x...
  Version: EU07 (cmake), <hash> (...)
  Stack (addr2line -f -C -e <the eu07 file of this version> <offset>):
  <backtrace_symbols_fd>

to the end of the log file (its whole path, set when the log opens it)
and to the standard error, which StarterNG shows first. The Linux builds
carry their symbols (GENERATE_PDB adds -g, nothing strips them), so
addr2line on the eu07 file of the same version gives the files and lines.

Then the signal ends the process as before (SA_RESETHAND, raise): the
same exit status, and a core dump where the system makes one. The
handler runs on an alternate stack, so an overflow of the main thread's
stack is reported too; backtrace() is warmed up at install so it doesn't
allocate in the handler, and alarm(5) ends a handler that hangs (a crash
in the allocator or the loader). WAMR is built without its hardware bound
checks, so it installs no SIGSEGV handler of its own.

Elsewhere crash_signals does nothing. A unit test (Linux only) crashes a
child process and checks the report on its standard error and in the log,
and that the child still ended by SIGSEGV.

* fix: the crash report can't be cut by a second crash signal or end with SIGALRM

After review:
- the five crash signals are blocked while a report is written, so a
  second one waits rather than starting a second report in its middle
  (a fault that comes while blocked still ends the process).
- a report that hangs past alarm(5) ends the process by the signal of
  the crash, not by SIGALRM: a SIGALRM handler, set only in the crash
  handler, raises the crash signal and unblocks it.
- the child of the unit test calls alarm(10) first, so a child stuck
  before the crash can't hang the build.

---------

Co-authored-by: maj00r <maj00r@host>
2026-11-20 03:53:42 +01:00

289 lines
9.6 KiB
C++

/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
/*
MaSzyna EU07 locomotive simulator
Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others
*/
/*
Authors:
MarcinW, McZapkie, Shaxbee, ABu, nbmx, youBy, Ra, winger, mamut, Q424,
Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others
*/
#include "stdafx.h"
#include "application/application.h"
#include "simulation/simulationtest.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include "utilities/crashsignals.h"
#include "utilities/physicslog.h"
#include "version_info.h"
#include <cstdlib>
#include <exception>
#include <new>
#include <stdexcept>
#include <string_view>
#include <thread>
#include <vector>
#ifdef _WIN32
#include <cstdio>
#else
#include <sys/resource.h>
#endif
#ifdef WITHDUMPGEN
#ifdef _WIN32
#include <Windows.h>
#include <DbgHelp.h>
#endif
#endif
#ifdef _MSC_VER
#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
#endif
void export_e3d_standalone(std::string in, std::string out, int flags, bool dynamic);
int export_btf_standalone(std::string in, std::string out);
int generate_nodebank_previews(int Argc, char *Argv[]);
#include <ctime>
#include <string>
#include <sstream>
#include <iomanip>
#include <utilities/Globals.h>
#ifdef _WIN32
#pragma comment(lib, "Dbghelp.lib")
LONG WINAPI CrashHandler(EXCEPTION_POINTERS *ExceptionInfo)
{
// Get current local time
SYSTEMTIME st;
GetLocalTime(&st);
// Format: crash_YYYY-MM-DD_HH-MM-SS.dmp
std::ostringstream oss;
oss << "crash_" << std::setw(4) << std::setfill('0') << st.wYear << "-" << std::setw(2) << std::setfill('0') << st.wMonth << "-" << std::setw(2) << std::setfill('0') << st.wDay << "_"
<< std::setw(2) << std::setfill('0') << st.wHour << "-" << std::setw(2) << std::setfill('0') << st.wMinute << "-" << std::setw(2) << std::setfill('0') << st.wSecond << ".dmp";
std::string filename = oss.str();
HANDLE hFile = CreateFileA(filename.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hFile != INVALID_HANDLE_VALUE)
{
MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
dumpInfo.ThreadId = GetCurrentThreadId();
dumpInfo.ExceptionPointers = ExceptionInfo;
dumpInfo.ClientPointers = FALSE;
// a small dump by default: the stacks with the memory they point to, the threads with their process and thread
// blocks (the command line with the scenery and the vehicle), the modules, the handles and the modules' data
// (Global among them). all the memory of the simulator, as large as the memory it took, only with
// "crashdump.full yes" in eu07.ini
auto const dumpflags{Global.CrashDumpFull ? MiniDumpWithFullMemory : MiniDumpWithDataSegs};
MINIDUMP_TYPE dumpType = MINIDUMP_TYPE(dumpflags | MiniDumpWithProcessThreadData | MiniDumpWithHandleData | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules | MiniDumpWithIndirectlyReferencedMemory |
MiniDumpWithFullMemoryInfo | MiniDumpWithTokenInformation);
// in test mode nobody is there to close the box, and the run would wait for it until killed
if (false == Global.test.enabled)
MessageBoxA(nullptr, "Simulator crash occured :(\n", "Simulator crashed :(", MB_ICONERROR);
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, dumpType, &dumpInfo, nullptr, nullptr);
CloseHandle(hFile);
}
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
namespace
{
// the log is written by a thread of its own, which the closing of the application stops and waits for. on the ways
// out that skip the closing (a failed start, an exception) what was logged last would be lost with the process
void finish_log()
{
StopLogService();
if (auto const logservice{Global.threads.find("LogService")};
logservice != Global.threads.end() && logservice->second.joinable() && logservice->second.get_id() != std::this_thread::get_id())
logservice->second.join();
}
// ends a test run with its verdict on the standard output and in the exit code. a test the simulator didn't end
// (a failed start, an exception) ends with the error and Reason
[[noreturn]] void end_test_run(std::string_view const Reason)
{
simulation::test().conclude(simulation::test_result::error, Reason);
// the last two seconds of the physics logs, which the runner of the tests reads
PhysicsLogs.stop();
finish_log();
fflush(stdout);
fflush(stderr);
// skip destructors, there are ordering errors which causes segfaults
std::_Exit(simulation::test().exit_code());
}
// a test run (--test): whatever stops it, it ends with its verdict. any other run never gets here and ends as
// it always has
[[noreturn]] void run_test(int argc, char *argv[])
{
// for what doesn't reach the catch below: an exception leaving a noexcept function, or on Linux one leaving
// a thread (on Windows the handler is the main thread's only)
std::set_terminate([] { end_test_run(simulation::describe_exception(std::current_exception())); });
try
{
if (Application.init(argc, argv) == 0)
{
Application.run();
Application.exit();
}
}
catch (...)
{
end_test_run(simulation::describe_exception(std::current_exception()));
}
end_test_run("the simulator stopped before the test ended");
}
// the physics logs used to keep a file open for every vehicle with a driver, and on a scenery with some five hundred
// of them they took all the files the C library of Windows lets a process have open by default (512): the files
// opened after them, the shaders of the map among them, couldn't be read. they keep none open now (physicslog.h),
// but the limit is raised to the most either system allows still, for whatever else opens many files at once
void raise_open_files_limit()
{
#ifdef _WIN32
_setmaxstdio(8192);
#else
rlimit limit{};
if (getrlimit(RLIMIT_NOFILE, &limit) == 0 && limit.rlim_cur < limit.rlim_max)
{
limit.rlim_cur = limit.rlim_max;
setrlimit(RLIMIT_NOFILE, &limit);
}
#endif
}
} // namespace
int main(int argc, char *argv[])
{
raise_open_files_limit();
#ifdef WITHDUMPGEN
#ifdef _WIN32
SetUnhandledExceptionFilter(CrashHandler);
#endif
#endif
// on Linux, where no dump is written, the stack of a crash in the log and on the standard error
crash_signals::install(VERSION_INFO);
// init start timestamp
Global.startTimestamp = std::chrono::steady_clock::now();
// a start that failed ends with an error code, so whoever started the simulator (the starter) can tell it
// from a closing; how the simulator ends after a start that worked stays as it was
int exitcode{0};
// quick short-circuit for standalone e3d export
if (argc == 6 && std::string(argv[1]) == "-e3d")
{
std::string in(argv[2]);
std::string out(argv[3]);
int flags = std::stoi(std::string(argv[4]));
int dynamic = std::stoi(std::string(argv[5]));
export_e3d_standalone(in, out, flags, dynamic);
}
// standalone generation of preview images of the node bank models: -generate-nodebank-previews [options]
else if (argc >= 2 && std::string(argv[1]) == "-generate-nodebank-previews")
{
auto const result{generate_nodebank_previews(argc, argv)};
fflush(stdout);
fflush(stderr);
std::_Exit(result);
}
// standalone conversion of text terrain file to binary format: -btf -s <text file> [-o <binary file>]
else if (argc >= 4 && std::string(argv[1]) == "-btf")
{
std::string in;
std::string out;
for (int i = 2; i + 1 < argc; i += 2)
{
std::string const option(argv[i]);
if (option == "-s")
{
in = argv[i + 1];
}
else if (option == "-o")
{
out = argv[i + 1];
}
}
auto const result{export_btf_standalone(in, out)};
fflush(stdout);
fflush(stderr);
std::_Exit(result);
}
// unattended test run of a scenery, which says its result in the exit code (eu07/maszyna#541)
else if (simulation::parse_test_command_line(std::vector<char const *>(argv, argv + argc)).enabled)
{
run_test(argc, argv);
}
else
{
// below 0 when the start failed (see eu07_application::init())
int initresult{0};
try
{
initresult = Application.init(argc, argv);
if (initresult == 0)
{
Application.run();
Application.exit();
}
}
// an exception that ends the simulator is a crash, whether in the start or later: it says what it was in the
// log and ends with an error code
catch (std::bad_alloc const &Error)
{
ErrorLog("Critical error, memory allocation failure: " + std::string(Error.what()));
exitcode = 1;
}
#ifdef _WIN32
catch (std::runtime_error const &Error)
{
ErrorLog("Critical error: " + std::string(Error.what()));
std::string msg = "Simulator crash occured :(\n";
msg += Error.what();
MessageBoxA(nullptr, msg.c_str(), "Simulator crashed :(", MB_ICONERROR);
exitcode = 1;
}
#else
// elsewhere one not caught here ends the simulator through std::terminate, with no word in the log. on
// Windows it is left to CrashHandler, whose dump shows where it was thrown
catch (std::exception const &Error)
{
ErrorLog("Critical error: " + std::string(Error.what()));
exitcode = 1;
}
#endif
// the last two seconds of the physics logs, also after an error caught above; Application.exit() stops them
// otherwise, and a second stop only writes what came since
PhysicsLogs.stop();
// after a failed start or an error caught above the log thread still runs, and what it hasn't written yet
// (why the start failed) would go with the process. after Application.exit() it has stopped already
finish_log();
if (initresult < 0)
exitcode = 1;
}
#ifndef _WIN32
fflush(stdout);
fflush(stderr);
#endif
std::_Exit(exitcode); // skip destructors, there are ordering errors which causes segfaults
}