VirtualBox

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

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

FE/Qt: Yet another build fix for r163701; s.a. r163702.

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

© 2023 Oracle
ContactPrivacy policyTerms of Use