QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
Platform.cc
Go to the documentation of this file.
1#include "Platform.h"
2
3#include <cstdio>
4
5#include <QtCore/QCoreApplication>
6#include <QtCore/QProcessEnvironment>
7#include <QtQuick/QQuickWindow>
8#include <QtQuick/QSGRendererInterface>
9
11#include "VideoBackend.h"
12#include "qgc_version.h"
13
14#if !defined(Q_OS_IOS) && !defined(Q_OS_ANDROID)
15 #include "RunGuard.h"
16 #include "SignalHandler.h"
17#endif
18
19#if (defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD)) && !defined(Q_OS_ANDROID)
20 #include <unistd.h>
21 #include <sys/types.h>
22 #include <sys/wait.h>
23#endif
24
25#ifdef Q_OS_ANDROID
26#include <atomic>
27#include <cstdlib>
28#endif
29
30#if defined(Q_OS_MACOS)
31 #include <CoreFoundation/CoreFoundation.h>
32#elif defined(Q_OS_WIN)
33 #include <qt_windows.h>
34 #include <iostream>
35 #if defined(_MSC_VER)
36 #include <crtdbg.h>
37 #include <stdlib.h>
38 #endif
39#endif
40
41#if defined(Q_OS_WIN)
42// dbghelp.h needs the Windows types from qt_windows.h above.
43#include <cstdarg>
44#include <cwchar>
45#include <dbghelp.h>
46#endif
47
48namespace {
49
50#ifdef Q_OS_ANDROID
51std::atomic_int g_exitCode = EXIT_SUCCESS;
52#endif
53
54#if (defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD)) && !defined(Q_OS_ANDROID)
55static void showLinuxErrorDialog(const QByteArray& msg)
56{
57 // Try to show a GUI dialog — important for AppImage users where stderr is invisible.
58 // Fork a child and attempt dialog tools in order of preference; no shell is invoked.
59 const pid_t pid = fork();
60 if (pid == 0) {
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);
65 _exit(1);
66 } else if (pid > 0) {
67 int status = 0;
68 (void) waitpid(pid, &status, 0);
69 }
70 // Always write to stderr as well
71 fprintf(stderr, "Error: %s\n", msg.constData());
72}
73#endif // Q_OS_LINUX
74
75#if defined(Q_OS_MACOS)
76void disableAppNapViaInfoDict()
77{
78 CFBundleRef bundle = CFBundleGetMainBundle();
79 if (!bundle) {
80 return;
81 }
82 CFMutableDictionaryRef infoDict = const_cast<CFMutableDictionaryRef>(CFBundleGetInfoDictionary(bundle));
83 if (infoDict) {
84 CFDictionarySetValue(infoDict, CFSTR("NSAppSleepDisabled"), kCFBooleanTrue);
85 }
86}
87#endif // Q_OS_MACOS
88
89#if defined(Q_OS_WIN)
90
91#if defined(_MSC_VER)
92
93#if defined(_DEBUG)
94int __cdecl WindowsCrtReportHook(int reportType, char* message, int* returnValue)
95{
96 if (message) {
97 std::cerr << message << std::endl;
98 }
99 if (reportType == _CRT_ASSERT) {
100 if (returnValue) {
101 *returnValue = 0;
102 }
103 return 1; // handled
104 }
105 return 0; // let CRT continue
106}
107#endif // _DEBUG
108
109void __cdecl WindowsPurecallHandler()
110{
111 (void) OutputDebugStringW(L"QGC: _purecall\n");
112}
113
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)
119{
120
121}
122#endif // _MSC_VER
123
124LPTOP_LEVEL_EXCEPTION_FILTER g_prevUef = nullptr;
125
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] = {};
131
132// The crashed thread may hold the loader or heap lock, or have almost no stack left after an
133// overflow, so a thread started with QGC writes the minidump while the filter waits for it.
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;
141
142// Static so the filter itself needs little stack.
143wchar_t g_crashModulePath[MAX_PATH] = {};
144wchar_t g_crashMessage[2 * MAX_PATH] = {};
145char g_crashNarrow[6 * MAX_PATH] = {};
146
147template <std::size_t Size>
148bool formatWide(wchar_t (&buffer)[Size], const wchar_t* format, ...)
149{
150 va_list args;
151 va_start(args, format);
152#if defined(_MSC_VER)
153 const int length = _vsnwprintf_s(buffer, Size, _TRUNCATE, format, args);
154#else
155 const int length = std::vswprintf(buffer, Size, format, args);
156 buffer[Size - 1] = L'\0';
157#endif
158 va_end(args);
159 return length >= 0;
160}
161
162template <std::size_t Size>
163void writeCrashMessage(const wchar_t* message, char (&narrow)[Size])
164{
165 (void) OutputDebugStringW(message);
166
167 const HANDLE h = GetStdHandle(STD_ERROR_HANDLE);
168 if (!h || (h == INVALID_HANDLE_VALUE)) {
169 return;
170 }
171 const int length = WideCharToMultiByte(CP_UTF8, 0, message, -1, narrow, static_cast<int>(Size), nullptr, nullptr);
172 if (length > 1) {
173 DWORD ignored = 0;
174 (void) WriteFile(h, narrow, static_cast<DWORD>(length - 1), &ignored, nullptr);
175 }
176}
177
178// Runs on the dump thread, whose own buffer keeps it apart from the filter's messages.
179void writeCrashDump()
180{
181 char narrow[6 * MAX_PATH] = {};
182 const HANDLE file =
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);
186 return;
187 }
188
189 MINIDUMP_EXCEPTION_INFORMATION exceptionInfo = {};
190 exceptionInfo.ThreadId = g_crashThreadId;
191 exceptionInfo.ExceptionPointers = g_crashException;
192 exceptionInfo.ClientPointers = FALSE;
193 const BOOL written =
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);
199
200 // Only a complete dump gets the .dmp name that CI collects.
201 bool kept = false;
202 if (written) {
203 kept = MoveFileExW(g_crashDumpPartPath, g_crashDumpPath, MOVEFILE_REPLACE_EXISTING) != FALSE;
204 if (!kept) {
205 error = GetLastError();
206 }
207 }
208
209 wchar_t message[2 * MAX_PATH] = {};
210 if (kept) {
211 (void) formatWide(message, L"QGC: wrote crash dump %ls\n", g_crashDumpPath);
212 } else {
213 (void) DeleteFileW(g_crashDumpPartPath);
214 (void) formatWide(message, L"QGC: crash dump failed with error 0x%08lX\n", static_cast<unsigned long>(error));
215 }
216 writeCrashMessage(message, narrow);
217}
218
219DWORD WINAPI crashDumpThread(LPVOID)
220{
221 if (WaitForSingleObject(g_crashDumpRequested, INFINITE) == WAIT_OBJECT_0) {
222 writeCrashDump();
223 (void) SetEvent(g_crashDumpWritten);
224 }
225 return 0;
226}
227
228// Resolved before any crash: the exception filter must not load libraries or start threads.
229void setupCrashDumps()
230{
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)) {
234 return;
235 }
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';
240 return;
241 }
242
243 const HMODULE dbghelp = LoadLibraryExW(L"dbghelp.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
244 if (dbghelp) {
245 g_miniDumpWriteDump = reinterpret_cast<MiniDumpWriteDumpFn>(
246 reinterpret_cast<void (*)()>(GetProcAddress(dbghelp, "MiniDumpWriteDump")));
247 }
248 if (!g_miniDumpWriteDump) {
249 return;
250 }
251
252 g_crashDumpRequested = CreateEventW(nullptr, FALSE, FALSE, nullptr);
253 g_crashDumpWritten = CreateEventW(nullptr, TRUE, FALSE, nullptr);
254 if (!g_crashDumpRequested || !g_crashDumpWritten) {
255 return;
256 }
257 const HANDLE thread = CreateThread(nullptr, 256 * 1024, crashDumpThread, nullptr, 0, nullptr);
258 if (!thread) {
259 return;
260 }
261 (void) CloseHandle(thread);
262 g_crashDumpReady = true;
263}
264
265LONG WINAPI WindowsUnhandledExceptionFilter(EXCEPTION_POINTERS* ep)
266{
267 // A second crashing thread lets the first finish its report, then ends the process.
268 if (InterlockedExchange(&g_crashHandled, 1) != 0) {
269 if (g_crashDumpReady) {
270 (void) WaitForSingleObject(g_crashDumpWritten, CRASH_DUMP_WAIT_MS);
271 }
272 return EXCEPTION_EXECUTE_HANDLER;
273 }
274
275 const EXCEPTION_RECORD* const record = ep ? ep->ExceptionRecord : nullptr;
276 const DWORD code = record ? record->ExceptionCode : 0;
277 const ULONG_PTR address = record ? reinterpret_cast<ULONG_PTR>(record->ExceptionAddress) : 0;
278
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);
288 }
289
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);
294
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);
301 }
302 } else if (g_crashDumpPath[0] != L'\0') {
303 writeCrashMessage(L"QGC: no crash dump, the dump writer could not start\n", g_crashNarrow);
304 }
305
306 return EXCEPTION_EXECUTE_HANDLER;
307}
308
309void setWindowsErrorModes(bool quietWindowsAsserts)
310{
311 (void) SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
312 setupCrashDumps();
313 g_prevUef = SetUnhandledExceptionFilter(WindowsUnhandledExceptionFilter);
314
315#if defined(_MSC_VER)
316 (void) _set_invalid_parameter_handler(WindowsInvalidParameterHandler);
317 (void) _set_purecall_handler(WindowsPurecallHandler);
318
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);
326 }
327#else
328 Q_UNUSED(quietWindowsAsserts);
329#endif
330}
331#endif // Q_OS_WIN
332
333} // namespace
334
335std::optional<int> Platform::initialize(int argc, char* argv[],
337{
338#if (defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD)) && !defined(Q_OS_ANDROID)
339 if (isRunningAsRoot()) {
340 return showRootError(argc, argv);
341 }
342#endif
343
344#if !defined(Q_OS_ANDROID) && !defined(Q_OS_IOS)
345 const bool allowMultiple = args.allowMultiple || args.runningUnitTests || args.listTests;
346 if (!checkSingleInstance(allowMultiple)) {
347 return showMultipleInstanceError(argc, argv);
348 }
349#else
350 Q_UNUSED(argc);
351 Q_UNUSED(argv);
352#endif
353
354#ifdef Q_OS_UNIX
355#ifndef Q_OS_ANDROID
356 // On Android, skip these — either env var triggers shouldLogToStderr(),
357 // which bypasses Qt's __android_log_print path to logcat.
358 if (!qEnvironmentVariableIsSet("QT_ASSUME_STDERR_HAS_CONSOLE")) {
359 (void) qputenv("QT_ASSUME_STDERR_HAS_CONSOLE", "1");
360 }
361 if (!qEnvironmentVariableIsSet("QT_FORCE_STDERR_LOGGING")) {
362 (void) qputenv("QT_FORCE_STDERR_LOGGING", "1");
363 }
364#endif
365#endif
366
367#ifdef Q_OS_WIN
368 if (!qEnvironmentVariableIsSet("QT_WIN_DEBUG_CONSOLE")) {
369 (void) qputenv("QT_WIN_DEBUG_CONSOLE", "attach");
370 }
371 if (qEnvironmentVariable("QSG_RHI_BACKEND").compare(QLatin1String("d3d12"), Qt::CaseInsensitive) == 0) {
372 // Qt 6.10 does not reliably select D3D12 from QSG_RHI_BACKEND on Windows. Make the test/diagnostic override
373 // explicit before the scene graph is initialized; the default path remains Qt's D3D11 backend.
374 QQuickWindow::setGraphicsApi(QSGRendererInterface::Direct3D12);
375 }
376 setWindowsErrorModes(args.quietWindowsAsserts);
377#endif
378
379#ifdef Q_OS_MACOS
380 disableAppNapViaInfoDict();
381#endif
382
383#ifdef QGC_UNITTEST_BUILD
384 if ((args.runningUnitTests || args.listTests) && !args.onscreen) {
385 if (!qEnvironmentVariableIsSet("QT_QPA_PLATFORM")) {
386 (void) qputenv("QT_QPA_PLATFORM", "offscreen");
387 }
388 }
389#endif
390
391 // --- Qt attributes ---
392 if (args.useSwRast) {
393#ifdef Q_OS_WIN
394 // Qt 6 no longer ships opengl32sw.dll, so stay on D3D and pick the built-in WARP adapter instead.
395 (void) qputenv("QSG_RHI_PREFER_SOFTWARE_RENDERER", "1");
396#else
397 // RHI defaults to Metal on macOS; AA_UseSoftwareOpenGL only bites once the scene graph is on GL.
398 QQuickWindow::setGraphicsApi(QSGRendererInterface::OpenGL);
399 QCoreApplication::setAttribute(Qt::AA_UseSoftwareOpenGL);
400#endif
401 }
403 QCoreApplication::setAttribute(Qt::AA_CompressTabletEvents);
404
405 return std::nullopt;
406}
407
409{
410#if !defined(Q_OS_IOS) && !defined(Q_OS_ANDROID)
411 SignalHandler* signalHandler = new SignalHandler(QCoreApplication::instance());
412 (void) signalHandler->setupSignalHandlers();
413#endif
414}
415
416#ifdef Q_OS_ANDROID
417void Platform::skipStaticDestructorsAtExit(int exitCode)
418{
419 // Once the activity is destroyed, Qt calls exit(), whose static destructors include libhwui's CommonPool: it
420 // destroys its mutex while the pool's detached hwuiTask threads still lock it, which aborts the process ("FORTIFY:
421 // pthread_mutex_lock called on a destroyed mutex"). Android apps normally end without running static destructors.
422 // exit() runs the handler registered last first, so this one ends the process before the others run.
423 g_exitCode = exitCode;
424 (void) std::atexit([] { std::_Exit(g_exitCode); });
425}
426#endif
427
428#if (defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD)) && !defined(Q_OS_ANDROID)
429bool Platform::isRunningAsRoot()
430{
431 return ::getuid() == 0;
432}
433
434int Platform::showRootError([[maybe_unused]] int argc, [[maybe_unused]] char *argv[])
435{
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());
441 return -1;
442}
443#endif
444
445#if !defined(Q_OS_ANDROID) && !defined(Q_OS_IOS)
446int Platform::showMultipleInstanceError([[maybe_unused]] int argc, [[maybe_unused]] char *argv[])
447{
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)
452 // The native alert is GUI-only; also write to stderr so a CLI/headless launch sees the reason.
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)
461 // MessageBoxW is GUI-only; also write to stderr so a CLI/headless launch sees the reason.
462 fprintf(stderr, "Error: %s\n", message.toLocal8Bit().constData());
463 MessageBoxW(nullptr, message.toStdWString().c_str(), L"Error", MB_OK | MB_ICONERROR);
464#else
465 showLinuxErrorDialog(message.toLocal8Bit());
466#endif
467 return -1;
468}
469
470bool Platform::checkSingleInstance(bool allowMultiple)
471{
472 if (allowMultiple) {
473 return true;
474 }
475
476 static const QString runguardString = QStringLiteral("%1 RunGuardKey").arg(QLatin1String(QGC_APP_NAME));
477 static RunGuard guard(runguardString);
478 return guard.tryToRun();
479}
480#endif
bool tryToRun()
Definition RunGuard.cc:50
int setupSignalHandlers()
static VideoBackend & instance()
virtual void configureQtGraphics(bool softwareRendering)
void record(HwVideoBufferPath path, Counter counter) noexcept
bool checkSingleInstance(bool allowMultiple)
Check if another instance is already running (single instance guard).
Definition Platform.cc:470
void setupPostApp()
Complete platform setup after application exists.
Definition Platform.cc:408
std::optional< int > initialize(int argc, char *argv[], const QGCCommandLineParser::CommandLineParseResult &args)
Initialize platform: run safety checks and configure environment.
Definition Platform.cc:335
int showMultipleInstanceError(int argc, char *argv[])
Show error dialog when another instance is already running.
Definition Platform.cc:446
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).