VirtualBox

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

Last change on this file since 103795 was 103793, checked in by vboxsync, 9 months ago

FE/Qt: UICommon: Move versioning related functionality to UIVersion / UIVersionInfo; Rework user cases accordingly.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 31.9 KB
Line 
1/* $Id: main.cpp 103793 2024-03-11 19:17:31Z 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(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 /* Instantiate own NSApplication before QApplication do it for us: */
450 UICocoaApplication::instance();
451
452# ifdef VBOX_RUNTIME_UI
453 /* If we're a helper app inside Resources in the main application bundle,
454 * we need to amend the library path so the platform plugin can be found.
455 * Note! This builds on the initIprtForDarwinHelperApp() hack. */
456 {
457 char szExecDir[RTPATH_MAX];
458 int vrc = RTPathExecDir(szExecDir, sizeof(szExecDir));
459 AssertRC(vrc);
460 RTPathStripTrailingSlash(szExecDir); /* .../Contents/MacOS */
461 RTPathStripFilename(szExecDir); /* .../Contents */
462 RTPathAppend(szExecDir, sizeof(szExecDir), "plugins"); /* .../Contents/plugins */
463 QCoreApplication::addLibraryPath(QString::fromUtf8(szExecDir));
464 }
465# endif /* VBOX_RUNTIME_UI */
466#endif /* VBOX_WS_MAC */
467
468#ifdef VBOX_WS_NIX
469# if defined(RT_OS_LINUX) && defined(DEBUG)
470 /* Install signal handler to backtrace the call stack: */
471 InstallSignalHandler();
472# endif /* RT_OS_LINUX && DEBUG */
473#endif /* VBOX_WS_NIX */
474
475 /* Install Qt console message handler: */
476 qInstallMessageHandler(QtMessageOutput);
477
478#ifdef VBOX_WS_NIX
479 // WORKAROUND:
480 // Some Desktop Environments forcing this variable which was useful in Qt5 case.
481 // But in Qt6 case this variable is additional multiplier to scale-factor
482 // calculated automatic way, which means for x2 the effective factor will be 2x2=4.
483 // No idea how to proceed, probably we will ignore this variable for now, by
484 // setting it to be always equal to 1.
485 qputenv("QT_SCALE_FACTOR", "1");
486#endif /* VBOX_WS_NIX */
487
488 /* Create application: */
489 QApplication a(argc, argv);
490
491#ifdef VBOX_WS_MAC
492 /* Disable menu icons on MacOS X host: */
493 ::darwinDisableIconsInMenus();
494#endif /* VBOX_WS_MAC */
495
496#ifdef VBOX_WS_WIN
497 /* Drag in the sound drivers and DLLs early to get rid of the delay taking
498 * place when the main menu bar (or any action from that menu bar) is
499 * activated for the first time. This delay is especially annoying if it
500 * happens when the VM is executing in real mode (which gives 100% CPU
501 * load and slows down the load process that happens on the main GUI
502 * thread to several seconds). */
503 PlaySound(NULL, NULL, 0);
504#endif /* VBOX_WS_WIN */
505
506#ifdef VBOX_WS_NIX
507 /* Make all widget native.
508 * We did it to avoid various Qt crashes while testing widget attributes or acquiring winIds.
509 * Yes, we aware of note that alien widgets faster to draw but the only widget we need to be fast
510 * is viewport of VM which was always native since we are using his id for 3D service needs. */
511 a.setAttribute(Qt::AA_NativeWindows);
512
513# ifdef Q_OS_SOLARIS
514 a.setStyle("fusion");
515# endif /* Q_OS_SOLARIS */
516
517# ifndef Q_OS_SOLARIS
518 /* Apply font fixes (after QApplication get created and instantiated font-family): */
519 QFontDatabase fontDataBase;
520 QString currentFamily(QApplication::font().family());
521 bool isCurrentScaleable = fontDataBase.isScalable(currentFamily);
522 QString subFamily(QFont::substitute(currentFamily));
523 bool isSubScaleable = fontDataBase.isScalable(subFamily);
524 if (isCurrentScaleable && !isSubScaleable)
525 QFont::removeSubstitutions(currentFamily);
526# endif /* !Q_OS_SOLARIS */
527
528 /* Qt version check (major.minor are sensitive, fix number is ignored): */
529 if (UIVersionInfo::qtRTVersion() < (UIVersionInfo::qtCTVersion() & 0xFFFF00))
530 {
531 QString strMsg = QApplication::tr("Executable <b>%1</b> requires Qt %2.x, found Qt %3.")
532 .arg(qAppName())
533 .arg(UIVersionInfo::qtCTVersionString().section('.', 0, 1))
534 .arg(UIVersionInfo::qtRTVersionString());
535 QMessageBox::critical(0, QApplication::tr("Incompatible Qt Library Error"),
536 strMsg, QMessageBox::Abort, QMessageBox::NoButton);
537 qFatal("%s", strMsg.toUtf8().constData());
538 break;
539 }
540#endif /* VBOX_WS_NIX */
541
542 /* Create modal-window manager: */
543 UIModalWindowManager::create();
544
545#ifndef VBOX_RUNTIME_UI
546 /* Create global app instance for Selector UI: */
547 UICommon::create(UIType_ManagerUI);
548#else
549 /* Create global app instance for Runtime UI: */
550 UICommon::create(UIType_RuntimeUI);
551#endif
552
553 /* Simulate try-catch block: */
554 do
555 {
556 /* Exit if UICommon is not valid: */
557 if (!uiCommon().isValid())
558 break;
559 /* Exit if UICommon pre-processed arguments: */
560 if (uiCommon().processArgs())
561 break;
562
563 // WORKAROUND:
564 // Initially we wanted to make that workaround for Runtime UI only,
565 // because only there we had a strict handling for proper application quit
566 // procedure. But it appeared on X11 (as usually due to an async nature) there
567 // can happen situations that Qt application is checking whether at least one
568 // window is already shown and if not - exits prematurely _before_ it is actually
569 // shown. That can happen for example if window is not yet shown because blocked
570 // by startup error message-box which is not treated as real window by some
571 // reason. So we are making application exit manual everywhere.
572 a.setQuitOnLastWindowClosed(false);
573
574 /* Create UI starter: */
575 UIStarter uiStarter;
576 /* Request to Start UI _after_ QApplication executed: */
577 QMetaObject::invokeMethod(&uiStarter, "sltStartUI", Qt::QueuedConnection);
578
579 /* Start application: */
580 iResultCode = a.exec();
581 }
582 while (0);
583
584 /* Destroy global app instance: */
585 UICommon::destroy();
586
587 /* Destroy modal-window manager: */
588 UIModalWindowManager::destroy();
589 }
590 while (0);
591
592 /* Finish logging: */
593 LogFlowFunc(("rc=%d\n", iResultCode));
594 LogFlowFuncLeave();
595
596 /* Return result: */
597 return iResultCode;
598}
599
600#if !defined(VBOX_WITH_HARDENING) || !defined(VBOX_RUNTIME_UI)
601
602# if defined(RT_OS_DARWIN) && defined(VBOX_RUNTIME_UI)
603
604extern "C" const char *_dyld_get_image_name(uint32_t);
605
606/** Init runtime with the executable path pointing into the
607 * VirtualBox.app/Contents/MacOS/ rather than
608 * VirtualBox.app/Contents/Resource/VirtualBoxVM.app/Contents/MacOS/.
609 *
610 * This is a HACK to make codesign and friends happy on OS X. The idea is to
611 * improve and eliminate this over time.
612 */
613DECL_NO_INLINE(static, int) initIprtForDarwinHelperApp(int cArgs, char ***ppapszArgs, uint32_t fFlags)
614{
615 const char *pszImageName = _dyld_get_image_name(0);
616 AssertReturn(pszImageName, VERR_INTERNAL_ERROR);
617
618 char szTmpPath[PATH_MAX + 1];
619 const char *psz = realpath(pszImageName, szTmpPath);
620 int rc;
621 if (psz)
622 {
623 char *pszFilename = RTPathFilename(szTmpPath);
624 if (pszFilename)
625 {
626 char const chSavedFilename0 = *pszFilename;
627 *pszFilename = '\0';
628 RTPathStripTrailingSlash(szTmpPath); /* VirtualBox.app/Contents/Resources/VirtualBoxVM.app/Contents/MacOS */
629 RTPathStripFilename(szTmpPath); /* VirtualBox.app/Contents/Resources/VirtualBoxVM.app/Contents/ */
630 RTPathStripFilename(szTmpPath); /* VirtualBox.app/Contents/Resources/VirtualBoxVM.app */
631 RTPathStripFilename(szTmpPath); /* VirtualBox.app/Contents/Resources */
632 RTPathStripFilename(szTmpPath); /* VirtualBox.app/Contents */
633 char *pszDst = strchr(szTmpPath, '\0');
634 pszDst = (char *)memcpy(pszDst, RT_STR_TUPLE("/MacOS/")) + sizeof("/MacOS/") - 1; /** @todo where is mempcpy? */
635 *pszFilename = chSavedFilename0;
636 memmove(pszDst, pszFilename, strlen(pszFilename) + 1);
637
638 return RTR3InitEx(RTR3INIT_VER_CUR, fFlags, cArgs, ppapszArgs, szTmpPath);
639 }
640 rc = VERR_INVALID_NAME;
641 }
642 else
643 rc = RTErrConvertFromErrno(errno);
644 AssertMsgRCReturn(rc, ("rc=%Rrc pszLink=\"%s\"\nhex: %.*Rhxs\n", rc, pszImageName, strlen(pszImageName), pszImageName), rc);
645 return rc;
646}
647# endif
648
649
650int main(int argc, char **argv, char **envp)
651{
652# ifdef VBOX_WS_NIX
653 /* Make sure multi-threaded environment is safe: */
654 if (!MakeSureMultiThreadingIsSafe())
655 return 1;
656# endif /* VBOX_WS_NIX */
657
658 /*
659 * Determine the IPRT/SUPLib initialization flags if runtime UI process.
660 * Only initialize SUPLib if about to start a VM in this process.
661 *
662 * Note! This must must match the corresponding parsing in hardenedmain.cpp
663 * and UICommon.cpp exactly, otherwise there will be weird error messages.
664 */
665 /** @todo r=bird: We should consider just postponing this stuff till VM
666 * creation, it shouldn't make too much of a difference GIP-wise. */
667 uint32_t fFlags = 0;
668# ifdef VBOX_RUNTIME_UI
669 unsigned cOptionsLeft = 4;
670 bool fStartVM = false;
671 bool fSeparateProcess = false;
672 bool fExecuteAllInIem = false;
673 bool fDriverless = false;
674 for (int i = 1; i < argc && cOptionsLeft > 0; ++i)
675 {
676 if ( !strcmp(argv[i], "--startvm")
677 || !strcmp(argv[i], "-startvm"))
678 {
679 cOptionsLeft -= fStartVM == false;
680 fStartVM = true;
681 i++;
682 }
683 else if ( !strcmp(argv[i], "--separate")
684 || !strcmp(argv[i], "-separate"))
685 {
686 cOptionsLeft -= fSeparateProcess == false;
687 fSeparateProcess = true;
688 }
689 else if (!strcmp(argv[i], "--execute-all-in-iem"))
690 {
691 cOptionsLeft -= fExecuteAllInIem == false;
692 fExecuteAllInIem = true;
693 }
694 else if (!strcmp(argv[i], "--driverless"))
695 {
696 cOptionsLeft -= fDriverless == false;
697 fDriverless = true;
698 }
699 }
700 if (fStartVM && !fSeparateProcess)
701 {
702 fFlags |= RTR3INIT_FLAGS_TRY_SUPLIB;
703 if (fExecuteAllInIem)
704 fFlags |= SUPR3INIT_F_DRIVERLESS_IEM_ALLOWED << RTR3INIT_FLAGS_SUPLIB_SHIFT;
705 if (fDriverless)
706 fFlags |= SUPR3INIT_F_DRIVERLESS << RTR3INIT_FLAGS_SUPLIB_SHIFT;
707 }
708# endif /* VBOX_RUNTIME_UI */
709
710 /* Initialize VBox Runtime: */
711# if defined(RT_OS_DARWIN) && defined(VBOX_RUNTIME_UI)
712 int rc = initIprtForDarwinHelperApp(argc, &argv, fFlags);
713# else
714 int rc = RTR3InitExe(argc, &argv, fFlags);
715# endif
716 /* Initialization failed: */
717 if (RT_FAILURE(rc))
718 {
719 /* We have to create QApplication anyway
720 * just to show the only one error-message: */
721 QApplication a(argc, &argv[0]);
722 Q_UNUSED(a);
723
724# ifdef Q_OS_SOLARIS
725 a.setStyle("fusion");
726# endif
727
728 /* Prepare the error-message: */
729 QString strTitle = QApplication::tr("VirtualBox - Runtime Error");
730 QString strText = "<html>";
731 switch (rc)
732 {
733 case VERR_VM_DRIVER_NOT_INSTALLED:
734 case VERR_VM_DRIVER_LOAD_ERROR:
735 strText += QApplication::tr("<b>Cannot access the kernel driver!</b><br/><br/>");
736# ifdef RT_OS_LINUX
737 strText += g_QStrHintLinuxNoDriver;
738# else
739 strText += g_QStrHintOtherNoDriver;
740# endif
741 break;
742# ifdef RT_OS_LINUX
743 case VERR_NO_MEMORY:
744 strText += g_QStrHintLinuxNoMemory;
745 break;
746# endif
747 case VERR_VM_DRIVER_NOT_ACCESSIBLE:
748 strText += QApplication::tr("Kernel driver not accessible");
749 break;
750 case VERR_VM_DRIVER_VERSION_MISMATCH:
751# ifdef RT_OS_LINUX
752 strText += g_QStrHintLinuxWrongDriverVersion;
753# else
754 strText += g_QStrHintOtherWrongDriverVersion;
755# endif
756 break;
757 default:
758 strText += QApplication::tr("Unknown error %2 during initialization of the Runtime").arg(rc);
759 break;
760 }
761 strText += "</html>";
762
763 /* Show the error-message: */
764 QMessageBox::critical(0 /* parent */, strTitle, strText,
765 QMessageBox::Abort /* 1st button */, QMessageBox::NoButton /* 2nd button */);
766
767 /* Default error-result: */
768 return 1;
769 }
770
771 /* Call to actual main function: */
772 return TrustedMain(argc, argv, envp);
773}
774
775#endif /* !VBOX_WITH_HARDENING || !VBOX_RUNTIME_UI */
776
777#ifdef VBOX_WITH_HARDENING
778
779/**
780 * Special entrypoint used by the hardening code when something goes south.
781 *
782 * Display an error dialog to the user.
783 *
784 * @param pszWhere Indicates where the error occured.
785 * @param enmWhat Indicates what init operation was going on at the time.
786 * @param rc The VBox status code corresponding to the error.
787 * @param pszMsgFmt The message format string.
788 * @param va Format arguments.
789 */
790extern "C" DECLEXPORT(void) TrustedError(const char *pszWhere, SUPINITOP enmWhat, int rc, const char *pszMsgFmt, va_list va)
791{
792 char szMsgBuf[_16K];
793
794 /*
795 * We have to create QApplication anyway just to show the only one error-message.
796 * This is a bit hackish as we don't have the argument vector handy.
797 */
798 int argc = 0;
799 char *argv[2] = { NULL, NULL };
800 QApplication a(argc, &argv[0]);
801
802 /*
803 * The details starts off a properly formatted rc and where/what, we use
804 * the szMsgBuf for this, thus this have to come before the actual message
805 * formatting.
806 */
807 RTStrPrintf(szMsgBuf, sizeof(szMsgBuf),
808 "<!--EOM-->"
809 "where: %s\n"
810 "what: %d\n"
811 "%Rra\n",
812 pszWhere, enmWhat, rc);
813 QString strDetails = szMsgBuf;
814
815 /*
816 * Format the error message. Take whatever comes after a double new line as
817 * something better off in the details section.
818 */
819 RTStrPrintfV(szMsgBuf, sizeof(szMsgBuf), pszMsgFmt, va);
820
821 char *pszDetails = strstr(szMsgBuf, "\n\n");
822 if (pszDetails)
823 {
824 while (RT_C_IS_SPACE(*pszDetails))
825 *pszDetails++ = '\0';
826 if (*pszDetails)
827 {
828 strDetails += "\n";
829 strDetails += pszDetails;
830 }
831 RTStrStripR(szMsgBuf);
832 }
833
834 QString strText = QApplication::tr("<html><b>%1 (rc=%2)</b><br/><br/>").arg(szMsgBuf).arg(rc);
835 strText.replace(QString("\n"), QString("<br>"));
836
837 /*
838 * Append possibly helpful hints to the error message.
839 */
840 switch (enmWhat)
841 {
842 case kSupInitOp_Driver:
843# ifdef RT_OS_LINUX
844 strText += g_QStrHintLinuxNoDriver;
845# else /* RT_OS_LINUX */
846 strText += g_QStrHintOtherNoDriver;
847# endif /* !RT_OS_LINUX */
848 break;
849 case kSupInitOp_IPRT:
850 case kSupInitOp_Misc:
851 if (rc == VERR_VM_DRIVER_VERSION_MISMATCH)
852# ifndef RT_OS_LINUX
853 strText += g_QStrHintOtherWrongDriverVersion;
854# else
855 strText += g_QStrHintLinuxWrongDriverVersion;
856 else if (rc == VERR_NO_MEMORY)
857 strText += g_QStrHintLinuxNoMemory;
858# endif
859 else
860 strText += g_QStrHintReinstall;
861 break;
862 case kSupInitOp_Integrity:
863 case kSupInitOp_RootCheck:
864 strText += g_QStrHintReinstall;
865 break;
866 default:
867 /* no hints here */
868 break;
869 }
870
871# ifdef VBOX_WS_NIX
872 /* We have to to make sure that we display the error-message
873 * after the parent displayed its own message. */
874 sleep(2);
875# endif /* VBOX_WS_NIX */
876
877 /* Update strText with strDetails: */
878 if (!strDetails.isEmpty())
879 strText += QString("<br><br>%1").arg(strDetails);
880
881 /* Close the <html> scope: */
882 strText += "</html>";
883
884 /* Create and show the error message-box: */
885 QMessageBox::critical(0, QApplication::tr("VirtualBox - Error In %1").arg(pszWhere), strText);
886
887 qFatal("%s", strText.toUtf8().constData());
888}
889
890#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