VirtualBox

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

Last change on this file since 37215 was 37215, checked in by vboxsync, 14 years ago

Main/UsbWebcam: disabled peremeters for initialization of device & driver (for debug only).

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette