VirtualBox

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

Last change on this file since 100064 was 100064, checked in by vboxsync, 13 months ago

FE/Qt: bugref:10421. Replacing VBOX_WS_X11 with VBOX_WS_NIX.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 31.2 KB
Line 
1/* $Id: main.cpp 100064 2023-06-04 09:10:01Z 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 "\n"
297# ifdef VBOX_WITH_DEBUGGER_GUI
298 "The following environment (and extra data) variables are evaluated:\n"
299 " VBOX_GUI_DBG_ENABLED (GUI/Dbg/Enabled)\n"
300 " enable the GUI debug menu if set\n"
301 " VBOX_GUI_DBG_AUTO_SHOW (GUI/Dbg/AutoShow)\n"
302 " show debug windows at VM startup\n"
303 " VBOX_GUI_NO_DEBUGGER\n"
304 " disable the GUI debug menu and debug windows\n"
305# endif /* VBOX_WITH_DEBUGGER_GUI */
306#else
307 "No special options.\n"
308 "\n"
309 "If you are looking for --startvm and related options, you need to use VirtualBoxVM.\n"
310#endif
311 ;
312
313 RTPrintf("%s v%s\n"
314 "Copyright (C) 2005-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
315 "\n"
316 "%s",
317 s_szTitle, RTBldCfgVersion(), s_szUsage);
318
319#ifdef VBOX_WS_WIN
320 /* Show message box. Modify the option list a little
321 * to better make it fit in the upcoming dialog. */
322 char szTitleWithVersion[sizeof(s_szTitle) + 128];
323 char szMsg[sizeof(s_szUsage) + 128];
324 char *pszDst = szMsg;
325 size_t offSrc = 0;
326 while (offSrc < sizeof(s_szUsage) - 1U)
327 {
328 char ch;
329 if ( s_szUsage[offSrc] == ' '
330 && s_szUsage[offSrc + 1] == ' '
331 && ( (ch = s_szUsage[offSrc + 2]) == '-' /* option line */
332 || ch == 'V' /* env.var. line */))
333 {
334 /* Split option lines: */
335 if (ch == '-')
336 {
337 offSrc += 2;
338 size_t cchOption = 0;
339 while ( s_szUsage[offSrc + cchOption] != ' '
340 || s_szUsage[offSrc + cchOption + 1] != ' ')
341 ++cchOption;
342
343 memcpy(pszDst, &s_szUsage[offSrc], cchOption);
344 offSrc += cchOption + 2;
345 pszDst += cchOption;
346 }
347 /* Change environment variable indentation: */
348 else
349 {
350 offSrc += 2;
351 size_t cchLine = 0;
352 while ((ch = s_szUsage[offSrc + cchLine]) != '\n' && ch != '\0')
353 ++cchLine;
354
355 memcpy(pszDst, &s_szUsage[offSrc], cchLine);
356 offSrc += cchLine + 1;
357 pszDst += cchLine;
358 }
359 *pszDst++ = '\n';
360 *pszDst++ = '\t';
361
362 while (s_szUsage[offSrc] == ' ')
363 ++offSrc;
364 }
365
366 /* Copy up to and including end of line: */
367 while ((ch = s_szUsage[offSrc++]) != '\n' && ch != '\0')
368 *pszDst++ = ch;
369 *pszDst++ = ch;
370 }
371 *pszDst = '\0';
372
373 RTStrPrintf(szTitleWithVersion, sizeof(szTitleWithVersion), "%s v%s - Command Line Options", s_szTitle, RTBldCfgVersion());
374 MessageBoxExA(NULL /*hwndOwner*/, szMsg, szTitleWithVersion, MB_OK | MB_ICONINFORMATION,
375 MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL));
376#endif /* VBOX_WS_WIN */
377}
378
379extern "C" DECLEXPORT(int) TrustedMain(int argc, char **argv, char ** /*envp*/)
380{
381#ifdef VBOX_WS_WIN
382 ATL::CComModule _Module; /* Required internally by ATL (constructor records instance in global variable). */
383#endif
384
385 /* Failed result initially: */
386 int iResultCode = 1;
387
388 /* Start logging: */
389 LogFlowFuncEnter();
390
391 /* Simulate try-catch block: */
392 do
393 {
394#ifdef VBOX_WS_NIX
395 /* Make sure multi-threaded environment is safe: */
396 if (!MakeSureMultiThreadingIsSafe())
397 break;
398 VBGHDISPLAYSERVERTYPE enmDisplayServerType = VBGHDisplayServerTypeDetect();
399 /* Default to X11 if anything else was found: */
400 if (enmDisplayServerType == VBGHDISPLAYSERVERTYPE_NONE)
401 enmDisplayServerType = VBGHDISPLAYSERVERTYPE_X11;
402 if (VBGHDisplayServerTypeIsXAvailable(enmDisplayServerType))
403 /* Force using Qt platform plugin 'xcb', we have X11 specific code: */
404 RTEnvSet("QT_QPA_PLATFORM", "xcb");
405 else
406 /* Assume pure Wayland (without a X server):*/
407 RTEnvSet("QT_QPA_PLATFORM", "wayland");
408#endif /* VBOX_WS_NIX */
409
410 /* Console help preprocessing: */
411 bool fHelpShown = false;
412 for (int i = 0; i < argc; ++i)
413 {
414 if ( !strcmp(argv[i], "-h")
415 || !strcmp(argv[i], "-?")
416 || !strcmp(argv[i], "-help")
417 || !strcmp(argv[i], "--help"))
418 {
419 fHelpShown = true;
420 ShowHelp();
421 break;
422 }
423 }
424 if (fHelpShown)
425 {
426 iResultCode = 0;
427 break;
428 }
429
430#ifdef VBOX_WITH_HARDENING
431 /* Make sure the image verification code works: */
432 SUPR3HardenedVerifyInit();
433#endif /* VBOX_WITH_HARDENING */
434
435#ifdef VBOX_WS_MAC
436 /* Instantiate own NSApplication before QApplication do it for us: */
437 UICocoaApplication::instance();
438
439# ifdef VBOX_RUNTIME_UI
440 /* If we're a helper app inside Resources in the main application bundle,
441 * we need to amend the library path so the platform plugin can be found.
442 * Note! This builds on the initIprtForDarwinHelperApp() hack. */
443 {
444 char szExecDir[RTPATH_MAX];
445 int vrc = RTPathExecDir(szExecDir, sizeof(szExecDir));
446 AssertRC(vrc);
447 RTPathStripTrailingSlash(szExecDir); /* .../Contents/MacOS */
448 RTPathStripFilename(szExecDir); /* .../Contents */
449 RTPathAppend(szExecDir, sizeof(szExecDir), "plugins"); /* .../Contents/plugins */
450 QCoreApplication::addLibraryPath(QString::fromUtf8(szExecDir));
451 }
452# endif /* VBOX_RUNTIME_UI */
453#endif /* VBOX_WS_MAC */
454
455#ifdef VBOX_WS_NIX
456# if defined(RT_OS_LINUX) && defined(DEBUG)
457 /* Install signal handler to backtrace the call stack: */
458 InstallSignalHandler();
459# endif /* RT_OS_LINUX && DEBUG */
460#endif /* VBOX_WS_NIX */
461
462 /* Install Qt console message handler: */
463 qInstallMessageHandler(QtMessageOutput);
464
465 /* Enable HiDPI support: */
466#ifndef VBOX_IS_QT6_OR_LATER
467 QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
468# if (!defined(DEBUG_bird) || defined(RT_OS_DARWIN))
469# ifndef VBOX_GUI_WITH_CUSTOMIZATIONS1
470 /* This shouldn't be enabled for customer WM, since Qt has conflicts in that case. */
471 QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
472# endif
473# endif
474#endif
475
476 /* Create application: */
477 QApplication a(argc, argv);
478
479#ifdef VBOX_WS_MAC
480 /* Disable menu icons on MacOS X host: */
481 ::darwinDisableIconsInMenus();
482#endif /* VBOX_WS_MAC */
483
484#ifdef VBOX_WS_WIN
485 /* Drag in the sound drivers and DLLs early to get rid of the delay taking
486 * place when the main menu bar (or any action from that menu bar) is
487 * activated for the first time. This delay is especially annoying if it
488 * happens when the VM is executing in real mode (which gives 100% CPU
489 * load and slows down the load process that happens on the main GUI
490 * thread to several seconds). */
491 PlaySound(NULL, NULL, 0);
492#endif /* VBOX_WS_WIN */
493
494#ifdef VBOX_WS_NIX
495 /* Make all widget native.
496 * We did it to avoid various Qt crashes while testing widget attributes or acquiring winIds.
497 * Yes, we aware of note that alien widgets faster to draw but the only widget we need to be fast
498 * is viewport of VM which was always native since we are using his id for 3D service needs. */
499 a.setAttribute(Qt::AA_NativeWindows);
500
501# ifdef Q_OS_SOLARIS
502 a.setStyle("fusion");
503# endif /* Q_OS_SOLARIS */
504
505# ifndef Q_OS_SOLARIS
506 /* Apply font fixes (after QApplication get created and instantiated font-family): */
507 QFontDatabase fontDataBase;
508 QString currentFamily(QApplication::font().family());
509 bool isCurrentScaleable = fontDataBase.isScalable(currentFamily);
510 QString subFamily(QFont::substitute(currentFamily));
511 bool isSubScaleable = fontDataBase.isScalable(subFamily);
512 if (isCurrentScaleable && !isSubScaleable)
513 QFont::removeSubstitutions(currentFamily);
514# endif /* !Q_OS_SOLARIS */
515
516 /* Qt version check (major.minor are sensitive, fix number is ignored): */
517 if (UICommon::qtRTVersion() < (UICommon::qtCTVersion() & 0xFFFF00))
518 {
519 QString strMsg = QApplication::tr("Executable <b>%1</b> requires Qt %2.x, found Qt %3.")
520 .arg(qAppName())
521 .arg(UICommon::qtCTVersionString().section('.', 0, 1))
522 .arg(UICommon::qtRTVersionString());
523 QMessageBox::critical(0, QApplication::tr("Incompatible Qt Library Error"),
524 strMsg, QMessageBox::Abort, 0);
525 qFatal("%s", strMsg.toUtf8().constData());
526 break;
527 }
528#endif /* VBOX_WS_NIX */
529
530 /* Create modal-window manager: */
531 UIModalWindowManager::create();
532
533#ifndef VBOX_RUNTIME_UI
534 /* Create global app instance for Selector UI: */
535 UICommon::create(UICommon::UIType_SelectorUI);
536#else
537 /* Create global app instance for Runtime UI: */
538 UICommon::create(UICommon::UIType_RuntimeUI);
539#endif
540
541 /* Simulate try-catch block: */
542 do
543 {
544 /* Exit if UICommon is not valid: */
545 if (!uiCommon().isValid())
546 break;
547 /* Exit if UICommon pre-processed arguments: */
548 if (uiCommon().processArgs())
549 break;
550
551 // WORKAROUND:
552 // Initially we wanted to make that workaround for Runtime UI only,
553 // because only there we had a strict handling for proper application quit
554 // procedure. But it appeared on X11 (as usually due to an async nature) there
555 // can happen situations that Qt application is checking whether at least one
556 // window is already shown and if not - exits prematurely _before_ it is actually
557 // shown. That can happen for example if window is not yet shown because blocked
558 // by startup error message-box which is not treated as real window by some
559 // reason. So we are making application exit manual everywhere.
560 a.setQuitOnLastWindowClosed(false);
561
562 /* Create UI starter: */
563 UIStarter uiStarter;
564 /* Request to Start UI _after_ QApplication executed: */
565 QMetaObject::invokeMethod(&uiStarter, "sltStartUI", Qt::QueuedConnection);
566
567 /* Start application: */
568 iResultCode = a.exec();
569 }
570 while (0);
571
572 /* Destroy global app instance: */
573 UICommon::destroy();
574
575 /* Destroy modal-window manager: */
576 UIModalWindowManager::destroy();
577 }
578 while (0);
579
580 /* Finish logging: */
581 LogFlowFunc(("rc=%d\n", iResultCode));
582 LogFlowFuncLeave();
583
584 /* Return result: */
585 return iResultCode;
586}
587
588#if !defined(VBOX_WITH_HARDENING) || !defined(VBOX_RUNTIME_UI)
589
590# if defined(RT_OS_DARWIN) && defined(VBOX_RUNTIME_UI)
591
592extern "C" const char *_dyld_get_image_name(uint32_t);
593
594/** Init runtime with the executable path pointing into the
595 * VirtualBox.app/Contents/MacOS/ rather than
596 * VirtualBox.app/Contents/Resource/VirtualBoxVM.app/Contents/MacOS/.
597 *
598 * This is a HACK to make codesign and friends happy on OS X. The idea is to
599 * improve and eliminate this over time.
600 */
601DECL_NO_INLINE(static, int) initIprtForDarwinHelperApp(int cArgs, char ***ppapszArgs, uint32_t fFlags)
602{
603 const char *pszImageName = _dyld_get_image_name(0);
604 AssertReturn(pszImageName, VERR_INTERNAL_ERROR);
605
606 char szTmpPath[PATH_MAX + 1];
607 const char *psz = realpath(pszImageName, szTmpPath);
608 int rc;
609 if (psz)
610 {
611 char *pszFilename = RTPathFilename(szTmpPath);
612 if (pszFilename)
613 {
614 char const chSavedFilename0 = *pszFilename;
615 *pszFilename = '\0';
616 RTPathStripTrailingSlash(szTmpPath); /* VirtualBox.app/Contents/Resources/VirtualBoxVM.app/Contents/MacOS */
617 RTPathStripFilename(szTmpPath); /* VirtualBox.app/Contents/Resources/VirtualBoxVM.app/Contents/ */
618 RTPathStripFilename(szTmpPath); /* VirtualBox.app/Contents/Resources/VirtualBoxVM.app */
619 RTPathStripFilename(szTmpPath); /* VirtualBox.app/Contents/Resources */
620 RTPathStripFilename(szTmpPath); /* VirtualBox.app/Contents */
621 char *pszDst = strchr(szTmpPath, '\0');
622 pszDst = (char *)memcpy(pszDst, RT_STR_TUPLE("/MacOS/")) + sizeof("/MacOS/") - 1; /** @todo where is mempcpy? */
623 *pszFilename = chSavedFilename0;
624 memmove(pszDst, pszFilename, strlen(pszFilename) + 1);
625
626 return RTR3InitEx(RTR3INIT_VER_CUR, fFlags, cArgs, ppapszArgs, szTmpPath);
627 }
628 rc = VERR_INVALID_NAME;
629 }
630 else
631 rc = RTErrConvertFromErrno(errno);
632 AssertMsgRCReturn(rc, ("rc=%Rrc pszLink=\"%s\"\nhex: %.*Rhxs\n", rc, pszImageName, strlen(pszImageName), pszImageName), rc);
633 return rc;
634}
635# endif
636
637
638int main(int argc, char **argv, char **envp)
639{
640# ifdef VBOX_WS_NIX
641 /* Make sure multi-threaded environment is safe: */
642 if (!MakeSureMultiThreadingIsSafe())
643 return 1;
644# endif /* VBOX_WS_NIX */
645
646 /*
647 * Determine the IPRT/SUPLib initialization flags if runtime UI process.
648 * Only initialize SUPLib if about to start a VM in this process.
649 *
650 * Note! This must must match the corresponding parsing in hardenedmain.cpp
651 * and UICommon.cpp exactly, otherwise there will be weird error messages.
652 */
653 /** @todo r=bird: We should consider just postponing this stuff till VM
654 * creation, it shouldn't make too much of a difference GIP-wise. */
655 uint32_t fFlags = 0;
656# ifdef VBOX_RUNTIME_UI
657 unsigned cOptionsLeft = 4;
658 bool fStartVM = false;
659 bool fSeparateProcess = false;
660 bool fExecuteAllInIem = false;
661 bool fDriverless = false;
662 for (int i = 1; i < argc && cOptionsLeft > 0; ++i)
663 {
664 if ( !strcmp(argv[i], "--startvm")
665 || !strcmp(argv[i], "-startvm"))
666 {
667 cOptionsLeft -= fStartVM == false;
668 fStartVM = true;
669 i++;
670 }
671 else if ( !strcmp(argv[i], "--separate")
672 || !strcmp(argv[i], "-separate"))
673 {
674 cOptionsLeft -= fSeparateProcess == false;
675 fSeparateProcess = true;
676 }
677 else if (!strcmp(argv[i], "--execute-all-in-iem"))
678 {
679 cOptionsLeft -= fExecuteAllInIem == false;
680 fExecuteAllInIem = true;
681 }
682 else if (!strcmp(argv[i], "--driverless"))
683 {
684 cOptionsLeft -= fDriverless == false;
685 fDriverless = true;
686 }
687 }
688 if (fStartVM && !fSeparateProcess)
689 {
690 fFlags |= RTR3INIT_FLAGS_TRY_SUPLIB;
691 if (fExecuteAllInIem)
692 fFlags |= SUPR3INIT_F_DRIVERLESS_IEM_ALLOWED << RTR3INIT_FLAGS_SUPLIB_SHIFT;
693 if (fDriverless)
694 fFlags |= SUPR3INIT_F_DRIVERLESS << RTR3INIT_FLAGS_SUPLIB_SHIFT;
695 }
696# endif /* VBOX_RUNTIME_UI */
697
698 /* Initialize VBox Runtime: */
699# if defined(RT_OS_DARWIN) && defined(VBOX_RUNTIME_UI)
700 int rc = initIprtForDarwinHelperApp(argc, &argv, fFlags);
701# else
702 int rc = RTR3InitExe(argc, &argv, fFlags);
703# endif
704 /* Initialization failed: */
705 if (RT_FAILURE(rc))
706 {
707 /* We have to create QApplication anyway
708 * just to show the only one error-message: */
709 QApplication a(argc, &argv[0]);
710 Q_UNUSED(a);
711
712# ifdef Q_OS_SOLARIS
713 a.setStyle("fusion");
714# endif
715
716 /* Prepare the error-message: */
717 QString strTitle = QApplication::tr("VirtualBox - Runtime Error");
718 QString strText = "<html>";
719 switch (rc)
720 {
721 case VERR_VM_DRIVER_NOT_INSTALLED:
722 case VERR_VM_DRIVER_LOAD_ERROR:
723 strText += QApplication::tr("<b>Cannot access the kernel driver!</b><br/><br/>");
724# ifdef RT_OS_LINUX
725 strText += g_QStrHintLinuxNoDriver;
726# else
727 strText += g_QStrHintOtherNoDriver;
728# endif
729 break;
730# ifdef RT_OS_LINUX
731 case VERR_NO_MEMORY:
732 strText += g_QStrHintLinuxNoMemory;
733 break;
734# endif
735 case VERR_VM_DRIVER_NOT_ACCESSIBLE:
736 strText += QApplication::tr("Kernel driver not accessible");
737 break;
738 case VERR_VM_DRIVER_VERSION_MISMATCH:
739# ifdef RT_OS_LINUX
740 strText += g_QStrHintLinuxWrongDriverVersion;
741# else
742 strText += g_QStrHintOtherWrongDriverVersion;
743# endif
744 break;
745 default:
746 strText += QApplication::tr("Unknown error %2 during initialization of the Runtime").arg(rc);
747 break;
748 }
749 strText += "</html>";
750
751 /* Show the error-message: */
752 QMessageBox::critical(0 /* parent */, strTitle, strText,
753 QMessageBox::Abort /* 1st button */, 0 /* 2nd button */);
754
755 /* Default error-result: */
756 return 1;
757 }
758
759 /* Call to actual main function: */
760 return TrustedMain(argc, argv, envp);
761}
762
763#endif /* !VBOX_WITH_HARDENING || !VBOX_RUNTIME_UI */
764
765#ifdef VBOX_WITH_HARDENING
766
767/**
768 * Special entrypoint used by the hardening code when something goes south.
769 *
770 * Display an error dialog to the user.
771 *
772 * @param pszWhere Indicates where the error occured.
773 * @param enmWhat Indicates what init operation was going on at the time.
774 * @param rc The VBox status code corresponding to the error.
775 * @param pszMsgFmt The message format string.
776 * @param va Format arguments.
777 */
778extern "C" DECLEXPORT(void) TrustedError(const char *pszWhere, SUPINITOP enmWhat, int rc, const char *pszMsgFmt, va_list va)
779{
780 char szMsgBuf[_16K];
781
782 /*
783 * We have to create QApplication anyway just to show the only one error-message.
784 * This is a bit hackish as we don't have the argument vector handy.
785 */
786 int argc = 0;
787 char *argv[2] = { NULL, NULL };
788 QApplication a(argc, &argv[0]);
789
790 /*
791 * The details starts off a properly formatted rc and where/what, we use
792 * the szMsgBuf for this, thus this have to come before the actual message
793 * formatting.
794 */
795 RTStrPrintf(szMsgBuf, sizeof(szMsgBuf),
796 "<!--EOM-->"
797 "where: %s\n"
798 "what: %d\n"
799 "%Rra\n",
800 pszWhere, enmWhat, rc);
801 QString strDetails = szMsgBuf;
802
803 /*
804 * Format the error message. Take whatever comes after a double new line as
805 * something better off in the details section.
806 */
807 RTStrPrintfV(szMsgBuf, sizeof(szMsgBuf), pszMsgFmt, va);
808
809 char *pszDetails = strstr(szMsgBuf, "\n\n");
810 if (pszDetails)
811 {
812 while (RT_C_IS_SPACE(*pszDetails))
813 *pszDetails++ = '\0';
814 if (*pszDetails)
815 {
816 strDetails += "\n";
817 strDetails += pszDetails;
818 }
819 RTStrStripR(szMsgBuf);
820 }
821
822 QString strText = QApplication::tr("<html><b>%1 (rc=%2)</b><br/><br/>").arg(szMsgBuf).arg(rc);
823 strText.replace(QString("\n"), QString("<br>"));
824
825 /*
826 * Append possibly helpful hints to the error message.
827 */
828 switch (enmWhat)
829 {
830 case kSupInitOp_Driver:
831# ifdef RT_OS_LINUX
832 strText += g_QStrHintLinuxNoDriver;
833# else /* RT_OS_LINUX */
834 strText += g_QStrHintOtherNoDriver;
835# endif /* !RT_OS_LINUX */
836 break;
837 case kSupInitOp_IPRT:
838 case kSupInitOp_Misc:
839 if (rc == VERR_VM_DRIVER_VERSION_MISMATCH)
840# ifndef RT_OS_LINUX
841 strText += g_QStrHintOtherWrongDriverVersion;
842# else
843 strText += g_QStrHintLinuxWrongDriverVersion;
844 else if (rc == VERR_NO_MEMORY)
845 strText += g_QStrHintLinuxNoMemory;
846# endif
847 else
848 strText += g_QStrHintReinstall;
849 break;
850 case kSupInitOp_Integrity:
851 case kSupInitOp_RootCheck:
852 strText += g_QStrHintReinstall;
853 break;
854 default:
855 /* no hints here */
856 break;
857 }
858
859# ifdef VBOX_WS_NIX
860 /* We have to to make sure that we display the error-message
861 * after the parent displayed its own message. */
862 sleep(2);
863# endif /* VBOX_WS_NIX */
864
865 /* Update strText with strDetails: */
866 if (!strDetails.isEmpty())
867 strText += QString("<br><br>%1").arg(strDetails);
868
869 /* Close the <html> scope: */
870 strText += "</html>";
871
872 /* Create and show the error message-box: */
873 QMessageBox::critical(0, QApplication::tr("VirtualBox - Error In %1").arg(pszWhere), strText);
874
875 qFatal("%s", strText.toUtf8().constData());
876}
877
878#endif /* VBOX_WITH_HARDENING */
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use