VirtualBox

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

Last change on this file since 103131 was 102518, checked in by vboxsync, 12 months ago

FE/Qt: Added a --no-keyboard-grabbing option to help with debugging VirtualBoxVM on windows. Ignored on other hosts atm.

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette