5#include <QtCore/QCoreApplication>
6#include <QtCore/QProcessEnvironment>
7#include <QtQuick/QQuickWindow>
8#include <QtQuick/QSGRendererInterface>
12#include "qgc_version.h"
14#if !defined(Q_OS_IOS) && !defined(Q_OS_ANDROID)
19#if (defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD)) && !defined(Q_OS_ANDROID)
21 #include <sys/types.h>
30#if defined(Q_OS_MACOS)
31 #include <CoreFoundation/CoreFoundation.h>
32#elif defined(Q_OS_WIN)
33 #include <qt_windows.h>
51std::atomic_int g_exitCode = EXIT_SUCCESS;
54#if (defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD)) && !defined(Q_OS_ANDROID)
55static void showLinuxErrorDialog(
const QByteArray& msg)
59 const pid_t pid = fork();
61 const QByteArray zenityText = QByteArrayLiteral(
"--text=") + msg;
62 execlp(
"zenity",
"zenity",
"--error",
"--title=Error", zenityText.constData(),
nullptr);
63 execlp(
"kdialog",
"kdialog",
"--error", msg.constData(),
nullptr);
64 execlp(
"xmessage",
"xmessage",
"-center", msg.constData(),
nullptr);
68 (void) waitpid(pid, &status, 0);
71 fprintf(stderr,
"Error: %s\n", msg.constData());
75#if defined(Q_OS_MACOS)
76void disableAppNapViaInfoDict()
78 CFBundleRef bundle = CFBundleGetMainBundle();
82 CFMutableDictionaryRef infoDict =
const_cast<CFMutableDictionaryRef
>(CFBundleGetInfoDictionary(bundle));
84 CFDictionarySetValue(infoDict, CFSTR(
"NSAppSleepDisabled"), kCFBooleanTrue);
94int __cdecl WindowsCrtReportHook(
int reportType,
char* message,
int* returnValue)
97 std::cerr << message << std::endl;
99 if (reportType == _CRT_ASSERT) {
109void __cdecl WindowsPurecallHandler()
111 (void) OutputDebugStringW(L
"QGC: _purecall\n");
114void WindowsInvalidParameterHandler([[maybe_unused]]
const wchar_t* expression,
115 [[maybe_unused]]
const wchar_t* function,
116 [[maybe_unused]]
const wchar_t* file,
117 [[maybe_unused]]
unsigned int line,
118 [[maybe_unused]] uintptr_t pReserved)
124LPTOP_LEVEL_EXCEPTION_FILTER g_prevUef =
nullptr;
126using MiniDumpWriteDumpFn = BOOL(WINAPI*)(HANDLE, DWORD, HANDLE, MINIDUMP_TYPE, PMINIDUMP_EXCEPTION_INFORMATION,
127 PMINIDUMP_USER_STREAM_INFORMATION, PMINIDUMP_CALLBACK_INFORMATION);
128MiniDumpWriteDumpFn g_miniDumpWriteDump =
nullptr;
129wchar_t g_crashDumpPath[MAX_PATH] = {};
130wchar_t g_crashDumpPartPath[MAX_PATH] = {};
134constexpr DWORD CRASH_DUMP_WAIT_MS = 20000;
135bool g_crashDumpReady =
false;
136HANDLE g_crashDumpRequested =
nullptr;
137HANDLE g_crashDumpWritten =
nullptr;
138EXCEPTION_POINTERS* g_crashException =
nullptr;
139DWORD g_crashThreadId = 0;
140volatile LONG g_crashHandled = 0;
143wchar_t g_crashModulePath[MAX_PATH] = {};
144wchar_t g_crashMessage[2 * MAX_PATH] = {};
145char g_crashNarrow[6 * MAX_PATH] = {};
147template <std::
size_t Size>
148bool formatWide(
wchar_t (&buffer)[Size],
const wchar_t* format, ...)
151 va_start(args, format);
153 const int length = _vsnwprintf_s(buffer, Size, _TRUNCATE, format, args);
155 const int length = std::vswprintf(buffer, Size, format, args);
156 buffer[Size - 1] = L
'\0';
162template <std::
size_t Size>
163void writeCrashMessage(
const wchar_t* message,
char (&narrow)[Size])
165 (void) OutputDebugStringW(message);
167 const HANDLE h = GetStdHandle(STD_ERROR_HANDLE);
168 if (!h || (h == INVALID_HANDLE_VALUE)) {
171 const int length = WideCharToMultiByte(CP_UTF8, 0, message, -1, narrow,
static_cast<int>(Size),
nullptr,
nullptr);
174 (void) WriteFile(h, narrow,
static_cast<DWORD
>(length - 1), &ignored,
nullptr);
181 char narrow[6 * MAX_PATH] = {};
183 CreateFileW(g_crashDumpPartPath, GENERIC_WRITE, 0,
nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
nullptr);
184 if (file == INVALID_HANDLE_VALUE) {
185 writeCrashMessage(L
"QGC: no crash dump, cannot create a file in QGC_CRASH_DUMP_DIR\n", narrow);
189 MINIDUMP_EXCEPTION_INFORMATION exceptionInfo = {};
190 exceptionInfo.ThreadId = g_crashThreadId;
191 exceptionInfo.ExceptionPointers = g_crashException;
192 exceptionInfo.ClientPointers = FALSE;
194 g_miniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), file,
195 static_cast<MINIDUMP_TYPE
>(MiniDumpWithUnloadedModules | MiniDumpWithThreadInfo),
196 g_crashException ? &exceptionInfo :
nullptr,
nullptr,
nullptr);
197 DWORD error = written ? ERROR_SUCCESS : GetLastError();
198 (void) CloseHandle(file);
203 kept = MoveFileExW(g_crashDumpPartPath, g_crashDumpPath, MOVEFILE_REPLACE_EXISTING) != FALSE;
205 error = GetLastError();
209 wchar_t message[2 * MAX_PATH] = {};
211 (void) formatWide(message, L
"QGC: wrote crash dump %ls\n", g_crashDumpPath);
213 (void) DeleteFileW(g_crashDumpPartPath);
214 (void) formatWide(message, L
"QGC: crash dump failed with error 0x%08lX\n",
static_cast<unsigned long>(error));
216 writeCrashMessage(message, narrow);
219DWORD WINAPI crashDumpThread(LPVOID)
221 if (WaitForSingleObject(g_crashDumpRequested, INFINITE) == WAIT_OBJECT_0) {
223 (void) SetEvent(g_crashDumpWritten);
229void setupCrashDumps()
231 wchar_t directory[MAX_PATH] = {};
232 const DWORD length = GetEnvironmentVariableW(L
"QGC_CRASH_DUMP_DIR", directory, MAX_PATH);
233 if ((length == 0) || (length >= MAX_PATH)) {
236 if (!formatWide(g_crashDumpPath, L
"%ls\\QGC-crash-%lu.dmp", directory,
237 static_cast<unsigned long>(GetCurrentProcessId())) ||
238 !formatWide(g_crashDumpPartPath, L
"%ls.part", g_crashDumpPath)) {
239 g_crashDumpPath[0] = L
'\0';
243 const HMODULE dbghelp = LoadLibraryExW(L
"dbghelp.dll",
nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
245 g_miniDumpWriteDump =
reinterpret_cast<MiniDumpWriteDumpFn
>(
246 reinterpret_cast<void (*)()
>(GetProcAddress(dbghelp,
"MiniDumpWriteDump")));
248 if (!g_miniDumpWriteDump) {
252 g_crashDumpRequested = CreateEventW(
nullptr, FALSE, FALSE,
nullptr);
253 g_crashDumpWritten = CreateEventW(
nullptr, TRUE, FALSE,
nullptr);
254 if (!g_crashDumpRequested || !g_crashDumpWritten) {
257 const HANDLE thread = CreateThread(
nullptr, 256 * 1024, crashDumpThread,
nullptr, 0,
nullptr);
261 (void) CloseHandle(thread);
262 g_crashDumpReady =
true;
265LONG WINAPI WindowsUnhandledExceptionFilter(EXCEPTION_POINTERS* ep)
268 if (InterlockedExchange(&g_crashHandled, 1) != 0) {
269 if (g_crashDumpReady) {
270 (void) WaitForSingleObject(g_crashDumpWritten, CRASH_DUMP_WAIT_MS);
272 return EXCEPTION_EXECUTE_HANDLER;
275 const EXCEPTION_RECORD*
const record = ep ? ep->ExceptionRecord :
nullptr;
277 const ULONG_PTR address =
record ?
reinterpret_cast<ULONG_PTR
>(
record->ExceptionAddress) : 0;
279 const wchar_t* moduleName = L
"<unknown module>";
280 ULONG_PTR offset = address;
281 HMODULE module =
nullptr;
282 if ((address != 0) &&
283 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
284 reinterpret_cast<LPCWSTR
>(address), &module) &&
285 (GetModuleFileNameW(module, g_crashModulePath, MAX_PATH) > 0)) {
286 moduleName = g_crashModulePath;
287 offset = address -
reinterpret_cast<ULONG_PTR
>(module);
290 (void) formatWide(g_crashMessage, L
"QGC: unhandled SEH 0x%08lX at 0x%llX in %ls+0x%llX\n",
291 static_cast<unsigned long>(code),
static_cast<unsigned long long>(address), moduleName,
292 static_cast<unsigned long long>(offset));
293 writeCrashMessage(g_crashMessage, g_crashNarrow);
295 if (g_crashDumpReady) {
296 g_crashException = ep;
297 g_crashThreadId = GetCurrentThreadId();
298 if (SetEvent(g_crashDumpRequested) &&
299 (WaitForSingleObject(g_crashDumpWritten, CRASH_DUMP_WAIT_MS) == WAIT_TIMEOUT)) {
300 writeCrashMessage(L
"QGC: crash dump unfinished after 20 s; exiting without it\n", g_crashNarrow);
302 }
else if (g_crashDumpPath[0] != L
'\0') {
303 writeCrashMessage(L
"QGC: no crash dump, the dump writer could not start\n", g_crashNarrow);
306 return EXCEPTION_EXECUTE_HANDLER;
309void setWindowsErrorModes(
bool quietWindowsAsserts)
311 (void) SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
313 g_prevUef = SetUnhandledExceptionFilter(WindowsUnhandledExceptionFilter);
316 (void) _set_invalid_parameter_handler(WindowsInvalidParameterHandler);
317 (void) _set_purecall_handler(WindowsPurecallHandler);
319 if (quietWindowsAsserts) {
320 (void) _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
321 (void) _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);
322 (void) _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG);
323 (void) _CrtSetReportHook2(_CRT_RPTHOOK_INSTALL, WindowsCrtReportHook);
324 (void) _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
325 (void) _set_error_mode(_OUT_TO_STDERR);
328 Q_UNUSED(quietWindowsAsserts);
338#if (defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD)) && !defined(Q_OS_ANDROID)
339 if (isRunningAsRoot()) {
340 return showRootError(argc, argv);
344#if !defined(Q_OS_ANDROID) && !defined(Q_OS_IOS)
358 if (!qEnvironmentVariableIsSet(
"QT_ASSUME_STDERR_HAS_CONSOLE")) {
359 (void) qputenv(
"QT_ASSUME_STDERR_HAS_CONSOLE",
"1");
361 if (!qEnvironmentVariableIsSet(
"QT_FORCE_STDERR_LOGGING")) {
362 (void) qputenv(
"QT_FORCE_STDERR_LOGGING",
"1");
368 if (!qEnvironmentVariableIsSet(
"QT_WIN_DEBUG_CONSOLE")) {
369 (void) qputenv(
"QT_WIN_DEBUG_CONSOLE",
"attach");
371 if (qEnvironmentVariable(
"QSG_RHI_BACKEND").compare(QLatin1String(
"d3d12"), Qt::CaseInsensitive) == 0) {
374 QQuickWindow::setGraphicsApi(QSGRendererInterface::Direct3D12);
380 disableAppNapViaInfoDict();
383#ifdef QGC_UNITTEST_BUILD
385 if (!qEnvironmentVariableIsSet(
"QT_QPA_PLATFORM")) {
386 (void) qputenv(
"QT_QPA_PLATFORM",
"offscreen");
395 (void) qputenv(
"QSG_RHI_PREFER_SOFTWARE_RENDERER",
"1");
398 QQuickWindow::setGraphicsApi(QSGRendererInterface::OpenGL);
399 QCoreApplication::setAttribute(Qt::AA_UseSoftwareOpenGL);
403 QCoreApplication::setAttribute(Qt::AA_CompressTabletEvents);
410#if !defined(Q_OS_IOS) && !defined(Q_OS_ANDROID)
417void Platform::skipStaticDestructorsAtExit(
int exitCode)
423 g_exitCode = exitCode;
424 (void) std::atexit([] { std::_Exit(g_exitCode); });
428#if (defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD)) && !defined(Q_OS_ANDROID)
429bool Platform::isRunningAsRoot()
431 return ::getuid() == 0;
434int Platform::showRootError([[maybe_unused]]
int argc, [[maybe_unused]]
char *argv[])
436 const QString message = QCoreApplication::translate(
"main",
437 "You are running %1 as root. "
438 "You should not do this since it will cause other issues with %1. "
439 "%1 will now exit.").arg(QLatin1String(QGC_APP_NAME));
440 showLinuxErrorDialog(message.toLocal8Bit());
445#if !defined(Q_OS_ANDROID) && !defined(Q_OS_IOS)
448 const QString message = QCoreApplication::translate(
"main",
449 "A second instance of %1 is already running. "
450 "Please close the other instance and try again.").arg(QLatin1String(QGC_APP_NAME));
451#if defined(Q_OS_MACOS)
453 fprintf(stderr,
"Error: %s\n", message.toLocal8Bit().constData());
454 CFStringRef cfMessage = CFStringCreateWithCString(
nullptr, message.toUtf8().constData(), kCFStringEncodingUTF8);
455 CFUserNotificationDisplayAlert(0, kCFUserNotificationStopAlertLevel,
456 nullptr,
nullptr,
nullptr,
457 CFSTR(
"Error"), cfMessage,
458 nullptr,
nullptr,
nullptr,
nullptr);
459 CFRelease(cfMessage);
460#elif defined(Q_OS_WIN)
462 fprintf(stderr,
"Error: %s\n", message.toLocal8Bit().constData());
463 MessageBoxW(
nullptr, message.toStdWString().c_str(), L
"Error", MB_OK | MB_ICONERROR);
465 showLinuxErrorDialog(message.toLocal8Bit());
476 static const QString runguardString = QStringLiteral(
"%1 RunGuardKey").arg(QLatin1String(QGC_APP_NAME));
477 static RunGuard guard(runguardString);
int setupSignalHandlers()
static VideoBackend & instance()
virtual void configureQtGraphics(bool softwareRendering)
void record(HwVideoBufferPath path, Counter counter) noexcept
Result of parsing command-line arguments.
bool quietWindowsAsserts
Windows only: Disable assert dialogs.
bool listTests
List available tests and exit.
bool useSwRast
Windows/macOS: Force software rendering.
bool onscreen
Show test windows on screen (skip offscreen override).