VirtualBox

source: vbox/trunk/src/VBox/Frontends/VirtualBox/src/main.cpp

Last change on this file was 104127, checked in by vboxsync, 4 weeks ago

FE/Qt: bugref:10450: Linux: Disabling w/a added in r158575 as it's fixed from the upstream (Mate DE).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 32.1 KB
Line 
1/* $Id: main.cpp 104127 2024-03-30 23:59:46Z vboxsync $ */
2/** @file
3 * VBox Qt GUI - The main() function.
4 */
5
6/*
7 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28/* Qt includes: */
29#include <QApplication>
30#include <QMessageBox>
31#ifdef VBOX_WS_NIX
32# ifndef Q_OS_SOLARIS
33# include <QFontDatabase>
34# endif
35#endif
36
37/* GUI includes: */
38#include "UICommon.h"
39#include "UILoggingDefs.h"
40#include "UIModalWindowManager.h"
41#include "UIStarter.h"
42#ifdef VBOX_WS_MAC
43# include "VBoxUtils.h"
44# include "UICocoaApplication.h"
45#endif /* VBOX_WS_MAC */
46#ifdef VBOX_WS_NIX
47# include "UIVersion.h"
48#endif
49
50/* Other VBox includes: */
51#include <iprt/buildconfig.h>
52#include <iprt/stream.h>
53#include <VBox/err.h>
54#include <VBox/version.h>
55#include <VBox/sup.h>
56#if !defined(VBOX_WITH_HARDENING) || !defined(VBOX_RUNTIME_UI)
57# include <iprt/initterm.h>
58# ifdef VBOX_WS_MAC
59# include <iprt/asm.h>
60# endif
61#endif
62#ifdef VBOX_WS_NIX
63# include <iprt/env.h>
64#endif
65#ifdef VBOX_WITH_HARDENING
66# include <iprt/ctype.h>
67#endif
68#if defined(VBOX_RUNTIME_UI) && defined(VBOX_WS_MAC)
69# include <iprt/path.h>
70#endif
71
72/* Other includes: */
73#ifdef VBOX_WS_MAC
74# include <dlfcn.h>
75# include <sys/mman.h>
76#endif /* VBOX_WS_MAC */
77#ifdef VBOX_WS_NIX
78# include <dlfcn.h>
79# include <unistd.h>
80# include <X11/Xlib.h>
81# include "VBoxUtils-nix.h"
82# if defined(RT_OS_LINUX) && defined(DEBUG)
83# include <signal.h>
84# include <execinfo.h>
85# ifndef __USE_GNU
86# define __USE_GNU
87# endif /* !__USE_GNU */
88# include <ucontext.h>
89# ifdef RT_ARCH_AMD64
90# define REG_PC REG_RIP
91# else /* !RT_ARCH_AMD64 */
92# define REG_PC REG_EIP
93# endif /* !RT_ARCH_AMD64 */
94# endif /* RT_OS_LINUX && DEBUG */
95#endif /* VBOX_WS_NIX */
96
97
98/* XXX Temporarily. Don't rely on the user to hack the Makefile himself! */
99QString g_QStrHintLinuxNoMemory = QApplication::tr(
100 "This error means that the kernel driver was either not able to "
101 "allocate enough memory or that some mapping operation failed."
102 );
103
104QString g_QStrHintLinuxNoDriver = QApplication::tr(
105 "The VirtualBox Linux kernel driver is either not loaded or not set "
106 "up correctly. Please try setting it up again by executing<br/><br/>"
107 " <font color=blue>'/sbin/vboxconfig'</font><br/><br/>"
108 "as root.<br/><br/>"
109 "If your system has EFI Secure Boot enabled you may also need to sign "
110 "the kernel modules (vboxdrv, vboxnetflt, vboxnetadp, vboxpci) before "
111 "you can load them. Please see your Linux system's documentation for "
112 "more information."
113 );
114
115QString g_QStrHintOtherWrongDriverVersion = QApplication::tr(
116 "The VirtualBox kernel modules do not match this version of "
117 "VirtualBox. The installation of VirtualBox was apparently not "
118 "successful. Please try completely uninstalling and reinstalling "
119 "VirtualBox."
120 );
121
122QString g_QStrHintLinuxWrongDriverVersion = QApplication::tr(
123 "The VirtualBox kernel modules do not match this version of "
124 "VirtualBox. The installation of VirtualBox was apparently not "
125 "successful. Executing<br/><br/>"
126 " <font color=blue>'/sbin/vboxconfig'</font><br/><br/>"
127 "may correct this. Make sure that you are not mixing builds "
128 "of VirtualBox from different sources."
129 );
130
131QString g_QStrHintOtherNoDriver = QApplication::tr(
132 "Make sure the kernel module has been loaded successfully."
133 );
134
135/* I hope this isn't (C), (TM) or (R) Microsoft support ;-) */
136QString g_QStrHintReinstall = QApplication::tr(
137 "Please try reinstalling VirtualBox."
138 );
139
140
141#ifdef VBOX_WS_NIX
142/** X11: For versions of Xlib which are aware of multi-threaded environments this function
143 * calls for XInitThreads() which initializes Xlib support for concurrent threads.
144 * @returns @c non-zero unless it is unsafe to make multi-threaded calls to Xlib.
145 * @remarks This is a workaround for a bug on old Xlib versions, fixed in commit
146 * 941f02e and released in Xlib version 1.1. We check for the symbol
147 * "xcb_connect" which was introduced in that version. */
148static Status MakeSureMultiThreadingIsSafe()
149{
150 /* Success by default: */
151 Status rc = 1;
152 /* Get a global handle to process symbols: */
153 void *pvProcess = dlopen(0, RTLD_GLOBAL | RTLD_LAZY);
154 /* Initialize multi-thread environment only if we can obtain
155 * an address of xcb_connect symbol in this process: */
156 if (pvProcess && dlsym(pvProcess, "xcb_connect"))
157 rc = XInitThreads();
158 /* Close the handle: */
159 if (pvProcess)
160 dlclose(pvProcess);
161 /* Return result: */
162 return rc;
163}
164
165# if (defined(RT_OS_LINUX) && !defined(RT_ARCH_ARM64)) && defined(DEBUG)
166/** X11, Linux, Debug: The signal handler that prints out a backtrace of the call stack.
167 * @remarks The code is taken from http://www.linuxjournal.com/article/6391. */
168static void BackTraceSignalHandler(int sig, siginfo_t *pInfo, void *pSecret)
169{
170 void *trace[16];
171 char **messages = (char **)0;
172 int i, iTraceSize = 0;
173 ucontext_t *uc = (ucontext_t *)pSecret;
174
175 /* Do something useful with siginfo_t: */
176 if (sig == SIGSEGV)
177 Log(("GUI: Got signal %d, faulty address is %p, from %p\n",
178 sig, pInfo->si_addr, uc->uc_mcontext.gregs[REG_PC]));
179 /* Or do nothing by default: */
180 else
181 Log(("GUI: Got signal %d\n", sig));
182
183 /* Acquire backtrace of 16 lvls depth: */
184 iTraceSize = backtrace(trace, 16);
185
186 /* Overwrite sigaction with caller's address: */
187 trace[1] = (void *)uc->uc_mcontext.gregs[REG_PC];
188
189 /* Translate the addresses into an array of messages: */
190 messages = backtrace_symbols(trace, iTraceSize);
191
192 /* Skip first stack frame (points here): */
193 Log(("GUI: [bt] Execution path:\n"));
194 for (i = 1; i < iTraceSize; ++i)
195 Log(("GUI: [bt] %s\n", messages[i]));
196
197 exit(0);
198}
199
200/** X11, Linux, Debug: Installs signal handler printing backtrace of the call stack. */
201static void InstallSignalHandler()
202{
203 struct sigaction sa;
204 sa.sa_sigaction = BackTraceSignalHandler;
205 sigemptyset(&sa.sa_mask);
206 sa.sa_flags = SA_RESTART | SA_SIGINFO;
207 sigaction(SIGSEGV, &sa, 0);
208 sigaction(SIGBUS, &sa, 0);
209 sigaction(SIGUSR1, &sa, 0);
210}
211# endif /* RT_OS_LINUX && DEBUG */
212#endif /* VBOX_WS_NIX */
213
214/** Qt5 message handler, function that prints out
215 * debug, warning, critical, fatal and system error messages.
216 * @param enmType Holds the type of the message.
217 * @param context Holds the message context.
218 * @param strMessage Holds the message body. */
219static void QtMessageOutput(QtMsgType enmType, const QMessageLogContext &context, const QString &strMessage)
220{
221 NOREF(context);
222# ifndef VBOX_WS_NIX
223 NOREF(strMessage);
224# endif
225 switch (enmType)
226 {
227 case QtDebugMsg:
228 Log(("Qt DEBUG: %s\n", strMessage.toUtf8().constData()));
229 break;
230 case QtWarningMsg:
231 Log(("Qt WARNING: %s\n", strMessage.toUtf8().constData()));
232# ifdef VBOX_WS_NIX
233 /* Needed for instance for the message ``cannot connect to X server'': */
234 RTStrmPrintf(g_pStdErr, "Qt WARNING: %s\n", strMessage.toUtf8().constData());
235# endif
236 break;
237 case QtCriticalMsg:
238 Log(("Qt CRITICAL: %s\n", strMessage.toUtf8().constData()));
239# ifdef VBOX_WS_NIX
240 /* Needed for instance for the message ``cannot connect to X server'': */
241 RTStrmPrintf(g_pStdErr, "Qt CRITICAL: %s\n", strMessage.toUtf8().constData());
242# endif
243 break;
244 case QtFatalMsg:
245 Log(("Qt FATAL: %s\n", strMessage.toUtf8().constData()));
246# ifdef VBOX_WS_NIX
247 /* Needed for instance for the message ``cannot connect to X server'': */
248 RTStrmPrintf(g_pStdErr, "Qt FATAL: %s\n", strMessage.toUtf8().constData());
249# endif
250 break;
251# if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
252 case QtInfoMsg:
253 /** @todo ignore? */
254 break;
255# endif
256 }
257}
258
259/** Shows all available command line parameters. */
260static void ShowHelp()
261{
262#ifndef VBOX_RUNTIME_UI
263 static const char s_szTitle[] = VBOX_PRODUCT " Manager";
264#else
265 static const char s_szTitle[] = VBOX_PRODUCT " Runner";
266#endif
267
268 static const char s_szUsage[] =
269#ifdef VBOX_RUNTIME_UI
270 "Options:\n"
271 " --startvm <vmname|UUID> start a VM by specifying its UUID or name\n"
272 " --separate start a separate VM process\n"
273 " --normal keep normal (windowed) mode during startup\n"
274 " --fullscreen switch to fullscreen mode during startup\n"
275 " --seamless switch to seamless mode during startup\n"
276 " --scale switch to scale mode during startup\n"
277 " --no-startvm-errormsgbox do not show a message box for VM start errors\n"
278 " --restore-current restore the current snapshot before starting\n"
279 " --no-aggressive-caching delays caching media info in VM processes\n"
280 " --fda <image|none> Mount the specified floppy image\n"
281 " --dvd <image|none> Mount the specified DVD image\n"
282# ifdef VBOX_GUI_WITH_PIDFILE
283 " --pidfile <file> create a pidfile file when a VM is up and running\n"
284# endif /* VBOX_GUI_WITH_PIDFILE */
285# ifdef VBOX_WITH_DEBUGGER_GUI
286 " --dbg enable the GUI debug menu\n"
287 " --debug like --dbg and show debug windows at VM startup\n"
288 " --debug-command-line like --dbg and show command line window at VM startup\n"
289 " --debug-statistics like --dbg and show statistics window at VM startup\n"
290 " --statistics-expand <pat> expand the matching statistics (can be repeated)\n"
291 " --statistics-filter <pat> statistics filter\n"
292 " --statistics-config <str> statistics configuration\n"
293 " --no-debug disable the GUI debug menu and debug windows\n"
294 " --start-paused start the VM in the paused state\n"
295 " --start-running start the VM running (for overriding --debug*)\n"
296# endif /* VBOX_WITH_DEBUGGER_GUI */
297 "\n"
298 "Expert options:\n"
299 " --execute-all-in-iem For debugging the interpreted execution mode.\n"
300 " --driverless Do not open the support driver (NEM or IEM mode).\n"
301 " --warp-pct <pct> time warp factor, 100%% (= 1.0) = normal speed\n"
302 " --no-keyboard-grabbing Don't grab the keyboard on windows (for debugging).\n"
303 "\n"
304# ifdef VBOX_WITH_DEBUGGER_GUI
305 "The following environment (and extra data) variables are evaluated:\n"
306 " VBOX_GUI_DBG_ENABLED (GUI/Dbg/Enabled)\n"
307 " enable the GUI debug menu if set\n"
308 " VBOX_GUI_DBG_AUTO_SHOW (GUI/Dbg/AutoShow)\n"
309 " show debug windows at VM startup\n"
310 " VBOX_GUI_NO_DEBUGGER\n"
311 " disable the GUI debug menu and debug windows\n"
312# endif /* VBOX_WITH_DEBUGGER_GUI */
313#else
314 "No special options.\n"
315 "\n"
316 "If you are looking for --startvm and related options, you need to use VirtualBoxVM.\n"
317#endif
318 ;
319
320 RTPrintf("%s v%s\n"
321 "Copyright (C) 2005-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
322 "\n"
323 "%s",
324 s_szTitle, RTBldCfgVersion(), s_szUsage);
325
326#ifdef VBOX_WS_WIN
327 /* Show message box. Modify the option list a little
328 * to better make it fit in the upcoming dialog. */
329 char szTitleWithVersion[sizeof(s_szTitle) + 128];
330 char szMsg[sizeof(s_szUsage) + 128];
331 char *pszDst = szMsg;
332 size_t offSrc = 0;
333 while (offSrc < sizeof(s_szUsage) - 1U)
334 {
335 char ch;
336 if ( s_szUsage[offSrc] == ' '
337 && s_szUsage[offSrc + 1] == ' '
338 && ( (ch = s_szUsage[offSrc + 2]) == '-' /* option line */
339 || ch == 'V' /* env.var. line */))
340 {
341 /* Split option lines: */
342 if (ch == '-')
343 {
344 offSrc += 2;
345 size_t cchOption = 0;
346 while ( s_szUsage[offSrc + cchOption] != ' '
347 || s_szUsage[offSrc + cchOption + 1] != ' ')
348 ++cchOption;
349
350 memcpy(pszDst, &s_szUsage[offSrc], cchOption);
351 offSrc += cchOption + 2;
352 pszDst += cchOption;
353 }
354 /* Change environment variable indentation: */
355 else
356 {
357 offSrc += 2;
358 size_t cchLine = 0;
359 while ((ch = s_szUsage[offSrc + cchLine]) != '\n' && ch != '\0')
360 ++cchLine;
361
362 memcpy(pszDst, &s_szUsage[offSrc], cchLine);
363 offSrc += cchLine + 1;
364 pszDst += cchLine;
365 }
366 *pszDst++ = '\n';
367 *pszDst++ = '\t';
368
369 while (s_szUsage[offSrc] == ' ')
370 ++offSrc;
371 }
372
373 /* Copy up to and including end of line: */
374 while ((ch = s_szUsage[offSrc++]) != '\n' && ch != '\0')
375 *pszDst++ = ch;
376 *pszDst++ = ch;
377 }
378 *pszDst = '\0';
379
380 RTStrPrintf(szTitleWithVersion, sizeof(szTitleWithVersion), "%s v%s - Command Line Options", s_szTitle, RTBldCfgVersion());
381 MessageBoxExA(NULL /*hwndOwner*/, szMsg, szTitleWithVersion, MB_OK | MB_ICONINFORMATION,
382 MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL));
383#endif /* VBOX_WS_WIN */
384}
385
386extern "C" DECLEXPORT(int) TrustedMain(int argc, char **argv, char ** /*envp*/)
387{
388#ifdef VBOX_WS_WIN
389 ATL::CComModule _Module; /* Required internally by ATL (constructor records instance in global variable). */
390#endif
391
392 /* Failed result initially: */
393 int iResultCode = 1;
394
395 /* Start logging: */
396 LogFlowFuncEnter();
397
398 /* Simulate try-catch block: */
399 do
400 {
401#ifdef VBOX_WS_NIX
402 /* Make sure multi-threaded environment is safe: */
403 if (!MakeSureMultiThreadingIsSafe())
404 break;
405 VBGHDISPLAYSERVERTYPE enmDisplayServerType = VBGHDisplayServerTypeDetect();
406 /* Abort before instantiating QApplication in case no active display server can be found to
407 * prevent QApplication from aborting: */
408 if (enmDisplayServerType == VBGHDISPLAYSERVERTYPE_NONE)
409 {
410 iResultCode = 1;
411 Log(("We could not detect an active display server. Exiting."));
412 RTStrmPrintf(g_pStdErr, "No active display server, X11 or Wayland, detected. Exiting.\n");
413 break;
414 }
415 if (VBGHDisplayServerTypeIsXAvailable(enmDisplayServerType))
416 /* Force using Qt platform plugin 'xcb', we have X11 specific code: */
417 RTEnvSet("QT_QPA_PLATFORM", "xcb");
418 else
419 /* Assume pure Wayland (without a X server):*/
420 RTEnvSet("QT_QPA_PLATFORM", "wayland");
421#endif /* VBOX_WS_NIX */
422
423 /* Console help preprocessing: */
424 bool fHelpShown = false;
425 for (int i = 0; i < argc; ++i)
426 {
427 if ( !strcmp(argv[i], "-h")
428 || !strcmp(argv[i], "-?")
429 || !strcmp(argv[i], "-help")
430 || !strcmp(argv[i], "--help"))
431 {
432 fHelpShown = true;
433 ShowHelp();
434 break;
435 }
436 }
437 if (fHelpShown)
438 {
439 iResultCode = 0;
440 break;
441 }
442
443#ifdef VBOX_WITH_HARDENING
444 /* Make sure the image verification code works: */
445 SUPR3HardenedVerifyInit();
446#endif /* VBOX_WITH_HARDENING */
447
448#ifdef VBOX_WS_MAC
449 /* Prevent AppNap for Runtime UI only: */
450 bool fPreventAppNap = false;
451# ifdef VBOX_RUNTIME_UI
452 fPreventAppNap = true;
453# endif
454 /* Instantiate own NSApplication before QApplication do it for us: */
455 UICocoaApplication::create(fPreventAppNap);
456
457# ifdef VBOX_RUNTIME_UI
458 /* If we're a helper app inside Resources in the main application bundle,
459 * we need to amend the library path so the platform plugin can be found.
460 * Note! This builds on the initIprtForDarwinHelperApp() hack. */
461 {
462 char szExecDir[RTPATH_MAX];
463 int vrc = RTPathExecDir(szExecDir, sizeof(szExecDir));
464 AssertRC(vrc);
465 RTPathStripTrailingSlash(szExecDir); /* .../Contents/MacOS */
466 RTPathStripFilename(szExecDir); /* .../Contents */
467 RTPathAppend(szExecDir, sizeof(szExecDir), "plugins"); /* .../Contents/plugins */
468 QCoreApplication::addLibraryPath(QString::fromUtf8(szExecDir));
469 }
470# endif /* VBOX_RUNTIME_UI */
471#endif /* VBOX_WS_MAC */
472
473#ifdef VBOX_WS_NIX
474# if (defined(RT_OS_LINUX) && !defined(RT_ARCH_ARM64)) && defined(DEBUG)
475 /* Install signal handler to backtrace the call stack: */
476 InstallSignalHandler();
477# endif /* RT_OS_LINUX && DEBUG */
478#endif /* VBOX_WS_NIX */
479
480 /* Install Qt console message handler: */
481 qInstallMessageHandler(QtMessageOutput);
482
483#ifdef VBOX_WS_NIX
484 // WORKAROUND:
485 // Some Desktop Environments forcing this variable which was useful in Qt5 case.
486 // But in Qt6 case this variable is additional multiplier to scale-factor
487 // calculated automatic way, which means for x2 the effective factor will be 2x2=4.
488 // No idea how to proceed, probably we will ignore this variable for now, by
489 // setting it to be always equal to 1.
490 //qputenv("QT_SCALE_FACTOR", "1");
491#endif /* VBOX_WS_NIX */
492
493 /* Create application: */
494 QApplication a(argc, argv);
495
496#ifdef VBOX_WS_MAC
497 /* Disable menu icons on MacOS X host: */
498 ::darwinDisableIconsInMenus();
499#endif /* VBOX_WS_MAC */
500
501#ifdef VBOX_WS_WIN
502 /* Drag in the sound drivers and DLLs early to get rid of the delay taking
503 * place when the main menu bar (or any action from that menu bar) is
504 * activated for the first time. This delay is especially annoying if it
505 * happens when the VM is executing in real mode (which gives 100% CPU
506 * load and slows down the load process that happens on the main GUI
507 * thread to several seconds). */
508 PlaySound(NULL, NULL, 0);
509#endif /* VBOX_WS_WIN */
510
511#ifdef VBOX_WS_NIX
512 /* Make all widget native.
513 * We did it to avoid various Qt crashes while testing widget attributes or acquiring winIds.
514 * Yes, we aware of note that alien widgets faster to draw but the only widget we need to be fast
515 * is viewport of VM which was always native since we are using his id for 3D service needs. */
516 a.setAttribute(Qt::AA_NativeWindows);
517
518# ifdef Q_OS_SOLARIS
519 a.setStyle("fusion");
520# endif /* Q_OS_SOLARIS */
521
522# ifndef Q_OS_SOLARIS
523 /* Apply font fixes (after QApplication get created and instantiated font-family): */
524 QFontDatabase fontDataBase;
525 QString currentFamily(QApplication::font().family());
526 bool isCurrentScaleable = fontDataBase.isScalable(currentFamily);
527 QString subFamily(QFont::substitute(currentFamily));
528 bool isSubScaleable = fontDataBase.isScalable(subFamily);
529 if (isCurrentScaleable && !isSubScaleable)
530 QFont::removeSubstitutions(currentFamily);
531# endif /* !Q_OS_SOLARIS */
532
533 /* Qt version check (major.minor are sensitive, fix number is ignored): */
534 if (UIVersionInfo::qtRTVersion() < (UIVersionInfo::qtCTVersion() & 0xFFFF00))
535 {
536 QString strMsg = QApplication::tr("Executable <b>%1</b> requires Qt %2.x, found Qt %3.")
537 .arg(qAppName())
538 .arg(UIVersionInfo::qtCTVersionString().section('.', 0, 1))
539 .arg(UIVersionInfo::qtRTVersionString());
540 QMessageBox::critical(0, QApplication::tr("Incompatible Qt Library Error"),
541 strMsg, QMessageBox::Abort, QMessageBox::NoButton);
542 qFatal("%s", strMsg.toUtf8().constData());
543 break;
544 }
545#endif /* VBOX_WS_NIX */
546
547 /* Create modal-window manager: */
548 UIModalWindowManager::create();
549
550#ifndef VBOX_RUNTIME_UI
551 /* Create global app instance for Selector UI: */
552 UICommon::create(UIType_ManagerUI);
553#else
554 /* Create global app instance for Runtime UI: */
555 UICommon::create(UIType_RuntimeUI);
556#endif
557
558 /* Simulate try-catch block: */
559 do
560 {
561 /* Exit if UICommon is not valid: */
562 if (!uiCommon().isValid())
563 break;
564 /* Exit if UICommon pre-processed arguments: */
565 if (uiCommon().processArgs())
566 break;
567
568 // WORKAROUND:
569 // Initially we wanted to make that workaround for Runtime UI only,
570 // because only there we had a strict handling for proper application quit
571 // procedure. But it appeared on X11 (as usually due to an async nature) there
572 // can happen situations that Qt application is checking whether at least one
573 // window is already shown and if not - exits prematurely _before_ it is actually
574 // shown. That can happen for example if window is not yet shown because blocked
575 // by startup error message-box which is not treated as real window by some
576 // reason. So we are making application exit manual everywhere.
577 a.setQuitOnLastWindowClosed(false);
578
579 /* Create UI starter: */
580 UIStarter uiStarter;
581 /* Request to Start UI _after_ QApplication executed: */
582 QMetaObject::invokeMethod(&uiStarter, "sltStartUI", Qt::QueuedConnection);
583
584 /* Start application: */
585 iResultCode = a.exec();
586 }
587 while (0);
588
589 /* Destroy global app instance: */
590 UICommon::destroy();
591
592 /* Destroy modal-window manager: */
593 UIModalWindowManager::destroy();
594 }
595 while (0);
596
597 /* Finish logging: */
598 LogFlowFunc(("rc=%d\n", iResultCode));
599 LogFlowFuncLeave();
600
601 /* Return result: */
602 return iResultCode;
603}
604
605#if !defined(VBOX_WITH_HARDENING) || !defined(VBOX_RUNTIME_UI)
606
607# if defined(RT_OS_DARWIN) && defined(VBOX_RUNTIME_UI)
608
609extern "C" const char *_dyld_get_image_name(uint32_t);
610
611/** Init runtime with the executable path pointing into the
612 * VirtualBox.app/Contents/MacOS/ rather than
613 * VirtualBox.app/Contents/Resource/VirtualBoxVM.app/Contents/MacOS/.
614 *
615 * This is a HACK to make codesign and friends happy on OS X. The idea is to
616 * improve and eliminate this over time.
617 */
618DECL_NO_INLINE(static, int) initIprtForDarwinHelperApp(int cArgs, char ***ppapszArgs, uint32_t fFlags)
619{
620 const char *pszImageName = _dyld_get_image_name(0);
621 AssertReturn(pszImageName, VERR_INTERNAL_ERROR);
622
623 char szTmpPath[PATH_MAX + 1];
624 const char *psz = realpath(pszImageName, szTmpPath);
625 int rc;
626 if (psz)
627 {
628 char *pszFilename = RTPathFilename(szTmpPath);
629 if (pszFilename)
630 {
631 char const chSavedFilename0 = *pszFilename;
632 *pszFilename = '\0';
633 RTPathStripTrailingSlash(szTmpPath); /* VirtualBox.app/Contents/Resources/VirtualBoxVM.app/Contents/MacOS */
634 RTPathStripFilename(szTmpPath); /* VirtualBox.app/Contents/Resources/VirtualBoxVM.app/Contents/ */
635 RTPathStripFilename(szTmpPath); /* VirtualBox.app/Contents/Resources/VirtualBoxVM.app */
636 RTPathStripFilename(szTmpPath); /* VirtualBox.app/Contents/Resources */
637 RTPathStripFilename(szTmpPath); /* VirtualBox.app/Contents */
638 char *pszDst = strchr(szTmpPath, '\0');
639 pszDst = (char *)memcpy(pszDst, RT_STR_TUPLE("/MacOS/")) + sizeof("/MacOS/") - 1; /** @todo where is mempcpy? */
640 *pszFilename = chSavedFilename0;
641 memmove(pszDst, pszFilename, strlen(pszFilename) + 1);
642
643 return RTR3InitEx(RTR3INIT_VER_CUR, fFlags, cArgs, ppapszArgs, szTmpPath);
644 }
645 rc = VERR_INVALID_NAME;
646 }
647 else
648 rc = RTErrConvertFromErrno(errno);
649 AssertMsgRCReturn(rc, ("rc=%Rrc pszLink=\"%s\"\nhex: %.*Rhxs\n", rc, pszImageName, strlen(pszImageName), pszImageName), rc);
650 return rc;
651}
652# endif
653
654
655int main(int argc, char **argv, char **envp)
656{
657# ifdef VBOX_WS_NIX
658 /* Make sure multi-threaded environment is safe: */
659 if (!MakeSureMultiThreadingIsSafe())
660 return 1;
661# endif /* VBOX_WS_NIX */
662
663 /*
664 * Determine the IPRT/SUPLib initialization flags if runtime UI process.
665 * Only initialize SUPLib if about to start a VM in this process.
666 *
667 * Note! This must must match the corresponding parsing in hardenedmain.cpp
668 * and UICommon.cpp exactly, otherwise there will be weird error messages.
669 */
670 /** @todo r=bird: We should consider just postponing this stuff till VM
671 * creation, it shouldn't make too much of a difference GIP-wise. */
672 uint32_t fFlags = 0;
673# ifdef VBOX_RUNTIME_UI
674 unsigned cOptionsLeft = 4;
675 bool fStartVM = false;
676 bool fSeparateProcess = false;
677 bool fExecuteAllInIem = false;
678 bool fDriverless = false;
679 for (int i = 1; i < argc && cOptionsLeft > 0; ++i)
680 {
681 if ( !strcmp(argv[i], "--startvm")
682 || !strcmp(argv[i], "-startvm"))
683 {
684 cOptionsLeft -= fStartVM == false;
685 fStartVM = true;
686 i++;
687 }
688 else if ( !strcmp(argv[i], "--separate")
689 || !strcmp(argv[i], "-separate"))
690 {
691 cOptionsLeft -= fSeparateProcess == false;
692 fSeparateProcess = true;
693 }
694 else if (!strcmp(argv[i], "--execute-all-in-iem"))
695 {
696 cOptionsLeft -= fExecuteAllInIem == false;
697 fExecuteAllInIem = true;
698 }
699 else if (!strcmp(argv[i], "--driverless"))
700 {
701 cOptionsLeft -= fDriverless == false;
702 fDriverless = true;
703 }
704 }
705 if (fStartVM && !fSeparateProcess)
706 {
707 fFlags |= RTR3INIT_FLAGS_TRY_SUPLIB;
708 if (fExecuteAllInIem)
709 fFlags |= SUPR3INIT_F_DRIVERLESS_IEM_ALLOWED << RTR3INIT_FLAGS_SUPLIB_SHIFT;
710 if (fDriverless)
711 fFlags |= SUPR3INIT_F_DRIVERLESS << RTR3INIT_FLAGS_SUPLIB_SHIFT;
712 }
713# endif /* VBOX_RUNTIME_UI */
714
715 /* Initialize VBox Runtime: */
716# if defined(RT_OS_DARWIN) && defined(VBOX_RUNTIME_UI)
717 int rc = initIprtForDarwinHelperApp(argc, &argv, fFlags);
718# else
719 int rc = RTR3InitExe(argc, &argv, fFlags);
720# endif
721 /* Initialization failed: */
722 if (RT_FAILURE(rc))
723 {
724 /* We have to create QApplication anyway
725 * just to show the only one error-message: */
726 QApplication a(argc, &argv[0]);
727 Q_UNUSED(a);
728
729# ifdef Q_OS_SOLARIS
730 a.setStyle("fusion");
731# endif
732
733 /* Prepare the error-message: */
734 QString strTitle = QApplication::tr("VirtualBox - Runtime Error");
735 QString strText = "<html>";
736 switch (rc)
737 {
738 case VERR_VM_DRIVER_NOT_INSTALLED:
739 case VERR_VM_DRIVER_LOAD_ERROR:
740 strText += QApplication::tr("<b>Cannot access the kernel driver!</b><br/><br/>");
741# ifdef RT_OS_LINUX
742 strText += g_QStrHintLinuxNoDriver;
743# else
744 strText += g_QStrHintOtherNoDriver;
745# endif
746 break;
747# ifdef RT_OS_LINUX
748 case VERR_NO_MEMORY:
749 strText += g_QStrHintLinuxNoMemory;
750 break;
751# endif
752 case VERR_VM_DRIVER_NOT_ACCESSIBLE:
753 strText += QApplication::tr("Kernel driver not accessible");
754 break;
755 case VERR_VM_DRIVER_VERSION_MISMATCH:
756# ifdef RT_OS_LINUX
757 strText += g_QStrHintLinuxWrongDriverVersion;
758# else
759 strText += g_QStrHintOtherWrongDriverVersion;
760# endif
761 break;
762 default:
763 strText += QApplication::tr("Unknown error %2 during initialization of the Runtime").arg(rc);
764 break;
765 }
766 strText += "</html>";
767
768 /* Show the error-message: */
769 QMessageBox::critical(0 /* parent */, strTitle, strText,
770 QMessageBox::Abort /* 1st button */, QMessageBox::NoButton /* 2nd button */);
771
772 /* Default error-result: */
773 return 1;
774 }
775
776 /* Call to actual main function: */
777 return TrustedMain(argc, argv, envp);
778}
779
780#endif /* !VBOX_WITH_HARDENING || !VBOX_RUNTIME_UI */
781
782#ifdef VBOX_WITH_HARDENING
783
784/**
785 * Special entrypoint used by the hardening code when something goes south.
786 *
787 * Display an error dialog to the user.
788 *
789 * @param pszWhere Indicates where the error occured.
790 * @param enmWhat Indicates what init operation was going on at the time.
791 * @param rc The VBox status code corresponding to the error.
792 * @param pszMsgFmt The message format string.
793 * @param va Format arguments.
794 */
795extern "C" DECLEXPORT(void) TrustedError(const char *pszWhere, SUPINITOP enmWhat, int rc, const char *pszMsgFmt, va_list va)
796{
797 char szMsgBuf[_16K];
798
799 /*
800 * We have to create QApplication anyway just to show the only one error-message.
801 * This is a bit hackish as we don't have the argument vector handy.
802 */
803 int argc = 0;
804 char *argv[2] = { NULL, NULL };
805 QApplication a(argc, &argv[0]);
806
807 /*
808 * The details starts off a properly formatted rc and where/what, we use
809 * the szMsgBuf for this, thus this have to come before the actual message
810 * formatting.
811 */
812 RTStrPrintf(szMsgBuf, sizeof(szMsgBuf),
813 "<!--EOM-->"
814 "where: %s\n"
815 "what: %d\n"
816 "%Rra\n",
817 pszWhere, enmWhat, rc);
818 QString strDetails = szMsgBuf;
819
820 /*
821 * Format the error message. Take whatever comes after a double new line as
822 * something better off in the details section.
823 */
824 RTStrPrintfV(szMsgBuf, sizeof(szMsgBuf), pszMsgFmt, va);
825
826 char *pszDetails = strstr(szMsgBuf, "\n\n");
827 if (pszDetails)
828 {
829 while (RT_C_IS_SPACE(*pszDetails))
830 *pszDetails++ = '\0';
831 if (*pszDetails)
832 {
833 strDetails += "\n";
834 strDetails += pszDetails;
835 }
836 RTStrStripR(szMsgBuf);
837 }
838
839 QString strText = QApplication::tr("<html><b>%1 (rc=%2)</b><br/><br/>").arg(szMsgBuf).arg(rc);
840 strText.replace(QString("\n"), QString("<br>"));
841
842 /*
843 * Append possibly helpful hints to the error message.
844 */
845 switch (enmWhat)
846 {
847 case kSupInitOp_Driver:
848# ifdef RT_OS_LINUX
849 strText += g_QStrHintLinuxNoDriver;
850# else /* RT_OS_LINUX */
851 strText += g_QStrHintOtherNoDriver;
852# endif /* !RT_OS_LINUX */
853 break;
854 case kSupInitOp_IPRT:
855 case kSupInitOp_Misc:
856 if (rc == VERR_VM_DRIVER_VERSION_MISMATCH)
857# ifndef RT_OS_LINUX
858 strText += g_QStrHintOtherWrongDriverVersion;
859# else
860 strText += g_QStrHintLinuxWrongDriverVersion;
861 else if (rc == VERR_NO_MEMORY)
862 strText += g_QStrHintLinuxNoMemory;
863# endif
864 else
865 strText += g_QStrHintReinstall;
866 break;
867 case kSupInitOp_Integrity:
868 case kSupInitOp_RootCheck:
869 strText += g_QStrHintReinstall;
870 break;
871 default:
872 /* no hints here */
873 break;
874 }
875
876# ifdef VBOX_WS_NIX
877 /* We have to to make sure that we display the error-message
878 * after the parent displayed its own message. */
879 sleep(2);
880# endif /* VBOX_WS_NIX */
881
882 /* Update strText with strDetails: */
883 if (!strDetails.isEmpty())
884 strText += QString("<br><br>%1").arg(strDetails);
885
886 /* Close the <html> scope: */
887 strText += "</html>";
888
889 /* Create and show the error message-box: */
890 QMessageBox::critical(0, QApplication::tr("VirtualBox - Error In %1").arg(pszWhere), strText);
891
892 qFatal("%s", strText.toUtf8().constData());
893}
894
895#endif /* VBOX_WITH_HARDENING */
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use