VirtualBox

source: vbox/trunk/src/VBox/Main/src-client/ConsoleImpl2.cpp@ 48968

Last change on this file since 48968 was 48915, checked in by vboxsync, 11 years ago

Always set the HVP bit, seems 10.6.8 requires it.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 217.8 KB
Line 
1/* $Id: ConsoleImpl2.cpp 48915 2013-10-07 11:44:24Z vboxsync $ */
2/** @file
3 * VBox Console COM Class implementation - VM Configuration Bits.
4 *
5 * @remark We've split out the code that the 64-bit VC++ v8 compiler finds
6 * problematic to optimize so we can disable optimizations and later,
7 * perhaps, find a real solution for it (like rewriting the code and
8 * to stop resemble a tonne of spaghetti).
9 */
10
11/*
12 * Copyright (C) 2006-2013 Oracle Corporation
13 *
14 * This file is part of VirtualBox Open Source Edition (OSE), as
15 * available from http://www.virtualbox.org. This file is free software;
16 * you can redistribute it and/or modify it under the terms of the GNU
17 * General Public License (GPL) as published by the Free Software
18 * Foundation, in version 2 as it comes in the "COPYING" file of the
19 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
20 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
21 */
22
23/*******************************************************************************
24* Header Files *
25*******************************************************************************/
26// for some reason Windows burns in sdk\...\winsock.h if this isn't included first
27#include "VBox/com/ptr.h"
28
29#include "ConsoleImpl.h"
30#include "DisplayImpl.h"
31#ifdef VBOX_WITH_GUEST_CONTROL
32# include "GuestImpl.h"
33#endif
34#ifdef VBOX_WITH_DRAG_AND_DROP
35# include "GuestDnDImpl.h"
36#endif
37#include "VMMDev.h"
38#include "Global.h"
39#ifdef VBOX_WITH_PCI_PASSTHROUGH
40# include "PCIRawDevImpl.h"
41#endif
42
43// generated header
44#include "SchemaDefs.h"
45
46#include "AutoCaller.h"
47#include "Logging.h"
48
49#include <iprt/base64.h>
50#include <iprt/buildconfig.h>
51#include <iprt/ctype.h>
52#include <iprt/dir.h>
53#include <iprt/file.h>
54#include <iprt/param.h>
55#include <iprt/path.h>
56#include <iprt/string.h>
57#include <iprt/system.h>
58#include <iprt/cpp/exception.h>
59#if 0 /* enable to play with lots of memory. */
60# include <iprt/env.h>
61#endif
62#include <iprt/stream.h>
63
64#include <VBox/vmm/vmapi.h>
65#include <VBox/err.h>
66#include <VBox/param.h>
67#include <VBox/vmm/pdmapi.h> /* For PDMR3DriverAttach/PDMR3DriverDetach */
68#include <VBox/version.h>
69#include <VBox/HostServices/VBoxClipboardSvc.h>
70#ifdef VBOX_WITH_CROGL
71# include <VBox/HostServices/VBoxCrOpenGLSvc.h>
72#include <VBox/VBoxOGLTest.h>
73#endif
74#ifdef VBOX_WITH_GUEST_PROPS
75# include <VBox/HostServices/GuestPropertySvc.h>
76# include <VBox/com/defs.h>
77# include <VBox/com/array.h>
78# include "HGCM.h" /** @todo it should be possible to register a service
79 * extension using a VMMDev callback. */
80# include <vector>
81#endif /* VBOX_WITH_GUEST_PROPS */
82#include <VBox/intnet.h>
83
84#include <VBox/com/com.h>
85#include <VBox/com/string.h>
86#include <VBox/com/array.h>
87
88#ifdef VBOX_WITH_NETFLT
89# if defined(RT_OS_SOLARIS)
90# include <zone.h>
91# elif defined(RT_OS_LINUX)
92# include <unistd.h>
93# include <sys/ioctl.h>
94# include <sys/socket.h>
95# include <linux/types.h>
96# include <linux/if.h>
97# include <linux/wireless.h>
98# elif defined(RT_OS_FREEBSD)
99# include <unistd.h>
100# include <sys/types.h>
101# include <sys/ioctl.h>
102# include <sys/socket.h>
103# include <net/if.h>
104# include <net80211/ieee80211_ioctl.h>
105# endif
106# if defined(RT_OS_WINDOWS)
107# include <VBox/VBoxNetCfg-win.h>
108# include <Ntddndis.h>
109# include <devguid.h>
110# else
111# include <HostNetworkInterfaceImpl.h>
112# include <netif.h>
113# include <stdlib.h>
114# endif
115#endif /* VBOX_WITH_NETFLT */
116
117#include "NetworkServiceRunner.h"
118#include "BusAssignmentManager.h"
119#ifdef VBOX_WITH_EXTPACK
120# include "ExtPackManagerImpl.h"
121#endif
122#if defined(RT_OS_DARWIN)
123# include "IOKit/IOKitLib.h"
124#endif
125
126
127/*******************************************************************************
128* Internal Functions *
129*******************************************************************************/
130static Utf8Str *GetExtraDataBoth(IVirtualBox *pVirtualBox, IMachine *pMachine, const char *pszName, Utf8Str *pStrValue);
131
132
133
134#if defined(RT_OS_DARWIN)
135
136static int DarwinSmcKey(char *pabKey, uint32_t cbKey)
137{
138 /*
139 * Method as described in Amit Singh's article:
140 * http://osxbook.com/book/bonus/chapter7/tpmdrmmyth/
141 */
142 typedef struct
143 {
144 uint32_t key;
145 uint8_t pad0[22];
146 uint32_t datasize;
147 uint8_t pad1[10];
148 uint8_t cmd;
149 uint32_t pad2;
150 uint8_t data[32];
151 } AppleSMCBuffer;
152
153 AssertReturn(cbKey >= 65, VERR_INTERNAL_ERROR);
154
155 io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault,
156 IOServiceMatching("AppleSMC"));
157 if (!service)
158 return VERR_NOT_FOUND;
159
160 io_connect_t port = (io_connect_t)0;
161 kern_return_t kr = IOServiceOpen(service, mach_task_self(), 0, &port);
162 IOObjectRelease(service);
163
164 if (kr != kIOReturnSuccess)
165 return RTErrConvertFromDarwin(kr);
166
167 AppleSMCBuffer inputStruct = { 0, {0}, 32, {0}, 5, };
168 AppleSMCBuffer outputStruct;
169 size_t cbOutputStruct = sizeof(outputStruct);
170
171 for (int i = 0; i < 2; i++)
172 {
173 inputStruct.key = (uint32_t)(i == 0 ? 'OSK0' : 'OSK1');
174 kr = IOConnectCallStructMethod((mach_port_t)port,
175 (uint32_t)2,
176 (const void *)&inputStruct,
177 sizeof(inputStruct),
178 (void *)&outputStruct,
179 &cbOutputStruct);
180 if (kr != kIOReturnSuccess)
181 {
182 IOServiceClose(port);
183 return RTErrConvertFromDarwin(kr);
184 }
185
186 for (int j = 0; j < 32; j++)
187 pabKey[j + i*32] = outputStruct.data[j];
188 }
189
190 IOServiceClose(port);
191
192 pabKey[64] = 0;
193
194 return VINF_SUCCESS;
195}
196
197#endif /* RT_OS_DARWIN */
198
199/* Darwin compile kludge */
200#undef PVM
201
202/* Comment out the following line to remove VMWare compatibility hack. */
203#define VMWARE_NET_IN_SLOT_11
204
205/**
206 * Translate IDE StorageControllerType_T to string representation.
207 */
208const char* controllerString(StorageControllerType_T enmType)
209{
210 switch (enmType)
211 {
212 case StorageControllerType_PIIX3:
213 return "PIIX3";
214 case StorageControllerType_PIIX4:
215 return "PIIX4";
216 case StorageControllerType_ICH6:
217 return "ICH6";
218 default:
219 return "Unknown";
220 }
221}
222
223/**
224 * Simple class for storing network boot information.
225 */
226struct BootNic
227{
228 ULONG mInstance;
229 PCIBusAddress mPCIAddress;
230
231 ULONG mBootPrio;
232 bool operator < (const BootNic &rhs) const
233 {
234 ULONG lval = mBootPrio - 1; /* 0 will wrap around and get the lowest priority. */
235 ULONG rval = rhs.mBootPrio - 1;
236 return lval < rval; /* Zero compares as highest number (lowest prio). */
237 }
238};
239
240static int findEfiRom(IVirtualBox* vbox, FirmwareType_T aFirmwareType, Utf8Str *pEfiRomFile)
241{
242 Bstr aFilePath, empty;
243 BOOL fPresent = FALSE;
244 HRESULT hrc = vbox->CheckFirmwarePresent(aFirmwareType, empty.raw(),
245 empty.asOutParam(), aFilePath.asOutParam(), &fPresent);
246 AssertComRCReturn(hrc, Global::vboxStatusCodeFromCOM(hrc));
247
248 if (!fPresent)
249 {
250 LogRel(("Failed to find an EFI ROM file.\n"));
251 return VERR_FILE_NOT_FOUND;
252 }
253
254 *pEfiRomFile = Utf8Str(aFilePath);
255
256 return VINF_SUCCESS;
257}
258
259/**
260 * @throws HRESULT on extra data retrival error.
261 */
262static int getSmcDeviceKey(IVirtualBox *pVirtualBox, IMachine *pMachine, Utf8Str *pStrKey, bool *pfGetKeyFromRealSMC)
263{
264 *pfGetKeyFromRealSMC = false;
265
266 /*
267 * The extra data takes precedence (if non-zero).
268 */
269 GetExtraDataBoth(pVirtualBox, pMachine, "VBoxInternal2/SmcDeviceKey", pStrKey);
270 if (pStrKey->isNotEmpty())
271 return VINF_SUCCESS;
272
273#ifdef RT_OS_DARWIN
274 /*
275 * Query it here and now.
276 */
277 char abKeyBuf[65];
278 int rc = DarwinSmcKey(abKeyBuf, sizeof(abKeyBuf));
279 if (SUCCEEDED(rc))
280 {
281 *pStrKey = abKeyBuf;
282 *pfGetKeyFromRealSMC = true;
283 return rc;
284 }
285 LogRel(("Warning: DarwinSmcKey failed with rc=%Rrc!\n", rc));
286
287#else
288 /*
289 * Is it apple hardware in bootcamp?
290 */
291 /** @todo implement + test RTSYSDMISTR_MANUFACTURER on all hosts.
292 * Currently falling back on the product name. */
293 char szManufacturer[256];
294 szManufacturer[0] = '\0';
295 RTSystemQueryDmiString(RTSYSDMISTR_MANUFACTURER, szManufacturer, sizeof(szManufacturer));
296 if (szManufacturer[0] != '\0')
297 {
298 if ( !strcmp(szManufacturer, "Apple Computer, Inc.")
299 || !strcmp(szManufacturer, "Apple Inc.")
300 )
301 *pfGetKeyFromRealSMC = true;
302 }
303 else
304 {
305 char szProdName[256];
306 szProdName[0] = '\0';
307 RTSystemQueryDmiString(RTSYSDMISTR_PRODUCT_NAME, szProdName, sizeof(szProdName));
308 if ( ( !strncmp(szProdName, RT_STR_TUPLE("Mac"))
309 || !strncmp(szProdName, RT_STR_TUPLE("iMac"))
310 || !strncmp(szProdName, RT_STR_TUPLE("iMac"))
311 || !strncmp(szProdName, RT_STR_TUPLE("Xserve"))
312 )
313 && !strchr(szProdName, ' ') /* no spaces */
314 && RT_C_IS_DIGIT(szProdName[strlen(szProdName) - 1]) /* version number */
315 )
316 *pfGetKeyFromRealSMC = true;
317 }
318
319 int rc = VINF_SUCCESS;
320#endif
321
322 return rc;
323}
324
325
326/*
327 * VC++ 8 / amd64 has some serious trouble with the next functions.
328 * As a temporary measure, we'll drop global optimizations.
329 */
330#if defined(_MSC_VER) && defined(RT_ARCH_AMD64)
331# pragma optimize("g", off)
332#endif
333
334static const char *const g_apszIDEDrives[4] =
335 { "PrimaryMaster", "PrimarySlave", "SecondaryMaster", "SecondarySlave" };
336
337class ConfigError : public RTCError
338{
339public:
340
341 ConfigError(const char *pcszFunction,
342 int vrc,
343 const char *pcszName)
344 : RTCError(Utf8StrFmt("%s failed: rc=%Rrc, pcszName=%s", pcszFunction, vrc, pcszName)),
345 m_vrc(vrc)
346 {
347 AssertMsgFailed(("%s\n", what())); // in strict mode, hit a breakpoint here
348 }
349
350 int m_vrc;
351};
352
353
354/**
355 * Helper that calls CFGMR3InsertString and throws an RTCError if that
356 * fails (C-string variant).
357 * @param pParent See CFGMR3InsertStringN.
358 * @param pcszNodeName See CFGMR3InsertStringN.
359 * @param pcszValue The string value.
360 */
361static void InsertConfigString(PCFGMNODE pNode,
362 const char *pcszName,
363 const char *pcszValue)
364{
365 int vrc = CFGMR3InsertString(pNode,
366 pcszName,
367 pcszValue);
368 if (RT_FAILURE(vrc))
369 throw ConfigError("CFGMR3InsertString", vrc, pcszName);
370}
371
372/**
373 * Helper that calls CFGMR3InsertString and throws an RTCError if that
374 * fails (Utf8Str variant).
375 * @param pParent See CFGMR3InsertStringN.
376 * @param pcszNodeName See CFGMR3InsertStringN.
377 * @param rStrValue The string value.
378 */
379static void InsertConfigString(PCFGMNODE pNode,
380 const char *pcszName,
381 const Utf8Str &rStrValue)
382{
383 int vrc = CFGMR3InsertStringN(pNode,
384 pcszName,
385 rStrValue.c_str(),
386 rStrValue.length());
387 if (RT_FAILURE(vrc))
388 throw ConfigError("CFGMR3InsertStringLengthKnown", vrc, pcszName);
389}
390
391/**
392 * Helper that calls CFGMR3InsertString and throws an RTCError if that
393 * fails (Bstr variant).
394 *
395 * @param pParent See CFGMR3InsertStringN.
396 * @param pcszNodeName See CFGMR3InsertStringN.
397 * @param rBstrValue The string value.
398 */
399static void InsertConfigString(PCFGMNODE pNode,
400 const char *pcszName,
401 const Bstr &rBstrValue)
402{
403 InsertConfigString(pNode, pcszName, Utf8Str(rBstrValue));
404}
405
406/**
407 * Helper that calls CFGMR3InsertBytes and throws an RTCError if that fails.
408 *
409 * @param pNode See CFGMR3InsertBytes.
410 * @param pcszName See CFGMR3InsertBytes.
411 * @param pvBytes See CFGMR3InsertBytes.
412 * @param cbBytes See CFGMR3InsertBytes.
413 */
414static void InsertConfigBytes(PCFGMNODE pNode,
415 const char *pcszName,
416 const void *pvBytes,
417 size_t cbBytes)
418{
419 int vrc = CFGMR3InsertBytes(pNode,
420 pcszName,
421 pvBytes,
422 cbBytes);
423 if (RT_FAILURE(vrc))
424 throw ConfigError("CFGMR3InsertBytes", vrc, pcszName);
425}
426
427/**
428 * Helper that calls CFGMR3InsertInteger and throws an RTCError if that
429 * fails.
430 *
431 * @param pNode See CFGMR3InsertInteger.
432 * @param pcszName See CFGMR3InsertInteger.
433 * @param u64Integer See CFGMR3InsertInteger.
434 */
435static void InsertConfigInteger(PCFGMNODE pNode,
436 const char *pcszName,
437 uint64_t u64Integer)
438{
439 int vrc = CFGMR3InsertInteger(pNode,
440 pcszName,
441 u64Integer);
442 if (RT_FAILURE(vrc))
443 throw ConfigError("CFGMR3InsertInteger", vrc, pcszName);
444}
445
446/**
447 * Helper that calls CFGMR3InsertNode and throws an RTCError if that fails.
448 *
449 * @param pNode See CFGMR3InsertNode.
450 * @param pcszName See CFGMR3InsertNode.
451 * @param ppChild See CFGMR3InsertNode.
452 */
453static void InsertConfigNode(PCFGMNODE pNode,
454 const char *pcszName,
455 PCFGMNODE *ppChild)
456{
457 int vrc = CFGMR3InsertNode(pNode, pcszName, ppChild);
458 if (RT_FAILURE(vrc))
459 throw ConfigError("CFGMR3InsertNode", vrc, pcszName);
460}
461
462/**
463 * Helper that calls CFGMR3RemoveValue and throws an RTCError if that fails.
464 *
465 * @param pNode See CFGMR3RemoveValue.
466 * @param pcszName See CFGMR3RemoveValue.
467 */
468static void RemoveConfigValue(PCFGMNODE pNode,
469 const char *pcszName)
470{
471 int vrc = CFGMR3RemoveValue(pNode, pcszName);
472 if (RT_FAILURE(vrc))
473 throw ConfigError("CFGMR3RemoveValue", vrc, pcszName);
474}
475
476/**
477 * Gets an extra data value, consulting both machine and global extra data.
478 *
479 * @throws HRESULT on failure
480 * @returns pStrValue for the callers convenience.
481 * @param pVirtualBox Pointer to the IVirtualBox interface.
482 * @param pMachine Pointer to the IMachine interface.
483 * @param pszName The value to get.
484 * @param pStrValue Where to return it's value (empty string if not
485 * found).
486 */
487static Utf8Str *GetExtraDataBoth(IVirtualBox *pVirtualBox, IMachine *pMachine, const char *pszName, Utf8Str *pStrValue)
488{
489 pStrValue->setNull();
490
491 Bstr bstrName(pszName);
492 Bstr bstrValue;
493 HRESULT hrc = pMachine->GetExtraData(bstrName.raw(), bstrValue.asOutParam());
494 if (FAILED(hrc))
495 throw hrc;
496 if (bstrValue.isEmpty())
497 {
498 hrc = pVirtualBox->GetExtraData(bstrName.raw(), bstrValue.asOutParam());
499 if (FAILED(hrc))
500 throw hrc;
501 }
502
503 if (bstrValue.isNotEmpty())
504 *pStrValue = bstrValue;
505 return pStrValue;
506}
507
508
509/** Helper that finds out the next SATA port used
510 */
511static LONG GetNextUsedSataPort(LONG aSataPortUsed[30], LONG lBaseVal, uint32_t u32Size)
512{
513 LONG lNextPortUsed = 30;
514 for (size_t j = 0; j < u32Size; ++j)
515 {
516 if ( aSataPortUsed[j] > lBaseVal
517 && aSataPortUsed[j] <= lNextPortUsed)
518 lNextPortUsed = aSataPortUsed[j];
519 }
520 return lNextPortUsed;
521}
522
523#ifdef VBOX_WITH_PCI_PASSTHROUGH
524HRESULT Console::attachRawPCIDevices(PUVM pUVM, BusAssignmentManager *pBusMgr, PCFGMNODE pDevices)
525{
526 HRESULT hrc = S_OK;
527 PCFGMNODE pInst, pCfg, pLunL0, pLunL1;
528
529 SafeIfaceArray<IPCIDeviceAttachment> assignments;
530 ComPtr<IMachine> aMachine = machine();
531
532 hrc = aMachine->COMGETTER(PCIDeviceAssignments)(ComSafeArrayAsOutParam(assignments));
533 if ( hrc != S_OK
534 || assignments.size() < 1)
535 return hrc;
536
537 /*
538 * PCI passthrough is only available if the proper ExtPack is installed.
539 *
540 * Note. Configuring PCI passthrough here and providing messages about
541 * the missing extpack isn't exactly clean, but it is a necessary evil
542 * to patch over legacy compatability issues introduced by the new
543 * distribution model.
544 */
545# ifdef VBOX_WITH_EXTPACK
546 static const char *s_pszPCIRawExtPackName = "Oracle VM VirtualBox Extension Pack";
547 if (!mptrExtPackManager->isExtPackUsable(s_pszPCIRawExtPackName))
548 /* Always fatal! */
549 return VMR3SetError(pUVM, VERR_NOT_FOUND, RT_SRC_POS,
550 N_("Implementation of the PCI passthrough framework not found!\n"
551 "The VM cannot be started. To fix this problem, either "
552 "install the '%s' or disable PCI passthrough via VBoxManage"),
553 s_pszPCIRawExtPackName);
554# endif
555
556 PCFGMNODE pBridges = CFGMR3GetChild(pDevices, "ich9pcibridge");
557 Assert(pBridges);
558
559 /* Find required bridges, and add missing ones */
560 for (size_t iDev = 0; iDev < assignments.size(); iDev++)
561 {
562 ComPtr<IPCIDeviceAttachment> assignment = assignments[iDev];
563 LONG guest = 0;
564 PCIBusAddress GuestPCIAddress;
565
566 assignment->COMGETTER(GuestAddress)(&guest);
567 GuestPCIAddress.fromLong(guest);
568 Assert(GuestPCIAddress.valid());
569
570 if (GuestPCIAddress.miBus > 0)
571 {
572 int iBridgesMissed = 0;
573 int iBase = GuestPCIAddress.miBus - 1;
574
575 while (!pBusMgr->hasPCIDevice("ich9pcibridge", iBase) && iBase > 0)
576 {
577 iBridgesMissed++; iBase--;
578 }
579 iBase++;
580
581 for (int iBridge = 0; iBridge < iBridgesMissed; iBridge++)
582 {
583 InsertConfigNode(pBridges, Utf8StrFmt("%d", iBase + iBridge).c_str(), &pInst);
584 InsertConfigInteger(pInst, "Trusted", 1);
585 hrc = pBusMgr->assignPCIDevice("ich9pcibridge", pInst);
586 }
587 }
588 }
589
590 /* Now actually add devices */
591 PCFGMNODE pPCIDevs = NULL;
592
593 if (assignments.size() > 0)
594 {
595 InsertConfigNode(pDevices, "pciraw", &pPCIDevs);
596
597 PCFGMNODE pRoot = CFGMR3GetParent(pDevices); Assert(pRoot);
598
599 /* Tell PGM to tell GPCIRaw about guest mappings. */
600 CFGMR3InsertNode(pRoot, "PGM", NULL);
601 InsertConfigInteger(CFGMR3GetChild(pRoot, "PGM"), "PciPassThrough", 1);
602
603 /*
604 * Currently, using IOMMU needed for PCI passthrough
605 * requires RAM preallocation.
606 */
607 /** @todo: check if we can lift this requirement */
608 CFGMR3RemoveValue(pRoot, "RamPreAlloc");
609 InsertConfigInteger(pRoot, "RamPreAlloc", 1);
610 }
611
612 for (size_t iDev = 0; iDev < assignments.size(); iDev++)
613 {
614 PCIBusAddress HostPCIAddress, GuestPCIAddress;
615 ComPtr<IPCIDeviceAttachment> assignment = assignments[iDev];
616 LONG host, guest;
617 Bstr aDevName;
618
619 assignment->COMGETTER(HostAddress)(&host);
620 assignment->COMGETTER(GuestAddress)(&guest);
621 assignment->COMGETTER(Name)(aDevName.asOutParam());
622
623 InsertConfigNode(pPCIDevs, Utf8StrFmt("%d", iDev).c_str(), &pInst);
624 InsertConfigInteger(pInst, "Trusted", 1);
625
626 HostPCIAddress.fromLong(host);
627 Assert(HostPCIAddress.valid());
628 InsertConfigNode(pInst, "Config", &pCfg);
629 InsertConfigString(pCfg, "DeviceName", aDevName);
630
631 InsertConfigInteger(pCfg, "DetachHostDriver", 1);
632 InsertConfigInteger(pCfg, "HostPCIBusNo", HostPCIAddress.miBus);
633 InsertConfigInteger(pCfg, "HostPCIDeviceNo", HostPCIAddress.miDevice);
634 InsertConfigInteger(pCfg, "HostPCIFunctionNo", HostPCIAddress.miFn);
635
636 GuestPCIAddress.fromLong(guest);
637 Assert(GuestPCIAddress.valid());
638 hrc = pBusMgr->assignHostPCIDevice("pciraw", pInst, HostPCIAddress, GuestPCIAddress, true);
639 if (hrc != S_OK)
640 return hrc;
641
642 InsertConfigInteger(pCfg, "GuestPCIBusNo", GuestPCIAddress.miBus);
643 InsertConfigInteger(pCfg, "GuestPCIDeviceNo", GuestPCIAddress.miDevice);
644 InsertConfigInteger(pCfg, "GuestPCIFunctionNo", GuestPCIAddress.miFn);
645
646 /* the driver */
647 InsertConfigNode(pInst, "LUN#0", &pLunL0);
648 InsertConfigString(pLunL0, "Driver", "pciraw");
649 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
650
651 /* the Main driver */
652 InsertConfigString(pLunL1, "Driver", "MainPciRaw");
653 InsertConfigNode(pLunL1, "Config", &pCfg);
654 PCIRawDev* pMainDev = new PCIRawDev(this);
655 InsertConfigInteger(pCfg, "Object", (uintptr_t)pMainDev);
656 }
657
658 return hrc;
659}
660#endif
661
662
663void Console::attachStatusDriver(PCFGMNODE pCtlInst, PPDMLED *papLeds,
664 uint64_t uFirst, uint64_t uLast,
665 Console::MediumAttachmentMap *pmapMediumAttachments,
666 const char *pcszDevice, unsigned uInstance)
667{
668 PCFGMNODE pLunL0, pCfg;
669 InsertConfigNode(pCtlInst, "LUN#999", &pLunL0);
670 InsertConfigString(pLunL0, "Driver", "MainStatus");
671 InsertConfigNode(pLunL0, "Config", &pCfg);
672 InsertConfigInteger(pCfg, "papLeds", (uintptr_t)papLeds);
673 if (pmapMediumAttachments)
674 {
675 InsertConfigInteger(pCfg, "pmapMediumAttachments", (uintptr_t)pmapMediumAttachments);
676 InsertConfigInteger(pCfg, "pConsole", (uintptr_t)this);
677 AssertPtr(pcszDevice);
678 Utf8Str deviceInstance = Utf8StrFmt("%s/%u", pcszDevice, uInstance);
679 InsertConfigString(pCfg, "DeviceInstance", deviceInstance.c_str());
680 }
681 InsertConfigInteger(pCfg, "First", uFirst);
682 InsertConfigInteger(pCfg, "Last", uLast);
683}
684
685
686/**
687 * Construct the VM configuration tree (CFGM).
688 *
689 * This is a callback for VMR3Create() call. It is called from CFGMR3Init()
690 * in the emulation thread (EMT). Any per thread COM/XPCOM initialization
691 * is done here.
692 *
693 * @param pUVM The user mode VM handle.
694 * @param pVM The cross context VM handle.
695 * @param pvConsole Pointer to the VMPowerUpTask object.
696 * @return VBox status code.
697 *
698 * @note Locks the Console object for writing.
699 */
700DECLCALLBACK(int) Console::configConstructor(PUVM pUVM, PVM pVM, void *pvConsole)
701{
702 LogFlowFuncEnter();
703
704 AssertReturn(pvConsole, VERR_GENERAL_FAILURE);
705 ComObjPtr<Console> pConsole = static_cast<Console *>(pvConsole);
706
707 AutoCaller autoCaller(pConsole);
708 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
709
710 /* lock the console because we widely use internal fields and methods */
711 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
712
713 /*
714 * Set the VM handle and do the rest of the job in an worker method so we
715 * can easily reset the VM handle on failure.
716 */
717 pConsole->mpUVM = pUVM;
718 VMR3RetainUVM(pUVM);
719 int vrc;
720 try
721 {
722 vrc = pConsole->configConstructorInner(pUVM, pVM, &alock);
723 }
724 catch (...)
725 {
726 vrc = VERR_UNEXPECTED_EXCEPTION;
727 }
728 if (RT_FAILURE(vrc))
729 {
730 pConsole->mpUVM = NULL;
731 VMR3ReleaseUVM(pUVM);
732 }
733
734 return vrc;
735}
736
737
738/**
739 * Worker for configConstructor.
740 *
741 * @return VBox status code.
742 * @param pUVM The user mode VM handle.
743 * @param pVM The cross context VM handle.
744 * @param pAlock The automatic lock instance. This is for when we have
745 * to leave it in order to avoid deadlocks (ext packs and
746 * more).
747 */
748int Console::configConstructorInner(PUVM pUVM, PVM pVM, AutoWriteLock *pAlock)
749{
750 VMMDev *pVMMDev = m_pVMMDev; Assert(pVMMDev);
751 ComPtr<IMachine> pMachine = machine();
752
753 int rc;
754 HRESULT hrc;
755 Utf8Str strTmp;
756 Bstr bstr;
757
758#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
759
760 /*
761 * Get necessary objects and frequently used parameters.
762 */
763 ComPtr<IVirtualBox> virtualBox;
764 hrc = pMachine->COMGETTER(Parent)(virtualBox.asOutParam()); H();
765
766 ComPtr<IHost> host;
767 hrc = virtualBox->COMGETTER(Host)(host.asOutParam()); H();
768
769 ComPtr<ISystemProperties> systemProperties;
770 hrc = virtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam()); H();
771
772 ComPtr<IBIOSSettings> biosSettings;
773 hrc = pMachine->COMGETTER(BIOSSettings)(biosSettings.asOutParam()); H();
774
775 hrc = pMachine->COMGETTER(HardwareUUID)(bstr.asOutParam()); H();
776 RTUUID HardwareUuid;
777 rc = RTUuidFromUtf16(&HardwareUuid, bstr.raw());
778 AssertRCReturn(rc, rc);
779
780 ULONG cRamMBs;
781 hrc = pMachine->COMGETTER(MemorySize)(&cRamMBs); H();
782#if 0 /* enable to play with lots of memory. */
783 if (RTEnvExist("VBOX_RAM_SIZE"))
784 cRamMBs = RTStrToUInt64(RTEnvGet("VBOX_RAM_SIZE"));
785#endif
786 uint64_t const cbRam = cRamMBs * (uint64_t)_1M;
787 uint32_t cbRamHole = MM_RAM_HOLE_SIZE_DEFAULT;
788 uint64_t uMcfgBase = 0;
789 uint32_t cbMcfgLength = 0;
790
791 ChipsetType_T chipsetType;
792 hrc = pMachine->COMGETTER(ChipsetType)(&chipsetType); H();
793 if (chipsetType == ChipsetType_ICH9)
794 {
795 /* We'd better have 0x10000000 region, to cover 256 buses
796 but this put too much load on hypervisor heap */
797 cbMcfgLength = 0x4000000; //0x10000000;
798 cbRamHole += cbMcfgLength;
799 uMcfgBase = _4G - cbRamHole;
800 }
801
802 BusAssignmentManager *pBusMgr = mBusMgr = BusAssignmentManager::createInstance(chipsetType);
803
804 ULONG cCpus = 1;
805 hrc = pMachine->COMGETTER(CPUCount)(&cCpus); H();
806
807 ULONG ulCpuExecutionCap = 100;
808 hrc = pMachine->COMGETTER(CPUExecutionCap)(&ulCpuExecutionCap); H();
809
810 Bstr osTypeId;
811 hrc = pMachine->COMGETTER(OSTypeId)(osTypeId.asOutParam()); H();
812 LogRel(("Guest OS type: '%s'\n", Utf8Str(osTypeId).c_str()));
813
814 BOOL fIOAPIC;
815 hrc = biosSettings->COMGETTER(IOAPICEnabled)(&fIOAPIC); H();
816
817 ComPtr<IGuestOSType> guestOSType;
818 hrc = virtualBox->GetGuestOSType(osTypeId.raw(), guestOSType.asOutParam()); H();
819
820 Bstr guestTypeFamilyId;
821 hrc = guestOSType->COMGETTER(FamilyId)(guestTypeFamilyId.asOutParam()); H();
822 BOOL fOsXGuest = guestTypeFamilyId == Bstr("MacOS");
823
824 ULONG maxNetworkAdapters;
825 hrc = systemProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters); H();
826 /*
827 * Get root node first.
828 * This is the only node in the tree.
829 */
830 PCFGMNODE pRoot = CFGMR3GetRootU(pUVM);
831 Assert(pRoot);
832
833 // InsertConfigString throws
834 try
835 {
836
837 /*
838 * Set the root (and VMM) level values.
839 */
840 hrc = pMachine->COMGETTER(Name)(bstr.asOutParam()); H();
841 InsertConfigString(pRoot, "Name", bstr);
842 InsertConfigBytes(pRoot, "UUID", &HardwareUuid, sizeof(HardwareUuid));
843 InsertConfigInteger(pRoot, "RamSize", cbRam);
844 InsertConfigInteger(pRoot, "RamHoleSize", cbRamHole);
845 InsertConfigInteger(pRoot, "NumCPUs", cCpus);
846 InsertConfigInteger(pRoot, "CpuExecutionCap", ulCpuExecutionCap);
847 InsertConfigInteger(pRoot, "TimerMillies", 10);
848#ifdef VBOX_WITH_RAW_MODE
849 InsertConfigInteger(pRoot, "RawR3Enabled", 1); /* boolean */
850 InsertConfigInteger(pRoot, "RawR0Enabled", 1); /* boolean */
851 /** @todo Config: RawR0, PATMEnabled and CSAMEnabled needs attention later. */
852 InsertConfigInteger(pRoot, "PATMEnabled", 1); /* boolean */
853 InsertConfigInteger(pRoot, "CSAMEnabled", 1); /* boolean */
854#endif
855
856#ifdef VBOX_WITH_RAW_RING1
857 if (osTypeId == "QNX")
858 {
859 /* QNX needs special treatment in raw mode due to its use of ring-1. */
860 InsertConfigInteger(pRoot, "RawR1Enabled", 1); /* boolean */
861 }
862#endif
863
864 /* Not necessary, but to make sure these two settings end up in the release log. */
865 BOOL fPageFusion = FALSE;
866 hrc = pMachine->COMGETTER(PageFusionEnabled)(&fPageFusion); H();
867 InsertConfigInteger(pRoot, "PageFusion", fPageFusion); /* boolean */
868 ULONG ulBalloonSize = 0;
869 hrc = pMachine->COMGETTER(MemoryBalloonSize)(&ulBalloonSize); H();
870 InsertConfigInteger(pRoot, "MemBalloonSize", ulBalloonSize);
871
872 /*
873 * CPUM values.
874 */
875 PCFGMNODE pCPUM;
876 InsertConfigNode(pRoot, "CPUM", &pCPUM);
877
878 /* cpuid leaf overrides. */
879 static uint32_t const s_auCpuIdRanges[] =
880 {
881 UINT32_C(0x00000000), UINT32_C(0x0000000a),
882 UINT32_C(0x80000000), UINT32_C(0x8000000a)
883 };
884 for (unsigned i = 0; i < RT_ELEMENTS(s_auCpuIdRanges); i += 2)
885 for (uint32_t uLeaf = s_auCpuIdRanges[i]; uLeaf < s_auCpuIdRanges[i + 1]; uLeaf++)
886 {
887 ULONG ulEax, ulEbx, ulEcx, ulEdx;
888 hrc = pMachine->GetCPUIDLeaf(uLeaf, &ulEax, &ulEbx, &ulEcx, &ulEdx);
889 if (SUCCEEDED(hrc))
890 {
891 PCFGMNODE pLeaf;
892 InsertConfigNode(pCPUM, Utf8StrFmt("HostCPUID/%RX32", uLeaf).c_str(), &pLeaf);
893
894 InsertConfigInteger(pLeaf, "eax", ulEax);
895 InsertConfigInteger(pLeaf, "ebx", ulEbx);
896 InsertConfigInteger(pLeaf, "ecx", ulEcx);
897 InsertConfigInteger(pLeaf, "edx", ulEdx);
898 }
899 else if (hrc != E_INVALIDARG) H();
900 }
901
902 /* We must limit CPUID count for Windows NT 4, as otherwise it stops
903 with error 0x3e (MULTIPROCESSOR_CONFIGURATION_NOT_SUPPORTED). */
904 if (osTypeId == "WindowsNT4")
905 {
906 LogRel(("Limiting CPUID leaf count for NT4 guests\n"));
907 InsertConfigInteger(pCPUM, "NT4LeafLimit", true);
908 }
909
910 /* Expose CMPXCHG16B. Currently a hack. */
911 if ( osTypeId == "Windows81_64"
912 || osTypeId == "Windows2012_64")
913 {
914 LogRel(("Enabling CMPXCHG16B for Windows 8.1 / 2k12 guests\n"));
915 InsertConfigInteger(pCPUM, "CMPXCHG16B", true);
916 }
917
918 /* Expose extended MWAIT features to Mac OS X guests. */
919 if (fOsXGuest)
920 {
921 LogRel(("Using MWAIT extensions\n"));
922 InsertConfigInteger(pCPUM, "MWaitExtensions", true);
923 }
924
925 if (fOsXGuest)
926 {
927 InsertConfigInteger(pCPUM, "EnableHVP", 1);
928
929 /* Fake the CPU family/model so the guest works. This is partly
930 because older mac releases really doesn't work on newer cpus,
931 and partly because mac os x expects more from systems with newer
932 cpus (MSRs, power features, whatever). */
933 uint32_t uMaxIntelFamilyModelStep = UINT32_MAX;
934 if ( osTypeId == "MacOS"
935 || osTypeId == "MacOS_64")
936 uMaxIntelFamilyModelStep = RT_MAKE_U32_FROM_U8(1, 23, 6, 7); /* Penryn / X5482. */
937 else if ( osTypeId == "MacOS106"
938 || osTypeId == "MacOS106_64")
939 uMaxIntelFamilyModelStep = RT_MAKE_U32_FROM_U8(1, 23, 6, 7); /* Penryn / X5482 */
940 else if ( osTypeId == "MacOS107"
941 || osTypeId == "MacOS107_64")
942 uMaxIntelFamilyModelStep = RT_MAKE_U32_FROM_U8(1, 23, 6, 7); /* Penryn / X5482 */ /** @todo figure out what is required here. */
943 else if ( osTypeId == "MacOS108"
944 || osTypeId == "MacOS108_64")
945 uMaxIntelFamilyModelStep = RT_MAKE_U32_FROM_U8(1, 23, 6, 7); /* Penryn / X5482 */ /** @todo figure out what is required here. */
946 else if ( osTypeId == "MacOS109"
947 || osTypeId == "MacOS109_64")
948 uMaxIntelFamilyModelStep = RT_MAKE_U32_FROM_U8(1, 23, 6, 7); /* Penryn / X5482 */ /** @todo figure out what is required here. */
949 if (uMaxIntelFamilyModelStep != UINT32_MAX)
950 InsertConfigInteger(pCPUM, "MaxIntelFamilyModelStep", uMaxIntelFamilyModelStep);
951 }
952
953
954 /* Synthetic CPU */
955 BOOL fSyntheticCpu = false;
956 hrc = pMachine->GetCPUProperty(CPUPropertyType_Synthetic, &fSyntheticCpu); H();
957 InsertConfigInteger(pCPUM, "SyntheticCpu", fSyntheticCpu);
958
959 /* Physical Address Extension (PAE) */
960 BOOL fEnablePAE = false;
961 hrc = pMachine->GetCPUProperty(CPUPropertyType_PAE, &fEnablePAE); H();
962 InsertConfigInteger(pRoot, "EnablePAE", fEnablePAE);
963
964
965 /*
966 * Hardware virtualization extensions.
967 */
968 BOOL fIsGuest64Bit;
969 hrc = pMachine->GetCPUProperty(CPUPropertyType_LongMode, &fIsGuest64Bit); H();
970 BOOL fSupportsLongMode;
971 hrc = host->GetProcessorFeature(ProcessorFeature_LongMode, &fSupportsLongMode); H();
972 if (!fSupportsLongMode && fIsGuest64Bit)
973 {
974 LogRel(("WARNING! 64-bit guest type selected but the host CPU does NOT support 64-bit.\n"));
975 fIsGuest64Bit = FALSE;
976 }
977
978 BOOL fHMEnabled;
979 hrc = pMachine->GetHWVirtExProperty(HWVirtExPropertyType_Enabled, &fHMEnabled); H();
980 if (cCpus > 1 && !fHMEnabled)
981 {
982 LogRel(("Forced fHMEnabled to TRUE by SMP guest.\n"));
983 fHMEnabled = TRUE;
984 }
985 if (!fHMEnabled && fIsGuest64Bit)
986 {
987 LogRel(("WARNING! 64-bit guest type selected on host without hardware virtualization (VT-x or AMD-V).\n"));
988 fIsGuest64Bit = FALSE;
989 }
990
991 BOOL fHMForced;
992#ifdef VBOX_WITH_RAW_MODE
993 /* - With more than 4GB PGM will use different RAMRANGE sizes for raw
994 mode and hv mode to optimize lookup times.
995 - With more than one virtual CPU, raw-mode isn't a fallback option.
996 - With a 64-bit guest, raw-mode isn't a fallback option either. */
997 fHMForced = fHMEnabled
998 && ( cbRam + cbRamHole > _4G
999 || cCpus > 1
1000 || fIsGuest64Bit);
1001# ifdef RT_OS_DARWIN
1002 fHMForced = fHMEnabled;
1003# endif
1004 if (fHMForced)
1005 {
1006 if (cbRam + cbRamHole > _4G)
1007 LogRel(("fHMForced=true - Lots of RAM\n"));
1008 if (cCpus > 1)
1009 LogRel(("fHMForced=true - SMP\n"));
1010 if (fIsGuest64Bit)
1011 LogRel(("fHMForced=true - 64-bit guest\n"));
1012# ifdef RT_OS_DARWIN
1013 LogRel(("fHMForced=true - Darwin host\n"));
1014# endif
1015 }
1016#else /* !VBOX_WITH_RAW_MODE */
1017 fHMEnabled = fHMForced = TRUE;
1018 LogRel(("fHMForced=true - No raw-mode support in this build!\n"));
1019#endif /* !VBOX_WITH_RAW_MODE */
1020 if (!fHMForced) /* No need to query if already forced above. */
1021 {
1022 hrc = pMachine->GetHWVirtExProperty(HWVirtExPropertyType_Force, &fHMForced); H();
1023 if (fHMForced)
1024 LogRel(("fHMForced=true - HWVirtExPropertyType_Force\n"));
1025 }
1026 InsertConfigInteger(pRoot, "HMEnabled", fHMEnabled);
1027
1028 /* /HM/xzy */
1029 PCFGMNODE pHM;
1030 InsertConfigNode(pRoot, "HM", &pHM);
1031 InsertConfigInteger(pRoot, "HMForced", fHMForced);
1032 if (fHMEnabled)
1033 {
1034 /* Indicate whether 64-bit guests are supported or not. */
1035 InsertConfigInteger(pHM, "64bitEnabled", fIsGuest64Bit);
1036#if ARCH_BITS == 32 /* The recompiler must use VBoxREM64 (32-bit host only). */
1037 PCFGMNODE pREM;
1038 InsertConfigNode(pRoot, "REM", &pREM);
1039 InsertConfigInteger(pREM, "64bitEnabled", 1);
1040#endif
1041
1042 /** @todo Not exactly pretty to check strings; VBOXOSTYPE would be better, but that requires quite a bit of API change in Main. */
1043 if ( !fIsGuest64Bit
1044 && fIOAPIC
1045 && ( osTypeId == "WindowsNT4"
1046 || osTypeId == "Windows2000"
1047 || osTypeId == "WindowsXP"
1048 || osTypeId == "Windows2003"))
1049 {
1050 /* Only allow TPR patching for NT, Win2k, XP and Windows Server 2003. (32 bits mode)
1051 * We may want to consider adding more guest OSes (Solaris) later on.
1052 */
1053 InsertConfigInteger(pHM, "TPRPatchingEnabled", 1);
1054 }
1055 }
1056
1057 /* HWVirtEx exclusive mode */
1058 BOOL fHMExclusive = true;
1059 hrc = systemProperties->COMGETTER(ExclusiveHwVirt)(&fHMExclusive); H();
1060 InsertConfigInteger(pHM, "Exclusive", fHMExclusive);
1061
1062 /* Nested paging (VT-x/AMD-V) */
1063 BOOL fEnableNestedPaging = false;
1064 hrc = pMachine->GetHWVirtExProperty(HWVirtExPropertyType_NestedPaging, &fEnableNestedPaging); H();
1065 InsertConfigInteger(pHM, "EnableNestedPaging", fEnableNestedPaging);
1066
1067 /* Large pages; requires nested paging */
1068 BOOL fEnableLargePages = false;
1069 hrc = pMachine->GetHWVirtExProperty(HWVirtExPropertyType_LargePages, &fEnableLargePages); H();
1070 InsertConfigInteger(pHM, "EnableLargePages", fEnableLargePages);
1071
1072 /* VPID (VT-x) */
1073 BOOL fEnableVPID = false;
1074 hrc = pMachine->GetHWVirtExProperty(HWVirtExPropertyType_VPID, &fEnableVPID); H();
1075 InsertConfigInteger(pHM, "EnableVPID", fEnableVPID);
1076
1077 /* Unrestricted execution aka UX (VT-x) */
1078 BOOL fEnableUX = false;
1079 hrc = pMachine->GetHWVirtExProperty(HWVirtExPropertyType_UnrestrictedExecution, &fEnableUX); H();
1080 InsertConfigInteger(pHM, "EnableUX", fEnableUX);
1081
1082 /* Reset overwrite. */
1083 if (isResetTurnedIntoPowerOff())
1084 InsertConfigInteger(pRoot, "PowerOffInsteadOfReset", 1);
1085
1086
1087 /*
1088 * MM values.
1089 */
1090 PCFGMNODE pMM;
1091 InsertConfigNode(pRoot, "MM", &pMM);
1092 InsertConfigInteger(pMM, "CanUseLargerHeap", chipsetType == ChipsetType_ICH9);
1093
1094 /*
1095 * PDM config.
1096 * Load drivers in VBoxC.[so|dll]
1097 */
1098 PCFGMNODE pPDM;
1099 PCFGMNODE pNode;
1100 PCFGMNODE pMod;
1101 InsertConfigNode(pRoot, "PDM", &pPDM);
1102 InsertConfigNode(pPDM, "Devices", &pNode);
1103 InsertConfigNode(pPDM, "Drivers", &pNode);
1104 InsertConfigNode(pNode, "VBoxC", &pMod);
1105#ifdef VBOX_WITH_XPCOM
1106 // VBoxC is located in the components subdirectory
1107 char szPathVBoxC[RTPATH_MAX];
1108 rc = RTPathAppPrivateArch(szPathVBoxC, RTPATH_MAX - sizeof("/components/VBoxC")); AssertRC(rc);
1109 strcat(szPathVBoxC, "/components/VBoxC");
1110 InsertConfigString(pMod, "Path", szPathVBoxC);
1111#else
1112 InsertConfigString(pMod, "Path", "VBoxC");
1113#endif
1114
1115
1116 /*
1117 * Block cache settings.
1118 */
1119 PCFGMNODE pPDMBlkCache;
1120 InsertConfigNode(pPDM, "BlkCache", &pPDMBlkCache);
1121
1122 /* I/O cache size */
1123 ULONG ioCacheSize = 5;
1124 hrc = pMachine->COMGETTER(IOCacheSize)(&ioCacheSize); H();
1125 InsertConfigInteger(pPDMBlkCache, "CacheSize", ioCacheSize * _1M);
1126
1127 /*
1128 * Bandwidth groups.
1129 */
1130 PCFGMNODE pAc;
1131 PCFGMNODE pAcFile;
1132 PCFGMNODE pAcFileBwGroups;
1133 ComPtr<IBandwidthControl> bwCtrl;
1134 com::SafeIfaceArray<IBandwidthGroup> bwGroups;
1135
1136 hrc = pMachine->COMGETTER(BandwidthControl)(bwCtrl.asOutParam()); H();
1137
1138 hrc = bwCtrl->GetAllBandwidthGroups(ComSafeArrayAsOutParam(bwGroups)); H();
1139
1140 InsertConfigNode(pPDM, "AsyncCompletion", &pAc);
1141 InsertConfigNode(pAc, "File", &pAcFile);
1142 InsertConfigNode(pAcFile, "BwGroups", &pAcFileBwGroups);
1143#ifdef VBOX_WITH_NETSHAPER
1144 PCFGMNODE pNetworkShaper;
1145 PCFGMNODE pNetworkBwGroups;
1146
1147 InsertConfigNode(pPDM, "NetworkShaper", &pNetworkShaper);
1148 InsertConfigNode(pNetworkShaper, "BwGroups", &pNetworkBwGroups);
1149#endif /* VBOX_WITH_NETSHAPER */
1150
1151 for (size_t i = 0; i < bwGroups.size(); i++)
1152 {
1153 Bstr strName;
1154 LONG64 cMaxBytesPerSec;
1155 BandwidthGroupType_T enmType;
1156
1157 hrc = bwGroups[i]->COMGETTER(Name)(strName.asOutParam()); H();
1158 hrc = bwGroups[i]->COMGETTER(Type)(&enmType); H();
1159 hrc = bwGroups[i]->COMGETTER(MaxBytesPerSec)(&cMaxBytesPerSec); H();
1160
1161 if (enmType == BandwidthGroupType_Disk)
1162 {
1163 PCFGMNODE pBwGroup;
1164 InsertConfigNode(pAcFileBwGroups, Utf8Str(strName).c_str(), &pBwGroup);
1165 InsertConfigInteger(pBwGroup, "Max", cMaxBytesPerSec);
1166 InsertConfigInteger(pBwGroup, "Start", cMaxBytesPerSec);
1167 InsertConfigInteger(pBwGroup, "Step", 0);
1168 }
1169#ifdef VBOX_WITH_NETSHAPER
1170 else if (enmType == BandwidthGroupType_Network)
1171 {
1172 /* Network bandwidth groups. */
1173 PCFGMNODE pBwGroup;
1174 InsertConfigNode(pNetworkBwGroups, Utf8Str(strName).c_str(), &pBwGroup);
1175 InsertConfigInteger(pBwGroup, "Max", cMaxBytesPerSec);
1176 }
1177#endif /* VBOX_WITH_NETSHAPER */
1178 }
1179
1180 /*
1181 * Devices
1182 */
1183 PCFGMNODE pDevices = NULL; /* /Devices */
1184 PCFGMNODE pDev = NULL; /* /Devices/Dev/ */
1185 PCFGMNODE pInst = NULL; /* /Devices/Dev/0/ */
1186 PCFGMNODE pCfg = NULL; /* /Devices/Dev/.../Config/ */
1187 PCFGMNODE pLunL0 = NULL; /* /Devices/Dev/0/LUN#0/ */
1188 PCFGMNODE pLunL1 = NULL; /* /Devices/Dev/0/LUN#0/AttachedDriver/ */
1189 PCFGMNODE pLunL2 = NULL; /* /Devices/Dev/0/LUN#0/AttachedDriver/Config/ */
1190 PCFGMNODE pBiosCfg = NULL; /* /Devices/pcbios/0/Config/ */
1191 PCFGMNODE pNetBootCfg = NULL; /* /Devices/pcbios/0/Config/NetBoot/ */
1192
1193 InsertConfigNode(pRoot, "Devices", &pDevices);
1194
1195 /*
1196 * PC Arch.
1197 */
1198 InsertConfigNode(pDevices, "pcarch", &pDev);
1199 InsertConfigNode(pDev, "0", &pInst);
1200 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1201 InsertConfigNode(pInst, "Config", &pCfg);
1202
1203 /*
1204 * The time offset
1205 */
1206 LONG64 timeOffset;
1207 hrc = biosSettings->COMGETTER(TimeOffset)(&timeOffset); H();
1208 PCFGMNODE pTMNode;
1209 InsertConfigNode(pRoot, "TM", &pTMNode);
1210 InsertConfigInteger(pTMNode, "UTCOffset", timeOffset * 1000000);
1211
1212 /*
1213 * DMA
1214 */
1215 InsertConfigNode(pDevices, "8237A", &pDev);
1216 InsertConfigNode(pDev, "0", &pInst);
1217 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1218
1219 /*
1220 * PCI buses.
1221 */
1222 uint32_t uIocPCIAddress, uHbcPCIAddress;
1223 switch (chipsetType)
1224 {
1225 default:
1226 Assert(false);
1227 case ChipsetType_PIIX3:
1228 InsertConfigNode(pDevices, "pci", &pDev);
1229 uHbcPCIAddress = (0x0 << 16) | 0;
1230 uIocPCIAddress = (0x1 << 16) | 0; // ISA controller
1231 break;
1232 case ChipsetType_ICH9:
1233 InsertConfigNode(pDevices, "ich9pci", &pDev);
1234 uHbcPCIAddress = (0x1e << 16) | 0;
1235 uIocPCIAddress = (0x1f << 16) | 0; // LPC controller
1236 break;
1237 }
1238 InsertConfigNode(pDev, "0", &pInst);
1239 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1240 InsertConfigNode(pInst, "Config", &pCfg);
1241 InsertConfigInteger(pCfg, "IOAPIC", fIOAPIC);
1242 if (chipsetType == ChipsetType_ICH9)
1243 {
1244 /* Provide MCFG info */
1245 InsertConfigInteger(pCfg, "McfgBase", uMcfgBase);
1246 InsertConfigInteger(pCfg, "McfgLength", cbMcfgLength);
1247
1248
1249 /* And register 2 bridges */
1250 InsertConfigNode(pDevices, "ich9pcibridge", &pDev);
1251 InsertConfigNode(pDev, "0", &pInst);
1252 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1253 hrc = pBusMgr->assignPCIDevice("ich9pcibridge", pInst); H();
1254
1255 InsertConfigNode(pDev, "1", &pInst);
1256 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1257 hrc = pBusMgr->assignPCIDevice("ich9pcibridge", pInst); H();
1258
1259#ifdef VBOX_WITH_PCI_PASSTHROUGH
1260 /* Add PCI passthrough devices */
1261 hrc = attachRawPCIDevices(pUVM, pBusMgr, pDevices); H();
1262#endif
1263 }
1264
1265 /*
1266 * Enable the following devices: HPET, SMC and LPC on MacOS X guests or on ICH9 chipset
1267 */
1268
1269 /*
1270 * High Precision Event Timer (HPET)
1271 */
1272 BOOL fHPETEnabled;
1273 /* Other guests may wish to use HPET too, but MacOS X not functional without it */
1274 hrc = pMachine->COMGETTER(HPETEnabled)(&fHPETEnabled); H();
1275 /* so always enable HPET in extended profile */
1276 fHPETEnabled |= fOsXGuest;
1277 /* HPET is always present on ICH9 */
1278 fHPETEnabled |= (chipsetType == ChipsetType_ICH9);
1279 if (fHPETEnabled)
1280 {
1281 InsertConfigNode(pDevices, "hpet", &pDev);
1282 InsertConfigNode(pDev, "0", &pInst);
1283 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1284 InsertConfigNode(pInst, "Config", &pCfg);
1285 InsertConfigInteger(pCfg, "ICH9", (chipsetType == ChipsetType_ICH9) ? 1 : 0); /* boolean */
1286 }
1287
1288 /*
1289 * System Management Controller (SMC)
1290 */
1291 BOOL fSmcEnabled;
1292 fSmcEnabled = fOsXGuest;
1293 if (fSmcEnabled)
1294 {
1295 InsertConfigNode(pDevices, "smc", &pDev);
1296 InsertConfigNode(pDev, "0", &pInst);
1297 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1298 InsertConfigNode(pInst, "Config", &pCfg);
1299
1300 bool fGetKeyFromRealSMC;
1301 Utf8Str strKey;
1302 rc = getSmcDeviceKey(virtualBox, pMachine, &strKey, &fGetKeyFromRealSMC);
1303 AssertRCReturn(rc, rc);
1304
1305 InsertConfigString(pCfg, "DeviceKey", strKey);
1306 InsertConfigInteger(pCfg, "GetKeyFromRealSMC", fGetKeyFromRealSMC);
1307 }
1308
1309 /*
1310 * Low Pin Count (LPC) bus
1311 */
1312 BOOL fLpcEnabled;
1313 /** @todo: implement appropriate getter */
1314 fLpcEnabled = fOsXGuest || (chipsetType == ChipsetType_ICH9);
1315 if (fLpcEnabled)
1316 {
1317 InsertConfigNode(pDevices, "lpc", &pDev);
1318 InsertConfigNode(pDev, "0", &pInst);
1319 hrc = pBusMgr->assignPCIDevice("lpc", pInst); H();
1320 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1321 }
1322
1323 BOOL fShowRtc;
1324 fShowRtc = fOsXGuest || (chipsetType == ChipsetType_ICH9);
1325
1326 /*
1327 * PS/2 keyboard & mouse.
1328 */
1329 InsertConfigNode(pDevices, "pckbd", &pDev);
1330 InsertConfigNode(pDev, "0", &pInst);
1331 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1332 InsertConfigNode(pInst, "Config", &pCfg);
1333
1334 InsertConfigNode(pInst, "LUN#0", &pLunL0);
1335 InsertConfigString(pLunL0, "Driver", "KeyboardQueue");
1336 InsertConfigNode(pLunL0, "Config", &pCfg);
1337 InsertConfigInteger(pCfg, "QueueSize", 64);
1338
1339 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
1340 InsertConfigString(pLunL1, "Driver", "MainKeyboard");
1341 InsertConfigNode(pLunL1, "Config", &pCfg);
1342 Keyboard *pKeyboard = mKeyboard;
1343 InsertConfigInteger(pCfg, "Object", (uintptr_t)pKeyboard);
1344
1345 Mouse *pMouse = mMouse;
1346 PointingHIDType_T aPointingHID;
1347 hrc = pMachine->COMGETTER(PointingHIDType)(&aPointingHID); H();
1348 InsertConfigNode(pInst, "LUN#1", &pLunL0);
1349 InsertConfigString(pLunL0, "Driver", "MouseQueue");
1350 InsertConfigNode(pLunL0, "Config", &pCfg);
1351 InsertConfigInteger(pCfg, "QueueSize", 128);
1352
1353 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
1354 InsertConfigString(pLunL1, "Driver", "MainMouse");
1355 InsertConfigNode(pLunL1, "Config", &pCfg);
1356 InsertConfigInteger(pCfg, "Object", (uintptr_t)pMouse);
1357
1358 /*
1359 * i8254 Programmable Interval Timer And Dummy Speaker
1360 */
1361 InsertConfigNode(pDevices, "i8254", &pDev);
1362 InsertConfigNode(pDev, "0", &pInst);
1363 InsertConfigNode(pInst, "Config", &pCfg);
1364#ifdef DEBUG
1365 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1366#endif
1367
1368 /*
1369 * i8259 Programmable Interrupt Controller.
1370 */
1371 InsertConfigNode(pDevices, "i8259", &pDev);
1372 InsertConfigNode(pDev, "0", &pInst);
1373 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1374 InsertConfigNode(pInst, "Config", &pCfg);
1375
1376 /*
1377 * Advanced Programmable Interrupt Controller.
1378 * SMP: Each CPU has a LAPIC, but we have a single device representing all LAPICs states,
1379 * thus only single insert
1380 */
1381 InsertConfigNode(pDevices, "apic", &pDev);
1382 InsertConfigNode(pDev, "0", &pInst);
1383 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1384 InsertConfigNode(pInst, "Config", &pCfg);
1385 InsertConfigInteger(pCfg, "IOAPIC", fIOAPIC);
1386 InsertConfigInteger(pCfg, "NumCPUs", cCpus);
1387
1388 if (fIOAPIC)
1389 {
1390 /*
1391 * I/O Advanced Programmable Interrupt Controller.
1392 */
1393 InsertConfigNode(pDevices, "ioapic", &pDev);
1394 InsertConfigNode(pDev, "0", &pInst);
1395 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1396 InsertConfigNode(pInst, "Config", &pCfg);
1397 InsertConfigInteger(pCfg, "NumCPUs", cCpus);
1398 }
1399
1400 /*
1401 * RTC MC146818.
1402 */
1403 InsertConfigNode(pDevices, "mc146818", &pDev);
1404 InsertConfigNode(pDev, "0", &pInst);
1405 InsertConfigNode(pInst, "Config", &pCfg);
1406 BOOL fRTCUseUTC;
1407 hrc = pMachine->COMGETTER(RTCUseUTC)(&fRTCUseUTC); H();
1408 InsertConfigInteger(pCfg, "UseUTC", fRTCUseUTC ? 1 : 0);
1409
1410 /*
1411 * VGA.
1412 */
1413 GraphicsControllerType_T graphicsController;
1414 hrc = pMachine->COMGETTER(GraphicsControllerType)(&graphicsController); H();
1415 switch (graphicsController)
1416 {
1417 case GraphicsControllerType_Null:
1418 break;
1419 case GraphicsControllerType_VBoxVGA:
1420 rc = configGraphicsController(pDevices, "vga", pBusMgr, pMachine, biosSettings,
1421 RT_BOOL(fHMEnabled));
1422 if (FAILED(rc))
1423 return rc;
1424 break;
1425 default:
1426 AssertMsgFailed(("Invalid graphicsController=%d\n", graphicsController));
1427 return VMR3SetError(pUVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
1428 N_("Invalid graphics controller type '%d'"), graphicsController);
1429 }
1430
1431 /*
1432 * Firmware.
1433 */
1434 FirmwareType_T eFwType = FirmwareType_BIOS;
1435 hrc = pMachine->COMGETTER(FirmwareType)(&eFwType); H();
1436
1437#ifdef VBOX_WITH_EFI
1438 BOOL fEfiEnabled = (eFwType >= FirmwareType_EFI) && (eFwType <= FirmwareType_EFIDUAL);
1439#else
1440 BOOL fEfiEnabled = false;
1441#endif
1442 if (!fEfiEnabled)
1443 {
1444 /*
1445 * PC Bios.
1446 */
1447 InsertConfigNode(pDevices, "pcbios", &pDev);
1448 InsertConfigNode(pDev, "0", &pInst);
1449 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1450 InsertConfigNode(pInst, "Config", &pBiosCfg);
1451 InsertConfigInteger(pBiosCfg, "RamSize", cbRam);
1452 InsertConfigInteger(pBiosCfg, "RamHoleSize", cbRamHole);
1453 InsertConfigInteger(pBiosCfg, "NumCPUs", cCpus);
1454 InsertConfigString(pBiosCfg, "HardDiskDevice", "piix3ide");
1455 InsertConfigString(pBiosCfg, "FloppyDevice", "i82078");
1456 InsertConfigInteger(pBiosCfg, "IOAPIC", fIOAPIC);
1457 BOOL fPXEDebug;
1458 hrc = biosSettings->COMGETTER(PXEDebugEnabled)(&fPXEDebug); H();
1459 InsertConfigInteger(pBiosCfg, "PXEDebug", fPXEDebug);
1460 InsertConfigBytes(pBiosCfg, "UUID", &HardwareUuid,sizeof(HardwareUuid));
1461 InsertConfigNode(pBiosCfg, "NetBoot", &pNetBootCfg);
1462 InsertConfigInteger(pBiosCfg, "McfgBase", uMcfgBase);
1463 InsertConfigInteger(pBiosCfg, "McfgLength", cbMcfgLength);
1464
1465 DeviceType_T bootDevice;
1466 AssertMsgReturn(SchemaDefs::MaxBootPosition <= 9, ("Too many boot devices %d\n", SchemaDefs::MaxBootPosition),
1467 VERR_INVALID_PARAMETER);
1468
1469 for (ULONG pos = 1; pos <= SchemaDefs::MaxBootPosition; ++pos)
1470 {
1471 hrc = pMachine->GetBootOrder(pos, &bootDevice); H();
1472
1473 char szParamName[] = "BootDeviceX";
1474 szParamName[sizeof(szParamName) - 2] = ((char (pos - 1)) + '0');
1475
1476 const char *pszBootDevice;
1477 switch (bootDevice)
1478 {
1479 case DeviceType_Null:
1480 pszBootDevice = "NONE";
1481 break;
1482 case DeviceType_HardDisk:
1483 pszBootDevice = "IDE";
1484 break;
1485 case DeviceType_DVD:
1486 pszBootDevice = "DVD";
1487 break;
1488 case DeviceType_Floppy:
1489 pszBootDevice = "FLOPPY";
1490 break;
1491 case DeviceType_Network:
1492 pszBootDevice = "LAN";
1493 break;
1494 default:
1495 AssertMsgFailed(("Invalid bootDevice=%d\n", bootDevice));
1496 return VMR3SetError(pUVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
1497 N_("Invalid boot device '%d'"), bootDevice);
1498 }
1499 InsertConfigString(pBiosCfg, szParamName, pszBootDevice);
1500 }
1501 }
1502 else
1503 {
1504 /* Autodetect firmware type, basing on guest type */
1505 if (eFwType == FirmwareType_EFI)
1506 {
1507 eFwType = fIsGuest64Bit
1508 ? (FirmwareType_T)FirmwareType_EFI64
1509 : (FirmwareType_T)FirmwareType_EFI32;
1510 }
1511 bool const f64BitEntry = eFwType == FirmwareType_EFI64;
1512
1513 Utf8Str efiRomFile;
1514 rc = findEfiRom(virtualBox, eFwType, &efiRomFile);
1515 AssertRCReturn(rc, rc);
1516
1517 /* Get boot args */
1518 Utf8Str bootArgs;
1519 GetExtraDataBoth(virtualBox, pMachine, "VBoxInternal2/EfiBootArgs", &bootArgs);
1520
1521 /* Get device props */
1522 Utf8Str deviceProps;
1523 GetExtraDataBoth(virtualBox, pMachine, "VBoxInternal2/EfiDeviceProps", &deviceProps);
1524
1525 /* Get GOP mode settings */
1526 uint32_t u32GopMode = UINT32_MAX;
1527 GetExtraDataBoth(virtualBox, pMachine, "VBoxInternal2/EfiGopMode", &strTmp);
1528 if (!strTmp.isEmpty())
1529 u32GopMode = strTmp.toUInt32();
1530
1531 /* UGA mode settings */
1532 uint32_t u32UgaHorisontal = 0;
1533 GetExtraDataBoth(virtualBox, pMachine, "VBoxInternal2/EfiUgaHorizontalResolution", &strTmp);
1534 if (!strTmp.isEmpty())
1535 u32UgaHorisontal = strTmp.toUInt32();
1536
1537 uint32_t u32UgaVertical = 0;
1538 GetExtraDataBoth(virtualBox, pMachine, "VBoxInternal2/EfiUgaVerticalResolution", &strTmp);
1539 if (!strTmp.isEmpty())
1540 u32UgaVertical = strTmp.toUInt32();
1541
1542 /*
1543 * EFI subtree.
1544 */
1545 InsertConfigNode(pDevices, "efi", &pDev);
1546 InsertConfigNode(pDev, "0", &pInst);
1547 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1548 InsertConfigNode(pInst, "Config", &pCfg);
1549 InsertConfigInteger(pCfg, "RamSize", cbRam);
1550 InsertConfigInteger(pCfg, "RamHoleSize", cbRamHole);
1551 InsertConfigInteger(pCfg, "NumCPUs", cCpus);
1552 InsertConfigString(pCfg, "EfiRom", efiRomFile);
1553 InsertConfigString(pCfg, "BootArgs", bootArgs);
1554 InsertConfigString(pCfg, "DeviceProps", deviceProps);
1555 InsertConfigInteger(pCfg, "IOAPIC", fIOAPIC);
1556 InsertConfigBytes(pCfg, "UUID", &HardwareUuid,sizeof(HardwareUuid));
1557 InsertConfigInteger(pCfg, "64BitEntry", f64BitEntry); /* boolean */
1558 InsertConfigInteger(pCfg, "GopMode", u32GopMode);
1559 InsertConfigInteger(pCfg, "UgaHorizontalResolution", u32UgaHorisontal);
1560 InsertConfigInteger(pCfg, "UgaVerticalResolution", u32UgaVertical);
1561
1562 /* For OS X guests we'll force passing host's DMI info to the guest */
1563 if (fOsXGuest)
1564 {
1565 InsertConfigInteger(pCfg, "DmiUseHostInfo", 1);
1566 InsertConfigInteger(pCfg, "DmiExposeMemoryTable", 1);
1567 }
1568 InsertConfigNode(pInst, "LUN#0", &pLunL0);
1569 InsertConfigString(pLunL0, "Driver", "NvramStorage");
1570 InsertConfigNode(pLunL0, "Config", &pCfg);
1571 InsertConfigInteger(pCfg, "Object", (uintptr_t)mNvram);
1572#ifdef DEBUG_vvl
1573 InsertConfigInteger(pCfg, "PermanentSave", 1);
1574#endif
1575 }
1576
1577 /*
1578 * Storage controllers.
1579 */
1580 com::SafeIfaceArray<IStorageController> ctrls;
1581 PCFGMNODE aCtrlNodes[StorageControllerType_LsiLogicSas + 1] = {};
1582 hrc = pMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls)); H();
1583
1584 bool fFdcEnabled = false;
1585 for (size_t i = 0; i < ctrls.size(); ++i)
1586 {
1587 DeviceType_T *paLedDevType = NULL;
1588
1589 StorageControllerType_T enmCtrlType;
1590 rc = ctrls[i]->COMGETTER(ControllerType)(&enmCtrlType); H();
1591 AssertRelease((unsigned)enmCtrlType < RT_ELEMENTS(aCtrlNodes));
1592
1593 StorageBus_T enmBus;
1594 rc = ctrls[i]->COMGETTER(Bus)(&enmBus); H();
1595
1596 Bstr controllerName;
1597 rc = ctrls[i]->COMGETTER(Name)(controllerName.asOutParam()); H();
1598
1599 ULONG ulInstance = 999;
1600 rc = ctrls[i]->COMGETTER(Instance)(&ulInstance); H();
1601
1602 BOOL fUseHostIOCache;
1603 rc = ctrls[i]->COMGETTER(UseHostIOCache)(&fUseHostIOCache); H();
1604
1605 BOOL fBootable;
1606 rc = ctrls[i]->COMGETTER(Bootable)(&fBootable); H();
1607
1608 /* /Devices/<ctrldev>/ */
1609 const char *pszCtrlDev = convertControllerTypeToDev(enmCtrlType);
1610 pDev = aCtrlNodes[enmCtrlType];
1611 if (!pDev)
1612 {
1613 InsertConfigNode(pDevices, pszCtrlDev, &pDev);
1614 aCtrlNodes[enmCtrlType] = pDev; /* IDE variants are handled in the switch */
1615 }
1616
1617 /* /Devices/<ctrldev>/<instance>/ */
1618 PCFGMNODE pCtlInst = NULL;
1619 InsertConfigNode(pDev, Utf8StrFmt("%u", ulInstance).c_str(), &pCtlInst);
1620
1621 /* Device config: /Devices/<ctrldev>/<instance>/<values> & /ditto/Config/<values> */
1622 InsertConfigInteger(pCtlInst, "Trusted", 1);
1623 InsertConfigNode(pCtlInst, "Config", &pCfg);
1624
1625 switch (enmCtrlType)
1626 {
1627 case StorageControllerType_LsiLogic:
1628 {
1629 hrc = pBusMgr->assignPCIDevice("lsilogic", pCtlInst); H();
1630
1631 InsertConfigInteger(pCfg, "Bootable", fBootable);
1632
1633 /* Attach the status driver */
1634 Assert(cLedScsi >= 16);
1635 attachStatusDriver(pCtlInst, &mapStorageLeds[iLedScsi], 0, 15,
1636 &mapMediumAttachments, pszCtrlDev, ulInstance);
1637 paLedDevType = &maStorageDevType[iLedScsi];
1638 break;
1639 }
1640
1641 case StorageControllerType_BusLogic:
1642 {
1643 hrc = pBusMgr->assignPCIDevice("buslogic", pCtlInst); H();
1644
1645 InsertConfigInteger(pCfg, "Bootable", fBootable);
1646
1647 /* Attach the status driver */
1648 Assert(cLedScsi >= 16);
1649 attachStatusDriver(pCtlInst, &mapStorageLeds[iLedScsi], 0, 15,
1650 &mapMediumAttachments, pszCtrlDev, ulInstance);
1651 paLedDevType = &maStorageDevType[iLedScsi];
1652 break;
1653 }
1654
1655 case StorageControllerType_IntelAhci:
1656 {
1657 hrc = pBusMgr->assignPCIDevice("ahci", pCtlInst); H();
1658
1659 ULONG cPorts = 0;
1660 hrc = ctrls[i]->COMGETTER(PortCount)(&cPorts); H();
1661 InsertConfigInteger(pCfg, "PortCount", cPorts);
1662 InsertConfigInteger(pCfg, "Bootable", fBootable);
1663
1664 /* Needed configuration values for the bios, only first controller. */
1665 if (!pBusMgr->hasPCIDevice("ahci", 1))
1666 {
1667#define MAX_SATA_LUN_COUNT 4
1668#define MAX_SATA_PORTS 30
1669
1670 static const char * const s_apszBiosConfig[4] =
1671 { "SataLUN1", "SataLUN2", "SataLUN3", "SataLUN4" };
1672
1673 LONG lPortLUN[MAX_SATA_LUN_COUNT];
1674 LONG lPortUsed[MAX_SATA_PORTS];
1675 uint32_t u32HDSataPortCount = 0;
1676
1677 /* init to max value */
1678 lPortLUN[0] = MAX_SATA_PORTS;
1679
1680 if (pBiosCfg)
1681 {
1682 InsertConfigString(pBiosCfg, "SataHardDiskDevice", "ahci");
1683 }
1684
1685 com::SafeIfaceArray<IMediumAttachment> atts;
1686 hrc = pMachine->GetMediumAttachmentsOfController(controllerName.raw(),
1687 ComSafeArrayAsOutParam(atts)); H();
1688 size_t uNumAttachments = atts.size();
1689 if (uNumAttachments > MAX_SATA_PORTS)
1690 {
1691 LogRel(("Number of Sata Port Attachments > Max=%d.\n", uNumAttachments));
1692 uNumAttachments = MAX_SATA_PORTS;
1693 }
1694
1695 /* find the relavant ports i.e Sata ports to which
1696 * HD is attached.
1697 */
1698 for (size_t j = 0; j < uNumAttachments; ++j)
1699 {
1700 IMediumAttachment *pMediumAtt = atts[j];
1701 LONG lPortNum = 0;
1702 hrc = pMediumAtt->COMGETTER(Port)(&lPortNum); H();
1703 if (SUCCEEDED(hrc))
1704 {
1705 DeviceType_T lType;
1706 hrc = pMediumAtt->COMGETTER(Type)(&lType); H();
1707 if (SUCCEEDED(hrc) && lType == DeviceType_HardDisk)
1708 {
1709 /* find min port number used for HD */
1710 if (lPortNum < lPortLUN[0])
1711 lPortLUN[0] = lPortNum;
1712 lPortUsed[u32HDSataPortCount++] = lPortNum;
1713 LogFlowFunc(("HD Sata port Count=%d\n", u32HDSataPortCount));
1714 }
1715 }
1716 }
1717
1718
1719 /* Pick only the top 4 used HD Sata Ports as CMOS doesn't have space
1720 * to save details for every 30 ports
1721 */
1722 uint32_t u32MaxPortCount = MAX_SATA_LUN_COUNT;
1723 if (u32HDSataPortCount < MAX_SATA_LUN_COUNT)
1724 u32MaxPortCount = u32HDSataPortCount;
1725 for (size_t j = 1; j < u32MaxPortCount; j++)
1726 lPortLUN[j] = GetNextUsedSataPort(lPortUsed,
1727 lPortLUN[j-1],
1728 u32HDSataPortCount);
1729 if (pBiosCfg)
1730 {
1731 for (size_t j = 0; j < u32MaxPortCount; j++)
1732 {
1733 InsertConfigInteger(pBiosCfg, s_apszBiosConfig[j], lPortLUN[j]);
1734 LogFlowFunc(("Top %d ports = %s, %d\n", j, s_apszBiosConfig[j], lPortLUN[j]));
1735 }
1736 }
1737 }
1738
1739 /* Attach the status driver */
1740 AssertRelease(cPorts <= cLedSata);
1741 attachStatusDriver(pCtlInst, &mapStorageLeds[iLedSata], 0, cPorts - 1,
1742 &mapMediumAttachments, pszCtrlDev, ulInstance);
1743 paLedDevType = &maStorageDevType[iLedSata];
1744 break;
1745 }
1746
1747 case StorageControllerType_PIIX3:
1748 case StorageControllerType_PIIX4:
1749 case StorageControllerType_ICH6:
1750 {
1751 /*
1752 * IDE (update this when the main interface changes)
1753 */
1754 hrc = pBusMgr->assignPCIDevice("piix3ide", pCtlInst); H();
1755 InsertConfigString(pCfg, "Type", controllerString(enmCtrlType));
1756 /* Attach the status driver */
1757 Assert(cLedIde >= 4);
1758 attachStatusDriver(pCtlInst, &mapStorageLeds[iLedIde], 0, 3,
1759 &mapMediumAttachments, pszCtrlDev, ulInstance);
1760 paLedDevType = &maStorageDevType[iLedIde];
1761
1762 /* IDE flavors */
1763 aCtrlNodes[StorageControllerType_PIIX3] = pDev;
1764 aCtrlNodes[StorageControllerType_PIIX4] = pDev;
1765 aCtrlNodes[StorageControllerType_ICH6] = pDev;
1766 break;
1767 }
1768
1769 case StorageControllerType_I82078:
1770 {
1771 /*
1772 * i82078 Floppy drive controller
1773 */
1774 fFdcEnabled = true;
1775 InsertConfigInteger(pCfg, "IRQ", 6);
1776 InsertConfigInteger(pCfg, "DMA", 2);
1777 InsertConfigInteger(pCfg, "MemMapped", 0 );
1778 InsertConfigInteger(pCfg, "IOBase", 0x3f0);
1779
1780 /* Attach the status driver */
1781 Assert(cLedFloppy >= 2);
1782 attachStatusDriver(pCtlInst, &mapStorageLeds[iLedFloppy], 0, 1,
1783 &mapMediumAttachments, pszCtrlDev, ulInstance);
1784 paLedDevType = &maStorageDevType[iLedFloppy];
1785 break;
1786 }
1787
1788 case StorageControllerType_LsiLogicSas:
1789 {
1790 hrc = pBusMgr->assignPCIDevice("lsilogicsas", pCtlInst); H();
1791
1792 InsertConfigString(pCfg, "ControllerType", "SAS1068");
1793 InsertConfigInteger(pCfg, "Bootable", fBootable);
1794
1795 /* Attach the status driver */
1796 Assert(cLedSas >= 8);
1797 attachStatusDriver(pCtlInst, &mapStorageLeds[iLedSas], 0, 7,
1798 &mapMediumAttachments, pszCtrlDev, ulInstance);
1799 paLedDevType = &maStorageDevType[iLedSas];
1800 break;
1801 }
1802
1803 default:
1804 AssertMsgFailedReturn(("invalid storage controller type: %d\n", enmCtrlType), VERR_GENERAL_FAILURE);
1805 }
1806
1807 /* Attach the media to the storage controllers. */
1808 com::SafeIfaceArray<IMediumAttachment> atts;
1809 hrc = pMachine->GetMediumAttachmentsOfController(controllerName.raw(),
1810 ComSafeArrayAsOutParam(atts)); H();
1811
1812 /* Builtin I/O cache - per device setting. */
1813 BOOL fBuiltinIOCache = true;
1814 hrc = pMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache); H();
1815
1816
1817 for (size_t j = 0; j < atts.size(); ++j)
1818 {
1819 IMediumAttachment *pMediumAtt = atts[j];
1820 rc = configMediumAttachment(pCtlInst,
1821 pszCtrlDev,
1822 ulInstance,
1823 enmBus,
1824 !!fUseHostIOCache,
1825 !!fBuiltinIOCache,
1826 false /* fSetupMerge */,
1827 0 /* uMergeSource */,
1828 0 /* uMergeTarget */,
1829 pMediumAtt,
1830 mMachineState,
1831 NULL /* phrc */,
1832 false /* fAttachDetach */,
1833 false /* fForceUnmount */,
1834 false /* fHotplug */,
1835 pUVM,
1836 paLedDevType);
1837 if (RT_FAILURE(rc))
1838 return rc;
1839 }
1840 H();
1841 }
1842 H();
1843
1844 /*
1845 * Network adapters
1846 */
1847#ifdef VMWARE_NET_IN_SLOT_11
1848 bool fSwapSlots3and11 = false;
1849#endif
1850 PCFGMNODE pDevPCNet = NULL; /* PCNet-type devices */
1851 InsertConfigNode(pDevices, "pcnet", &pDevPCNet);
1852#ifdef VBOX_WITH_E1000
1853 PCFGMNODE pDevE1000 = NULL; /* E1000-type devices */
1854 InsertConfigNode(pDevices, "e1000", &pDevE1000);
1855#endif
1856#ifdef VBOX_WITH_VIRTIO
1857 PCFGMNODE pDevVirtioNet = NULL; /* Virtio network devices */
1858 InsertConfigNode(pDevices, "virtio-net", &pDevVirtioNet);
1859#endif /* VBOX_WITH_VIRTIO */
1860 std::list<BootNic> llBootNics;
1861 for (ULONG ulInstance = 0; ulInstance < maxNetworkAdapters; ++ulInstance)
1862 {
1863 ComPtr<INetworkAdapter> networkAdapter;
1864 hrc = pMachine->GetNetworkAdapter(ulInstance, networkAdapter.asOutParam()); H();
1865 BOOL fEnabledNetAdapter = FALSE;
1866 hrc = networkAdapter->COMGETTER(Enabled)(&fEnabledNetAdapter); H();
1867 if (!fEnabledNetAdapter)
1868 continue;
1869
1870 /*
1871 * The virtual hardware type. Create appropriate device first.
1872 */
1873 const char *pszAdapterName = "pcnet";
1874 NetworkAdapterType_T adapterType;
1875 hrc = networkAdapter->COMGETTER(AdapterType)(&adapterType); H();
1876 switch (adapterType)
1877 {
1878 case NetworkAdapterType_Am79C970A:
1879 case NetworkAdapterType_Am79C973:
1880 pDev = pDevPCNet;
1881 break;
1882#ifdef VBOX_WITH_E1000
1883 case NetworkAdapterType_I82540EM:
1884 case NetworkAdapterType_I82543GC:
1885 case NetworkAdapterType_I82545EM:
1886 pDev = pDevE1000;
1887 pszAdapterName = "e1000";
1888 break;
1889#endif
1890#ifdef VBOX_WITH_VIRTIO
1891 case NetworkAdapterType_Virtio:
1892 pDev = pDevVirtioNet;
1893 pszAdapterName = "virtio-net";
1894 break;
1895#endif /* VBOX_WITH_VIRTIO */
1896 default:
1897 AssertMsgFailed(("Invalid network adapter type '%d' for slot '%d'",
1898 adapterType, ulInstance));
1899 return VMR3SetError(pUVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
1900 N_("Invalid network adapter type '%d' for slot '%d'"),
1901 adapterType, ulInstance);
1902 }
1903
1904 InsertConfigNode(pDev, Utf8StrFmt("%u", ulInstance).c_str(), &pInst);
1905 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1906 /* the first network card gets the PCI ID 3, the next 3 gets 8..10,
1907 * next 4 get 16..19. */
1908 int iPCIDeviceNo;
1909 switch (ulInstance)
1910 {
1911 case 0:
1912 iPCIDeviceNo = 3;
1913 break;
1914 case 1: case 2: case 3:
1915 iPCIDeviceNo = ulInstance - 1 + 8;
1916 break;
1917 case 4: case 5: case 6: case 7:
1918 iPCIDeviceNo = ulInstance - 4 + 16;
1919 break;
1920 default:
1921 /* auto assignment */
1922 iPCIDeviceNo = -1;
1923 break;
1924 }
1925#ifdef VMWARE_NET_IN_SLOT_11
1926 /*
1927 * Dirty hack for PCI slot compatibility with VMWare,
1928 * it assigns slot 0x11 to the first network controller.
1929 */
1930 if (iPCIDeviceNo == 3 && adapterType == NetworkAdapterType_I82545EM)
1931 {
1932 iPCIDeviceNo = 0x11;
1933 fSwapSlots3and11 = true;
1934 }
1935 else if (iPCIDeviceNo == 0x11 && fSwapSlots3and11)
1936 iPCIDeviceNo = 3;
1937#endif
1938 PCIBusAddress PCIAddr = PCIBusAddress(0, iPCIDeviceNo, 0);
1939 hrc = pBusMgr->assignPCIDevice(pszAdapterName, pInst, PCIAddr); H();
1940
1941 InsertConfigNode(pInst, "Config", &pCfg);
1942#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE /* not safe here yet. */ /** @todo Make PCNet ring-0 safe on 32-bit mac kernels! */
1943 if (pDev == pDevPCNet)
1944 {
1945 InsertConfigInteger(pCfg, "R0Enabled", false);
1946 }
1947#endif
1948 /*
1949 * Collect information needed for network booting and add it to the list.
1950 */
1951 BootNic nic;
1952
1953 nic.mInstance = ulInstance;
1954 /* Could be updated by reference, if auto assigned */
1955 nic.mPCIAddress = PCIAddr;
1956
1957 hrc = networkAdapter->COMGETTER(BootPriority)(&nic.mBootPrio); H();
1958
1959 llBootNics.push_back(nic);
1960
1961 /*
1962 * The virtual hardware type. PCNet supports two types.
1963 */
1964 switch (adapterType)
1965 {
1966 case NetworkAdapterType_Am79C970A:
1967 InsertConfigInteger(pCfg, "Am79C973", 0);
1968 break;
1969 case NetworkAdapterType_Am79C973:
1970 InsertConfigInteger(pCfg, "Am79C973", 1);
1971 break;
1972 case NetworkAdapterType_I82540EM:
1973 InsertConfigInteger(pCfg, "AdapterType", 0);
1974 break;
1975 case NetworkAdapterType_I82543GC:
1976 InsertConfigInteger(pCfg, "AdapterType", 1);
1977 break;
1978 case NetworkAdapterType_I82545EM:
1979 InsertConfigInteger(pCfg, "AdapterType", 2);
1980 break;
1981 }
1982
1983 /*
1984 * Get the MAC address and convert it to binary representation
1985 */
1986 Bstr macAddr;
1987 hrc = networkAdapter->COMGETTER(MACAddress)(macAddr.asOutParam()); H();
1988 Assert(!macAddr.isEmpty());
1989 Utf8Str macAddrUtf8 = macAddr;
1990 char *macStr = (char*)macAddrUtf8.c_str();
1991 Assert(strlen(macStr) == 12);
1992 RTMAC Mac;
1993 RT_ZERO(Mac);
1994 char *pMac = (char*)&Mac;
1995 for (uint32_t i = 0; i < 6; ++i)
1996 {
1997 char c1 = *macStr++ - '0';
1998 if (c1 > 9)
1999 c1 -= 7;
2000 char c2 = *macStr++ - '0';
2001 if (c2 > 9)
2002 c2 -= 7;
2003 *pMac++ = ((c1 & 0x0f) << 4) | (c2 & 0x0f);
2004 }
2005 InsertConfigBytes(pCfg, "MAC", &Mac, sizeof(Mac));
2006
2007 /*
2008 * Check if the cable is supposed to be unplugged
2009 */
2010 BOOL fCableConnected;
2011 hrc = networkAdapter->COMGETTER(CableConnected)(&fCableConnected); H();
2012 InsertConfigInteger(pCfg, "CableConnected", fCableConnected ? 1 : 0);
2013
2014 /*
2015 * Line speed to report from custom drivers
2016 */
2017 ULONG ulLineSpeed;
2018 hrc = networkAdapter->COMGETTER(LineSpeed)(&ulLineSpeed); H();
2019 InsertConfigInteger(pCfg, "LineSpeed", ulLineSpeed);
2020
2021 /*
2022 * Attach the status driver.
2023 */
2024 attachStatusDriver(pInst, &mapNetworkLeds[ulInstance], 0, 0, NULL, NULL, 0);
2025
2026 /*
2027 * Configure the network card now
2028 */
2029 bool fIgnoreConnectFailure = mMachineState == MachineState_Restoring;
2030 rc = configNetwork(pszAdapterName,
2031 ulInstance,
2032 0,
2033 networkAdapter,
2034 pCfg,
2035 pLunL0,
2036 pInst,
2037 false /*fAttachDetach*/,
2038 fIgnoreConnectFailure);
2039 if (RT_FAILURE(rc))
2040 return rc;
2041 }
2042
2043 /*
2044 * Build network boot information and transfer it to the BIOS.
2045 */
2046 if (pNetBootCfg && !llBootNics.empty()) /* NetBoot node doesn't exist for EFI! */
2047 {
2048 llBootNics.sort(); /* Sort the list by boot priority. */
2049
2050 char achBootIdx[] = "0";
2051 unsigned uBootIdx = 0;
2052
2053 for (std::list<BootNic>::iterator it = llBootNics.begin(); it != llBootNics.end(); ++it)
2054 {
2055 /* A NIC with priority 0 is only used if it's first in the list. */
2056 if (it->mBootPrio == 0 && uBootIdx != 0)
2057 break;
2058
2059 PCFGMNODE pNetBtDevCfg;
2060 achBootIdx[0] = '0' + uBootIdx++; /* Boot device order. */
2061 InsertConfigNode(pNetBootCfg, achBootIdx, &pNetBtDevCfg);
2062 InsertConfigInteger(pNetBtDevCfg, "NIC", it->mInstance);
2063 InsertConfigInteger(pNetBtDevCfg, "PCIBusNo", it->mPCIAddress.miBus);
2064 InsertConfigInteger(pNetBtDevCfg, "PCIDeviceNo", it->mPCIAddress.miDevice);
2065 InsertConfigInteger(pNetBtDevCfg, "PCIFunctionNo", it->mPCIAddress.miFn);
2066 }
2067 }
2068
2069 /*
2070 * Serial (UART) Ports
2071 */
2072 /* serial enabled mask to be passed to dev ACPI */
2073 uint16_t auSerialIoPortBase[SchemaDefs::SerialPortCount] = {0};
2074 uint8_t auSerialIrq[SchemaDefs::SerialPortCount] = {0};
2075 InsertConfigNode(pDevices, "serial", &pDev);
2076 for (ULONG ulInstance = 0; ulInstance < SchemaDefs::SerialPortCount; ++ulInstance)
2077 {
2078 ComPtr<ISerialPort> serialPort;
2079 hrc = pMachine->GetSerialPort(ulInstance, serialPort.asOutParam()); H();
2080 BOOL fEnabledSerPort = FALSE;
2081 if (serialPort)
2082 hrc = serialPort->COMGETTER(Enabled)(&fEnabledSerPort); H();
2083 if (!fEnabledSerPort)
2084 continue;
2085
2086 InsertConfigNode(pDev, Utf8StrFmt("%u", ulInstance).c_str(), &pInst);
2087 InsertConfigNode(pInst, "Config", &pCfg);
2088
2089 ULONG ulIRQ;
2090 hrc = serialPort->COMGETTER(IRQ)(&ulIRQ); H();
2091 InsertConfigInteger(pCfg, "IRQ", ulIRQ);
2092 auSerialIrq[ulInstance] = (uint8_t)ulIRQ;
2093
2094 ULONG ulIOBase;
2095 hrc = serialPort->COMGETTER(IOBase)(&ulIOBase); H();
2096 InsertConfigInteger(pCfg, "IOBase", ulIOBase);
2097 auSerialIoPortBase[ulInstance] = (uint16_t)ulIOBase;
2098
2099 BOOL fServer;
2100 hrc = serialPort->COMGETTER(Server)(&fServer); H();
2101 hrc = serialPort->COMGETTER(Path)(bstr.asOutParam()); H();
2102 PortMode_T eHostMode;
2103 hrc = serialPort->COMGETTER(HostMode)(&eHostMode); H();
2104 if (eHostMode != PortMode_Disconnected)
2105 {
2106 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2107 if (eHostMode == PortMode_HostPipe)
2108 {
2109 InsertConfigString(pLunL0, "Driver", "Char");
2110 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2111 InsertConfigString(pLunL1, "Driver", "NamedPipe");
2112 InsertConfigNode(pLunL1, "Config", &pLunL2);
2113 InsertConfigString(pLunL2, "Location", bstr);
2114 InsertConfigInteger(pLunL2, "IsServer", fServer);
2115 }
2116 else if (eHostMode == PortMode_HostDevice)
2117 {
2118 InsertConfigString(pLunL0, "Driver", "Host Serial");
2119 InsertConfigNode(pLunL0, "Config", &pLunL1);
2120 InsertConfigString(pLunL1, "DevicePath", bstr);
2121 }
2122 else if (eHostMode == PortMode_RawFile)
2123 {
2124 InsertConfigString(pLunL0, "Driver", "Char");
2125 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2126 InsertConfigString(pLunL1, "Driver", "RawFile");
2127 InsertConfigNode(pLunL1, "Config", &pLunL2);
2128 InsertConfigString(pLunL2, "Location", bstr);
2129 }
2130 }
2131 }
2132
2133 /*
2134 * Parallel (LPT) Ports
2135 */
2136 InsertConfigNode(pDevices, "parallel", &pDev);
2137 for (ULONG ulInstance = 0; ulInstance < SchemaDefs::ParallelPortCount; ++ulInstance)
2138 {
2139 ComPtr<IParallelPort> parallelPort;
2140 hrc = pMachine->GetParallelPort(ulInstance, parallelPort.asOutParam()); H();
2141 BOOL fEnabledParPort = FALSE;
2142 if (parallelPort)
2143 {
2144 hrc = parallelPort->COMGETTER(Enabled)(&fEnabledParPort); H();
2145 }
2146 if (!fEnabledParPort)
2147 continue;
2148
2149 InsertConfigNode(pDev, Utf8StrFmt("%u", ulInstance).c_str(), &pInst);
2150 InsertConfigNode(pInst, "Config", &pCfg);
2151
2152 ULONG ulIRQ;
2153 hrc = parallelPort->COMGETTER(IRQ)(&ulIRQ); H();
2154 InsertConfigInteger(pCfg, "IRQ", ulIRQ);
2155 ULONG ulIOBase;
2156 hrc = parallelPort->COMGETTER(IOBase)(&ulIOBase); H();
2157 InsertConfigInteger(pCfg, "IOBase", ulIOBase);
2158 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2159 InsertConfigString(pLunL0, "Driver", "HostParallel");
2160 InsertConfigNode(pLunL0, "Config", &pLunL1);
2161 hrc = parallelPort->COMGETTER(Path)(bstr.asOutParam()); H();
2162 InsertConfigString(pLunL1, "DevicePath", bstr);
2163 }
2164
2165 /*
2166 * VMM Device
2167 */
2168 InsertConfigNode(pDevices, "VMMDev", &pDev);
2169 InsertConfigNode(pDev, "0", &pInst);
2170 InsertConfigNode(pInst, "Config", &pCfg);
2171 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2172 hrc = pBusMgr->assignPCIDevice("VMMDev", pInst); H();
2173
2174 Bstr hwVersion;
2175 hrc = pMachine->COMGETTER(HardwareVersion)(hwVersion.asOutParam()); H();
2176 InsertConfigInteger(pCfg, "RamSize", cbRam);
2177 if (hwVersion.compare(Bstr("1").raw()) == 0) /* <= 2.0.x */
2178 InsertConfigInteger(pCfg, "HeapEnabled", 0);
2179 Bstr snapshotFolder;
2180 hrc = pMachine->COMGETTER(SnapshotFolder)(snapshotFolder.asOutParam()); H();
2181 InsertConfigString(pCfg, "GuestCoreDumpDir", snapshotFolder);
2182
2183 /* the VMM device's Main driver */
2184 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2185 InsertConfigString(pLunL0, "Driver", "HGCM");
2186 InsertConfigNode(pLunL0, "Config", &pCfg);
2187 InsertConfigInteger(pCfg, "Object", (uintptr_t)pVMMDev);
2188
2189 /*
2190 * Attach the status driver.
2191 */
2192 attachStatusDriver(pInst, &mapSharedFolderLed, 0, 0, NULL, NULL, 0);
2193
2194 /*
2195 * Audio Sniffer Device
2196 */
2197 InsertConfigNode(pDevices, "AudioSniffer", &pDev);
2198 InsertConfigNode(pDev, "0", &pInst);
2199 InsertConfigNode(pInst, "Config", &pCfg);
2200
2201 /* the Audio Sniffer device's Main driver */
2202 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2203 InsertConfigString(pLunL0, "Driver", "MainAudioSniffer");
2204 InsertConfigNode(pLunL0, "Config", &pCfg);
2205 AudioSniffer *pAudioSniffer = mAudioSniffer;
2206 InsertConfigInteger(pCfg, "Object", (uintptr_t)pAudioSniffer);
2207
2208 /*
2209 * AC'97 ICH / SoundBlaster16 audio / Intel HD Audio
2210 */
2211 BOOL fAudioEnabled = FALSE;
2212 ComPtr<IAudioAdapter> audioAdapter;
2213 hrc = pMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam()); H();
2214 if (audioAdapter)
2215 hrc = audioAdapter->COMGETTER(Enabled)(&fAudioEnabled); H();
2216
2217 if (fAudioEnabled)
2218 {
2219 AudioControllerType_T audioController;
2220 hrc = audioAdapter->COMGETTER(AudioController)(&audioController); H();
2221 switch (audioController)
2222 {
2223 case AudioControllerType_AC97:
2224 {
2225 /* default: ICH AC97 */
2226 InsertConfigNode(pDevices, "ichac97", &pDev);
2227 InsertConfigNode(pDev, "0", &pInst);
2228 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2229 hrc = pBusMgr->assignPCIDevice("ichac97", pInst); H();
2230 InsertConfigNode(pInst, "Config", &pCfg);
2231 break;
2232 }
2233 case AudioControllerType_SB16:
2234 {
2235 /* legacy SoundBlaster16 */
2236 InsertConfigNode(pDevices, "sb16", &pDev);
2237 InsertConfigNode(pDev, "0", &pInst);
2238 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2239 InsertConfigNode(pInst, "Config", &pCfg);
2240 InsertConfigInteger(pCfg, "IRQ", 5);
2241 InsertConfigInteger(pCfg, "DMA", 1);
2242 InsertConfigInteger(pCfg, "DMA16", 5);
2243 InsertConfigInteger(pCfg, "Port", 0x220);
2244 InsertConfigInteger(pCfg, "Version", 0x0405);
2245 break;
2246 }
2247 case AudioControllerType_HDA:
2248 {
2249 /* Intel HD Audio */
2250 InsertConfigNode(pDevices, "hda", &pDev);
2251 InsertConfigNode(pDev, "0", &pInst);
2252 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2253 hrc = pBusMgr->assignPCIDevice("hda", pInst); H();
2254 InsertConfigNode(pInst, "Config", &pCfg);
2255 }
2256 }
2257
2258 /* the Audio driver */
2259 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2260 InsertConfigString(pLunL0, "Driver", "AUDIO");
2261 InsertConfigNode(pLunL0, "Config", &pCfg);
2262
2263 AudioDriverType_T audioDriver;
2264 hrc = audioAdapter->COMGETTER(AudioDriver)(&audioDriver); H();
2265 switch (audioDriver)
2266 {
2267 case AudioDriverType_Null:
2268 {
2269 InsertConfigString(pCfg, "AudioDriver", "null");
2270 break;
2271 }
2272#ifdef RT_OS_WINDOWS
2273#ifdef VBOX_WITH_WINMM
2274 case AudioDriverType_WinMM:
2275 {
2276 InsertConfigString(pCfg, "AudioDriver", "winmm");
2277 break;
2278 }
2279#endif
2280 case AudioDriverType_DirectSound:
2281 {
2282 InsertConfigString(pCfg, "AudioDriver", "dsound");
2283 break;
2284 }
2285#endif /* RT_OS_WINDOWS */
2286#ifdef RT_OS_SOLARIS
2287 case AudioDriverType_SolAudio:
2288 {
2289 InsertConfigString(pCfg, "AudioDriver", "solaudio");
2290 break;
2291 }
2292#endif
2293#ifdef RT_OS_LINUX
2294# ifdef VBOX_WITH_ALSA
2295 case AudioDriverType_ALSA:
2296 {
2297 InsertConfigString(pCfg, "AudioDriver", "alsa");
2298 break;
2299 }
2300# endif
2301# ifdef VBOX_WITH_PULSE
2302 case AudioDriverType_Pulse:
2303 {
2304 InsertConfigString(pCfg, "AudioDriver", "pulse");
2305 break;
2306 }
2307# endif
2308#endif /* RT_OS_LINUX */
2309#if defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD) || defined(VBOX_WITH_SOLARIS_OSS)
2310 case AudioDriverType_OSS:
2311 {
2312 InsertConfigString(pCfg, "AudioDriver", "oss");
2313 break;
2314 }
2315#endif
2316#ifdef RT_OS_FREEBSD
2317# ifdef VBOX_WITH_PULSE
2318 case AudioDriverType_Pulse:
2319 {
2320 InsertConfigString(pCfg, "AudioDriver", "pulse");
2321 break;
2322 }
2323# endif
2324#endif
2325#ifdef RT_OS_DARWIN
2326 case AudioDriverType_CoreAudio:
2327 {
2328 InsertConfigString(pCfg, "AudioDriver", "coreaudio");
2329 break;
2330 }
2331#endif
2332 }
2333 hrc = pMachine->COMGETTER(Name)(bstr.asOutParam()); H();
2334 InsertConfigString(pCfg, "StreamName", bstr);
2335 }
2336
2337 /*
2338 * The USB Controllers.
2339 */
2340 com::SafeIfaceArray<IUSBController> usbCtrls;
2341 hrc = pMachine->COMGETTER(USBControllers)(ComSafeArrayAsOutParam(usbCtrls)); H();
2342 bool fOhciPresent = false; /**< Flag whether at least one OHCI controller is presnet. */
2343
2344 for (size_t i = 0; i < usbCtrls.size(); ++i)
2345 {
2346 USBControllerType_T enmCtrlType;
2347 rc = usbCtrls[i]->COMGETTER(Type)(&enmCtrlType); H();
2348 if (enmCtrlType == USBControllerType_OHCI)
2349 {
2350 fOhciPresent = true;
2351 break;
2352 }
2353 }
2354
2355 /*
2356 * Currently EHCI is only enabled when a OHCI controller is present too.
2357 * This might change when XHCI is supported.
2358 */
2359 if (fOhciPresent)
2360 mfVMHasUsbController = true;
2361
2362 if (mfVMHasUsbController)
2363 {
2364 for (size_t i = 0; i < usbCtrls.size(); ++i)
2365 {
2366 USBControllerType_T enmCtrlType;
2367 rc = usbCtrls[i]->COMGETTER(Type)(&enmCtrlType); H();
2368
2369 if (enmCtrlType == USBControllerType_OHCI)
2370 {
2371 InsertConfigNode(pDevices, "usb-ohci", &pDev);
2372 InsertConfigNode(pDev, "0", &pInst);
2373 InsertConfigNode(pInst, "Config", &pCfg);
2374 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2375 hrc = pBusMgr->assignPCIDevice("usb-ohci", pInst); H();
2376 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2377 InsertConfigString(pLunL0, "Driver", "VUSBRootHub");
2378 InsertConfigNode(pLunL0, "Config", &pCfg);
2379
2380 /*
2381 * Attach the status driver.
2382 */
2383 attachStatusDriver(pInst, &mapUSBLed[0], 0, 0, NULL, NULL, 0);
2384 }
2385#ifdef VBOX_WITH_EHCI
2386 else if (enmCtrlType == USBControllerType_EHCI)
2387 {
2388 /*
2389 * USB 2.0 is only available if the proper ExtPack is installed.
2390 *
2391 * Note. Configuring EHCI here and providing messages about
2392 * the missing extpack isn't exactly clean, but it is a
2393 * necessary evil to patch over legacy compatability issues
2394 * introduced by the new distribution model.
2395 */
2396 static const char *s_pszUsbExtPackName = "Oracle VM VirtualBox Extension Pack";
2397# ifdef VBOX_WITH_EXTPACK
2398 if (mptrExtPackManager->isExtPackUsable(s_pszUsbExtPackName))
2399# endif
2400 {
2401 InsertConfigNode(pDevices, "usb-ehci", &pDev);
2402 InsertConfigNode(pDev, "0", &pInst);
2403 InsertConfigNode(pInst, "Config", &pCfg);
2404 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2405 hrc = pBusMgr->assignPCIDevice("usb-ehci", pInst); H();
2406
2407 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2408 InsertConfigString(pLunL0, "Driver", "VUSBRootHub");
2409 InsertConfigNode(pLunL0, "Config", &pCfg);
2410
2411 /*
2412 * Attach the status driver.
2413 */
2414 attachStatusDriver(pInst, &mapUSBLed[1], 0, 0, NULL, NULL, 0);
2415 }
2416# ifdef VBOX_WITH_EXTPACK
2417 else
2418 {
2419 /* Always fatal! Up to VBox 4.0.4 we allowed to start the VM anyway
2420 * but this induced problems when the user saved + restored the VM! */
2421 return VMR3SetError(pUVM, VERR_NOT_FOUND, RT_SRC_POS,
2422 N_("Implementation of the USB 2.0 controller not found!\n"
2423 "Because the USB 2.0 controller state is part of the saved "
2424 "VM state, the VM cannot be started. To fix "
2425 "this problem, either install the '%s' or disable USB 2.0 "
2426 "support in the VM settings"),
2427 s_pszUsbExtPackName);
2428 }
2429# endif
2430 }
2431#endif
2432 } /* for every USB controller. */
2433
2434
2435 /*
2436 * Virtual USB Devices.
2437 */
2438 PCFGMNODE pUsbDevices = NULL;
2439 InsertConfigNode(pRoot, "USB", &pUsbDevices);
2440
2441#ifdef VBOX_WITH_USB
2442 {
2443 /*
2444 * Global USB options, currently unused as we'll apply the 2.0 -> 1.1 morphing
2445 * on a per device level now.
2446 */
2447 InsertConfigNode(pUsbDevices, "USBProxy", &pCfg);
2448 InsertConfigNode(pCfg, "GlobalConfig", &pCfg);
2449 // This globally enables the 2.0 -> 1.1 device morphing of proxied devices to keep windows quiet.
2450 //InsertConfigInteger(pCfg, "Force11Device", true);
2451 // The following breaks stuff, but it makes MSDs work in vista. (I include it here so
2452 // that it's documented somewhere.) Users needing it can use:
2453 // VBoxManage setextradata "myvm" "VBoxInternal/USB/USBProxy/GlobalConfig/Force11PacketSize" 1
2454 //InsertConfigInteger(pCfg, "Force11PacketSize", true);
2455 }
2456#endif
2457
2458#ifdef VBOX_WITH_USB_CARDREADER
2459 BOOL aEmulatedUSBCardReaderEnabled = FALSE;
2460 hrc = pMachine->COMGETTER(EmulatedUSBCardReaderEnabled)(&aEmulatedUSBCardReaderEnabled); H();
2461 if (aEmulatedUSBCardReaderEnabled)
2462 {
2463 InsertConfigNode(pUsbDevices, "CardReader", &pDev);
2464 InsertConfigNode(pDev, "0", &pInst);
2465 InsertConfigNode(pInst, "Config", &pCfg);
2466
2467 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2468# ifdef VBOX_WITH_USB_CARDREADER_TEST
2469 InsertConfigString(pLunL0, "Driver", "DrvDirectCardReader");
2470 InsertConfigNode(pLunL0, "Config", &pCfg);
2471# else
2472 InsertConfigString(pLunL0, "Driver", "UsbCardReader");
2473 InsertConfigNode(pLunL0, "Config", &pCfg);
2474 InsertConfigInteger(pCfg, "Object", (uintptr_t)mUsbCardReader);
2475# endif
2476 }
2477#endif
2478
2479# if 0 /* Virtual MSD*/
2480 InsertConfigNode(pUsbDevices, "Msd", &pDev);
2481 InsertConfigNode(pDev, "0", &pInst);
2482 InsertConfigNode(pInst, "Config", &pCfg);
2483 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2484
2485 InsertConfigString(pLunL0, "Driver", "SCSI");
2486 InsertConfigNode(pLunL0, "Config", &pCfg);
2487
2488 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2489 InsertConfigString(pLunL1, "Driver", "Block");
2490 InsertConfigNode(pLunL1, "Config", &pCfg);
2491 InsertConfigString(pCfg, "Type", "HardDisk");
2492 InsertConfigInteger(pCfg, "Mountable", 0);
2493
2494 InsertConfigNode(pLunL1, "AttachedDriver", &pLunL2);
2495 InsertConfigString(pLunL2, "Driver", "VD");
2496 InsertConfigNode(pLunL2, "Config", &pCfg);
2497 InsertConfigString(pCfg, "Path", "/Volumes/DataHFS/bird/VDIs/linux.vdi");
2498 InsertConfigString(pCfg, "Format", "VDI");
2499# endif
2500
2501 /* Virtual USB Mouse/Tablet */
2502 if ( aPointingHID == PointingHIDType_USBMouse
2503 || aPointingHID == PointingHIDType_ComboMouse
2504 || aPointingHID == PointingHIDType_USBTablet
2505 || aPointingHID == PointingHIDType_USBMultiTouch)
2506 InsertConfigNode(pUsbDevices, "HidMouse", &pDev);
2507 if (aPointingHID == PointingHIDType_USBMouse)
2508 {
2509 InsertConfigNode(pDev, "0", &pInst);
2510 InsertConfigNode(pInst, "Config", &pCfg);
2511
2512 InsertConfigString(pCfg, "Mode", "relative");
2513 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2514 InsertConfigString(pLunL0, "Driver", "MouseQueue");
2515 InsertConfigNode(pLunL0, "Config", &pCfg);
2516 InsertConfigInteger(pCfg, "QueueSize", 128);
2517
2518 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2519 InsertConfigString(pLunL1, "Driver", "MainMouse");
2520 InsertConfigNode(pLunL1, "Config", &pCfg);
2521 InsertConfigInteger(pCfg, "Object", (uintptr_t)pMouse);
2522 }
2523 if ( aPointingHID == PointingHIDType_USBTablet
2524 || aPointingHID == PointingHIDType_USBMultiTouch)
2525 {
2526 InsertConfigNode(pDev, "1", &pInst);
2527 InsertConfigNode(pInst, "Config", &pCfg);
2528
2529 InsertConfigString(pCfg, "Mode", "absolute");
2530 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2531 InsertConfigString(pLunL0, "Driver", "MouseQueue");
2532 InsertConfigNode(pLunL0, "Config", &pCfg);
2533 InsertConfigInteger(pCfg, "QueueSize", 128);
2534
2535 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2536 InsertConfigString(pLunL1, "Driver", "MainMouse");
2537 InsertConfigNode(pLunL1, "Config", &pCfg);
2538 InsertConfigInteger(pCfg, "Object", (uintptr_t)pMouse);
2539 }
2540 if (aPointingHID == PointingHIDType_USBMultiTouch)
2541 {
2542 InsertConfigNode(pDev, "2", &pInst);
2543 InsertConfigNode(pInst, "Config", &pCfg);
2544
2545 InsertConfigString(pCfg, "Mode", "multitouch");
2546 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2547 InsertConfigString(pLunL0, "Driver", "MouseQueue");
2548 InsertConfigNode(pLunL0, "Config", &pCfg);
2549 InsertConfigInteger(pCfg, "QueueSize", 128);
2550
2551 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2552 InsertConfigString(pLunL1, "Driver", "MainMouse");
2553 InsertConfigNode(pLunL1, "Config", &pCfg);
2554 InsertConfigInteger(pCfg, "Object", (uintptr_t)pMouse);
2555 }
2556
2557 /* Virtual USB Keyboard */
2558 KeyboardHIDType_T aKbdHID;
2559 hrc = pMachine->COMGETTER(KeyboardHIDType)(&aKbdHID); H();
2560 if (aKbdHID == KeyboardHIDType_USBKeyboard)
2561 {
2562 InsertConfigNode(pUsbDevices, "HidKeyboard", &pDev);
2563 InsertConfigNode(pDev, "0", &pInst);
2564 InsertConfigNode(pInst, "Config", &pCfg);
2565
2566 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2567 InsertConfigString(pLunL0, "Driver", "KeyboardQueue");
2568 InsertConfigNode(pLunL0, "Config", &pCfg);
2569 InsertConfigInteger(pCfg, "QueueSize", 64);
2570
2571 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2572 InsertConfigString(pLunL1, "Driver", "MainKeyboard");
2573 InsertConfigNode(pLunL1, "Config", &pCfg);
2574 pKeyboard = mKeyboard;
2575 InsertConfigInteger(pCfg, "Object", (uintptr_t)pKeyboard);
2576 }
2577 }
2578
2579 /*
2580 * Clipboard
2581 */
2582 {
2583 ClipboardMode_T mode = ClipboardMode_Disabled;
2584 hrc = pMachine->COMGETTER(ClipboardMode)(&mode); H();
2585
2586 if (/* mode != ClipboardMode_Disabled */ true)
2587 {
2588 /* Load the service */
2589 rc = pVMMDev->hgcmLoadService("VBoxSharedClipboard", "VBoxSharedClipboard");
2590
2591 if (RT_FAILURE(rc))
2592 {
2593 LogRel(("VBoxSharedClipboard is not available. rc = %Rrc\n", rc));
2594 /* That is not a fatal failure. */
2595 rc = VINF_SUCCESS;
2596 }
2597 else
2598 {
2599 changeClipboardMode(mode);
2600
2601 /* Setup the service. */
2602 VBOXHGCMSVCPARM parm;
2603 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
2604 parm.setUInt32(!useHostClipboard());
2605 pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_HEADLESS, 1, &parm);
2606
2607 Log(("Set VBoxSharedClipboard mode\n"));
2608 }
2609 }
2610 }
2611
2612 /*
2613 * HGCM HostChannel
2614 */
2615 {
2616 Bstr value;
2617 hrc = pMachine->GetExtraData(Bstr("HGCM/HostChannel").raw(),
2618 value.asOutParam());
2619
2620 if ( hrc == S_OK
2621 && value == "1")
2622 {
2623 rc = pVMMDev->hgcmLoadService("VBoxHostChannel", "VBoxHostChannel");
2624
2625 if (RT_FAILURE(rc))
2626 {
2627 LogRel(("VBoxHostChannel is not available. rc = %Rrc\n", rc));
2628 /* That is not a fatal failure. */
2629 rc = VINF_SUCCESS;
2630 }
2631 }
2632 }
2633
2634#ifdef VBOX_WITH_DRAG_AND_DROP
2635 /*
2636 * Drag & Drop
2637 */
2638 {
2639 DragAndDropMode_T mode = DragAndDropMode_Disabled;
2640 hrc = pMachine->COMGETTER(DragAndDropMode)(&mode); H();
2641
2642 /* Load the service */
2643 rc = pVMMDev->hgcmLoadService("VBoxDragAndDropSvc", "VBoxDragAndDropSvc");
2644
2645 if (RT_FAILURE(rc))
2646 {
2647 LogRel(("VBoxDragAndDropService is not available. rc = %Rrc\n", rc));
2648 /* That is not a fatal failure. */
2649 rc = VINF_SUCCESS;
2650 }
2651 else
2652 {
2653 HGCMSVCEXTHANDLE hDummy;
2654 rc = HGCMHostRegisterServiceExtension(&hDummy, "VBoxDragAndDropSvc",
2655 &GuestDnD::notifyGuestDragAndDropEvent,
2656 getGuest());
2657 if (RT_FAILURE(rc))
2658 Log(("Cannot register VBoxDragAndDropSvc extension!\n"));
2659 else
2660 {
2661 changeDragAndDropMode(mode);
2662 Log(("VBoxDragAndDropSvc loaded\n"));
2663 }
2664 }
2665 }
2666#endif /* VBOX_WITH_DRAG_AND_DROP */
2667
2668#ifdef VBOX_WITH_CROGL
2669 /*
2670 * crOpenGL
2671 */
2672 {
2673 BOOL fEnabled3D = false;
2674 hrc = pMachine->COMGETTER(Accelerate3DEnabled)(&fEnabled3D); H();
2675
2676 if (fEnabled3D)
2677 {
2678 BOOL fSupports3D = VBoxOglIs3DAccelerationSupported();
2679 if (!fSupports3D)
2680 return VMR3SetError(pUVM, VERR_NOT_AVAILABLE, RT_SRC_POS,
2681 N_("This VM was configured to use 3D acceleration. However, the "
2682 "3D support of the host is not working properly and the "
2683 "VM cannot be started. To fix this problem, either "
2684 "fix the host 3D support (update the host graphics driver?) "
2685 "or disable 3D acceleration in the VM settings"));
2686
2687 /* Load the service */
2688 rc = pVMMDev->hgcmLoadService("VBoxSharedCrOpenGL", "VBoxSharedCrOpenGL");
2689 if (RT_FAILURE(rc))
2690 {
2691 LogRel(("Failed to load Shared OpenGL service %Rrc\n", rc));
2692 /* That is not a fatal failure. */
2693 rc = VINF_SUCCESS;
2694 }
2695 else
2696 {
2697 LogRel(("Shared crOpenGL service loaded.\n"));
2698
2699 /* Setup the service. */
2700 VBOXHGCMSVCPARM parm;
2701 parm.type = VBOX_HGCM_SVC_PARM_PTR;
2702
2703 parm.u.pointer.addr = (IConsole *)(Console *)this;
2704 parm.u.pointer.size = sizeof(IConsole *);
2705
2706 rc = pVMMDev->hgcmHostCall("VBoxSharedCrOpenGL", SHCRGL_HOST_FN_SET_CONSOLE, SHCRGL_CPARMS_SET_CONSOLE, &parm);
2707 if (!RT_SUCCESS(rc))
2708 AssertMsgFailed(("SHCRGL_HOST_FN_SET_CONSOLE failed with %Rrc\n", rc));
2709
2710 parm.u.pointer.addr = pVM;
2711 parm.u.pointer.size = sizeof(pVM);
2712 rc = pVMMDev->hgcmHostCall("VBoxSharedCrOpenGL", SHCRGL_HOST_FN_SET_VM, SHCRGL_CPARMS_SET_VM, &parm);
2713 if (!RT_SUCCESS(rc))
2714 AssertMsgFailed(("SHCRGL_HOST_FN_SET_VM failed with %Rrc\n", rc));
2715 }
2716
2717 }
2718 }
2719#endif
2720
2721#ifdef VBOX_WITH_GUEST_PROPS
2722 /*
2723 * Guest property service
2724 */
2725
2726 rc = configGuestProperties(this, pUVM);
2727#endif /* VBOX_WITH_GUEST_PROPS defined */
2728
2729#ifdef VBOX_WITH_GUEST_CONTROL
2730 /*
2731 * Guest control service
2732 */
2733
2734 rc = configGuestControl(this);
2735#endif /* VBOX_WITH_GUEST_CONTROL defined */
2736
2737 /*
2738 * ACPI
2739 */
2740 BOOL fACPI;
2741 hrc = biosSettings->COMGETTER(ACPIEnabled)(&fACPI); H();
2742 if (fACPI)
2743 {
2744 /* Always show the CPU leafs when we have multiple VCPUs or when the IO-APIC is enabled.
2745 * The Windows SMP kernel needs a CPU leaf or else its idle loop will burn cpu cycles; the
2746 * intelppm driver refuses to register an idle state handler.
2747 * Always show CPU leafs for OS X guests. */
2748 BOOL fShowCpu = fOsXGuest;
2749 if (cCpus > 1 || fIOAPIC)
2750 fShowCpu = true;
2751
2752 BOOL fCpuHotPlug;
2753 hrc = pMachine->COMGETTER(CPUHotPlugEnabled)(&fCpuHotPlug); H();
2754
2755 InsertConfigNode(pDevices, "acpi", &pDev);
2756 InsertConfigNode(pDev, "0", &pInst);
2757 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2758 InsertConfigNode(pInst, "Config", &pCfg);
2759 hrc = pBusMgr->assignPCIDevice("acpi", pInst); H();
2760
2761 InsertConfigInteger(pCfg, "RamSize", cbRam);
2762 InsertConfigInteger(pCfg, "RamHoleSize", cbRamHole);
2763 InsertConfigInteger(pCfg, "NumCPUs", cCpus);
2764
2765 InsertConfigInteger(pCfg, "IOAPIC", fIOAPIC);
2766 InsertConfigInteger(pCfg, "FdcEnabled", fFdcEnabled);
2767 InsertConfigInteger(pCfg, "HpetEnabled", fHPETEnabled);
2768 InsertConfigInteger(pCfg, "SmcEnabled", fSmcEnabled);
2769 InsertConfigInteger(pCfg, "ShowRtc", fShowRtc);
2770 if (fOsXGuest && !llBootNics.empty())
2771 {
2772 BootNic aNic = llBootNics.front();
2773 uint32_t u32NicPCIAddr = (aNic.mPCIAddress.miDevice << 16) | aNic.mPCIAddress.miFn;
2774 InsertConfigInteger(pCfg, "NicPciAddress", u32NicPCIAddr);
2775 }
2776 if (fOsXGuest && fAudioEnabled)
2777 {
2778 PCIBusAddress Address;
2779 if (pBusMgr->findPCIAddress("hda", 0, Address))
2780 {
2781 uint32_t u32AudioPCIAddr = (Address.miDevice << 16) | Address.miFn;
2782 InsertConfigInteger(pCfg, "AudioPciAddress", u32AudioPCIAddr);
2783 }
2784 }
2785 InsertConfigInteger(pCfg, "IocPciAddress", uIocPCIAddress);
2786 if (chipsetType == ChipsetType_ICH9)
2787 {
2788 InsertConfigInteger(pCfg, "McfgBase", uMcfgBase);
2789 InsertConfigInteger(pCfg, "McfgLength", cbMcfgLength);
2790 }
2791 InsertConfigInteger(pCfg, "HostBusPciAddress", uHbcPCIAddress);
2792 InsertConfigInteger(pCfg, "ShowCpu", fShowCpu);
2793 InsertConfigInteger(pCfg, "CpuHotPlug", fCpuHotPlug);
2794
2795 InsertConfigInteger(pCfg, "Serial0IoPortBase", auSerialIoPortBase[0]);
2796 InsertConfigInteger(pCfg, "Serial0Irq", auSerialIrq[0]);
2797
2798 InsertConfigInteger(pCfg, "Serial1IoPortBase", auSerialIoPortBase[1]);
2799 InsertConfigInteger(pCfg, "Serial1Irq", auSerialIrq[1]);
2800
2801 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2802 InsertConfigString(pLunL0, "Driver", "ACPIHost");
2803 InsertConfigNode(pLunL0, "Config", &pCfg);
2804
2805 /* Attach the dummy CPU drivers */
2806 for (ULONG iCpuCurr = 1; iCpuCurr < cCpus; iCpuCurr++)
2807 {
2808 BOOL fCpuAttached = true;
2809
2810 if (fCpuHotPlug)
2811 {
2812 hrc = pMachine->GetCPUStatus(iCpuCurr, &fCpuAttached); H();
2813 }
2814
2815 if (fCpuAttached)
2816 {
2817 InsertConfigNode(pInst, Utf8StrFmt("LUN#%u", iCpuCurr).c_str(), &pLunL0);
2818 InsertConfigString(pLunL0, "Driver", "ACPICpu");
2819 InsertConfigNode(pLunL0, "Config", &pCfg);
2820 }
2821 }
2822 }
2823
2824 /*
2825 * Configure DBGF (Debug(ger) Facility).
2826 */
2827 {
2828 PCFGMNODE pDbgf;
2829 InsertConfigNode(pRoot, "DBGF", &pDbgf);
2830
2831 /* Paths to search for debug info and such things. */
2832 hrc = pMachine->COMGETTER(SettingsFilePath)(bstr.asOutParam()); H();
2833 Utf8Str strSettingsPath(bstr);
2834 bstr.setNull();
2835 strSettingsPath.stripFilename();
2836
2837 char szHomeDir[RTPATH_MAX];
2838 rc = RTPathUserHome(szHomeDir, sizeof(szHomeDir));
2839 if (RT_FAILURE(rc))
2840 szHomeDir[0] = '\0';
2841
2842 Utf8Str strPath;
2843 strPath.append(strSettingsPath).append("/debug/;");
2844 strPath.append(strSettingsPath).append("/;");
2845 strPath.append(szHomeDir).append("/");
2846
2847 InsertConfigString(pDbgf, "Path", strPath.c_str());
2848
2849 /* Tracing configuration. */
2850 BOOL fTracingEnabled;
2851 hrc = pMachine->COMGETTER(TracingEnabled)(&fTracingEnabled); H();
2852 if (fTracingEnabled)
2853 InsertConfigInteger(pDbgf, "TracingEnabled", 1);
2854
2855 hrc = pMachine->COMGETTER(TracingConfig)(bstr.asOutParam()); H();
2856 if (fTracingEnabled)
2857 InsertConfigString(pDbgf, "TracingConfig", bstr);
2858
2859 BOOL fAllowTracingToAccessVM;
2860 hrc = pMachine->COMGETTER(AllowTracingToAccessVM)(&fAllowTracingToAccessVM); H();
2861 if (fAllowTracingToAccessVM)
2862 InsertConfigInteger(pPDM, "AllowTracingToAccessVM", 1);
2863 }
2864 }
2865 catch (ConfigError &x)
2866 {
2867 // InsertConfig threw something:
2868 return x.m_vrc;
2869 }
2870 catch (HRESULT hrcXcpt)
2871 {
2872 AssertMsgFailedReturn(("hrc=%Rhrc\n", hrcXcpt), VERR_GENERAL_FAILURE);
2873 }
2874
2875#ifdef VBOX_WITH_EXTPACK
2876 /*
2877 * Call the extension pack hooks if everything went well thus far.
2878 */
2879 if (RT_SUCCESS(rc))
2880 {
2881 pAlock->release();
2882 rc = mptrExtPackManager->callAllVmConfigureVmmHooks(this, pVM);
2883 pAlock->acquire();
2884 }
2885#endif
2886
2887 /*
2888 * Apply the CFGM overlay.
2889 */
2890 if (RT_SUCCESS(rc))
2891 rc = configCfgmOverlay(pRoot, virtualBox, pMachine);
2892
2893 /*
2894 * Dump all extradata API settings tweaks, both global and per VM.
2895 */
2896 if (RT_SUCCESS(rc))
2897 rc = configDumpAPISettingsTweaks(virtualBox, pMachine);
2898
2899#undef H
2900
2901 pAlock->release(); /* Avoid triggering the lock order inversion check. */
2902
2903 /*
2904 * Register VM state change handler.
2905 */
2906 int rc2 = VMR3AtStateRegister(pUVM, Console::vmstateChangeCallback, this);
2907 AssertRC(rc2);
2908 if (RT_SUCCESS(rc))
2909 rc = rc2;
2910
2911 /*
2912 * Register VM runtime error handler.
2913 */
2914 rc2 = VMR3AtRuntimeErrorRegister(pUVM, Console::setVMRuntimeErrorCallback, this);
2915 AssertRC(rc2);
2916 if (RT_SUCCESS(rc))
2917 rc = rc2;
2918
2919 pAlock->acquire();
2920
2921 LogFlowFunc(("vrc = %Rrc\n", rc));
2922 LogFlowFuncLeave();
2923
2924 return rc;
2925}
2926
2927/**
2928 * Applies the CFGM overlay as specified by VBoxInternal/XXX extra data
2929 * values.
2930 *
2931 * @returns VBox status code.
2932 * @param pRoot The root of the configuration tree.
2933 * @param pVirtualBox Pointer to the IVirtualBox interface.
2934 * @param pMachine Pointer to the IMachine interface.
2935 */
2936/* static */
2937int Console::configCfgmOverlay(PCFGMNODE pRoot, IVirtualBox *pVirtualBox, IMachine *pMachine)
2938{
2939 /*
2940 * CFGM overlay handling.
2941 *
2942 * Here we check the extra data entries for CFGM values
2943 * and create the nodes and insert the values on the fly. Existing
2944 * values will be removed and reinserted. CFGM is typed, so by default
2945 * we will guess whether it's a string or an integer (byte arrays are
2946 * not currently supported). It's possible to override this autodetection
2947 * by adding "string:", "integer:" or "bytes:" (future).
2948 *
2949 * We first perform a run on global extra data, then on the machine
2950 * extra data to support global settings with local overrides.
2951 */
2952 int rc = VINF_SUCCESS;
2953 try
2954 {
2955 /** @todo add support for removing nodes and byte blobs. */
2956 /*
2957 * Get the next key
2958 */
2959 SafeArray<BSTR> aGlobalExtraDataKeys;
2960 SafeArray<BSTR> aMachineExtraDataKeys;
2961 HRESULT hrc = pVirtualBox->GetExtraDataKeys(ComSafeArrayAsOutParam(aGlobalExtraDataKeys));
2962 AssertMsg(SUCCEEDED(hrc), ("VirtualBox::GetExtraDataKeys failed with %Rhrc\n", hrc));
2963
2964 // remember the no. of global values so we can call the correct method below
2965 size_t cGlobalValues = aGlobalExtraDataKeys.size();
2966
2967 hrc = pMachine->GetExtraDataKeys(ComSafeArrayAsOutParam(aMachineExtraDataKeys));
2968 AssertMsg(SUCCEEDED(hrc), ("Machine::GetExtraDataKeys failed with %Rhrc\n", hrc));
2969
2970 // build a combined list from global keys...
2971 std::list<Utf8Str> llExtraDataKeys;
2972
2973 for (size_t i = 0; i < aGlobalExtraDataKeys.size(); ++i)
2974 llExtraDataKeys.push_back(Utf8Str(aGlobalExtraDataKeys[i]));
2975 // ... and machine keys
2976 for (size_t i = 0; i < aMachineExtraDataKeys.size(); ++i)
2977 llExtraDataKeys.push_back(Utf8Str(aMachineExtraDataKeys[i]));
2978
2979 size_t i2 = 0;
2980 for (std::list<Utf8Str>::const_iterator it = llExtraDataKeys.begin();
2981 it != llExtraDataKeys.end();
2982 ++it, ++i2)
2983 {
2984 const Utf8Str &strKey = *it;
2985
2986 /*
2987 * We only care about keys starting with "VBoxInternal/" (skip "G:" or "M:")
2988 */
2989 if (!strKey.startsWith("VBoxInternal/"))
2990 continue;
2991
2992 const char *pszExtraDataKey = strKey.c_str() + sizeof("VBoxInternal/") - 1;
2993
2994 // get the value
2995 Bstr bstrExtraDataValue;
2996 if (i2 < cGlobalValues)
2997 // this is still one of the global values:
2998 hrc = pVirtualBox->GetExtraData(Bstr(strKey).raw(),
2999 bstrExtraDataValue.asOutParam());
3000 else
3001 hrc = pMachine->GetExtraData(Bstr(strKey).raw(),
3002 bstrExtraDataValue.asOutParam());
3003 if (FAILED(hrc))
3004 LogRel(("Warning: Cannot get extra data key %s, rc = %Rhrc\n", strKey.c_str(), hrc));
3005
3006 /*
3007 * The key will be in the format "Node1/Node2/Value" or simply "Value".
3008 * Split the two and get the node, delete the value and create the node
3009 * if necessary.
3010 */
3011 PCFGMNODE pNode;
3012 const char *pszCFGMValueName = strrchr(pszExtraDataKey, '/');
3013 if (pszCFGMValueName)
3014 {
3015 /* terminate the node and advance to the value (Utf8Str might not
3016 offically like this but wtf) */
3017 *(char*)pszCFGMValueName = '\0';
3018 ++pszCFGMValueName;
3019
3020 /* does the node already exist? */
3021 pNode = CFGMR3GetChild(pRoot, pszExtraDataKey);
3022 if (pNode)
3023 CFGMR3RemoveValue(pNode, pszCFGMValueName);
3024 else
3025 {
3026 /* create the node */
3027 rc = CFGMR3InsertNode(pRoot, pszExtraDataKey, &pNode);
3028 if (RT_FAILURE(rc))
3029 {
3030 AssertLogRelMsgRC(rc, ("failed to insert node '%s'\n", pszExtraDataKey));
3031 continue;
3032 }
3033 Assert(pNode);
3034 }
3035 }
3036 else
3037 {
3038 /* root value (no node path). */
3039 pNode = pRoot;
3040 pszCFGMValueName = pszExtraDataKey;
3041 pszExtraDataKey--;
3042 CFGMR3RemoveValue(pNode, pszCFGMValueName);
3043 }
3044
3045 /*
3046 * Now let's have a look at the value.
3047 * Empty strings means that we should remove the value, which we've
3048 * already done above.
3049 */
3050 Utf8Str strCFGMValueUtf8(bstrExtraDataValue);
3051 if (!strCFGMValueUtf8.isEmpty())
3052 {
3053 uint64_t u64Value;
3054
3055 /* check for type prefix first. */
3056 if (!strncmp(strCFGMValueUtf8.c_str(), RT_STR_TUPLE("string:")))
3057 InsertConfigString(pNode, pszCFGMValueName, strCFGMValueUtf8.c_str() + sizeof("string:") - 1);
3058 else if (!strncmp(strCFGMValueUtf8.c_str(), RT_STR_TUPLE("integer:")))
3059 {
3060 rc = RTStrToUInt64Full(strCFGMValueUtf8.c_str() + sizeof("integer:") - 1, 0, &u64Value);
3061 if (RT_SUCCESS(rc))
3062 rc = CFGMR3InsertInteger(pNode, pszCFGMValueName, u64Value);
3063 }
3064 else if (!strncmp(strCFGMValueUtf8.c_str(), RT_STR_TUPLE("bytes:")))
3065 {
3066 char const *pszBase64 = strCFGMValueUtf8.c_str() + sizeof("bytes:") - 1;
3067 ssize_t cbValue = RTBase64DecodedSize(pszBase64, NULL);
3068 if (cbValue > 0)
3069 {
3070 void *pvBytes = RTMemTmpAlloc(cbValue);
3071 if (pvBytes)
3072 {
3073 rc = RTBase64Decode(pszBase64, pvBytes, cbValue, NULL, NULL);
3074 if (RT_SUCCESS(rc))
3075 rc = CFGMR3InsertBytes(pNode, pszCFGMValueName, pvBytes, cbValue);
3076 RTMemTmpFree(pvBytes);
3077 }
3078 else
3079 rc = VERR_NO_TMP_MEMORY;
3080 }
3081 else if (cbValue == 0)
3082 rc = CFGMR3InsertBytes(pNode, pszCFGMValueName, NULL, 0);
3083 else
3084 rc = VERR_INVALID_BASE64_ENCODING;
3085 }
3086 /* auto detect type. */
3087 else if (RT_SUCCESS(RTStrToUInt64Full(strCFGMValueUtf8.c_str(), 0, &u64Value)))
3088 rc = CFGMR3InsertInteger(pNode, pszCFGMValueName, u64Value);
3089 else
3090 InsertConfigString(pNode, pszCFGMValueName, strCFGMValueUtf8);
3091 AssertLogRelMsgRCBreak(rc, ("failed to insert CFGM value '%s' to key '%s'\n", strCFGMValueUtf8.c_str(), pszExtraDataKey));
3092 }
3093 }
3094 }
3095 catch (ConfigError &x)
3096 {
3097 // InsertConfig threw something:
3098 return x.m_vrc;
3099 }
3100 return rc;
3101}
3102
3103/**
3104 * Dumps the API settings tweaks as specified by VBoxInternal2/XXX extra data
3105 * values.
3106 *
3107 * @returns VBox status code.
3108 * @param pVirtualBox Pointer to the IVirtualBox interface.
3109 * @param pMachine Pointer to the IMachine interface.
3110 */
3111/* static */
3112int Console::configDumpAPISettingsTweaks(IVirtualBox *pVirtualBox, IMachine *pMachine)
3113{
3114 {
3115 SafeArray<BSTR> aGlobalExtraDataKeys;
3116 HRESULT hrc = pVirtualBox->GetExtraDataKeys(ComSafeArrayAsOutParam(aGlobalExtraDataKeys));
3117 AssertMsg(SUCCEEDED(hrc), ("VirtualBox::GetExtraDataKeys failed with %Rhrc\n", hrc));
3118 bool hasKey = false;
3119 for (size_t i = 0; i < aGlobalExtraDataKeys.size(); i++)
3120 {
3121 Utf8Str strKey(aGlobalExtraDataKeys[i]);
3122 if (!strKey.startsWith("VBoxInternal2/"))
3123 continue;
3124
3125 Bstr bstrValue;
3126 hrc = pVirtualBox->GetExtraData(Bstr(strKey).raw(),
3127 bstrValue.asOutParam());
3128 if (FAILED(hrc))
3129 continue;
3130 if (!hasKey)
3131 LogRel(("Global extradata API settings:\n"));
3132 LogRel((" %s=\"%ls\"\n", strKey.c_str(), bstrValue.raw()));
3133 hasKey = true;
3134 }
3135 }
3136
3137 {
3138 SafeArray<BSTR> aMachineExtraDataKeys;
3139 HRESULT hrc = pMachine->GetExtraDataKeys(ComSafeArrayAsOutParam(aMachineExtraDataKeys));
3140 AssertMsg(SUCCEEDED(hrc), ("Machine::GetExtraDataKeys failed with %Rhrc\n", hrc));
3141 bool hasKey = false;
3142 for (size_t i = 0; i < aMachineExtraDataKeys.size(); i++)
3143 {
3144 Utf8Str strKey(aMachineExtraDataKeys[i]);
3145 if (!strKey.startsWith("VBoxInternal2/"))
3146 continue;
3147
3148 Bstr bstrValue;
3149 hrc = pMachine->GetExtraData(Bstr(strKey).raw(),
3150 bstrValue.asOutParam());
3151 if (FAILED(hrc))
3152 continue;
3153 if (!hasKey)
3154 LogRel(("Per-VM extradata API settings:\n"));
3155 LogRel((" %s=\"%ls\"\n", strKey.c_str(), bstrValue.raw()));
3156 hasKey = true;
3157 }
3158 }
3159
3160 return VINF_SUCCESS;
3161}
3162
3163int Console::configGraphicsController(PCFGMNODE pDevices,
3164 const char *pcszDevice,
3165 BusAssignmentManager *pBusMgr,
3166 const ComPtr<IMachine> &pMachine,
3167 const ComPtr<IBIOSSettings> &biosSettings,
3168 bool fHMEnabled)
3169{
3170 // InsertConfig* throws
3171 try
3172 {
3173 PCFGMNODE pDev, pInst, pCfg, pLunL0;
3174 HRESULT hrc;
3175 Bstr bstr;
3176
3177#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
3178 InsertConfigNode(pDevices, pcszDevice, &pDev);
3179 InsertConfigNode(pDev, "0", &pInst);
3180 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
3181
3182 hrc = pBusMgr->assignPCIDevice(pcszDevice, pInst); H();
3183 InsertConfigNode(pInst, "Config", &pCfg);
3184 ULONG cVRamMBs;
3185 hrc = pMachine->COMGETTER(VRAMSize)(&cVRamMBs); H();
3186 InsertConfigInteger(pCfg, "VRamSize", cVRamMBs * _1M);
3187 ULONG cMonitorCount;
3188 hrc = pMachine->COMGETTER(MonitorCount)(&cMonitorCount); H();
3189 InsertConfigInteger(pCfg, "MonitorCount", cMonitorCount);
3190#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
3191 InsertConfigInteger(pCfg, "R0Enabled", fHMEnabled);
3192#else
3193 NOREF(fHMEnabled);
3194#endif
3195
3196 /* Custom VESA mode list */
3197 unsigned cModes = 0;
3198 for (unsigned iMode = 1; iMode <= 16; ++iMode)
3199 {
3200 char szExtraDataKey[sizeof("CustomVideoModeXX")];
3201 RTStrPrintf(szExtraDataKey, sizeof(szExtraDataKey), "CustomVideoMode%u", iMode);
3202 hrc = pMachine->GetExtraData(Bstr(szExtraDataKey).raw(), bstr.asOutParam()); H();
3203 if (bstr.isEmpty())
3204 break;
3205 InsertConfigString(pCfg, szExtraDataKey, bstr);
3206 ++cModes;
3207 }
3208 InsertConfigInteger(pCfg, "CustomVideoModes", cModes);
3209
3210 /* VESA height reduction */
3211 ULONG ulHeightReduction;
3212 IFramebuffer *pFramebuffer = getDisplay()->getFramebuffer();
3213 if (pFramebuffer)
3214 {
3215 hrc = pFramebuffer->COMGETTER(HeightReduction)(&ulHeightReduction); H();
3216 }
3217 else
3218 {
3219 /* If framebuffer is not available, there is no height reduction. */
3220 ulHeightReduction = 0;
3221 }
3222 InsertConfigInteger(pCfg, "HeightReduction", ulHeightReduction);
3223
3224 /*
3225 * BIOS logo
3226 */
3227 BOOL fFadeIn;
3228 hrc = biosSettings->COMGETTER(LogoFadeIn)(&fFadeIn); H();
3229 InsertConfigInteger(pCfg, "FadeIn", fFadeIn ? 1 : 0);
3230 BOOL fFadeOut;
3231 hrc = biosSettings->COMGETTER(LogoFadeOut)(&fFadeOut); H();
3232 InsertConfigInteger(pCfg, "FadeOut", fFadeOut ? 1: 0);
3233 ULONG logoDisplayTime;
3234 hrc = biosSettings->COMGETTER(LogoDisplayTime)(&logoDisplayTime); H();
3235 InsertConfigInteger(pCfg, "LogoTime", logoDisplayTime);
3236 Bstr logoImagePath;
3237 hrc = biosSettings->COMGETTER(LogoImagePath)(logoImagePath.asOutParam()); H();
3238 InsertConfigString(pCfg, "LogoFile", Utf8Str(!logoImagePath.isEmpty() ? logoImagePath : "") );
3239
3240 /*
3241 * Boot menu
3242 */
3243 BIOSBootMenuMode_T eBootMenuMode;
3244 int iShowBootMenu;
3245 biosSettings->COMGETTER(BootMenuMode)(&eBootMenuMode);
3246 switch (eBootMenuMode)
3247 {
3248 case BIOSBootMenuMode_Disabled: iShowBootMenu = 0; break;
3249 case BIOSBootMenuMode_MenuOnly: iShowBootMenu = 1; break;
3250 default: iShowBootMenu = 2; break;
3251 }
3252 InsertConfigInteger(pCfg, "ShowBootMenu", iShowBootMenu);
3253
3254 /* Attach the display. */
3255 InsertConfigNode(pInst, "LUN#0", &pLunL0);
3256 InsertConfigString(pLunL0, "Driver", "MainDisplay");
3257 InsertConfigNode(pLunL0, "Config", &pCfg);
3258 Display *pDisplay = mDisplay;
3259 InsertConfigInteger(pCfg, "Object", (uintptr_t)pDisplay);
3260 }
3261 catch (ConfigError &x)
3262 {
3263 // InsertConfig threw something:
3264 return x.m_vrc;
3265 }
3266
3267#undef H
3268
3269 return VINF_SUCCESS;
3270}
3271
3272
3273/**
3274 * Ellipsis to va_list wrapper for calling setVMRuntimeErrorCallback.
3275 */
3276void Console::setVMRuntimeErrorCallbackF(uint32_t fFlags, const char *pszErrorId, const char *pszFormat, ...)
3277{
3278 va_list va;
3279 va_start(va, pszFormat);
3280 setVMRuntimeErrorCallback(NULL, this, fFlags, pszErrorId, pszFormat, va);
3281 va_end(va);
3282}
3283
3284/* XXX introduce RT format specifier */
3285static uint64_t formatDiskSize(uint64_t u64Size, const char **pszUnit)
3286{
3287 if (u64Size > INT64_C(5000)*_1G)
3288 {
3289 *pszUnit = "TB";
3290 return u64Size / _1T;
3291 }
3292 else if (u64Size > INT64_C(5000)*_1M)
3293 {
3294 *pszUnit = "GB";
3295 return u64Size / _1G;
3296 }
3297 else
3298 {
3299 *pszUnit = "MB";
3300 return u64Size / _1M;
3301 }
3302}
3303
3304int Console::configMediumAttachment(PCFGMNODE pCtlInst,
3305 const char *pcszDevice,
3306 unsigned uInstance,
3307 StorageBus_T enmBus,
3308 bool fUseHostIOCache,
3309 bool fBuiltinIOCache,
3310 bool fSetupMerge,
3311 unsigned uMergeSource,
3312 unsigned uMergeTarget,
3313 IMediumAttachment *pMediumAtt,
3314 MachineState_T aMachineState,
3315 HRESULT *phrc,
3316 bool fAttachDetach,
3317 bool fForceUnmount,
3318 bool fHotplug,
3319 PUVM pUVM,
3320 DeviceType_T *paLedDevType)
3321{
3322 // InsertConfig* throws
3323 try
3324 {
3325 int rc = VINF_SUCCESS;
3326 HRESULT hrc;
3327 Bstr bstr;
3328
3329// #define RC_CHECK() AssertMsgReturn(RT_SUCCESS(rc), ("rc=%Rrc\n", rc), rc)
3330#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
3331
3332 LONG lDev;
3333 hrc = pMediumAtt->COMGETTER(Device)(&lDev); H();
3334 LONG lPort;
3335 hrc = pMediumAtt->COMGETTER(Port)(&lPort); H();
3336 DeviceType_T lType;
3337 hrc = pMediumAtt->COMGETTER(Type)(&lType); H();
3338 BOOL fNonRotational;
3339 hrc = pMediumAtt->COMGETTER(NonRotational)(&fNonRotational); H();
3340 BOOL fDiscard;
3341 hrc = pMediumAtt->COMGETTER(Discard)(&fDiscard); H();
3342
3343 unsigned uLUN;
3344 PCFGMNODE pLunL0 = NULL;
3345 hrc = Console::convertBusPortDeviceToLun(enmBus, lPort, lDev, uLUN); H();
3346
3347 /* First check if the LUN already exists. */
3348 pLunL0 = CFGMR3GetChildF(pCtlInst, "LUN#%u", uLUN);
3349 if (pLunL0)
3350 {
3351 if (fAttachDetach)
3352 {
3353 if (lType != DeviceType_HardDisk)
3354 {
3355 /* Unmount existing media only for floppy and DVD drives. */
3356 PPDMIBASE pBase;
3357 rc = PDMR3QueryLun(pUVM, pcszDevice, uInstance, uLUN, &pBase);
3358 if (RT_FAILURE(rc))
3359 {
3360 if (rc == VERR_PDM_LUN_NOT_FOUND || rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
3361 rc = VINF_SUCCESS;
3362 AssertRC(rc);
3363 }
3364 else
3365 {
3366 PPDMIMOUNT pIMount = PDMIBASE_QUERY_INTERFACE(pBase, PDMIMOUNT);
3367 AssertReturn(pIMount, VERR_INVALID_POINTER);
3368
3369 /* Unmount the media (but do not eject the medium!) */
3370 rc = pIMount->pfnUnmount(pIMount, fForceUnmount, false /*=fEject*/);
3371 if (rc == VERR_PDM_MEDIA_NOT_MOUNTED)
3372 rc = VINF_SUCCESS;
3373 /* for example if the medium is locked */
3374 else if (RT_FAILURE(rc))
3375 return rc;
3376 }
3377 }
3378
3379 rc = PDMR3DeviceDetach(pUVM, pcszDevice, uInstance, uLUN, fHotplug ? 0 : PDM_TACH_FLAGS_NOT_HOT_PLUG);
3380 if (rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
3381 rc = VINF_SUCCESS;
3382 AssertRCReturn(rc, rc);
3383
3384 CFGMR3RemoveNode(pLunL0);
3385 }
3386 else
3387 AssertFailedReturn(VERR_INTERNAL_ERROR);
3388 }
3389
3390 InsertConfigNode(pCtlInst, Utf8StrFmt("LUN#%u", uLUN).c_str(), &pLunL0);
3391
3392 PCFGMNODE pCfg = CFGMR3GetChild(pCtlInst, "Config");
3393 if (pCfg)
3394 {
3395 if (!strcmp(pcszDevice, "piix3ide"))
3396 {
3397 PCFGMNODE pDrive = CFGMR3GetChild(pCfg, g_apszIDEDrives[uLUN]);
3398 if (!pDrive)
3399 InsertConfigNode(pCfg, g_apszIDEDrives[uLUN], &pDrive);
3400 /* Don't use the RemoveConfigValue wrapper above, as we don't
3401 * know if the leaf is present or not. */
3402 CFGMR3RemoveValue(pDrive, "NonRotationalMedium");
3403 InsertConfigInteger(pDrive, "NonRotationalMedium", !!fNonRotational);
3404 }
3405 else if (!strcmp(pcszDevice, "ahci"))
3406 {
3407 Utf8Str strPort = Utf8StrFmt("Port%u", uLUN);
3408 PCFGMNODE pDrive = CFGMR3GetChild(pCfg, strPort.c_str());
3409 if (!pDrive)
3410 InsertConfigNode(pCfg, strPort.c_str(), &pDrive);
3411 /* Don't use the RemoveConfigValue wrapper above, as we don't
3412 * know if the leaf is present or not. */
3413 CFGMR3RemoveValue(pDrive, "NonRotationalMedium");
3414 InsertConfigInteger(pDrive, "NonRotationalMedium", !!fNonRotational);
3415 }
3416 }
3417
3418 Utf8Str devicePath = Utf8StrFmt("%s/%u/LUN#%u", pcszDevice, uInstance, uLUN);
3419 mapMediumAttachments[devicePath] = pMediumAtt;
3420
3421 /* SCSI has a another driver between device and block. */
3422 if (enmBus == StorageBus_SCSI || enmBus == StorageBus_SAS)
3423 {
3424 InsertConfigString(pLunL0, "Driver", "SCSI");
3425 PCFGMNODE pL1Cfg = NULL;
3426 InsertConfigNode(pLunL0, "Config", &pL1Cfg);
3427 InsertConfigInteger(pL1Cfg, "NonRotationalMedium", !!fNonRotational);
3428
3429 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
3430 }
3431
3432 ComPtr<IMedium> pMedium;
3433 hrc = pMediumAtt->COMGETTER(Medium)(pMedium.asOutParam()); H();
3434
3435 /*
3436 * 1. Only check this for hard disk images.
3437 * 2. Only check during VM creation and not later, especially not during
3438 * taking an online snapshot!
3439 */
3440 if ( lType == DeviceType_HardDisk
3441 && ( aMachineState == MachineState_Starting
3442 || aMachineState == MachineState_Restoring))
3443 {
3444 /*
3445 * Some sanity checks.
3446 */
3447 ComPtr<IMediumFormat> pMediumFormat;
3448 hrc = pMedium->COMGETTER(MediumFormat)(pMediumFormat.asOutParam()); H();
3449 ULONG uCaps = 0;
3450 com::SafeArray <MediumFormatCapabilities_T> mediumFormatCap;
3451 hrc = pMediumFormat->COMGETTER(Capabilities)(ComSafeArrayAsOutParam(mediumFormatCap)); H();
3452
3453 for (ULONG j = 0; j < mediumFormatCap.size(); j++)
3454 uCaps |= mediumFormatCap[j];
3455
3456 if (uCaps & MediumFormatCapabilities_File)
3457 {
3458 Bstr strFile;
3459 hrc = pMedium->COMGETTER(Location)(strFile.asOutParam()); H();
3460 Utf8Str utfFile = Utf8Str(strFile);
3461 Bstr strSnap;
3462 ComPtr<IMachine> pMachine = machine();
3463 hrc = pMachine->COMGETTER(SnapshotFolder)(strSnap.asOutParam()); H();
3464 Utf8Str utfSnap = Utf8Str(strSnap);
3465 RTFSTYPE enmFsTypeFile = RTFSTYPE_UNKNOWN;
3466 RTFSTYPE enmFsTypeSnap = RTFSTYPE_UNKNOWN;
3467 int rc2 = RTFsQueryType(utfFile.c_str(), &enmFsTypeFile);
3468 AssertMsgRCReturn(rc2, ("Querying the file type of '%s' failed!\n", utfFile.c_str()), rc2);
3469 /* Ignore the error code. On error, the file system type is still 'unknown' so
3470 * none of the following paths are taken. This can happen for new VMs which
3471 * still don't have a snapshot folder. */
3472 (void)RTFsQueryType(utfSnap.c_str(), &enmFsTypeSnap);
3473 if (!mfSnapshotFolderDiskTypeShown)
3474 {
3475 LogRel(("File system of '%s' (snapshots) is %s\n",
3476 utfSnap.c_str(), RTFsTypeName(enmFsTypeSnap)));
3477 mfSnapshotFolderDiskTypeShown = true;
3478 }
3479 LogRel(("File system of '%s' is %s\n", utfFile.c_str(), RTFsTypeName(enmFsTypeFile)));
3480 LONG64 i64Size;
3481 hrc = pMedium->COMGETTER(LogicalSize)(&i64Size); H();
3482#ifdef RT_OS_WINDOWS
3483 if ( enmFsTypeFile == RTFSTYPE_FAT
3484 && i64Size >= _4G)
3485 {
3486 const char *pszUnit;
3487 uint64_t u64Print = formatDiskSize((uint64_t)i64Size, &pszUnit);
3488 setVMRuntimeErrorCallbackF(0, "FatPartitionDetected",
3489 N_("The medium '%ls' has a logical size of %RU64%s "
3490 "but the file system the medium is located on seems "
3491 "to be FAT(32) which cannot handle files bigger than 4GB.\n"
3492 "We strongly recommend to put all your virtual disk images and "
3493 "the snapshot folder onto an NTFS partition"),
3494 strFile.raw(), u64Print, pszUnit);
3495 }
3496#else /* !RT_OS_WINDOWS */
3497 if ( enmFsTypeFile == RTFSTYPE_FAT
3498 || enmFsTypeFile == RTFSTYPE_EXT
3499 || enmFsTypeFile == RTFSTYPE_EXT2
3500 || enmFsTypeFile == RTFSTYPE_EXT3
3501 || enmFsTypeFile == RTFSTYPE_EXT4)
3502 {
3503 RTFILE file;
3504 rc = RTFileOpen(&file, utfFile.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
3505 if (RT_SUCCESS(rc))
3506 {
3507 RTFOFF maxSize;
3508 /* Careful: This function will work only on selected local file systems! */
3509 rc = RTFileGetMaxSizeEx(file, &maxSize);
3510 RTFileClose(file);
3511 if ( RT_SUCCESS(rc)
3512 && maxSize > 0
3513 && i64Size > (LONG64)maxSize)
3514 {
3515 const char *pszUnitSiz;
3516 const char *pszUnitMax;
3517 uint64_t u64PrintSiz = formatDiskSize((LONG64)i64Size, &pszUnitSiz);
3518 uint64_t u64PrintMax = formatDiskSize(maxSize, &pszUnitMax);
3519 setVMRuntimeErrorCallbackF(0, "FatPartitionDetected", /* <= not exact but ... */
3520 N_("The medium '%ls' has a logical size of %RU64%s "
3521 "but the file system the medium is located on can "
3522 "only handle files up to %RU64%s in theory.\n"
3523 "We strongly recommend to put all your virtual disk "
3524 "images and the snapshot folder onto a proper "
3525 "file system (e.g. ext3) with a sufficient size"),
3526 strFile.raw(), u64PrintSiz, pszUnitSiz, u64PrintMax, pszUnitMax);
3527 }
3528 }
3529 }
3530#endif /* !RT_OS_WINDOWS */
3531
3532 /*
3533 * Snapshot folder:
3534 * Here we test only for a FAT partition as we had to create a dummy file otherwise
3535 */
3536 if ( enmFsTypeSnap == RTFSTYPE_FAT
3537 && i64Size >= _4G
3538 && !mfSnapshotFolderSizeWarningShown)
3539 {
3540 const char *pszUnit;
3541 uint64_t u64Print = formatDiskSize(i64Size, &pszUnit);
3542 setVMRuntimeErrorCallbackF(0, "FatPartitionDetected",
3543#ifdef RT_OS_WINDOWS
3544 N_("The snapshot folder of this VM '%ls' seems to be located on "
3545 "a FAT(32) file system. The logical size of the medium '%ls' "
3546 "(%RU64%s) is bigger than the maximum file size this file "
3547 "system can handle (4GB).\n"
3548 "We strongly recommend to put all your virtual disk images and "
3549 "the snapshot folder onto an NTFS partition"),
3550#else
3551 N_("The snapshot folder of this VM '%ls' seems to be located on "
3552 "a FAT(32) file system. The logical size of the medium '%ls' "
3553 "(%RU64%s) is bigger than the maximum file size this file "
3554 "system can handle (4GB).\n"
3555 "We strongly recommend to put all your virtual disk images and "
3556 "the snapshot folder onto a proper file system (e.g. ext3)"),
3557#endif
3558 strSnap.raw(), strFile.raw(), u64Print, pszUnit);
3559 /* Show this particular warning only once */
3560 mfSnapshotFolderSizeWarningShown = true;
3561 }
3562
3563#ifdef RT_OS_LINUX
3564 /*
3565 * Ext4 bug: Check if the host I/O cache is disabled and the disk image is located
3566 * on an ext4 partition. Later we have to check the Linux kernel version!
3567 * This bug apparently applies to the XFS file system as well.
3568 * Linux 2.6.36 is known to be fixed (tested with 2.6.36-rc4).
3569 */
3570
3571 char szOsRelease[128];
3572 rc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szOsRelease, sizeof(szOsRelease));
3573 bool fKernelHasODirectBug = RT_FAILURE(rc)
3574 || (RTStrVersionCompare(szOsRelease, "2.6.36-rc4") < 0);
3575
3576 if ( (uCaps & MediumFormatCapabilities_Asynchronous)
3577 && !fUseHostIOCache
3578 && fKernelHasODirectBug)
3579 {
3580 if ( enmFsTypeFile == RTFSTYPE_EXT4
3581 || enmFsTypeFile == RTFSTYPE_XFS)
3582 {
3583 setVMRuntimeErrorCallbackF(0, "Ext4PartitionDetected",
3584 N_("The host I/O cache for at least one controller is disabled "
3585 "and the medium '%ls' for this VM "
3586 "is located on an %s partition. There is a known Linux "
3587 "kernel bug which can lead to the corruption of the virtual "
3588 "disk image under these conditions.\n"
3589 "Either enable the host I/O cache permanently in the VM "
3590 "settings or put the disk image and the snapshot folder "
3591 "onto a different file system.\n"
3592 "The host I/O cache will now be enabled for this medium"),
3593 strFile.raw(), enmFsTypeFile == RTFSTYPE_EXT4 ? "ext4" : "xfs");
3594 fUseHostIOCache = true;
3595 }
3596 else if ( ( enmFsTypeSnap == RTFSTYPE_EXT4
3597 || enmFsTypeSnap == RTFSTYPE_XFS)
3598 && !mfSnapshotFolderExt4WarningShown)
3599 {
3600 setVMRuntimeErrorCallbackF(0, "Ext4PartitionDetected",
3601 N_("The host I/O cache for at least one controller is disabled "
3602 "and the snapshot folder for this VM "
3603 "is located on an %s partition. There is a known Linux "
3604 "kernel bug which can lead to the corruption of the virtual "
3605 "disk image under these conditions.\n"
3606 "Either enable the host I/O cache permanently in the VM "
3607 "settings or put the disk image and the snapshot folder "
3608 "onto a different file system.\n"
3609 "The host I/O cache will now be enabled for this medium"),
3610 enmFsTypeSnap == RTFSTYPE_EXT4 ? "ext4" : "xfs");
3611 fUseHostIOCache = true;
3612 mfSnapshotFolderExt4WarningShown = true;
3613 }
3614 }
3615#endif
3616 }
3617 }
3618
3619 if (pMedium)
3620 {
3621 BOOL fHostDrive;
3622 hrc = pMedium->COMGETTER(HostDrive)(&fHostDrive); H();
3623 if ( ( lType == DeviceType_DVD
3624 || lType == DeviceType_Floppy)
3625 && !fHostDrive)
3626 {
3627 /*
3628 * Informative logging.
3629 */
3630 Bstr strFile;
3631 hrc = pMedium->COMGETTER(Location)(strFile.asOutParam()); H();
3632 Utf8Str utfFile = Utf8Str(strFile);
3633 RTFSTYPE enmFsTypeFile = RTFSTYPE_UNKNOWN;
3634 (void)RTFsQueryType(utfFile.c_str(), &enmFsTypeFile);
3635 LogRel(("File system of '%s' (%s) is %s\n",
3636 utfFile.c_str(), lType == DeviceType_DVD ? "DVD" : "Floppy",
3637 RTFsTypeName(enmFsTypeFile)));
3638 }
3639 }
3640
3641 BOOL fPassthrough;
3642 hrc = pMediumAtt->COMGETTER(Passthrough)(&fPassthrough); H();
3643
3644 ComObjPtr<IBandwidthGroup> pBwGroup;
3645 Bstr strBwGroup;
3646 hrc = pMediumAtt->COMGETTER(BandwidthGroup)(pBwGroup.asOutParam()); H();
3647
3648 if (!pBwGroup.isNull())
3649 {
3650 hrc = pBwGroup->COMGETTER(Name)(strBwGroup.asOutParam()); H();
3651 }
3652
3653 rc = configMedium(pLunL0,
3654 !!fPassthrough,
3655 lType,
3656 fUseHostIOCache,
3657 fBuiltinIOCache,
3658 fSetupMerge,
3659 uMergeSource,
3660 uMergeTarget,
3661 strBwGroup.isEmpty() ? NULL : Utf8Str(strBwGroup).c_str(),
3662 !!fDiscard,
3663 pMedium,
3664 aMachineState,
3665 phrc);
3666 if (RT_FAILURE(rc))
3667 return rc;
3668
3669 if (fAttachDetach)
3670 {
3671 /* Attach the new driver. */
3672 rc = PDMR3DeviceAttach(pUVM, pcszDevice, uInstance, uLUN,
3673 fHotplug ? 0 : PDM_TACH_FLAGS_NOT_HOT_PLUG, NULL /*ppBase*/);
3674 AssertRCReturn(rc, rc);
3675
3676 /* There is no need to handle removable medium mounting, as we
3677 * unconditionally replace everthing including the block driver level.
3678 * This means the new medium will be picked up automatically. */
3679 }
3680
3681 if (paLedDevType)
3682 paLedDevType[uLUN] = lType;
3683 }
3684 catch (ConfigError &x)
3685 {
3686 // InsertConfig threw something:
3687 return x.m_vrc;
3688 }
3689
3690#undef H
3691
3692 return VINF_SUCCESS;
3693}
3694
3695int Console::configMedium(PCFGMNODE pLunL0,
3696 bool fPassthrough,
3697 DeviceType_T enmType,
3698 bool fUseHostIOCache,
3699 bool fBuiltinIOCache,
3700 bool fSetupMerge,
3701 unsigned uMergeSource,
3702 unsigned uMergeTarget,
3703 const char *pcszBwGroup,
3704 bool fDiscard,
3705 IMedium *pMedium,
3706 MachineState_T aMachineState,
3707 HRESULT *phrc)
3708{
3709 // InsertConfig* throws
3710 try
3711 {
3712 int rc = VINF_SUCCESS;
3713 HRESULT hrc;
3714 Bstr bstr;
3715 PCFGMNODE pLunL1 = NULL;
3716 PCFGMNODE pCfg = NULL;
3717
3718#define H() \
3719 AssertMsgReturnStmt(SUCCEEDED(hrc), ("hrc=%Rhrc\n", hrc), if (phrc) *phrc = hrc, Global::vboxStatusCodeFromCOM(hrc))
3720
3721
3722 BOOL fHostDrive = FALSE;
3723 MediumType_T mediumType = MediumType_Normal;
3724 if (pMedium)
3725 {
3726 hrc = pMedium->COMGETTER(HostDrive)(&fHostDrive); H();
3727 hrc = pMedium->COMGETTER(Type)(&mediumType); H();
3728 }
3729
3730 if (fHostDrive)
3731 {
3732 Assert(pMedium);
3733 if (enmType == DeviceType_DVD)
3734 {
3735 InsertConfigString(pLunL0, "Driver", "HostDVD");
3736 InsertConfigNode(pLunL0, "Config", &pCfg);
3737
3738 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3739 InsertConfigString(pCfg, "Path", bstr);
3740
3741 InsertConfigInteger(pCfg, "Passthrough", fPassthrough);
3742 }
3743 else if (enmType == DeviceType_Floppy)
3744 {
3745 InsertConfigString(pLunL0, "Driver", "HostFloppy");
3746 InsertConfigNode(pLunL0, "Config", &pCfg);
3747
3748 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3749 InsertConfigString(pCfg, "Path", bstr);
3750 }
3751 }
3752 else
3753 {
3754 InsertConfigString(pLunL0, "Driver", "Block");
3755 InsertConfigNode(pLunL0, "Config", &pCfg);
3756 switch (enmType)
3757 {
3758 case DeviceType_DVD:
3759 InsertConfigString(pCfg, "Type", "DVD");
3760 InsertConfigInteger(pCfg, "Mountable", 1);
3761 break;
3762 case DeviceType_Floppy:
3763 InsertConfigString(pCfg, "Type", "Floppy 1.44");
3764 InsertConfigInteger(pCfg, "Mountable", 1);
3765 break;
3766 case DeviceType_HardDisk:
3767 default:
3768 InsertConfigString(pCfg, "Type", "HardDisk");
3769 InsertConfigInteger(pCfg, "Mountable", 0);
3770 }
3771
3772 if ( pMedium
3773 && ( enmType == DeviceType_DVD
3774 || enmType == DeviceType_Floppy)
3775 )
3776 {
3777 // if this medium represents an ISO image and this image is inaccessible,
3778 // the ignore it instead of causing a failure; this can happen when we
3779 // restore a VM state and the ISO has disappeared, e.g. because the Guest
3780 // Additions were mounted and the user upgraded VirtualBox. Previously
3781 // we failed on startup, but that's not good because the only way out then
3782 // would be to discard the VM state...
3783 MediumState_T mediumState;
3784 hrc = pMedium->RefreshState(&mediumState); H();
3785 if (mediumState == MediumState_Inaccessible)
3786 {
3787 Bstr loc;
3788 hrc = pMedium->COMGETTER(Location)(loc.asOutParam()); H();
3789 setVMRuntimeErrorCallbackF(0, "DvdOrFloppyImageInaccessible",
3790 "The image file '%ls' is inaccessible and is being ignored. Please select a different image file for the virtual %s drive.",
3791 loc.raw(),
3792 enmType == DeviceType_DVD ? "DVD" : "floppy");
3793 pMedium = NULL;
3794 }
3795 }
3796
3797 if (pMedium)
3798 {
3799 /* Start with length of parent chain, as the list is reversed */
3800 unsigned uImage = 0;
3801 IMedium *pTmp = pMedium;
3802 while (pTmp)
3803 {
3804 uImage++;
3805 hrc = pTmp->COMGETTER(Parent)(&pTmp); H();
3806 }
3807 /* Index of last image */
3808 uImage--;
3809
3810#if 0 /* Enable for I/O debugging */
3811 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
3812 InsertConfigString(pLunL0, "Driver", "DiskIntegrity");
3813 InsertConfigNode(pLunL0, "Config", &pCfg);
3814 InsertConfigInteger(pCfg, "CheckConsistency", 0);
3815 InsertConfigInteger(pCfg, "CheckDoubleCompletions", 1);
3816#endif
3817
3818 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
3819 InsertConfigString(pLunL1, "Driver", "VD");
3820 InsertConfigNode(pLunL1, "Config", &pCfg);
3821
3822 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3823 InsertConfigString(pCfg, "Path", bstr);
3824
3825 hrc = pMedium->COMGETTER(Format)(bstr.asOutParam()); H();
3826 InsertConfigString(pCfg, "Format", bstr);
3827
3828 if (mediumType == MediumType_Readonly)
3829 InsertConfigInteger(pCfg, "ReadOnly", 1);
3830 else if (enmType == DeviceType_Floppy)
3831 InsertConfigInteger(pCfg, "MaybeReadOnly", 1);
3832
3833 /* Start without exclusive write access to the images. */
3834 /** @todo Live Migration: I don't quite like this, we risk screwing up when
3835 * we're resuming the VM if some 3rd dude have any of the VDIs open
3836 * with write sharing denied. However, if the two VMs are sharing a
3837 * image it really is necessary....
3838 *
3839 * So, on the "lock-media" command, the target teleporter should also
3840 * make DrvVD undo TempReadOnly. It gets interesting if we fail after
3841 * that. Grumble. */
3842 if ( enmType == DeviceType_HardDisk
3843 && ( aMachineState == MachineState_TeleportingIn
3844 || aMachineState == MachineState_FaultTolerantSyncing))
3845 InsertConfigInteger(pCfg, "TempReadOnly", 1);
3846
3847 /* Flag for opening the medium for sharing between VMs. This
3848 * is done at the moment only for the first (and only) medium
3849 * in the chain, as shared media can have no diffs. */
3850 if (mediumType == MediumType_Shareable)
3851 InsertConfigInteger(pCfg, "Shareable", 1);
3852
3853 if (!fUseHostIOCache)
3854 {
3855 InsertConfigInteger(pCfg, "UseNewIo", 1);
3856 /*
3857 * Activate the builtin I/O cache for harddisks only.
3858 * It caches writes only which doesn't make sense for DVD drives
3859 * and just increases the overhead.
3860 */
3861 if ( fBuiltinIOCache
3862 && (enmType == DeviceType_HardDisk))
3863 InsertConfigInteger(pCfg, "BlockCache", 1);
3864 }
3865
3866 if (fSetupMerge)
3867 {
3868 InsertConfigInteger(pCfg, "SetupMerge", 1);
3869 if (uImage == uMergeSource)
3870 InsertConfigInteger(pCfg, "MergeSource", 1);
3871 else if (uImage == uMergeTarget)
3872 InsertConfigInteger(pCfg, "MergeTarget", 1);
3873 }
3874
3875 switch (enmType)
3876 {
3877 case DeviceType_DVD:
3878 InsertConfigString(pCfg, "Type", "DVD");
3879 break;
3880 case DeviceType_Floppy:
3881 InsertConfigString(pCfg, "Type", "Floppy");
3882 break;
3883 case DeviceType_HardDisk:
3884 default:
3885 InsertConfigString(pCfg, "Type", "HardDisk");
3886 }
3887
3888 if (pcszBwGroup)
3889 InsertConfigString(pCfg, "BwGroup", pcszBwGroup);
3890
3891 if (fDiscard)
3892 InsertConfigInteger(pCfg, "Discard", 1);
3893
3894 /* Pass all custom parameters. */
3895 bool fHostIP = true;
3896 SafeArray<BSTR> names;
3897 SafeArray<BSTR> values;
3898 hrc = pMedium->GetProperties(Bstr().raw(),
3899 ComSafeArrayAsOutParam(names),
3900 ComSafeArrayAsOutParam(values)); H();
3901
3902 if (names.size() != 0)
3903 {
3904 PCFGMNODE pVDC;
3905 InsertConfigNode(pCfg, "VDConfig", &pVDC);
3906 for (size_t ii = 0; ii < names.size(); ++ii)
3907 {
3908 if (values[ii] && *values[ii])
3909 {
3910 Utf8Str name = names[ii];
3911 Utf8Str value = values[ii];
3912 InsertConfigString(pVDC, name.c_str(), value);
3913 if ( name.compare("HostIPStack") == 0
3914 && value.compare("0") == 0)
3915 fHostIP = false;
3916 }
3917 }
3918 }
3919
3920 /* Create an inverted list of parents. */
3921 uImage--;
3922 IMedium *pParentMedium = pMedium;
3923 for (PCFGMNODE pParent = pCfg;; uImage--)
3924 {
3925 hrc = pParentMedium->COMGETTER(Parent)(&pMedium); H();
3926 if (!pMedium)
3927 break;
3928
3929 PCFGMNODE pCur;
3930 InsertConfigNode(pParent, "Parent", &pCur);
3931 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3932 InsertConfigString(pCur, "Path", bstr);
3933
3934 hrc = pMedium->COMGETTER(Format)(bstr.asOutParam()); H();
3935 InsertConfigString(pCur, "Format", bstr);
3936
3937 if (fSetupMerge)
3938 {
3939 if (uImage == uMergeSource)
3940 InsertConfigInteger(pCur, "MergeSource", 1);
3941 else if (uImage == uMergeTarget)
3942 InsertConfigInteger(pCur, "MergeTarget", 1);
3943 }
3944
3945 /* Pass all custom parameters. */
3946 SafeArray<BSTR> aNames;
3947 SafeArray<BSTR> aValues;
3948 hrc = pMedium->GetProperties(NULL,
3949 ComSafeArrayAsOutParam(aNames),
3950 ComSafeArrayAsOutParam(aValues)); H();
3951
3952 if (aNames.size() != 0)
3953 {
3954 PCFGMNODE pVDC;
3955 InsertConfigNode(pCur, "VDConfig", &pVDC);
3956 for (size_t ii = 0; ii < aNames.size(); ++ii)
3957 {
3958 if (aValues[ii] && *aValues[ii])
3959 {
3960 Utf8Str name = aNames[ii];
3961 Utf8Str value = aValues[ii];
3962 InsertConfigString(pVDC, name.c_str(), value);
3963 if ( name.compare("HostIPStack") == 0
3964 && value.compare("0") == 0)
3965 fHostIP = false;
3966 }
3967 }
3968 }
3969
3970 /* next */
3971 pParent = pCur;
3972 pParentMedium = pMedium;
3973 }
3974
3975 /* Custom code: put marker to not use host IP stack to driver
3976 * configuration node. Simplifies life of DrvVD a bit. */
3977 if (!fHostIP)
3978 InsertConfigInteger(pCfg, "HostIPStack", 0);
3979 }
3980 }
3981#undef H
3982 }
3983 catch (ConfigError &x)
3984 {
3985 // InsertConfig threw something:
3986 return x.m_vrc;
3987 }
3988
3989 return VINF_SUCCESS;
3990}
3991
3992/**
3993 * Construct the Network configuration tree
3994 *
3995 * @returns VBox status code.
3996 *
3997 * @param pszDevice The PDM device name.
3998 * @param uInstance The PDM device instance.
3999 * @param uLun The PDM LUN number of the drive.
4000 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
4001 * @param pCfg Configuration node for the device
4002 * @param pLunL0 To store the pointer to the LUN#0.
4003 * @param pInst The instance CFGM node
4004 * @param fAttachDetach To determine if the network attachment should
4005 * be attached/detached after/before
4006 * configuration.
4007 * @param fIgnoreConnectFailure
4008 * True if connection failures should be ignored
4009 * (makes only sense for bridged/host-only networks).
4010 *
4011 * @note Locks this object for writing.
4012 * @thread EMT
4013 */
4014int Console::configNetwork(const char *pszDevice,
4015 unsigned uInstance,
4016 unsigned uLun,
4017 INetworkAdapter *aNetworkAdapter,
4018 PCFGMNODE pCfg,
4019 PCFGMNODE pLunL0,
4020 PCFGMNODE pInst,
4021 bool fAttachDetach,
4022 bool fIgnoreConnectFailure)
4023{
4024 AutoCaller autoCaller(this);
4025 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
4026
4027 // InsertConfig* throws
4028 try
4029 {
4030 int rc = VINF_SUCCESS;
4031 HRESULT hrc;
4032 Bstr bstr;
4033
4034#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
4035
4036 /*
4037 * Locking the object before doing VMR3* calls is quite safe here, since
4038 * we're on EMT. Write lock is necessary because we indirectly modify the
4039 * meAttachmentType member.
4040 */
4041 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4042
4043 ComPtr<IMachine> pMachine = machine();
4044
4045 ComPtr<IVirtualBox> virtualBox;
4046 hrc = pMachine->COMGETTER(Parent)(virtualBox.asOutParam()); H();
4047
4048 ComPtr<IHost> host;
4049 hrc = virtualBox->COMGETTER(Host)(host.asOutParam()); H();
4050
4051 BOOL fSniffer;
4052 hrc = aNetworkAdapter->COMGETTER(TraceEnabled)(&fSniffer); H();
4053
4054 NetworkAdapterPromiscModePolicy_T enmPromiscModePolicy;
4055 hrc = aNetworkAdapter->COMGETTER(PromiscModePolicy)(&enmPromiscModePolicy); H();
4056 const char *pszPromiscuousGuestPolicy;
4057 switch (enmPromiscModePolicy)
4058 {
4059 case NetworkAdapterPromiscModePolicy_Deny: pszPromiscuousGuestPolicy = "deny"; break;
4060 case NetworkAdapterPromiscModePolicy_AllowNetwork: pszPromiscuousGuestPolicy = "allow-network"; break;
4061 case NetworkAdapterPromiscModePolicy_AllowAll: pszPromiscuousGuestPolicy = "allow-all"; break;
4062 default: AssertFailedReturn(VERR_INTERNAL_ERROR_4);
4063 }
4064
4065 if (fAttachDetach)
4066 {
4067 rc = PDMR3DeviceDetach(mpUVM, pszDevice, uInstance, uLun, 0 /*fFlags*/);
4068 if (rc == VINF_PDM_NO_DRIVER_ATTACHED_TO_LUN)
4069 rc = VINF_SUCCESS;
4070 AssertLogRelRCReturn(rc, rc);
4071
4072 /* nuke anything which might have been left behind. */
4073 CFGMR3RemoveNode(CFGMR3GetChildF(pInst, "LUN#%u", uLun));
4074 }
4075
4076#ifdef VBOX_WITH_NETSHAPER
4077 ComObjPtr<IBandwidthGroup> pBwGroup;
4078 Bstr strBwGroup;
4079 hrc = aNetworkAdapter->COMGETTER(BandwidthGroup)(pBwGroup.asOutParam()); H();
4080
4081 if (!pBwGroup.isNull())
4082 {
4083 hrc = pBwGroup->COMGETTER(Name)(strBwGroup.asOutParam()); H();
4084 }
4085#endif /* VBOX_WITH_NETSHAPER */
4086
4087 Utf8Str strNetDriver;
4088
4089
4090 InsertConfigNode(pInst, "LUN#0", &pLunL0);
4091
4092#ifdef VBOX_WITH_NETSHAPER
4093 if (!strBwGroup.isEmpty())
4094 {
4095 InsertConfigString(pLunL0, "Driver", "NetShaper");
4096 InsertConfigNode(pLunL0, "Config", &pCfg);
4097 InsertConfigString(pCfg, "BwGroup", strBwGroup);
4098 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
4099 }
4100#endif /* VBOX_WITH_NETSHAPER */
4101
4102 if (fSniffer)
4103 {
4104 InsertConfigString(pLunL0, "Driver", "NetSniffer");
4105 InsertConfigNode(pLunL0, "Config", &pCfg);
4106 hrc = aNetworkAdapter->COMGETTER(TraceFile)(bstr.asOutParam()); H();
4107 if (!bstr.isEmpty()) /* check convention for indicating default file. */
4108 InsertConfigString(pCfg, "File", bstr);
4109 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
4110 }
4111
4112
4113 Bstr networkName, trunkName, trunkType;
4114 NetworkAttachmentType_T eAttachmentType;
4115 hrc = aNetworkAdapter->COMGETTER(AttachmentType)(&eAttachmentType); H();
4116 switch (eAttachmentType)
4117 {
4118 case NetworkAttachmentType_Null:
4119 break;
4120
4121 case NetworkAttachmentType_NAT:
4122 {
4123 ComPtr<INATEngine> natEngine;
4124 hrc = aNetworkAdapter->COMGETTER(NATEngine)(natEngine.asOutParam()); H();
4125 InsertConfigString(pLunL0, "Driver", "NAT");
4126 InsertConfigNode(pLunL0, "Config", &pCfg);
4127
4128 /* Configure TFTP prefix and boot filename. */
4129 hrc = virtualBox->COMGETTER(HomeFolder)(bstr.asOutParam()); H();
4130 if (!bstr.isEmpty())
4131 InsertConfigString(pCfg, "TFTPPrefix", Utf8StrFmt("%ls%c%s", bstr.raw(), RTPATH_DELIMITER, "TFTP"));
4132 hrc = pMachine->COMGETTER(Name)(bstr.asOutParam()); H();
4133 InsertConfigString(pCfg, "BootFile", Utf8StrFmt("%ls.pxe", bstr.raw()));
4134
4135 hrc = natEngine->COMGETTER(Network)(bstr.asOutParam()); H();
4136 if (!bstr.isEmpty())
4137 InsertConfigString(pCfg, "Network", bstr);
4138 else
4139 {
4140 ULONG uSlot;
4141 hrc = aNetworkAdapter->COMGETTER(Slot)(&uSlot); H();
4142 InsertConfigString(pCfg, "Network", Utf8StrFmt("10.0.%d.0/24", uSlot+2));
4143 }
4144 hrc = natEngine->COMGETTER(HostIP)(bstr.asOutParam()); H();
4145 if (!bstr.isEmpty())
4146 InsertConfigString(pCfg, "BindIP", bstr);
4147 ULONG mtu = 0;
4148 ULONG sockSnd = 0;
4149 ULONG sockRcv = 0;
4150 ULONG tcpSnd = 0;
4151 ULONG tcpRcv = 0;
4152 hrc = natEngine->GetNetworkSettings(&mtu, &sockSnd, &sockRcv, &tcpSnd, &tcpRcv); H();
4153 if (mtu)
4154 InsertConfigInteger(pCfg, "SlirpMTU", mtu);
4155 if (sockRcv)
4156 InsertConfigInteger(pCfg, "SockRcv", sockRcv);
4157 if (sockSnd)
4158 InsertConfigInteger(pCfg, "SockSnd", sockSnd);
4159 if (tcpRcv)
4160 InsertConfigInteger(pCfg, "TcpRcv", tcpRcv);
4161 if (tcpSnd)
4162 InsertConfigInteger(pCfg, "TcpSnd", tcpSnd);
4163 hrc = natEngine->COMGETTER(TFTPPrefix)(bstr.asOutParam()); H();
4164 if (!bstr.isEmpty())
4165 {
4166 RemoveConfigValue(pCfg, "TFTPPrefix");
4167 InsertConfigString(pCfg, "TFTPPrefix", bstr);
4168 }
4169 hrc = natEngine->COMGETTER(TFTPBootFile)(bstr.asOutParam()); H();
4170 if (!bstr.isEmpty())
4171 {
4172 RemoveConfigValue(pCfg, "BootFile");
4173 InsertConfigString(pCfg, "BootFile", bstr);
4174 }
4175 hrc = natEngine->COMGETTER(TFTPNextServer)(bstr.asOutParam()); H();
4176 if (!bstr.isEmpty())
4177 InsertConfigString(pCfg, "NextServer", bstr);
4178 BOOL fDNSFlag;
4179 hrc = natEngine->COMGETTER(DNSPassDomain)(&fDNSFlag); H();
4180 InsertConfigInteger(pCfg, "PassDomain", fDNSFlag);
4181 hrc = natEngine->COMGETTER(DNSProxy)(&fDNSFlag); H();
4182 InsertConfigInteger(pCfg, "DNSProxy", fDNSFlag);
4183 hrc = natEngine->COMGETTER(DNSUseHostResolver)(&fDNSFlag); H();
4184 InsertConfigInteger(pCfg, "UseHostResolver", fDNSFlag);
4185
4186 ULONG aliasMode;
4187 hrc = natEngine->COMGETTER(AliasMode)(&aliasMode); H();
4188 InsertConfigInteger(pCfg, "AliasMode", aliasMode);
4189
4190 /* port-forwarding */
4191 SafeArray<BSTR> pfs;
4192 hrc = natEngine->COMGETTER(Redirects)(ComSafeArrayAsOutParam(pfs)); H();
4193 PCFGMNODE pPF = NULL; /* /Devices/Dev/.../Config/PF#0/ */
4194 for (unsigned int i = 0; i < pfs.size(); ++i)
4195 {
4196 uint16_t port = 0;
4197 BSTR r = pfs[i];
4198 Utf8Str utf = Utf8Str(r);
4199 Utf8Str strName;
4200 Utf8Str strProto;
4201 Utf8Str strHostPort;
4202 Utf8Str strHostIP;
4203 Utf8Str strGuestPort;
4204 Utf8Str strGuestIP;
4205 size_t pos, ppos;
4206 pos = ppos = 0;
4207#define ITERATE_TO_NEXT_TERM(res, str, pos, ppos) \
4208 do { \
4209 pos = str.find(",", ppos); \
4210 if (pos == Utf8Str::npos) \
4211 { \
4212 Log(( #res " extracting from %s is failed\n", str.c_str())); \
4213 continue; \
4214 } \
4215 res = str.substr(ppos, pos - ppos); \
4216 Log2((#res " %s pos:%d, ppos:%d\n", res.c_str(), pos, ppos)); \
4217 ppos = pos + 1; \
4218 } while (0)
4219 ITERATE_TO_NEXT_TERM(strName, utf, pos, ppos);
4220 ITERATE_TO_NEXT_TERM(strProto, utf, pos, ppos);
4221 ITERATE_TO_NEXT_TERM(strHostIP, utf, pos, ppos);
4222 ITERATE_TO_NEXT_TERM(strHostPort, utf, pos, ppos);
4223 ITERATE_TO_NEXT_TERM(strGuestIP, utf, pos, ppos);
4224 strGuestPort = utf.substr(ppos, utf.length() - ppos);
4225#undef ITERATE_TO_NEXT_TERM
4226
4227 uint32_t proto = strProto.toUInt32();
4228 bool fValid = true;
4229 switch (proto)
4230 {
4231 case NATProtocol_UDP:
4232 strProto = "UDP";
4233 break;
4234 case NATProtocol_TCP:
4235 strProto = "TCP";
4236 break;
4237 default:
4238 fValid = false;
4239 }
4240 /* continue with next rule if no valid proto was passed */
4241 if (!fValid)
4242 continue;
4243
4244 InsertConfigNode(pCfg, strName.c_str(), &pPF);
4245 InsertConfigString(pPF, "Protocol", strProto);
4246
4247 if (!strHostIP.isEmpty())
4248 InsertConfigString(pPF, "BindIP", strHostIP);
4249
4250 if (!strGuestIP.isEmpty())
4251 InsertConfigString(pPF, "GuestIP", strGuestIP);
4252
4253 port = RTStrToUInt16(strHostPort.c_str());
4254 if (port)
4255 InsertConfigInteger(pPF, "HostPort", port);
4256
4257 port = RTStrToUInt16(strGuestPort.c_str());
4258 if (port)
4259 InsertConfigInteger(pPF, "GuestPort", port);
4260 }
4261 break;
4262 }
4263
4264 case NetworkAttachmentType_Bridged:
4265 {
4266#if (defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT)
4267 hrc = attachToTapInterface(aNetworkAdapter);
4268 if (FAILED(hrc))
4269 {
4270 switch (hrc)
4271 {
4272 case VERR_ACCESS_DENIED:
4273 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4274 "Failed to open '/dev/net/tun' for read/write access. Please check the "
4275 "permissions of that node. Either run 'chmod 0666 /dev/net/tun' or "
4276 "change the group of that node and make yourself a member of that group. Make "
4277 "sure that these changes are permanent, especially if you are "
4278 "using udev"));
4279 default:
4280 AssertMsgFailed(("Could not attach to host interface! Bad!\n"));
4281 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4282 "Failed to initialize Host Interface Networking"));
4283 }
4284 }
4285
4286 Assert((int)maTapFD[uInstance] >= 0);
4287 if ((int)maTapFD[uInstance] >= 0)
4288 {
4289 InsertConfigString(pLunL0, "Driver", "HostInterface");
4290 InsertConfigNode(pLunL0, "Config", &pCfg);
4291 InsertConfigInteger(pCfg, "FileHandle", maTapFD[uInstance]);
4292 }
4293
4294#elif defined(VBOX_WITH_NETFLT)
4295 /*
4296 * This is the new VBoxNetFlt+IntNet stuff.
4297 */
4298 Bstr BridgedIfName;
4299 hrc = aNetworkAdapter->COMGETTER(BridgedInterface)(BridgedIfName.asOutParam());
4300 if (FAILED(hrc))
4301 {
4302 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(BridgedInterface) failed, hrc (0x%x)\n", hrc));
4303 H();
4304 }
4305
4306 Utf8Str BridgedIfNameUtf8(BridgedIfName);
4307 const char *pszBridgedIfName = BridgedIfNameUtf8.c_str();
4308
4309# if defined(RT_OS_DARWIN)
4310 /* The name is on the form 'ifX: long name', chop it off at the colon. */
4311 char szTrunk[8];
4312 RTStrCopy(szTrunk, sizeof(szTrunk), pszBridgedIfName);
4313 char *pszColon = (char *)memchr(szTrunk, ':', sizeof(szTrunk));
4314// Quick fix for @bugref{5633}
4315// if (!pszColon)
4316// {
4317// /*
4318// * Dynamic changing of attachment causes an attempt to configure
4319// * network with invalid host adapter (as it is must be changed before
4320// * the attachment), calling Detach here will cause a deadlock.
4321// * See @bugref{4750}.
4322// * hrc = aNetworkAdapter->Detach(); H();
4323// */
4324// return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4325// N_("Malformed host interface networking name '%ls'"),
4326// BridgedIfName.raw());
4327// }
4328 if (pszColon)
4329 *pszColon = '\0';
4330 const char *pszTrunk = szTrunk;
4331
4332# elif defined(RT_OS_SOLARIS)
4333 /* The name is on the form format 'ifX[:1] - long name, chop it off at space. */
4334 char szTrunk[256];
4335 strlcpy(szTrunk, pszBridgedIfName, sizeof(szTrunk));
4336 char *pszSpace = (char *)memchr(szTrunk, ' ', sizeof(szTrunk));
4337
4338 /*
4339 * Currently don't bother about malformed names here for the sake of people using
4340 * VBoxManage and setting only the NIC name from there. If there is a space we
4341 * chop it off and proceed, otherwise just use whatever we've got.
4342 */
4343 if (pszSpace)
4344 *pszSpace = '\0';
4345
4346 /* Chop it off at the colon (zone naming eg: e1000g:1 we need only the e1000g) */
4347 char *pszColon = (char *)memchr(szTrunk, ':', sizeof(szTrunk));
4348 if (pszColon)
4349 *pszColon = '\0';
4350
4351 const char *pszTrunk = szTrunk;
4352
4353# elif defined(RT_OS_WINDOWS)
4354 ComPtr<IHostNetworkInterface> hostInterface;
4355 hrc = host->FindHostNetworkInterfaceByName(BridgedIfName.raw(),
4356 hostInterface.asOutParam());
4357 if (!SUCCEEDED(hrc))
4358 {
4359 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: FindByName failed, rc=%Rhrc (0x%x)", hrc, hrc));
4360 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4361 N_("Nonexistent host networking interface, name '%ls'"),
4362 BridgedIfName.raw());
4363 }
4364
4365 HostNetworkInterfaceType_T eIfType;
4366 hrc = hostInterface->COMGETTER(InterfaceType)(&eIfType);
4367 if (FAILED(hrc))
4368 {
4369 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(InterfaceType) failed, hrc (0x%x)\n", hrc));
4370 H();
4371 }
4372
4373 if (eIfType != HostNetworkInterfaceType_Bridged)
4374 {
4375 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4376 N_("Interface ('%ls') is not a Bridged Adapter interface"),
4377 BridgedIfName.raw());
4378 }
4379
4380 hrc = hostInterface->COMGETTER(Id)(bstr.asOutParam());
4381 if (FAILED(hrc))
4382 {
4383 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(Id) failed, hrc (0x%x)\n", hrc));
4384 H();
4385 }
4386 Guid hostIFGuid(bstr);
4387
4388 INetCfg *pNc;
4389 ComPtr<INetCfgComponent> pAdaptorComponent;
4390 LPWSTR pszApp;
4391
4392 hrc = VBoxNetCfgWinQueryINetCfg(&pNc, FALSE, L"VirtualBox", 10, &pszApp);
4393 Assert(hrc == S_OK);
4394 if (hrc != S_OK)
4395 {
4396 LogRel(("NetworkAttachmentType_Bridged: Failed to get NetCfg, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4397 H();
4398 }
4399
4400 /* get the adapter's INetCfgComponent*/
4401 hrc = VBoxNetCfgWinGetComponentByGuid(pNc, &GUID_DEVCLASS_NET, (GUID*)hostIFGuid.raw(), pAdaptorComponent.asOutParam());
4402 if (hrc != S_OK)
4403 {
4404 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4405 LogRel(("NetworkAttachmentType_Bridged: VBoxNetCfgWinGetComponentByGuid failed, hrc (0x%x)\n", hrc));
4406 H();
4407 }
4408#define VBOX_WIN_BINDNAME_PREFIX "\\DEVICE\\"
4409 char szTrunkName[INTNET_MAX_TRUNK_NAME];
4410 char *pszTrunkName = szTrunkName;
4411 wchar_t * pswzBindName;
4412 hrc = pAdaptorComponent->GetBindName(&pswzBindName);
4413 Assert(hrc == S_OK);
4414 if (hrc == S_OK)
4415 {
4416 int cwBindName = (int)wcslen(pswzBindName) + 1;
4417 int cbFullBindNamePrefix = sizeof(VBOX_WIN_BINDNAME_PREFIX);
4418 if (sizeof(szTrunkName) > cbFullBindNamePrefix + cwBindName)
4419 {
4420 strcpy(szTrunkName, VBOX_WIN_BINDNAME_PREFIX);
4421 pszTrunkName += cbFullBindNamePrefix-1;
4422 if (!WideCharToMultiByte(CP_ACP, 0, pswzBindName, cwBindName, pszTrunkName,
4423 sizeof(szTrunkName) - cbFullBindNamePrefix + 1, NULL, NULL))
4424 {
4425 DWORD err = GetLastError();
4426 hrc = HRESULT_FROM_WIN32(err);
4427 AssertMsgFailed(("%hrc=%Rhrc %#x\n", hrc, hrc));
4428 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: WideCharToMultiByte failed, hr=%Rhrc (0x%x) err=%u\n", hrc, hrc, err));
4429 }
4430 }
4431 else
4432 {
4433 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: insufficient szTrunkName buffer space\n"));
4434 /** @todo set appropriate error code */
4435 hrc = E_FAIL;
4436 }
4437
4438 if (hrc != S_OK)
4439 {
4440 AssertFailed();
4441 CoTaskMemFree(pswzBindName);
4442 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4443 H();
4444 }
4445
4446 /* we're not freeing the bind name since we'll use it later for detecting wireless*/
4447 }
4448 else
4449 {
4450 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4451 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: VBoxNetCfgWinGetComponentByGuid failed, hrc (0x%x)", hrc));
4452 H();
4453 }
4454
4455 const char *pszTrunk = szTrunkName;
4456 /* we're not releasing the INetCfg stuff here since we use it later to figure out whether it is wireless */
4457
4458# elif defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
4459# if defined(RT_OS_FREEBSD)
4460 /*
4461 * If we bridge to a tap interface open it the `old' direct way.
4462 * This works and performs better than bridging a physical
4463 * interface via the current FreeBSD vboxnetflt implementation.
4464 */
4465 if (!strncmp(pszBridgedIfName, RT_STR_TUPLE("tap"))) {
4466 hrc = attachToTapInterface(aNetworkAdapter);
4467 if (FAILED(hrc))
4468 {
4469 switch (hrc)
4470 {
4471 case VERR_ACCESS_DENIED:
4472 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4473 "Failed to open '/dev/%s' for read/write access. Please check the "
4474 "permissions of that node, and that the net.link.tap.user_open "
4475 "sysctl is set. Either run 'chmod 0666 /dev/%s' or "
4476 "change the group of that node to vboxusers and make yourself "
4477 "a member of that group. Make sure that these changes are permanent."), pszBridgedIfName, pszBridgedIfName);
4478 default:
4479 AssertMsgFailed(("Could not attach to tap interface! Bad!\n"));
4480 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4481 "Failed to initialize Host Interface Networking"));
4482 }
4483 }
4484
4485 Assert((int)maTapFD[uInstance] >= 0);
4486 if ((int)maTapFD[uInstance] >= 0)
4487 {
4488 InsertConfigString(pLunL0, "Driver", "HostInterface");
4489 InsertConfigNode(pLunL0, "Config", &pCfg);
4490 InsertConfigInteger(pCfg, "FileHandle", maTapFD[uInstance]);
4491 }
4492 break;
4493 }
4494# endif
4495 /** @todo Check for malformed names. */
4496 const char *pszTrunk = pszBridgedIfName;
4497
4498 /* Issue a warning if the interface is down */
4499 {
4500 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
4501 if (iSock >= 0)
4502 {
4503 struct ifreq Req;
4504 RT_ZERO(Req);
4505 RTStrCopy(Req.ifr_name, sizeof(Req.ifr_name), pszBridgedIfName);
4506 if (ioctl(iSock, SIOCGIFFLAGS, &Req) >= 0)
4507 if ((Req.ifr_flags & IFF_UP) == 0)
4508 setVMRuntimeErrorCallbackF(0, "BridgedInterfaceDown",
4509 N_("Bridged interface %s is down. Guest will not be able to use this interface"),
4510 pszBridgedIfName);
4511
4512 close(iSock);
4513 }
4514 }
4515
4516# else
4517# error "PORTME (VBOX_WITH_NETFLT)"
4518# endif
4519
4520 InsertConfigString(pLunL0, "Driver", "IntNet");
4521 InsertConfigNode(pLunL0, "Config", &pCfg);
4522 InsertConfigString(pCfg, "Trunk", pszTrunk);
4523 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetFlt);
4524 InsertConfigInteger(pCfg, "IgnoreConnectFailure", (uint64_t)fIgnoreConnectFailure);
4525 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
4526 char szNetwork[INTNET_MAX_NETWORK_NAME];
4527
4528#if defined(RT_OS_SOLARIS) || defined(RT_OS_DARWIN)
4529 /*
4530 * 'pszTrunk' contains just the interface name required in ring-0, while 'pszBridgedIfName' contains
4531 * interface name + optional description. We must not pass any description to the VM as it can differ
4532 * for the same interface name, eg: "nge0 - ethernet" (GUI) vs "nge0" (VBoxManage).
4533 */
4534 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszTrunk);
4535#else
4536 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszBridgedIfName);
4537#endif
4538 InsertConfigString(pCfg, "Network", szNetwork);
4539 networkName = Bstr(szNetwork);
4540 trunkName = Bstr(pszTrunk);
4541 trunkType = Bstr(TRUNKTYPE_NETFLT);
4542
4543# if defined(RT_OS_DARWIN)
4544 /** @todo Come up with a better deal here. Problem is that IHostNetworkInterface is completely useless here. */
4545 if ( strstr(pszBridgedIfName, "Wireless")
4546 || strstr(pszBridgedIfName, "AirPort" ))
4547 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4548# elif defined(RT_OS_LINUX)
4549 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
4550 if (iSock >= 0)
4551 {
4552 struct iwreq WRq;
4553
4554 RT_ZERO(WRq);
4555 strncpy(WRq.ifr_name, pszBridgedIfName, IFNAMSIZ);
4556 bool fSharedMacOnWire = ioctl(iSock, SIOCGIWNAME, &WRq) >= 0;
4557 close(iSock);
4558 if (fSharedMacOnWire)
4559 {
4560 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4561 Log(("Set SharedMacOnWire\n"));
4562 }
4563 else
4564 Log(("Failed to get wireless name\n"));
4565 }
4566 else
4567 Log(("Failed to open wireless socket\n"));
4568# elif defined(RT_OS_FREEBSD)
4569 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
4570 if (iSock >= 0)
4571 {
4572 struct ieee80211req WReq;
4573 uint8_t abData[32];
4574
4575 RT_ZERO(WReq);
4576 strncpy(WReq.i_name, pszBridgedIfName, sizeof(WReq.i_name));
4577 WReq.i_type = IEEE80211_IOC_SSID;
4578 WReq.i_val = -1;
4579 WReq.i_data = abData;
4580 WReq.i_len = sizeof(abData);
4581
4582 bool fSharedMacOnWire = ioctl(iSock, SIOCG80211, &WReq) >= 0;
4583 close(iSock);
4584 if (fSharedMacOnWire)
4585 {
4586 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4587 Log(("Set SharedMacOnWire\n"));
4588 }
4589 else
4590 Log(("Failed to get wireless name\n"));
4591 }
4592 else
4593 Log(("Failed to open wireless socket\n"));
4594# elif defined(RT_OS_WINDOWS)
4595# define DEVNAME_PREFIX L"\\\\.\\"
4596 /* we are getting the medium type via IOCTL_NDIS_QUERY_GLOBAL_STATS Io Control
4597 * there is a pretty long way till there though since we need to obtain the symbolic link name
4598 * for the adapter device we are going to query given the device Guid */
4599
4600
4601 /* prepend the "\\\\.\\" to the bind name to obtain the link name */
4602
4603 wchar_t FileName[MAX_PATH];
4604 wcscpy(FileName, DEVNAME_PREFIX);
4605 wcscpy((wchar_t*)(((char*)FileName) + sizeof(DEVNAME_PREFIX) - sizeof(FileName[0])), pswzBindName);
4606
4607 /* open the device */
4608 HANDLE hDevice = CreateFile(FileName,
4609 GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
4610 NULL,
4611 OPEN_EXISTING,
4612 FILE_ATTRIBUTE_NORMAL,
4613 NULL);
4614
4615 if (hDevice != INVALID_HANDLE_VALUE)
4616 {
4617 bool fSharedMacOnWire = false;
4618
4619 /* now issue the OID_GEN_PHYSICAL_MEDIUM query */
4620 DWORD Oid = OID_GEN_PHYSICAL_MEDIUM;
4621 NDIS_PHYSICAL_MEDIUM PhMedium;
4622 DWORD cbResult;
4623 if (DeviceIoControl(hDevice,
4624 IOCTL_NDIS_QUERY_GLOBAL_STATS,
4625 &Oid,
4626 sizeof(Oid),
4627 &PhMedium,
4628 sizeof(PhMedium),
4629 &cbResult,
4630 NULL))
4631 {
4632 /* that was simple, now examine PhMedium */
4633 if ( PhMedium == NdisPhysicalMediumWirelessWan
4634 || PhMedium == NdisPhysicalMediumWirelessLan
4635 || PhMedium == NdisPhysicalMediumNative802_11
4636 || PhMedium == NdisPhysicalMediumBluetooth)
4637 fSharedMacOnWire = true;
4638 }
4639 else
4640 {
4641 int winEr = GetLastError();
4642 LogRel(("Console::configNetwork: DeviceIoControl failed, err (0x%x), ignoring\n", winEr));
4643 Assert(winEr == ERROR_INVALID_PARAMETER || winEr == ERROR_NOT_SUPPORTED || winEr == ERROR_BAD_COMMAND);
4644 }
4645 CloseHandle(hDevice);
4646
4647 if (fSharedMacOnWire)
4648 {
4649 Log(("this is a wireless adapter"));
4650 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4651 Log(("Set SharedMacOnWire\n"));
4652 }
4653 else
4654 Log(("this is NOT a wireless adapter"));
4655 }
4656 else
4657 {
4658 int winEr = GetLastError();
4659 AssertLogRelMsgFailed(("Console::configNetwork: CreateFile failed, err (0x%x), ignoring\n", winEr));
4660 }
4661
4662 CoTaskMemFree(pswzBindName);
4663
4664 pAdaptorComponent.setNull();
4665 /* release the pNc finally */
4666 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4667# else
4668 /** @todo PORTME: wireless detection */
4669# endif
4670
4671# if defined(RT_OS_SOLARIS)
4672# if 0 /* bird: this is a bit questionable and might cause more trouble than its worth. */
4673 /* Zone access restriction, don't allow snooping the global zone. */
4674 zoneid_t ZoneId = getzoneid();
4675 if (ZoneId != GLOBAL_ZONEID)
4676 {
4677 InsertConfigInteger(pCfg, "IgnoreAllPromisc", true);
4678 }
4679# endif
4680# endif
4681
4682#elif defined(RT_OS_WINDOWS) /* not defined NetFlt */
4683 /* NOTHING TO DO HERE */
4684#elif defined(RT_OS_LINUX)
4685/// @todo aleksey: is there anything to be done here?
4686#elif defined(RT_OS_FREEBSD)
4687/** @todo FreeBSD: Check out this later (HIF networking). */
4688#else
4689# error "Port me"
4690#endif
4691 break;
4692 }
4693
4694 case NetworkAttachmentType_Internal:
4695 {
4696 hrc = aNetworkAdapter->COMGETTER(InternalNetwork)(bstr.asOutParam()); H();
4697 if (!bstr.isEmpty())
4698 {
4699 InsertConfigString(pLunL0, "Driver", "IntNet");
4700 InsertConfigNode(pLunL0, "Config", &pCfg);
4701 InsertConfigString(pCfg, "Network", bstr);
4702 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_WhateverNone);
4703 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
4704 networkName = bstr;
4705 trunkType = Bstr(TRUNKTYPE_WHATEVER);
4706 }
4707 break;
4708 }
4709
4710 case NetworkAttachmentType_HostOnly:
4711 {
4712 InsertConfigString(pLunL0, "Driver", "IntNet");
4713 InsertConfigNode(pLunL0, "Config", &pCfg);
4714
4715 Bstr HostOnlyName;
4716 hrc = aNetworkAdapter->COMGETTER(HostOnlyInterface)(HostOnlyName.asOutParam());
4717 if (FAILED(hrc))
4718 {
4719 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(HostOnlyInterface) failed, hrc (0x%x)\n", hrc));
4720 H();
4721 }
4722
4723 Utf8Str HostOnlyNameUtf8(HostOnlyName);
4724 const char *pszHostOnlyName = HostOnlyNameUtf8.c_str();
4725 ComPtr<IHostNetworkInterface> hostInterface;
4726 rc = host->FindHostNetworkInterfaceByName(HostOnlyName.raw(),
4727 hostInterface.asOutParam());
4728 if (!SUCCEEDED(rc))
4729 {
4730 LogRel(("NetworkAttachmentType_HostOnly: FindByName failed, rc (0x%x)\n", rc));
4731 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4732 N_("Nonexistent host networking interface, name '%ls'"),
4733 HostOnlyName.raw());
4734 }
4735
4736 char szNetwork[INTNET_MAX_NETWORK_NAME];
4737 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszHostOnlyName);
4738
4739#if defined(RT_OS_WINDOWS)
4740# ifndef VBOX_WITH_NETFLT
4741 hrc = E_NOTIMPL;
4742 LogRel(("NetworkAttachmentType_HostOnly: Not Implemented\n"));
4743 H();
4744# else /* defined VBOX_WITH_NETFLT*/
4745 /** @todo r=bird: Put this in a function. */
4746
4747 HostNetworkInterfaceType_T eIfType;
4748 hrc = hostInterface->COMGETTER(InterfaceType)(&eIfType);
4749 if (FAILED(hrc))
4750 {
4751 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(InterfaceType) failed, hrc (0x%x)\n", hrc));
4752 H();
4753 }
4754
4755 if (eIfType != HostNetworkInterfaceType_HostOnly)
4756 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4757 N_("Interface ('%ls') is not a Host-Only Adapter interface"),
4758 HostOnlyName.raw());
4759
4760 hrc = hostInterface->COMGETTER(Id)(bstr.asOutParam());
4761 if (FAILED(hrc))
4762 {
4763 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(Id) failed, hrc (0x%x)\n", hrc));
4764 H();
4765 }
4766 Guid hostIFGuid(bstr);
4767
4768 INetCfg *pNc;
4769 ComPtr<INetCfgComponent> pAdaptorComponent;
4770 LPWSTR pszApp;
4771 hrc = VBoxNetCfgWinQueryINetCfg(&pNc, FALSE, L"VirtualBox", 10, &pszApp);
4772 Assert(hrc == S_OK);
4773 if (hrc != S_OK)
4774 {
4775 LogRel(("NetworkAttachmentType_HostOnly: Failed to get NetCfg, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4776 H();
4777 }
4778
4779 /* get the adapter's INetCfgComponent*/
4780 hrc = VBoxNetCfgWinGetComponentByGuid(pNc, &GUID_DEVCLASS_NET, (GUID*)hostIFGuid.raw(), pAdaptorComponent.asOutParam());
4781 if (hrc != S_OK)
4782 {
4783 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4784 LogRel(("NetworkAttachmentType_HostOnly: VBoxNetCfgWinGetComponentByGuid failed, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4785 H();
4786 }
4787# define VBOX_WIN_BINDNAME_PREFIX "\\DEVICE\\"
4788 char szTrunkName[INTNET_MAX_TRUNK_NAME];
4789 char *pszTrunkName = szTrunkName;
4790 wchar_t * pswzBindName;
4791 hrc = pAdaptorComponent->GetBindName(&pswzBindName);
4792 Assert(hrc == S_OK);
4793 if (hrc == S_OK)
4794 {
4795 int cwBindName = (int)wcslen(pswzBindName) + 1;
4796 int cbFullBindNamePrefix = sizeof(VBOX_WIN_BINDNAME_PREFIX);
4797 if (sizeof(szTrunkName) > cbFullBindNamePrefix + cwBindName)
4798 {
4799 strcpy(szTrunkName, VBOX_WIN_BINDNAME_PREFIX);
4800 pszTrunkName += cbFullBindNamePrefix-1;
4801 if (!WideCharToMultiByte(CP_ACP, 0, pswzBindName, cwBindName, pszTrunkName,
4802 sizeof(szTrunkName) - cbFullBindNamePrefix + 1, NULL, NULL))
4803 {
4804 DWORD err = GetLastError();
4805 hrc = HRESULT_FROM_WIN32(err);
4806 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: WideCharToMultiByte failed, hr=%Rhrc (0x%x) err=%u\n", hrc, hrc, err));
4807 }
4808 }
4809 else
4810 {
4811 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: insufficient szTrunkName buffer space\n"));
4812 /** @todo set appropriate error code */
4813 hrc = E_FAIL;
4814 }
4815
4816 if (hrc != S_OK)
4817 {
4818 AssertFailed();
4819 CoTaskMemFree(pswzBindName);
4820 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4821 H();
4822 }
4823 }
4824 else
4825 {
4826 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4827 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: VBoxNetCfgWinGetComponentByGuid failed, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4828 H();
4829 }
4830
4831
4832 CoTaskMemFree(pswzBindName);
4833
4834 pAdaptorComponent.setNull();
4835 /* release the pNc finally */
4836 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4837
4838 const char *pszTrunk = szTrunkName;
4839
4840 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetAdp);
4841 InsertConfigString(pCfg, "Trunk", pszTrunk);
4842 InsertConfigString(pCfg, "Network", szNetwork);
4843 InsertConfigInteger(pCfg, "IgnoreConnectFailure", (uint64_t)fIgnoreConnectFailure); /** @todo why is this windows only?? */
4844 networkName = Bstr(szNetwork);
4845 trunkName = Bstr(pszTrunk);
4846 trunkType = TRUNKTYPE_NETADP;
4847# endif /* defined VBOX_WITH_NETFLT*/
4848#elif defined(RT_OS_DARWIN)
4849 InsertConfigString(pCfg, "Trunk", pszHostOnlyName);
4850 InsertConfigString(pCfg, "Network", szNetwork);
4851 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetAdp);
4852 networkName = Bstr(szNetwork);
4853 trunkName = Bstr(pszHostOnlyName);
4854 trunkType = TRUNKTYPE_NETADP;
4855#else
4856 InsertConfigString(pCfg, "Trunk", pszHostOnlyName);
4857 InsertConfigString(pCfg, "Network", szNetwork);
4858 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetFlt);
4859 networkName = Bstr(szNetwork);
4860 trunkName = Bstr(pszHostOnlyName);
4861 trunkType = TRUNKTYPE_NETFLT;
4862#endif
4863 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
4864
4865#if !defined(RT_OS_WINDOWS) && defined(VBOX_WITH_NETFLT)
4866
4867 Bstr tmpAddr, tmpMask;
4868
4869 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPAddress",
4870 pszHostOnlyName).raw(),
4871 tmpAddr.asOutParam());
4872 if (SUCCEEDED(hrc) && !tmpAddr.isEmpty())
4873 {
4874 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPNetMask",
4875 pszHostOnlyName).raw(),
4876 tmpMask.asOutParam());
4877 if (SUCCEEDED(hrc) && !tmpMask.isEmpty())
4878 hrc = hostInterface->EnableStaticIPConfig(tmpAddr.raw(),
4879 tmpMask.raw());
4880 else
4881 hrc = hostInterface->EnableStaticIPConfig(tmpAddr.raw(),
4882 Bstr(VBOXNET_IPV4MASK_DEFAULT).raw());
4883 }
4884 else
4885 {
4886 /* Grab the IP number from the 'vboxnetX' instance number (see netif.h) */
4887 hrc = hostInterface->EnableStaticIPConfig(getDefaultIPv4Address(Bstr(pszHostOnlyName)).raw(),
4888 Bstr(VBOXNET_IPV4MASK_DEFAULT).raw());
4889 }
4890
4891 ComAssertComRC(hrc); /** @todo r=bird: Why this isn't fatal? (H()) */
4892
4893 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6Address",
4894 pszHostOnlyName).raw(),
4895 tmpAddr.asOutParam());
4896 if (SUCCEEDED(hrc))
4897 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6NetMask", pszHostOnlyName).raw(),
4898 tmpMask.asOutParam());
4899 if (SUCCEEDED(hrc) && !tmpAddr.isEmpty() && !tmpMask.isEmpty())
4900 {
4901 hrc = hostInterface->EnableStaticIPConfigV6(tmpAddr.raw(),
4902 Utf8Str(tmpMask).toUInt32());
4903 ComAssertComRC(hrc); /** @todo r=bird: Why this isn't fatal? (H()) */
4904 }
4905#endif
4906 break;
4907 }
4908
4909 case NetworkAttachmentType_Generic:
4910 {
4911 hrc = aNetworkAdapter->COMGETTER(GenericDriver)(bstr.asOutParam()); H();
4912 SafeArray<BSTR> names;
4913 SafeArray<BSTR> values;
4914 hrc = aNetworkAdapter->GetProperties(Bstr().raw(),
4915 ComSafeArrayAsOutParam(names),
4916 ComSafeArrayAsOutParam(values)); H();
4917
4918 InsertConfigString(pLunL0, "Driver", bstr);
4919 InsertConfigNode(pLunL0, "Config", &pCfg);
4920 for (size_t ii = 0; ii < names.size(); ++ii)
4921 {
4922 if (values[ii] && *values[ii])
4923 {
4924 Utf8Str name = names[ii];
4925 Utf8Str value = values[ii];
4926 InsertConfigString(pCfg, name.c_str(), value);
4927 }
4928 }
4929 break;
4930 }
4931
4932 case NetworkAttachmentType_NATNetwork:
4933 {
4934 hrc = aNetworkAdapter->COMGETTER(NATNetwork)(bstr.asOutParam()); H();
4935 if (!bstr.isEmpty())
4936 {
4937 /** @todo add intnet prefix to separate namespaces, and add trunk if dealing with vboxnatX */
4938 InsertConfigString(pLunL0, "Driver", "IntNet");
4939 InsertConfigNode(pLunL0, "Config", &pCfg);
4940 InsertConfigString(pCfg, "Network", bstr);
4941 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_WhateverNone);
4942 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
4943 networkName = bstr;
4944 trunkType = Bstr(TRUNKTYPE_WHATEVER);
4945 }
4946 break;
4947 }
4948
4949 default:
4950 AssertMsgFailed(("should not get here!\n"));
4951 break;
4952 }
4953
4954 /*
4955 * Attempt to attach the driver.
4956 */
4957 switch (eAttachmentType)
4958 {
4959 case NetworkAttachmentType_Null:
4960 break;
4961
4962 case NetworkAttachmentType_Bridged:
4963 case NetworkAttachmentType_Internal:
4964 case NetworkAttachmentType_HostOnly:
4965 case NetworkAttachmentType_NAT:
4966 case NetworkAttachmentType_Generic:
4967 case NetworkAttachmentType_NATNetwork:
4968 {
4969 if (SUCCEEDED(hrc) && SUCCEEDED(rc))
4970 {
4971 if (fAttachDetach)
4972 {
4973 rc = PDMR3DriverAttach(mpUVM, pszDevice, uInstance, uLun, 0 /*fFlags*/, NULL /* ppBase */);
4974 //AssertRC(rc);
4975 }
4976
4977 {
4978 /** @todo pritesh: get the dhcp server name from the
4979 * previous network configuration and then stop the server
4980 * else it may conflict with the dhcp server running with
4981 * the current attachment type
4982 */
4983 /* Stop the hostonly DHCP Server */
4984 }
4985
4986 if (!networkName.isEmpty())
4987 {
4988 /*
4989 * Until we implement service reference counters DHCP Server will be stopped
4990 * by DHCPServerRunner destructor.
4991 */
4992 ComPtr<IDHCPServer> dhcpServer;
4993 hrc = virtualBox->FindDHCPServerByNetworkName(networkName.raw(),
4994 dhcpServer.asOutParam());
4995 if (SUCCEEDED(hrc))
4996 {
4997 /* there is a DHCP server available for this network */
4998 BOOL fEnabledDhcp;
4999 hrc = dhcpServer->COMGETTER(Enabled)(&fEnabledDhcp);
5000 if (FAILED(hrc))
5001 {
5002 LogRel(("DHCP svr: COMGETTER(Enabled) failed, hrc (%Rhrc)\n", hrc));
5003 H();
5004 }
5005
5006 if (fEnabledDhcp)
5007 hrc = dhcpServer->Start(networkName.raw(),
5008 trunkName.raw(),
5009 trunkType.raw());
5010 }
5011 else
5012 hrc = S_OK;
5013 }
5014 }
5015
5016 break;
5017 }
5018
5019 default:
5020 AssertMsgFailed(("should not get here!\n"));
5021 break;
5022 }
5023
5024 meAttachmentType[uInstance] = eAttachmentType;
5025 }
5026 catch (ConfigError &x)
5027 {
5028 // InsertConfig threw something:
5029 return x.m_vrc;
5030 }
5031
5032#undef H
5033
5034 return VINF_SUCCESS;
5035}
5036
5037#ifdef VBOX_WITH_GUEST_PROPS
5038/**
5039 * Set an array of guest properties
5040 */
5041static void configSetProperties(VMMDev * const pVMMDev,
5042 void *names,
5043 void *values,
5044 void *timestamps,
5045 void *flags)
5046{
5047 VBOXHGCMSVCPARM parms[4];
5048
5049 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
5050 parms[0].u.pointer.addr = names;
5051 parms[0].u.pointer.size = 0; /* We don't actually care. */
5052 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
5053 parms[1].u.pointer.addr = values;
5054 parms[1].u.pointer.size = 0; /* We don't actually care. */
5055 parms[2].type = VBOX_HGCM_SVC_PARM_PTR;
5056 parms[2].u.pointer.addr = timestamps;
5057 parms[2].u.pointer.size = 0; /* We don't actually care. */
5058 parms[3].type = VBOX_HGCM_SVC_PARM_PTR;
5059 parms[3].u.pointer.addr = flags;
5060 parms[3].u.pointer.size = 0; /* We don't actually care. */
5061
5062 pVMMDev->hgcmHostCall("VBoxGuestPropSvc",
5063 guestProp::SET_PROPS_HOST,
5064 4,
5065 &parms[0]);
5066}
5067
5068/**
5069 * Set a single guest property
5070 */
5071static void configSetProperty(VMMDev * const pVMMDev,
5072 const char *pszName,
5073 const char *pszValue,
5074 const char *pszFlags)
5075{
5076 VBOXHGCMSVCPARM parms[4];
5077
5078 AssertPtrReturnVoid(pszName);
5079 AssertPtrReturnVoid(pszValue);
5080 AssertPtrReturnVoid(pszFlags);
5081 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
5082 parms[0].u.pointer.addr = (void *)pszName;
5083 parms[0].u.pointer.size = (uint32_t)strlen(pszName) + 1;
5084 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
5085 parms[1].u.pointer.addr = (void *)pszValue;
5086 parms[1].u.pointer.size = (uint32_t)strlen(pszValue) + 1;
5087 parms[2].type = VBOX_HGCM_SVC_PARM_PTR;
5088 parms[2].u.pointer.addr = (void *)pszFlags;
5089 parms[2].u.pointer.size = (uint32_t)strlen(pszFlags) + 1;
5090 pVMMDev->hgcmHostCall("VBoxGuestPropSvc", guestProp::SET_PROP_HOST, 3,
5091 &parms[0]);
5092}
5093
5094/**
5095 * Set the global flags value by calling the service
5096 * @returns the status returned by the call to the service
5097 *
5098 * @param pTable the service instance handle
5099 * @param eFlags the flags to set
5100 */
5101int configSetGlobalPropertyFlags(VMMDev * const pVMMDev,
5102 guestProp::ePropFlags eFlags)
5103{
5104 VBOXHGCMSVCPARM paParm;
5105 paParm.setUInt32(eFlags);
5106 int rc = pVMMDev->hgcmHostCall("VBoxGuestPropSvc",
5107 guestProp::SET_GLOBAL_FLAGS_HOST, 1,
5108 &paParm);
5109 if (RT_FAILURE(rc))
5110 {
5111 char szFlags[guestProp::MAX_FLAGS_LEN];
5112 if (RT_FAILURE(writeFlags(eFlags, szFlags)))
5113 Log(("Failed to set the global flags.\n"));
5114 else
5115 Log(("Failed to set the global flags \"%s\".\n", szFlags));
5116 }
5117 return rc;
5118}
5119#endif /* VBOX_WITH_GUEST_PROPS */
5120
5121/**
5122 * Set up the Guest Property service, populate it with properties read from
5123 * the machine XML and set a couple of initial properties.
5124 */
5125/* static */ int Console::configGuestProperties(void *pvConsole, PUVM pUVM)
5126{
5127#ifdef VBOX_WITH_GUEST_PROPS
5128 AssertReturn(pvConsole, VERR_GENERAL_FAILURE);
5129 ComObjPtr<Console> pConsole = static_cast<Console *>(pvConsole);
5130 AssertReturn(pConsole->m_pVMMDev, VERR_GENERAL_FAILURE);
5131
5132 /* Load the service */
5133 int rc = pConsole->m_pVMMDev->hgcmLoadService("VBoxGuestPropSvc", "VBoxGuestPropSvc");
5134
5135 if (RT_FAILURE(rc))
5136 {
5137 LogRel(("VBoxGuestPropSvc is not available. rc = %Rrc\n", rc));
5138 /* That is not a fatal failure. */
5139 rc = VINF_SUCCESS;
5140 }
5141 else
5142 {
5143 /*
5144 * Initialize built-in properties that can be changed and saved.
5145 *
5146 * These are typically transient properties that the guest cannot
5147 * change.
5148 */
5149
5150 {
5151 VBOXHGCMSVCPARM Params[2];
5152 int rc2 = pConsole->m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", guestProp::GET_DBGF_INFO_FN, 2, &Params[0]);
5153 if (RT_SUCCESS(rc2))
5154 {
5155 PFNDBGFHANDLEREXT pfnHandler = (PFNDBGFHANDLEREXT)(uintptr_t)Params[0].u.pointer.addr;
5156 void *pService = (void*)Params[1].u.pointer.addr;
5157 DBGFR3InfoRegisterExternal(pUVM, "guestprops", "Display the guest properties", pfnHandler, pService);
5158 }
5159 }
5160
5161 /* Sysprep execution by VBoxService. */
5162 configSetProperty(pConsole->m_pVMMDev,
5163 "/VirtualBox/HostGuest/SysprepExec", "",
5164 "TRANSIENT, RDONLYGUEST");
5165 configSetProperty(pConsole->m_pVMMDev,
5166 "/VirtualBox/HostGuest/SysprepArgs", "",
5167 "TRANSIENT, RDONLYGUEST");
5168
5169 /*
5170 * Pull over the properties from the server.
5171 */
5172 SafeArray<BSTR> namesOut;
5173 SafeArray<BSTR> valuesOut;
5174 SafeArray<LONG64> timestampsOut;
5175 SafeArray<BSTR> flagsOut;
5176 HRESULT hrc;
5177 hrc = pConsole->mControl->PullGuestProperties(ComSafeArrayAsOutParam(namesOut),
5178 ComSafeArrayAsOutParam(valuesOut),
5179 ComSafeArrayAsOutParam(timestampsOut),
5180 ComSafeArrayAsOutParam(flagsOut));
5181 AssertMsgReturn(SUCCEEDED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE);
5182 size_t cProps = namesOut.size();
5183 size_t cAlloc = cProps + 1;
5184 if ( valuesOut.size() != cProps
5185 || timestampsOut.size() != cProps
5186 || flagsOut.size() != cProps
5187 )
5188 AssertFailedReturn(VERR_INVALID_PARAMETER);
5189
5190 char **papszNames, **papszValues, **papszFlags;
5191 char szEmpty[] = "";
5192 LONG64 *pai64Timestamps;
5193 papszNames = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
5194 papszValues = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
5195 pai64Timestamps = (LONG64 *)RTMemTmpAllocZ(sizeof(LONG64) * cAlloc);
5196 papszFlags = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
5197 if (papszNames && papszValues && pai64Timestamps && papszFlags)
5198 {
5199 for (unsigned i = 0; RT_SUCCESS(rc) && i < cProps; ++i)
5200 {
5201 AssertPtrReturn(namesOut[i], VERR_INVALID_PARAMETER);
5202 rc = RTUtf16ToUtf8(namesOut[i], &papszNames[i]);
5203 if (RT_FAILURE(rc))
5204 break;
5205 if (valuesOut[i])
5206 rc = RTUtf16ToUtf8(valuesOut[i], &papszValues[i]);
5207 else
5208 papszValues[i] = szEmpty;
5209 if (RT_FAILURE(rc))
5210 break;
5211 pai64Timestamps[i] = timestampsOut[i];
5212 if (flagsOut[i])
5213 rc = RTUtf16ToUtf8(flagsOut[i], &papszFlags[i]);
5214 else
5215 papszFlags[i] = szEmpty;
5216 }
5217 if (RT_SUCCESS(rc))
5218 configSetProperties(pConsole->m_pVMMDev,
5219 (void *)papszNames,
5220 (void *)papszValues,
5221 (void *)pai64Timestamps,
5222 (void *)papszFlags);
5223 for (unsigned i = 0; i < cProps; ++i)
5224 {
5225 RTStrFree(papszNames[i]);
5226 if (valuesOut[i])
5227 RTStrFree(papszValues[i]);
5228 if (flagsOut[i])
5229 RTStrFree(papszFlags[i]);
5230 }
5231 }
5232 else
5233 rc = VERR_NO_MEMORY;
5234 RTMemTmpFree(papszNames);
5235 RTMemTmpFree(papszValues);
5236 RTMemTmpFree(pai64Timestamps);
5237 RTMemTmpFree(papszFlags);
5238 AssertRCReturn(rc, rc);
5239
5240 /*
5241 * These properties have to be set before pulling over the properties
5242 * from the machine XML, to ensure that properties saved in the XML
5243 * will override them.
5244 */
5245 /* Set the raw VBox version string as a guest property. Used for host/guest
5246 * version comparison. */
5247 configSetProperty(pConsole->m_pVMMDev, "/VirtualBox/HostInfo/VBoxVer",
5248 VBOX_VERSION_STRING_RAW, "TRANSIENT, RDONLYGUEST");
5249 /* Set the full VBox version string as a guest property. Can contain vendor-specific
5250 * information/branding and/or pre-release tags. */
5251 configSetProperty(pConsole->m_pVMMDev, "/VirtualBox/HostInfo/VBoxVerExt",
5252 VBOX_VERSION_STRING, "TRANSIENT, RDONLYGUEST");
5253 /* Set the VBox SVN revision as a guest property */
5254 configSetProperty(pConsole->m_pVMMDev, "/VirtualBox/HostInfo/VBoxRev",
5255 RTBldCfgRevisionStr(), "TRANSIENT, RDONLYGUEST");
5256
5257 /*
5258 * Register the host notification callback
5259 */
5260 HGCMSVCEXTHANDLE hDummy;
5261 HGCMHostRegisterServiceExtension(&hDummy, "VBoxGuestPropSvc",
5262 Console::doGuestPropNotification,
5263 pvConsole);
5264
5265#ifdef VBOX_WITH_GUEST_PROPS_RDONLY_GUEST
5266 rc = configSetGlobalPropertyFlags(pConsole->m_pVMMDev,
5267 guestProp::RDONLYGUEST);
5268 AssertRCReturn(rc, rc);
5269#endif
5270
5271 Log(("Set VBoxGuestPropSvc property store\n"));
5272 }
5273 return VINF_SUCCESS;
5274#else /* !VBOX_WITH_GUEST_PROPS */
5275 return VERR_NOT_SUPPORTED;
5276#endif /* !VBOX_WITH_GUEST_PROPS */
5277}
5278
5279/**
5280 * Set up the Guest Control service.
5281 */
5282/* static */ int Console::configGuestControl(void *pvConsole)
5283{
5284#ifdef VBOX_WITH_GUEST_CONTROL
5285 AssertReturn(pvConsole, VERR_GENERAL_FAILURE);
5286 ComObjPtr<Console> pConsole = static_cast<Console *>(pvConsole);
5287
5288 /* Load the service */
5289 int rc = pConsole->m_pVMMDev->hgcmLoadService("VBoxGuestControlSvc", "VBoxGuestControlSvc");
5290
5291 if (RT_FAILURE(rc))
5292 {
5293 LogRel(("VBoxGuestControlSvc is not available. rc = %Rrc\n", rc));
5294 /* That is not a fatal failure. */
5295 rc = VINF_SUCCESS;
5296 }
5297 else
5298 {
5299 HGCMSVCEXTHANDLE hDummy;
5300 rc = HGCMHostRegisterServiceExtension(&hDummy, "VBoxGuestControlSvc",
5301 &Guest::notifyCtrlDispatcher,
5302 pConsole->getGuest());
5303 if (RT_FAILURE(rc))
5304 Log(("Cannot register VBoxGuestControlSvc extension!\n"));
5305 else
5306 Log(("VBoxGuestControlSvc loaded\n"));
5307 }
5308
5309 return rc;
5310#else /* !VBOX_WITH_GUEST_CONTROL */
5311 return VERR_NOT_SUPPORTED;
5312#endif /* !VBOX_WITH_GUEST_CONTROL */
5313}
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