VirtualBox

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

Last change on this file was 107100, checked in by vboxsync, 3 months ago

FE/Qt,VBoxManage,VBoxHeadless: Refuse to run in WoW64 to prevent mixing up amd64 and arm64 builds in the out directory. jiraref:VBP-1466

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