VirtualBox

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

Last change on this file since 103551 was 103551, checked in by vboxsync, 8 months ago

FE/Qt: Moving UIType from UICommon to UIDefs for reuse purposes.

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