VirtualBox

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

Last change on this file was 106061, checked in by vboxsync, 3 weeks ago

Copyright year updates by scm.

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