VirtualBox

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

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

PCI: Main and VBoxManage work

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 194.4 KB
Line 
1/* $Id: ConsoleImpl2.cpp 36630 2011-04-08 18:41:51Z 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-2010 Oracle Corporation
13 *
14 * This file is part of VirtualBox Open Source Edition (OSE), as
15 * available from http://www.virtualbox.org. This file is free software;
16 * you can redistribute it and/or modify it under the terms of the GNU
17 * General Public License (GPL) as published by the Free Software
18 * Foundation, in version 2 as it comes in the "COPYING" file of the
19 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
20 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
21 */
22
23/*******************************************************************************
24* Header Files *
25*******************************************************************************/
26// for some reason Windows burns in sdk\...\winsock.h if this isn't included first
27#include "VBox/com/ptr.h"
28
29#include "ConsoleImpl.h"
30#include "DisplayImpl.h"
31#ifdef VBOX_WITH_GUEST_CONTROL
32# include "GuestImpl.h"
33#endif
34#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 pDev, 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 }
1075
1076 /*
1077 * System Management Controller (SMC)
1078 */
1079 BOOL fSmcEnabled;
1080 fSmcEnabled = fOsXGuest;
1081 if (fSmcEnabled)
1082 {
1083 InsertConfigNode(pDevices, "smc", &pDev);
1084 InsertConfigNode(pDev, "0", &pInst);
1085 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1086 InsertConfigNode(pInst, "Config", &pCfg);
1087
1088 bool fGetKeyFromRealSMC;
1089 Bstr bstrKey;
1090 rc = getSmcDeviceKey(pMachine, bstrKey.asOutParam(), &fGetKeyFromRealSMC);
1091 AssertRCReturn(rc, rc);
1092
1093 InsertConfigString(pCfg, "DeviceKey", bstrKey);
1094 InsertConfigInteger(pCfg, "GetKeyFromRealSMC", fGetKeyFromRealSMC);
1095 }
1096
1097 /*
1098 * Low Pin Count (LPC) bus
1099 */
1100 BOOL fLpcEnabled;
1101 /** @todo: implement appropriate getter */
1102 fLpcEnabled = fOsXGuest || (chipsetType == ChipsetType_ICH9);
1103 if (fLpcEnabled)
1104 {
1105 InsertConfigNode(pDevices, "lpc", &pDev);
1106 InsertConfigNode(pDev, "0", &pInst);
1107 hrc = BusMgr->assignPciDevice("lpc", pInst); H();
1108 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1109 }
1110
1111 BOOL fShowRtc;
1112 fShowRtc = fOsXGuest || (chipsetType == ChipsetType_ICH9);
1113
1114 /*
1115 * PS/2 keyboard & mouse.
1116 */
1117 InsertConfigNode(pDevices, "pckbd", &pDev);
1118 InsertConfigNode(pDev, "0", &pInst);
1119 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1120 InsertConfigNode(pInst, "Config", &pCfg);
1121
1122 InsertConfigNode(pInst, "LUN#0", &pLunL0);
1123 InsertConfigString(pLunL0, "Driver", "KeyboardQueue");
1124 InsertConfigNode(pLunL0, "Config", &pCfg);
1125 InsertConfigInteger(pCfg, "QueueSize", 64);
1126
1127 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
1128 InsertConfigString(pLunL1, "Driver", "MainKeyboard");
1129 InsertConfigNode(pLunL1, "Config", &pCfg);
1130 Keyboard *pKeyboard = mKeyboard;
1131 InsertConfigInteger(pCfg, "Object", (uintptr_t)pKeyboard);
1132
1133 InsertConfigNode(pInst, "LUN#1", &pLunL0);
1134 InsertConfigString(pLunL0, "Driver", "MouseQueue");
1135 InsertConfigNode(pLunL0, "Config", &pCfg);
1136 InsertConfigInteger(pCfg, "QueueSize", 128);
1137
1138 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
1139 InsertConfigString(pLunL1, "Driver", "MainMouse");
1140 InsertConfigNode(pLunL1, "Config", &pCfg);
1141 Mouse *pMouse = mMouse;
1142 InsertConfigInteger(pCfg, "Object", (uintptr_t)pMouse);
1143
1144 /*
1145 * i8254 Programmable Interval Timer And Dummy Speaker
1146 */
1147 InsertConfigNode(pDevices, "i8254", &pDev);
1148 InsertConfigNode(pDev, "0", &pInst);
1149 InsertConfigNode(pInst, "Config", &pCfg);
1150#ifdef DEBUG
1151 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1152#endif
1153
1154 /*
1155 * i8259 Programmable Interrupt Controller.
1156 */
1157 InsertConfigNode(pDevices, "i8259", &pDev);
1158 InsertConfigNode(pDev, "0", &pInst);
1159 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1160 InsertConfigNode(pInst, "Config", &pCfg);
1161
1162 /*
1163 * Advanced Programmable Interrupt Controller.
1164 * SMP: Each CPU has a LAPIC, but we have a single device representing all LAPICs states,
1165 * thus only single insert
1166 */
1167 InsertConfigNode(pDevices, "apic", &pDev);
1168 InsertConfigNode(pDev, "0", &pInst);
1169 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1170 InsertConfigNode(pInst, "Config", &pCfg);
1171 InsertConfigInteger(pCfg, "IOAPIC", fIOAPIC);
1172 InsertConfigInteger(pCfg, "NumCPUs", cCpus);
1173
1174 if (fIOAPIC)
1175 {
1176 /*
1177 * I/O Advanced Programmable Interrupt Controller.
1178 */
1179 InsertConfigNode(pDevices, "ioapic", &pDev);
1180 InsertConfigNode(pDev, "0", &pInst);
1181 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1182 InsertConfigNode(pInst, "Config", &pCfg);
1183 InsertConfigInteger(pCfg, "NumCPUs", cCpus);
1184 }
1185
1186 /*
1187 * RTC MC146818.
1188 */
1189 InsertConfigNode(pDevices, "mc146818", &pDev);
1190 InsertConfigNode(pDev, "0", &pInst);
1191 InsertConfigNode(pInst, "Config", &pCfg);
1192 BOOL fRTCUseUTC;
1193 hrc = pMachine->COMGETTER(RTCUseUTC)(&fRTCUseUTC); H();
1194 InsertConfigInteger(pCfg, "UseUTC", fRTCUseUTC ? 1 : 0);
1195
1196 /*
1197 * VGA.
1198 */
1199 InsertConfigNode(pDevices, "vga", &pDev);
1200 InsertConfigNode(pDev, "0", &pInst);
1201 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1202
1203 hrc = BusMgr->assignPciDevice("vga", pInst); H();
1204 InsertConfigNode(pInst, "Config", &pCfg);
1205 ULONG cVRamMBs;
1206 hrc = pMachine->COMGETTER(VRAMSize)(&cVRamMBs); H();
1207 InsertConfigInteger(pCfg, "VRamSize", cVRamMBs * _1M);
1208 ULONG cMonitorCount;
1209 hrc = pMachine->COMGETTER(MonitorCount)(&cMonitorCount); H();
1210 InsertConfigInteger(pCfg, "MonitorCount", cMonitorCount);
1211#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
1212 InsertConfigInteger(pCfg, "R0Enabled", fHWVirtExEnabled);
1213#endif
1214
1215 /*
1216 * BIOS logo
1217 */
1218 BOOL fFadeIn;
1219 hrc = biosSettings->COMGETTER(LogoFadeIn)(&fFadeIn); H();
1220 InsertConfigInteger(pCfg, "FadeIn", fFadeIn ? 1 : 0);
1221 BOOL fFadeOut;
1222 hrc = biosSettings->COMGETTER(LogoFadeOut)(&fFadeOut); H();
1223 InsertConfigInteger(pCfg, "FadeOut", fFadeOut ? 1: 0);
1224 ULONG logoDisplayTime;
1225 hrc = biosSettings->COMGETTER(LogoDisplayTime)(&logoDisplayTime); H();
1226 InsertConfigInteger(pCfg, "LogoTime", logoDisplayTime);
1227 Bstr logoImagePath;
1228 hrc = biosSettings->COMGETTER(LogoImagePath)(logoImagePath.asOutParam()); H();
1229 InsertConfigString(pCfg, "LogoFile", Utf8Str(!logoImagePath.isEmpty() ? logoImagePath : "") );
1230
1231 /*
1232 * Boot menu
1233 */
1234 BIOSBootMenuMode_T eBootMenuMode;
1235 int iShowBootMenu;
1236 biosSettings->COMGETTER(BootMenuMode)(&eBootMenuMode);
1237 switch (eBootMenuMode)
1238 {
1239 case BIOSBootMenuMode_Disabled: iShowBootMenu = 0; break;
1240 case BIOSBootMenuMode_MenuOnly: iShowBootMenu = 1; break;
1241 default: iShowBootMenu = 2; break;
1242 }
1243 InsertConfigInteger(pCfg, "ShowBootMenu", iShowBootMenu);
1244
1245 /* Custom VESA mode list */
1246 unsigned cModes = 0;
1247 for (unsigned iMode = 1; iMode <= 16; ++iMode)
1248 {
1249 char szExtraDataKey[sizeof("CustomVideoModeXX")];
1250 RTStrPrintf(szExtraDataKey, sizeof(szExtraDataKey), "CustomVideoMode%u", iMode);
1251 hrc = pMachine->GetExtraData(Bstr(szExtraDataKey).raw(), bstr.asOutParam()); H();
1252 if (bstr.isEmpty())
1253 break;
1254 InsertConfigString(pCfg, szExtraDataKey, bstr);
1255 ++cModes;
1256 }
1257 InsertConfigInteger(pCfg, "CustomVideoModes", cModes);
1258
1259 /* VESA height reduction */
1260 ULONG ulHeightReduction;
1261 IFramebuffer *pFramebuffer = getDisplay()->getFramebuffer();
1262 if (pFramebuffer)
1263 {
1264 hrc = pFramebuffer->COMGETTER(HeightReduction)(&ulHeightReduction); H();
1265 }
1266 else
1267 {
1268 /* If framebuffer is not available, there is no height reduction. */
1269 ulHeightReduction = 0;
1270 }
1271 InsertConfigInteger(pCfg, "HeightReduction", ulHeightReduction);
1272
1273 /* Attach the display. */
1274 InsertConfigNode(pInst, "LUN#0", &pLunL0);
1275 InsertConfigString(pLunL0, "Driver", "MainDisplay");
1276 InsertConfigNode(pLunL0, "Config", &pCfg);
1277 Display *pDisplay = mDisplay;
1278 InsertConfigInteger(pCfg, "Object", (uintptr_t)pDisplay);
1279
1280
1281 /*
1282 * Firmware.
1283 */
1284 FirmwareType_T eFwType = FirmwareType_BIOS;
1285 hrc = pMachine->COMGETTER(FirmwareType)(&eFwType); H();
1286
1287#ifdef VBOX_WITH_EFI
1288 BOOL fEfiEnabled = (eFwType >= FirmwareType_EFI) && (eFwType <= FirmwareType_EFIDUAL);
1289#else
1290 BOOL fEfiEnabled = false;
1291#endif
1292 if (!fEfiEnabled)
1293 {
1294 /*
1295 * PC Bios.
1296 */
1297 InsertConfigNode(pDevices, "pcbios", &pDev);
1298 InsertConfigNode(pDev, "0", &pInst);
1299 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1300 InsertConfigNode(pInst, "Config", &pBiosCfg);
1301 InsertConfigInteger(pBiosCfg, "RamSize", cbRam);
1302 InsertConfigInteger(pBiosCfg, "RamHoleSize", cbRamHole);
1303 InsertConfigInteger(pBiosCfg, "NumCPUs", cCpus);
1304 InsertConfigString(pBiosCfg, "HardDiskDevice", "piix3ide");
1305 InsertConfigString(pBiosCfg, "FloppyDevice", "i82078");
1306 InsertConfigInteger(pBiosCfg, "IOAPIC", fIOAPIC);
1307 InsertConfigInteger(pBiosCfg, "PXEDebug", fPXEDebug);
1308 InsertConfigBytes(pBiosCfg, "UUID", &HardwareUuid,sizeof(HardwareUuid));
1309 InsertConfigNode(pBiosCfg, "NetBoot", &pNetBootCfg);
1310 InsertConfigInteger(pBiosCfg, "McfgBase", uMcfgBase);
1311 InsertConfigInteger(pBiosCfg, "McfgLength", cbMcfgLength);
1312
1313 DeviceType_T bootDevice;
1314 if (SchemaDefs::MaxBootPosition > 9)
1315 {
1316 AssertMsgFailed(("Too many boot devices %d\n",
1317 SchemaDefs::MaxBootPosition));
1318 return VERR_INVALID_PARAMETER;
1319 }
1320
1321 for (ULONG pos = 1; pos <= SchemaDefs::MaxBootPosition; ++pos)
1322 {
1323 hrc = pMachine->GetBootOrder(pos, &bootDevice); H();
1324
1325 char szParamName[] = "BootDeviceX";
1326 szParamName[sizeof(szParamName) - 2] = ((char (pos - 1)) + '0');
1327
1328 const char *pszBootDevice;
1329 switch (bootDevice)
1330 {
1331 case DeviceType_Null:
1332 pszBootDevice = "NONE";
1333 break;
1334 case DeviceType_HardDisk:
1335 pszBootDevice = "IDE";
1336 break;
1337 case DeviceType_DVD:
1338 pszBootDevice = "DVD";
1339 break;
1340 case DeviceType_Floppy:
1341 pszBootDevice = "FLOPPY";
1342 break;
1343 case DeviceType_Network:
1344 pszBootDevice = "LAN";
1345 break;
1346 default:
1347 AssertMsgFailed(("Invalid bootDevice=%d\n", bootDevice));
1348 return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
1349 N_("Invalid boot device '%d'"), bootDevice);
1350 }
1351 InsertConfigString(pBiosCfg, szParamName, pszBootDevice);
1352 }
1353 }
1354 else
1355 {
1356 /* Autodetect firmware type, basing on guest type */
1357 if (eFwType == FirmwareType_EFI)
1358 {
1359 eFwType = fIsGuest64Bit
1360 ? (FirmwareType_T)FirmwareType_EFI64
1361 : (FirmwareType_T)FirmwareType_EFI32;
1362 }
1363 bool const f64BitEntry = eFwType == FirmwareType_EFI64;
1364
1365 Utf8Str efiRomFile;
1366 rc = findEfiRom(virtualBox, eFwType, &efiRomFile);
1367 AssertRCReturn(rc, rc);
1368
1369 /* Get boot args */
1370 Bstr bootArgs;
1371 hrc = pMachine->GetExtraData(Bstr("VBoxInternal2/EfiBootArgs").raw(), bootArgs.asOutParam()); H();
1372
1373 /* Get device props */
1374 Bstr deviceProps;
1375 hrc = pMachine->GetExtraData(Bstr("VBoxInternal2/EfiDeviceProps").raw(), deviceProps.asOutParam()); H();
1376
1377 /* Get GOP mode settings */
1378 uint32_t u32GopMode = UINT32_MAX;
1379 hrc = pMachine->GetExtraData(Bstr("VBoxInternal2/EfiGopMode").raw(), bstr.asOutParam()); H();
1380 if (!bstr.isEmpty())
1381 u32GopMode = Utf8Str(bstr).toUInt32();
1382
1383 /* UGA mode settings */
1384 uint32_t u32UgaHorisontal = 0;
1385 hrc = pMachine->GetExtraData(Bstr("VBoxInternal2/EfiUgaHorizontalResolution").raw(), bstr.asOutParam()); H();
1386 if (!bstr.isEmpty())
1387 u32UgaHorisontal = Utf8Str(bstr).toUInt32();
1388
1389 uint32_t u32UgaVertical = 0;
1390 hrc = pMachine->GetExtraData(Bstr("VBoxInternal2/EfiUgaVerticalResolution").raw(), bstr.asOutParam()); H();
1391 if (!bstr.isEmpty())
1392 u32UgaVertical = Utf8Str(bstr).toUInt32();
1393
1394 /*
1395 * EFI subtree.
1396 */
1397 InsertConfigNode(pDevices, "efi", &pDev);
1398 InsertConfigNode(pDev, "0", &pInst);
1399 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1400 InsertConfigNode(pInst, "Config", &pCfg);
1401 InsertConfigInteger(pCfg, "RamSize", cbRam);
1402 InsertConfigInteger(pCfg, "RamHoleSize", cbRamHole);
1403 InsertConfigInteger(pCfg, "NumCPUs", cCpus);
1404 InsertConfigString(pCfg, "EfiRom", efiRomFile);
1405 InsertConfigString(pCfg, "BootArgs", bootArgs);
1406 InsertConfigString(pCfg, "DeviceProps", deviceProps);
1407 InsertConfigInteger(pCfg, "IOAPIC", fIOAPIC);
1408 InsertConfigBytes(pCfg, "UUID", &HardwareUuid,sizeof(HardwareUuid));
1409 InsertConfigInteger(pCfg, "64BitEntry", f64BitEntry); /* boolean */
1410 InsertConfigInteger(pCfg, "GopMode", u32GopMode);
1411 InsertConfigInteger(pCfg, "UgaHorizontalResolution", u32UgaHorisontal);
1412 InsertConfigInteger(pCfg, "UgaVerticalResolution", u32UgaVertical);
1413
1414 /* For OS X guests we'll force passing host's DMI info to the guest */
1415 if (fOsXGuest)
1416 {
1417 InsertConfigInteger(pCfg, "DmiUseHostInfo", 1);
1418 InsertConfigInteger(pCfg, "DmiExposeMemoryTable", 1);
1419 }
1420 }
1421
1422 /*
1423 * Storage controllers.
1424 */
1425 com::SafeIfaceArray<IStorageController> ctrls;
1426 PCFGMNODE aCtrlNodes[StorageControllerType_LsiLogicSas + 1] = {};
1427 hrc = pMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls)); H();
1428
1429 bool fFdcEnabled = false;
1430 for (size_t i = 0; i < ctrls.size(); ++i)
1431 {
1432 DeviceType_T *paLedDevType = NULL;
1433
1434 StorageControllerType_T enmCtrlType;
1435 rc = ctrls[i]->COMGETTER(ControllerType)(&enmCtrlType); H();
1436 AssertRelease((unsigned)enmCtrlType < RT_ELEMENTS(aCtrlNodes));
1437
1438 StorageBus_T enmBus;
1439 rc = ctrls[i]->COMGETTER(Bus)(&enmBus); H();
1440
1441 Bstr controllerName;
1442 rc = ctrls[i]->COMGETTER(Name)(controllerName.asOutParam()); H();
1443
1444 ULONG ulInstance = 999;
1445 rc = ctrls[i]->COMGETTER(Instance)(&ulInstance); H();
1446
1447 BOOL fUseHostIOCache;
1448 rc = ctrls[i]->COMGETTER(UseHostIOCache)(&fUseHostIOCache); H();
1449
1450 BOOL fBootable;
1451 rc = ctrls[i]->COMGETTER(Bootable)(&fBootable); H();
1452
1453 /* /Devices/<ctrldev>/ */
1454 const char *pszCtrlDev = convertControllerTypeToDev(enmCtrlType);
1455 pDev = aCtrlNodes[enmCtrlType];
1456 if (!pDev)
1457 {
1458 InsertConfigNode(pDevices, pszCtrlDev, &pDev);
1459 aCtrlNodes[enmCtrlType] = pDev; /* IDE variants are handled in the switch */
1460 }
1461
1462 /* /Devices/<ctrldev>/<instance>/ */
1463 PCFGMNODE pCtlInst = NULL;
1464 InsertConfigNode(pDev, Utf8StrFmt("%u", ulInstance).c_str(), &pCtlInst);
1465
1466 /* Device config: /Devices/<ctrldev>/<instance>/<values> & /ditto/Config/<values> */
1467 InsertConfigInteger(pCtlInst, "Trusted", 1);
1468 InsertConfigNode(pCtlInst, "Config", &pCfg);
1469
1470 switch (enmCtrlType)
1471 {
1472 case StorageControllerType_LsiLogic:
1473 {
1474 hrc = BusMgr->assignPciDevice("lsilogic", pCtlInst); H();
1475
1476 InsertConfigInteger(pCfg, "Bootable", fBootable);
1477
1478 /* Attach the status driver */
1479 InsertConfigNode(pCtlInst, "LUN#999", &pLunL0);
1480 InsertConfigString(pLunL0, "Driver", "MainStatus");
1481 InsertConfigNode(pLunL0, "Config", &pCfg);
1482 InsertConfigInteger(pCfg, "papLeds", (uintptr_t)&mapStorageLeds[iLedScsi]);
1483 InsertConfigInteger(pCfg, "First", 0);
1484 Assert(cLedScsi >= 16);
1485 InsertConfigInteger(pCfg, "Last", 15);
1486 paLedDevType = &maStorageDevType[iLedScsi];
1487 break;
1488 }
1489
1490 case StorageControllerType_BusLogic:
1491 {
1492 hrc = BusMgr->assignPciDevice("buslogic", pCtlInst); H();
1493
1494 InsertConfigInteger(pCfg, "Bootable", fBootable);
1495
1496 /* Attach the status driver */
1497 InsertConfigNode(pCtlInst, "LUN#999", &pLunL0);
1498 InsertConfigString(pLunL0, "Driver", "MainStatus");
1499 InsertConfigNode(pLunL0, "Config", &pCfg);
1500 InsertConfigInteger(pCfg, "papLeds", (uintptr_t)&mapStorageLeds[iLedScsi]);
1501 InsertConfigInteger(pCfg, "First", 0);
1502 Assert(cLedScsi >= 16);
1503 InsertConfigInteger(pCfg, "Last", 15);
1504 paLedDevType = &maStorageDevType[iLedScsi];
1505 break;
1506 }
1507
1508 case StorageControllerType_IntelAhci:
1509 {
1510 hrc = BusMgr->assignPciDevice("ahci", pCtlInst); H();
1511
1512 ULONG cPorts = 0;
1513 hrc = ctrls[i]->COMGETTER(PortCount)(&cPorts); H();
1514 InsertConfigInteger(pCfg, "PortCount", cPorts);
1515 InsertConfigInteger(pCfg, "Bootable", fBootable);
1516
1517 /* Needed configuration values for the bios, only first controller. */
1518 if (!BusMgr->hasPciDevice("ahci", 1))
1519 {
1520 if (pBiosCfg)
1521 {
1522 InsertConfigString(pBiosCfg, "SataHardDiskDevice", "ahci");
1523 }
1524
1525 for (uint32_t j = 0; j < 4; ++j)
1526 {
1527 static const char * const s_apszConfig[4] =
1528 { "PrimaryMaster", "PrimarySlave", "SecondaryMaster", "SecondarySlave" };
1529 static const char * const s_apszBiosConfig[4] =
1530 { "SataPrimaryMasterLUN", "SataPrimarySlaveLUN", "SataSecondaryMasterLUN", "SataSecondarySlaveLUN" };
1531
1532 LONG lPortNumber = -1;
1533 hrc = ctrls[i]->GetIDEEmulationPort(j, &lPortNumber); H();
1534 InsertConfigInteger(pCfg, s_apszConfig[j], lPortNumber);
1535 if (pBiosCfg)
1536 InsertConfigInteger(pBiosCfg, s_apszBiosConfig[j], lPortNumber);
1537 }
1538 }
1539
1540 /* Attach the status driver */
1541 InsertConfigNode(pCtlInst, "LUN#999", &pLunL0);
1542 InsertConfigString(pLunL0, "Driver", "MainStatus");
1543 InsertConfigNode(pLunL0, "Config", &pCfg);
1544 AssertRelease(cPorts <= cLedSata);
1545 InsertConfigInteger(pCfg, "papLeds", (uintptr_t)&mapStorageLeds[iLedSata]);
1546 InsertConfigInteger(pCfg, "First", 0);
1547 InsertConfigInteger(pCfg, "Last", cPorts - 1);
1548 paLedDevType = &maStorageDevType[iLedSata];
1549 break;
1550 }
1551
1552 case StorageControllerType_PIIX3:
1553 case StorageControllerType_PIIX4:
1554 case StorageControllerType_ICH6:
1555 {
1556 /*
1557 * IDE (update this when the main interface changes)
1558 */
1559 hrc = BusMgr->assignPciDevice("piix3ide", pCtlInst); H();
1560 InsertConfigString(pCfg, "Type", controllerString(enmCtrlType));
1561
1562 /* Attach the status driver */
1563 InsertConfigNode(pCtlInst, "LUN#999", &pLunL0);
1564 InsertConfigString(pLunL0, "Driver", "MainStatus");
1565 InsertConfigNode(pLunL0, "Config", &pCfg);
1566 InsertConfigInteger(pCfg, "papLeds", (uintptr_t)&mapStorageLeds[iLedIde]);
1567 InsertConfigInteger(pCfg, "First", 0);
1568 Assert(cLedIde >= 4);
1569 InsertConfigInteger(pCfg, "Last", 3);
1570 paLedDevType = &maStorageDevType[iLedIde];
1571
1572 /* IDE flavors */
1573 aCtrlNodes[StorageControllerType_PIIX3] = pDev;
1574 aCtrlNodes[StorageControllerType_PIIX4] = pDev;
1575 aCtrlNodes[StorageControllerType_ICH6] = pDev;
1576 break;
1577 }
1578
1579 case StorageControllerType_I82078:
1580 {
1581 /*
1582 * i82078 Floppy drive controller
1583 */
1584 fFdcEnabled = true;
1585 InsertConfigInteger(pCfg, "IRQ", 6);
1586 InsertConfigInteger(pCfg, "DMA", 2);
1587 InsertConfigInteger(pCfg, "MemMapped", 0 );
1588 InsertConfigInteger(pCfg, "IOBase", 0x3f0);
1589
1590 /* Attach the status driver */
1591 InsertConfigNode(pCtlInst, "LUN#999", &pLunL0);
1592 InsertConfigString(pLunL0, "Driver", "MainStatus");
1593 InsertConfigNode(pLunL0, "Config", &pCfg);
1594 InsertConfigInteger(pCfg, "papLeds", (uintptr_t)&mapStorageLeds[iLedFloppy]);
1595 InsertConfigInteger(pCfg, "First", 0);
1596 Assert(cLedFloppy >= 1);
1597 InsertConfigInteger(pCfg, "Last", 0);
1598 paLedDevType = &maStorageDevType[iLedFloppy];
1599 break;
1600 }
1601
1602 case StorageControllerType_LsiLogicSas:
1603 {
1604 hrc = BusMgr->assignPciDevice("lsilogicsas", pCtlInst); H();
1605
1606 InsertConfigString(pCfg, "ControllerType", "SAS1068");
1607 InsertConfigInteger(pCfg, "Bootable", fBootable);
1608
1609 /* Attach the status driver */
1610 InsertConfigNode(pCtlInst, "LUN#999", &pLunL0);
1611 InsertConfigString(pLunL0, "Driver", "MainStatus");
1612 InsertConfigNode(pLunL0, "Config", &pCfg);
1613 InsertConfigInteger(pCfg, "papLeds", (uintptr_t)&mapStorageLeds[iLedSas]);
1614 InsertConfigInteger(pCfg, "First", 0);
1615 Assert(cLedSas >= 8);
1616 InsertConfigInteger(pCfg, "Last", 7);
1617 paLedDevType = &maStorageDevType[iLedSas];
1618 break;
1619 }
1620
1621 default:
1622 AssertMsgFailedReturn(("invalid storage controller type: %d\n", enmCtrlType), VERR_GENERAL_FAILURE);
1623 }
1624
1625 /* Attach the media to the storage controllers. */
1626 com::SafeIfaceArray<IMediumAttachment> atts;
1627 hrc = pMachine->GetMediumAttachmentsOfController(controllerName.raw(),
1628 ComSafeArrayAsOutParam(atts)); H();
1629
1630 /* Builtin I/O cache - per device setting. */
1631 BOOL fBuiltinIoCache = true;
1632 hrc = pMachine->COMGETTER(IoCacheEnabled)(&fBuiltinIoCache); H();
1633
1634
1635 for (size_t j = 0; j < atts.size(); ++j)
1636 {
1637 rc = configMediumAttachment(pCtlInst,
1638 pszCtrlDev,
1639 ulInstance,
1640 enmBus,
1641 !!fUseHostIOCache,
1642 !!fBuiltinIoCache,
1643 false /* fSetupMerge */,
1644 0 /* uMergeSource */,
1645 0 /* uMergeTarget */,
1646 atts[j],
1647 mMachineState,
1648 NULL /* phrc */,
1649 false /* fAttachDetach */,
1650 false /* fForceUnmount */,
1651 pVM,
1652 paLedDevType);
1653 if (RT_FAILURE(rc))
1654 return rc;
1655 }
1656 H();
1657 }
1658 H();
1659
1660 /*
1661 * Network adapters
1662 */
1663#ifdef VMWARE_NET_IN_SLOT_11
1664 bool fSwapSlots3and11 = false;
1665#endif
1666 PCFGMNODE pDevPCNet = NULL; /* PCNet-type devices */
1667 InsertConfigNode(pDevices, "pcnet", &pDevPCNet);
1668#ifdef VBOX_WITH_E1000
1669 PCFGMNODE pDevE1000 = NULL; /* E1000-type devices */
1670 InsertConfigNode(pDevices, "e1000", &pDevE1000);
1671#endif
1672#ifdef VBOX_WITH_VIRTIO
1673 PCFGMNODE pDevVirtioNet = NULL; /* Virtio network devices */
1674 InsertConfigNode(pDevices, "virtio-net", &pDevVirtioNet);
1675#endif /* VBOX_WITH_VIRTIO */
1676 std::list<BootNic> llBootNics;
1677 for (ULONG ulInstance = 0; ulInstance < SchemaDefs::NetworkAdapterCount; ++ulInstance)
1678 {
1679 ComPtr<INetworkAdapter> networkAdapter;
1680 hrc = pMachine->GetNetworkAdapter(ulInstance, networkAdapter.asOutParam()); H();
1681 BOOL fEnabled = FALSE;
1682 hrc = networkAdapter->COMGETTER(Enabled)(&fEnabled); H();
1683 if (!fEnabled)
1684 continue;
1685
1686 /*
1687 * The virtual hardware type. Create appropriate device first.
1688 */
1689 const char *pszAdapterName = "pcnet";
1690 NetworkAdapterType_T adapterType;
1691 hrc = networkAdapter->COMGETTER(AdapterType)(&adapterType); H();
1692 switch (adapterType)
1693 {
1694 case NetworkAdapterType_Am79C970A:
1695 case NetworkAdapterType_Am79C973:
1696 pDev = pDevPCNet;
1697 break;
1698#ifdef VBOX_WITH_E1000
1699 case NetworkAdapterType_I82540EM:
1700 case NetworkAdapterType_I82543GC:
1701 case NetworkAdapterType_I82545EM:
1702 pDev = pDevE1000;
1703 pszAdapterName = "e1000";
1704 break;
1705#endif
1706#ifdef VBOX_WITH_VIRTIO
1707 case NetworkAdapterType_Virtio:
1708 pDev = pDevVirtioNet;
1709 pszAdapterName = "virtio-net";
1710 break;
1711#endif /* VBOX_WITH_VIRTIO */
1712 default:
1713 AssertMsgFailed(("Invalid network adapter type '%d' for slot '%d'",
1714 adapterType, ulInstance));
1715 return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
1716 N_("Invalid network adapter type '%d' for slot '%d'"),
1717 adapterType, ulInstance);
1718 }
1719
1720 InsertConfigNode(pDev, Utf8StrFmt("%u", ulInstance).c_str(), &pInst);
1721 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1722 /* the first network card gets the PCI ID 3, the next 3 gets 8..10,
1723 * next 4 get 16..19. */
1724 int iPciDeviceNo;
1725 switch (ulInstance)
1726 {
1727 case 0:
1728 iPciDeviceNo = 3;
1729 break;
1730 case 1: case 2: case 3:
1731 iPciDeviceNo = ulInstance - 1 + 8;
1732 break;
1733 case 4: case 5: case 6: case 7:
1734 iPciDeviceNo = ulInstance - 4 + 16;
1735 break;
1736 default:
1737 /* auto assignment */
1738 iPciDeviceNo = -1;
1739 break;
1740 }
1741#ifdef VMWARE_NET_IN_SLOT_11
1742 /*
1743 * Dirty hack for PCI slot compatibility with VMWare,
1744 * it assigns slot 11 to the first network controller.
1745 */
1746 if (iPciDeviceNo == 3 && adapterType == NetworkAdapterType_I82545EM)
1747 {
1748 iPciDeviceNo = 0x11;
1749 fSwapSlots3and11 = true;
1750 }
1751 else if (iPciDeviceNo == 0x11 && fSwapSlots3and11)
1752 iPciDeviceNo = 3;
1753#endif
1754 PciBusAddress PciAddr = PciBusAddress(0, iPciDeviceNo, 0);
1755 hrc = BusMgr->assignPciDevice(pszAdapterName, pInst, PciAddr); H();
1756
1757 InsertConfigNode(pInst, "Config", &pCfg);
1758#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE /* not safe here yet. */
1759 if (pDev == pDevPCNet)
1760 {
1761 InsertConfigInteger(pCfg, "R0Enabled", false);
1762 }
1763#endif
1764 /*
1765 * Collect information needed for network booting and add it to the list.
1766 */
1767 BootNic nic;
1768
1769 nic.mInstance = ulInstance;
1770 /* Could be updated by reference, if auto assigned */
1771 nic.mPciAddress = PciAddr;
1772
1773 hrc = networkAdapter->COMGETTER(BootPriority)(&nic.mBootPrio); H();
1774
1775 llBootNics.push_back(nic);
1776
1777 /*
1778 * The virtual hardware type. PCNet supports two types.
1779 */
1780 switch (adapterType)
1781 {
1782 case NetworkAdapterType_Am79C970A:
1783 InsertConfigInteger(pCfg, "Am79C973", 0);
1784 break;
1785 case NetworkAdapterType_Am79C973:
1786 InsertConfigInteger(pCfg, "Am79C973", 1);
1787 break;
1788 case NetworkAdapterType_I82540EM:
1789 InsertConfigInteger(pCfg, "AdapterType", 0);
1790 break;
1791 case NetworkAdapterType_I82543GC:
1792 InsertConfigInteger(pCfg, "AdapterType", 1);
1793 break;
1794 case NetworkAdapterType_I82545EM:
1795 InsertConfigInteger(pCfg, "AdapterType", 2);
1796 break;
1797 }
1798
1799 /*
1800 * Get the MAC address and convert it to binary representation
1801 */
1802 Bstr macAddr;
1803 hrc = networkAdapter->COMGETTER(MACAddress)(macAddr.asOutParam()); H();
1804 Assert(!macAddr.isEmpty());
1805 Utf8Str macAddrUtf8 = macAddr;
1806 char *macStr = (char*)macAddrUtf8.c_str();
1807 Assert(strlen(macStr) == 12);
1808 RTMAC Mac;
1809 memset(&Mac, 0, sizeof(Mac));
1810 char *pMac = (char*)&Mac;
1811 for (uint32_t i = 0; i < 6; ++i)
1812 {
1813 char c1 = *macStr++ - '0';
1814 if (c1 > 9)
1815 c1 -= 7;
1816 char c2 = *macStr++ - '0';
1817 if (c2 > 9)
1818 c2 -= 7;
1819 *pMac++ = ((c1 & 0x0f) << 4) | (c2 & 0x0f);
1820 }
1821 InsertConfigBytes(pCfg, "MAC", &Mac, sizeof(Mac));
1822
1823 /*
1824 * Check if the cable is supposed to be unplugged
1825 */
1826 BOOL fCableConnected;
1827 hrc = networkAdapter->COMGETTER(CableConnected)(&fCableConnected); H();
1828 InsertConfigInteger(pCfg, "CableConnected", fCableConnected ? 1 : 0);
1829
1830 /*
1831 * Line speed to report from custom drivers
1832 */
1833 ULONG ulLineSpeed;
1834 hrc = networkAdapter->COMGETTER(LineSpeed)(&ulLineSpeed); H();
1835 InsertConfigInteger(pCfg, "LineSpeed", ulLineSpeed);
1836
1837 /*
1838 * Attach the status driver.
1839 */
1840 InsertConfigNode(pInst, "LUN#999", &pLunL0);
1841 InsertConfigString(pLunL0, "Driver", "MainStatus");
1842 InsertConfigNode(pLunL0, "Config", &pCfg);
1843 InsertConfigInteger(pCfg, "papLeds", (uintptr_t)&mapNetworkLeds[ulInstance]);
1844
1845 /*
1846 * Configure the network card now
1847 */
1848 bool fIgnoreConnectFailure = mMachineState == MachineState_Restoring;
1849 rc = configNetwork(pszAdapterName,
1850 ulInstance,
1851 0,
1852 networkAdapter,
1853 pCfg,
1854 pLunL0,
1855 pInst,
1856 false /*fAttachDetach*/,
1857 fIgnoreConnectFailure);
1858 if (RT_FAILURE(rc))
1859 return rc;
1860 }
1861
1862 /*
1863 * Build network boot information and transfer it to the BIOS.
1864 */
1865 if (pNetBootCfg && !llBootNics.empty()) /* NetBoot node doesn't exist for EFI! */
1866 {
1867 llBootNics.sort(); /* Sort the list by boot priority. */
1868
1869 char achBootIdx[] = "0";
1870 unsigned uBootIdx = 0;
1871
1872 for (std::list<BootNic>::iterator it = llBootNics.begin(); it != llBootNics.end(); ++it)
1873 {
1874 /* A NIC with priority 0 is only used if it's first in the list. */
1875 if (it->mBootPrio == 0 && uBootIdx != 0)
1876 break;
1877
1878 PCFGMNODE pNetBtDevCfg;
1879 achBootIdx[0] = '0' + uBootIdx++; /* Boot device order. */
1880 InsertConfigNode(pNetBootCfg, achBootIdx, &pNetBtDevCfg);
1881 InsertConfigInteger(pNetBtDevCfg, "NIC", it->mInstance);
1882 InsertConfigInteger(pNetBtDevCfg, "PCIBusNo", it->mPciAddress.miBus);
1883 InsertConfigInteger(pNetBtDevCfg, "PCIDeviceNo", it->mPciAddress.miDevice);
1884 InsertConfigInteger(pNetBtDevCfg, "PCIFunctionNo", it->mPciAddress.miFn);
1885 }
1886 }
1887
1888 /*
1889 * Serial (UART) Ports
1890 */
1891 /* serial enabled mask to be passed to dev ACPI */
1892 uint16_t auSerialIoPortBase[SchemaDefs::SerialPortCount] = {0};
1893 uint8_t auSerialIrq[SchemaDefs::SerialPortCount] = {0};
1894 InsertConfigNode(pDevices, "serial", &pDev);
1895 for (ULONG ulInstance = 0; ulInstance < SchemaDefs::SerialPortCount; ++ulInstance)
1896 {
1897 ComPtr<ISerialPort> serialPort;
1898 hrc = pMachine->GetSerialPort(ulInstance, serialPort.asOutParam()); H();
1899 BOOL fEnabled = FALSE;
1900 if (serialPort)
1901 hrc = serialPort->COMGETTER(Enabled)(&fEnabled); H();
1902 if (!fEnabled)
1903 continue;
1904
1905 InsertConfigNode(pDev, Utf8StrFmt("%u", ulInstance).c_str(), &pInst);
1906 InsertConfigNode(pInst, "Config", &pCfg);
1907
1908 ULONG ulIRQ;
1909 hrc = serialPort->COMGETTER(IRQ)(&ulIRQ); H();
1910 InsertConfigInteger(pCfg, "IRQ", ulIRQ);
1911 auSerialIrq[ulInstance] = (uint8_t)ulIRQ;
1912
1913 ULONG ulIOBase;
1914 hrc = serialPort->COMGETTER(IOBase)(&ulIOBase); H();
1915 InsertConfigInteger(pCfg, "IOBase", ulIOBase);
1916 auSerialIoPortBase[ulInstance] = (uint16_t)ulIOBase;
1917
1918 BOOL fServer;
1919 hrc = serialPort->COMGETTER(Server)(&fServer); H();
1920 hrc = serialPort->COMGETTER(Path)(bstr.asOutParam()); H();
1921 PortMode_T eHostMode;
1922 hrc = serialPort->COMGETTER(HostMode)(&eHostMode); H();
1923 if (eHostMode != PortMode_Disconnected)
1924 {
1925 InsertConfigNode(pInst, "LUN#0", &pLunL0);
1926 if (eHostMode == PortMode_HostPipe)
1927 {
1928 InsertConfigString(pLunL0, "Driver", "Char");
1929 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
1930 InsertConfigString(pLunL1, "Driver", "NamedPipe");
1931 InsertConfigNode(pLunL1, "Config", &pLunL2);
1932 InsertConfigString(pLunL2, "Location", bstr);
1933 InsertConfigInteger(pLunL2, "IsServer", fServer);
1934 }
1935 else if (eHostMode == PortMode_HostDevice)
1936 {
1937 InsertConfigString(pLunL0, "Driver", "Host Serial");
1938 InsertConfigNode(pLunL0, "Config", &pLunL1);
1939 InsertConfigString(pLunL1, "DevicePath", bstr);
1940 }
1941 else if (eHostMode == PortMode_RawFile)
1942 {
1943 InsertConfigString(pLunL0, "Driver", "Char");
1944 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
1945 InsertConfigString(pLunL1, "Driver", "RawFile");
1946 InsertConfigNode(pLunL1, "Config", &pLunL2);
1947 InsertConfigString(pLunL2, "Location", bstr);
1948 }
1949 }
1950 }
1951
1952 /*
1953 * Parallel (LPT) Ports
1954 */
1955 InsertConfigNode(pDevices, "parallel", &pDev);
1956 for (ULONG ulInstance = 0; ulInstance < SchemaDefs::ParallelPortCount; ++ulInstance)
1957 {
1958 ComPtr<IParallelPort> parallelPort;
1959 hrc = pMachine->GetParallelPort(ulInstance, parallelPort.asOutParam()); H();
1960 BOOL fEnabled = FALSE;
1961 if (parallelPort)
1962 {
1963 hrc = parallelPort->COMGETTER(Enabled)(&fEnabled); H();
1964 }
1965 if (!fEnabled)
1966 continue;
1967
1968 InsertConfigNode(pDev, Utf8StrFmt("%u", ulInstance).c_str(), &pInst);
1969 InsertConfigNode(pInst, "Config", &pCfg);
1970
1971 ULONG ulIRQ;
1972 hrc = parallelPort->COMGETTER(IRQ)(&ulIRQ); H();
1973 InsertConfigInteger(pCfg, "IRQ", ulIRQ);
1974 ULONG ulIOBase;
1975 hrc = parallelPort->COMGETTER(IOBase)(&ulIOBase); H();
1976 InsertConfigInteger(pCfg, "IOBase", ulIOBase);
1977 InsertConfigNode(pInst, "LUN#0", &pLunL0);
1978 InsertConfigString(pLunL0, "Driver", "HostParallel");
1979 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
1980 hrc = parallelPort->COMGETTER(Path)(bstr.asOutParam()); H();
1981 InsertConfigString(pLunL1, "DevicePath", bstr);
1982 }
1983
1984 /*
1985 * VMM Device
1986 */
1987 InsertConfigNode(pDevices, "VMMDev", &pDev);
1988 InsertConfigNode(pDev, "0", &pInst);
1989 InsertConfigNode(pInst, "Config", &pCfg);
1990 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1991 hrc = BusMgr->assignPciDevice("VMMDev", pInst); H();
1992
1993 Bstr hwVersion;
1994 hrc = pMachine->COMGETTER(HardwareVersion)(hwVersion.asOutParam()); H();
1995 InsertConfigInteger(pCfg, "RamSize", cbRam);
1996 if (hwVersion.compare(Bstr("1").raw()) == 0) /* <= 2.0.x */
1997 InsertConfigInteger(pCfg, "HeapEnabled", 0);
1998 Bstr snapshotFolder;
1999 hrc = pMachine->COMGETTER(SnapshotFolder)(snapshotFolder.asOutParam()); H();
2000 InsertConfigString(pCfg, "GuestCoreDumpDir", snapshotFolder);
2001
2002 /* the VMM device's Main driver */
2003 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2004 InsertConfigString(pLunL0, "Driver", "HGCM");
2005 InsertConfigNode(pLunL0, "Config", &pCfg);
2006 InsertConfigInteger(pCfg, "Object", (uintptr_t)pVMMDev);
2007
2008 /*
2009 * Attach the status driver.
2010 */
2011 InsertConfigNode(pInst, "LUN#999", &pLunL0);
2012 InsertConfigString(pLunL0, "Driver", "MainStatus");
2013 InsertConfigNode(pLunL0, "Config", &pCfg);
2014 InsertConfigInteger(pCfg, "papLeds", (uintptr_t)&mapSharedFolderLed);
2015 InsertConfigInteger(pCfg, "First", 0);
2016 InsertConfigInteger(pCfg, "Last", 0);
2017
2018 /*
2019 * Audio Sniffer Device
2020 */
2021 InsertConfigNode(pDevices, "AudioSniffer", &pDev);
2022 InsertConfigNode(pDev, "0", &pInst);
2023 InsertConfigNode(pInst, "Config", &pCfg);
2024
2025 /* the Audio Sniffer device's Main driver */
2026 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2027 InsertConfigString(pLunL0, "Driver", "MainAudioSniffer");
2028 InsertConfigNode(pLunL0, "Config", &pCfg);
2029 AudioSniffer *pAudioSniffer = mAudioSniffer;
2030 InsertConfigInteger(pCfg, "Object", (uintptr_t)pAudioSniffer);
2031
2032 /*
2033 * AC'97 ICH / SoundBlaster16 audio / Intel HD Audio
2034 */
2035 BOOL fAudioEnabled = FALSE;
2036 ComPtr<IAudioAdapter> audioAdapter;
2037 hrc = pMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam()); H();
2038 if (audioAdapter)
2039 hrc = audioAdapter->COMGETTER(Enabled)(&fAudioEnabled); H();
2040
2041 if (fAudioEnabled)
2042 {
2043 AudioControllerType_T audioController;
2044 hrc = audioAdapter->COMGETTER(AudioController)(&audioController); H();
2045 switch (audioController)
2046 {
2047 case AudioControllerType_AC97:
2048 {
2049 /* default: ICH AC97 */
2050 InsertConfigNode(pDevices, "ichac97", &pDev);
2051 InsertConfigNode(pDev, "0", &pInst);
2052 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2053 hrc = BusMgr->assignPciDevice("ichac97", pInst); H();
2054 InsertConfigNode(pInst, "Config", &pCfg);
2055 break;
2056 }
2057 case AudioControllerType_SB16:
2058 {
2059 /* legacy SoundBlaster16 */
2060 InsertConfigNode(pDevices, "sb16", &pDev);
2061 InsertConfigNode(pDev, "0", &pInst);
2062 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2063 InsertConfigNode(pInst, "Config", &pCfg);
2064 InsertConfigInteger(pCfg, "IRQ", 5);
2065 InsertConfigInteger(pCfg, "DMA", 1);
2066 InsertConfigInteger(pCfg, "DMA16", 5);
2067 InsertConfigInteger(pCfg, "Port", 0x220);
2068 InsertConfigInteger(pCfg, "Version", 0x0405);
2069 break;
2070 }
2071 case AudioControllerType_HDA:
2072 {
2073 /* Intel HD Audio */
2074 InsertConfigNode(pDevices, "hda", &pDev);
2075 InsertConfigNode(pDev, "0", &pInst);
2076 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2077 hrc = BusMgr->assignPciDevice("hda", pInst); H();
2078 InsertConfigNode(pInst, "Config", &pCfg);
2079 }
2080 }
2081
2082 /* the Audio driver */
2083 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2084 InsertConfigString(pLunL0, "Driver", "AUDIO");
2085 InsertConfigNode(pLunL0, "Config", &pCfg);
2086
2087 AudioDriverType_T audioDriver;
2088 hrc = audioAdapter->COMGETTER(AudioDriver)(&audioDriver); H();
2089 switch (audioDriver)
2090 {
2091 case AudioDriverType_Null:
2092 {
2093 InsertConfigString(pCfg, "AudioDriver", "null");
2094 break;
2095 }
2096#ifdef RT_OS_WINDOWS
2097#ifdef VBOX_WITH_WINMM
2098 case AudioDriverType_WinMM:
2099 {
2100 InsertConfigString(pCfg, "AudioDriver", "winmm");
2101 break;
2102 }
2103#endif
2104 case AudioDriverType_DirectSound:
2105 {
2106 InsertConfigString(pCfg, "AudioDriver", "dsound");
2107 break;
2108 }
2109#endif /* RT_OS_WINDOWS */
2110#ifdef RT_OS_SOLARIS
2111 case AudioDriverType_SolAudio:
2112 {
2113 InsertConfigString(pCfg, "AudioDriver", "solaudio");
2114 break;
2115 }
2116#endif
2117#ifdef RT_OS_LINUX
2118# ifdef VBOX_WITH_ALSA
2119 case AudioDriverType_ALSA:
2120 {
2121 InsertConfigString(pCfg, "AudioDriver", "alsa");
2122 break;
2123 }
2124# endif
2125# ifdef VBOX_WITH_PULSE
2126 case AudioDriverType_Pulse:
2127 {
2128 InsertConfigString(pCfg, "AudioDriver", "pulse");
2129 break;
2130 }
2131# endif
2132#endif /* RT_OS_LINUX */
2133#if defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD) || defined(VBOX_WITH_SOLARIS_OSS)
2134 case AudioDriverType_OSS:
2135 {
2136 InsertConfigString(pCfg, "AudioDriver", "oss");
2137 break;
2138 }
2139#endif
2140#ifdef RT_OS_FREEBSD
2141# ifdef VBOX_WITH_PULSE
2142 case AudioDriverType_Pulse:
2143 {
2144 InsertConfigString(pCfg, "AudioDriver", "pulse");
2145 break;
2146 }
2147# endif
2148#endif
2149#ifdef RT_OS_DARWIN
2150 case AudioDriverType_CoreAudio:
2151 {
2152 InsertConfigString(pCfg, "AudioDriver", "coreaudio");
2153 break;
2154 }
2155#endif
2156 }
2157 hrc = pMachine->COMGETTER(Name)(bstr.asOutParam()); H();
2158 InsertConfigString(pCfg, "StreamName", bstr);
2159 }
2160
2161 /*
2162 * The USB Controller.
2163 */
2164 ComPtr<IUSBController> USBCtlPtr;
2165 hrc = pMachine->COMGETTER(USBController)(USBCtlPtr.asOutParam());
2166 if (USBCtlPtr)
2167 {
2168 BOOL fOhciEnabled;
2169 hrc = USBCtlPtr->COMGETTER(Enabled)(&fOhciEnabled); H();
2170 if (fOhciEnabled)
2171 {
2172 InsertConfigNode(pDevices, "usb-ohci", &pDev);
2173 InsertConfigNode(pDev, "0", &pInst);
2174 InsertConfigNode(pInst, "Config", &pCfg);
2175 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2176 hrc = BusMgr->assignPciDevice("usb-ohci", pInst); H();
2177 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2178 InsertConfigString(pLunL0, "Driver", "VUSBRootHub");
2179 InsertConfigNode(pLunL0, "Config", &pCfg);
2180
2181 /*
2182 * Attach the status driver.
2183 */
2184 InsertConfigNode(pInst, "LUN#999", &pLunL0);
2185 InsertConfigString(pLunL0, "Driver", "MainStatus");
2186 InsertConfigNode(pLunL0, "Config", &pCfg);
2187 InsertConfigInteger(pCfg, "papLeds", (uintptr_t)&mapUSBLed[0]);
2188 InsertConfigInteger(pCfg, "First", 0);
2189 InsertConfigInteger(pCfg, "Last", 0);
2190
2191#ifdef VBOX_WITH_EHCI
2192 BOOL fEhciEnabled;
2193 hrc = USBCtlPtr->COMGETTER(EnabledEhci)(&fEhciEnabled); H();
2194 if (fEhciEnabled)
2195 {
2196 /*
2197 * USB 2.0 is only available if the proper ExtPack is installed.
2198 *
2199 * Note. Configuring EHCI here and providing messages about
2200 * the missing extpack isn't exactly clean, but it is a
2201 * necessary evil to patch over legacy compatability issues
2202 * introduced by the new distribution model.
2203 */
2204 static const char *s_pszUsbExtPackName = "Oracle VM VirtualBox Extension Pack";
2205# ifdef VBOX_WITH_EXTPACK
2206 if (mptrExtPackManager->isExtPackUsable(s_pszUsbExtPackName))
2207# endif
2208 {
2209 InsertConfigNode(pDevices, "usb-ehci", &pDev);
2210 InsertConfigNode(pDev, "0", &pInst);
2211 InsertConfigNode(pInst, "Config", &pCfg);
2212 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2213 hrc = BusMgr->assignPciDevice("usb-ehci", pInst); H();
2214
2215 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2216 InsertConfigString(pLunL0, "Driver", "VUSBRootHub");
2217 InsertConfigNode(pLunL0, "Config", &pCfg);
2218
2219 /*
2220 * Attach the status driver.
2221 */
2222 InsertConfigNode(pInst, "LUN#999", &pLunL0);
2223 InsertConfigString(pLunL0, "Driver", "MainStatus");
2224 InsertConfigNode(pLunL0, "Config", &pCfg);
2225 InsertConfigInteger(pCfg, "papLeds", (uintptr_t)&mapUSBLed[1]);
2226 InsertConfigInteger(pCfg, "First", 0);
2227 InsertConfigInteger(pCfg, "Last", 0);
2228 }
2229# ifdef VBOX_WITH_EXTPACK
2230 else
2231 {
2232 /* Always fatal! Up to VBox 4.0.4 we allowed to start the VM anyway
2233 * but this induced problems when the user saved + restored the VM! */
2234 return VMSetError(pVM, VERR_NOT_FOUND, RT_SRC_POS,
2235 N_("Implementation of the USB 2.0 controller not found!\n"
2236 "Because the USB 2.0 controller state is part of the saved "
2237 "VM state, the VM cannot be started. To fix "
2238 "this problem, either install the '%s' or disable USB 2.0 "
2239 "support in the VM settings"),
2240 s_pszUsbExtPackName);
2241 }
2242# endif
2243 }
2244#endif
2245
2246 /*
2247 * Virtual USB Devices.
2248 */
2249 PCFGMNODE pUsbDevices = NULL;
2250 InsertConfigNode(pRoot, "USB", &pUsbDevices);
2251
2252#ifdef VBOX_WITH_USB
2253 {
2254 /*
2255 * Global USB options, currently unused as we'll apply the 2.0 -> 1.1 morphing
2256 * on a per device level now.
2257 */
2258 InsertConfigNode(pUsbDevices, "USBProxy", &pCfg);
2259 InsertConfigNode(pCfg, "GlobalConfig", &pCfg);
2260 // This globally enables the 2.0 -> 1.1 device morphing of proxied devices to keep windows quiet.
2261 //InsertConfigInteger(pCfg, "Force11Device", true);
2262 // The following breaks stuff, but it makes MSDs work in vista. (I include it here so
2263 // that it's documented somewhere.) Users needing it can use:
2264 // VBoxManage setextradata "myvm" "VBoxInternal/USB/USBProxy/GlobalConfig/Force11PacketSize" 1
2265 //InsertConfigInteger(pCfg, "Force11PacketSize", true);
2266 }
2267#endif
2268
2269# if 0 /* Virtual Web Cam */
2270
2271 InsertConfigNode(pUsbDevices, "WebCam", &pDev);
2272 InsertConfigNode(pDev, "0", &pInst);
2273 InsertConfigNode(pInst, "Config", &pCfg);
2274# if 0 /* Experiments with attaching */
2275 InsertConfigInteger(pCfg, "USBVER", RT_BIT(2));
2276# endif
2277 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2278# endif
2279# if 0 /* Virtual MSD*/
2280
2281 InsertConfigNode(pUsbDevices, "Msd", &pDev);
2282 InsertConfigNode(pDev, "0", &pInst);
2283 InsertConfigNode(pInst, "Config", &pCfg);
2284 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2285
2286 InsertConfigString(pLunL0, "Driver", "SCSI");
2287 InsertConfigNode(pLunL0, "Config", &pCfg);
2288
2289 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2290 InsertConfigString(pLunL1, "Driver", "Block");
2291 InsertConfigNode(pLunL1, "Config", &pCfg);
2292 InsertConfigString(pCfg, "Type", "HardDisk");
2293 InsertConfigInteger(pCfg, "Mountable", 0);
2294
2295 InsertConfigNode(pLunL1, "AttachedDriver", &pLunL2);
2296 InsertConfigString(pLunL2, "Driver", "VD");
2297 InsertConfigNode(pLunL2, "Config", &pCfg);
2298 InsertConfigString(pCfg, "Path", "/Volumes/DataHFS/bird/VDIs/linux.vdi");
2299 InsertConfigString(pCfg, "Format", "VDI");
2300# endif
2301
2302 /* Virtual USB Mouse/Tablet */
2303 PointingHidType_T aPointingHid;
2304 hrc = pMachine->COMGETTER(PointingHidType)(&aPointingHid); H();
2305 if (aPointingHid == PointingHidType_USBMouse || aPointingHid == PointingHidType_USBTablet)
2306 {
2307 InsertConfigNode(pUsbDevices, "HidMouse", &pDev);
2308 InsertConfigNode(pDev, "0", &pInst);
2309 InsertConfigNode(pInst, "Config", &pCfg);
2310
2311 if (aPointingHid == PointingHidType_USBTablet)
2312 {
2313 InsertConfigInteger(pCfg, "Absolute", 1);
2314 }
2315 else
2316 {
2317 InsertConfigInteger(pCfg, "Absolute", 0);
2318 }
2319 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2320 InsertConfigString(pLunL0, "Driver", "MouseQueue");
2321 InsertConfigNode(pLunL0, "Config", &pCfg);
2322 InsertConfigInteger(pCfg, "QueueSize", 128);
2323
2324 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2325 InsertConfigString(pLunL1, "Driver", "MainMouse");
2326 InsertConfigNode(pLunL1, "Config", &pCfg);
2327 pMouse = mMouse;
2328 InsertConfigInteger(pCfg, "Object", (uintptr_t)pMouse);
2329 }
2330
2331 /* Virtual USB Keyboard */
2332 KeyboardHidType_T aKbdHid;
2333 hrc = pMachine->COMGETTER(KeyboardHidType)(&aKbdHid); H();
2334 if (aKbdHid == KeyboardHidType_USBKeyboard)
2335 {
2336 InsertConfigNode(pUsbDevices, "HidKeyboard", &pDev);
2337 InsertConfigNode(pDev, "0", &pInst);
2338 InsertConfigNode(pInst, "Config", &pCfg);
2339
2340 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2341 InsertConfigString(pLunL0, "Driver", "KeyboardQueue");
2342 InsertConfigNode(pLunL0, "Config", &pCfg);
2343 InsertConfigInteger(pCfg, "QueueSize", 64);
2344
2345 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2346 InsertConfigString(pLunL1, "Driver", "MainKeyboard");
2347 InsertConfigNode(pLunL1, "Config", &pCfg);
2348 pKeyboard = mKeyboard;
2349 InsertConfigInteger(pCfg, "Object", (uintptr_t)pKeyboard);
2350 }
2351 }
2352 }
2353
2354 /*
2355 * Clipboard
2356 */
2357 {
2358 ClipboardMode_T mode = ClipboardMode_Disabled;
2359 hrc = pMachine->COMGETTER(ClipboardMode)(&mode); H();
2360
2361 if (mode != ClipboardMode_Disabled)
2362 {
2363 /* Load the service */
2364 rc = pVMMDev->hgcmLoadService("VBoxSharedClipboard", "VBoxSharedClipboard");
2365
2366 if (RT_FAILURE(rc))
2367 {
2368 LogRel(("VBoxSharedClipboard is not available. rc = %Rrc\n", rc));
2369 /* That is not a fatal failure. */
2370 rc = VINF_SUCCESS;
2371 }
2372 else
2373 {
2374 /* Setup the service. */
2375 VBOXHGCMSVCPARM parm;
2376
2377 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
2378
2379 switch (mode)
2380 {
2381 default:
2382 case ClipboardMode_Disabled:
2383 {
2384 LogRel(("VBoxSharedClipboard mode: Off\n"));
2385 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_OFF;
2386 break;
2387 }
2388 case ClipboardMode_GuestToHost:
2389 {
2390 LogRel(("VBoxSharedClipboard mode: Guest to Host\n"));
2391 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_GUEST_TO_HOST;
2392 break;
2393 }
2394 case ClipboardMode_HostToGuest:
2395 {
2396 LogRel(("VBoxSharedClipboard mode: Host to Guest\n"));
2397 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_HOST_TO_GUEST;
2398 break;
2399 }
2400 case ClipboardMode_Bidirectional:
2401 {
2402 LogRel(("VBoxSharedClipboard mode: Bidirectional\n"));
2403 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_BIDIRECTIONAL;
2404 break;
2405 }
2406 }
2407
2408 pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE, 1, &parm);
2409
2410 Log(("Set VBoxSharedClipboard mode\n"));
2411 }
2412 }
2413 }
2414
2415#ifdef VBOX_WITH_CROGL
2416 /*
2417 * crOpenGL
2418 */
2419 {
2420 BOOL fEnabled = false;
2421 hrc = pMachine->COMGETTER(Accelerate3DEnabled)(&fEnabled); H();
2422
2423 if (fEnabled)
2424 {
2425 /* Load the service */
2426 rc = pVMMDev->hgcmLoadService("VBoxSharedCrOpenGL", "VBoxSharedCrOpenGL");
2427 if (RT_FAILURE(rc))
2428 {
2429 LogRel(("Failed to load Shared OpenGL service %Rrc\n", rc));
2430 /* That is not a fatal failure. */
2431 rc = VINF_SUCCESS;
2432 }
2433 else
2434 {
2435 LogRel(("Shared crOpenGL service loaded.\n"));
2436
2437 /* Setup the service. */
2438 VBOXHGCMSVCPARM parm;
2439 parm.type = VBOX_HGCM_SVC_PARM_PTR;
2440
2441 parm.u.pointer.addr = (IConsole *)(Console *)this;
2442 parm.u.pointer.size = sizeof(IConsole *);
2443
2444 rc = pVMMDev->hgcmHostCall("VBoxSharedCrOpenGL", SHCRGL_HOST_FN_SET_CONSOLE, SHCRGL_CPARMS_SET_CONSOLE, &parm);
2445 if (!RT_SUCCESS(rc))
2446 AssertMsgFailed(("SHCRGL_HOST_FN_SET_CONSOLE failed with %Rrc\n", rc));
2447
2448 parm.u.pointer.addr = pVM;
2449 parm.u.pointer.size = sizeof(pVM);
2450 rc = pVMMDev->hgcmHostCall("VBoxSharedCrOpenGL", SHCRGL_HOST_FN_SET_VM, SHCRGL_CPARMS_SET_VM, &parm);
2451 if (!RT_SUCCESS(rc))
2452 AssertMsgFailed(("SHCRGL_HOST_FN_SET_VM failed with %Rrc\n", rc));
2453 }
2454
2455 }
2456 }
2457#endif
2458
2459#ifdef VBOX_WITH_GUEST_PROPS
2460 /*
2461 * Guest property service
2462 */
2463
2464 rc = configGuestProperties(this);
2465#endif /* VBOX_WITH_GUEST_PROPS defined */
2466
2467#ifdef VBOX_WITH_GUEST_CONTROL
2468 /*
2469 * Guest control service
2470 */
2471
2472 rc = configGuestControl(this);
2473#endif /* VBOX_WITH_GUEST_CONTROL defined */
2474
2475 /*
2476 * ACPI
2477 */
2478 BOOL fACPI;
2479 hrc = biosSettings->COMGETTER(ACPIEnabled)(&fACPI); H();
2480 if (fACPI)
2481 {
2482 BOOL fCpuHotPlug = false;
2483 BOOL fShowCpu = fOsXGuest;
2484 /* Always show the CPU leafs when we have multiple VCPUs or when the IO-APIC is enabled.
2485 * The Windows SMP kernel needs a CPU leaf or else its idle loop will burn cpu cycles; the
2486 * intelppm driver refuses to register an idle state handler.
2487 */
2488 if ((cCpus > 1) || fIOAPIC)
2489 fShowCpu = true;
2490
2491 hrc = pMachine->COMGETTER(CPUHotPlugEnabled)(&fCpuHotPlug); H();
2492
2493 InsertConfigNode(pDevices, "acpi", &pDev);
2494 InsertConfigNode(pDev, "0", &pInst);
2495 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2496 InsertConfigNode(pInst, "Config", &pCfg);
2497 hrc = BusMgr->assignPciDevice("acpi", pInst); H();
2498
2499 InsertConfigInteger(pCfg, "RamSize", cbRam);
2500 InsertConfigInteger(pCfg, "RamHoleSize", cbRamHole);
2501 InsertConfigInteger(pCfg, "NumCPUs", cCpus);
2502
2503 InsertConfigInteger(pCfg, "IOAPIC", fIOAPIC);
2504 InsertConfigInteger(pCfg, "FdcEnabled", fFdcEnabled);
2505 InsertConfigInteger(pCfg, "HpetEnabled", fHpetEnabled);
2506 InsertConfigInteger(pCfg, "SmcEnabled", fSmcEnabled);
2507 InsertConfigInteger(pCfg, "ShowRtc", fShowRtc);
2508 if (fOsXGuest && !llBootNics.empty())
2509 {
2510 BootNic aNic = llBootNics.front();
2511 uint32_t u32NicPciAddr = (aNic.mPciAddress.miDevice << 16) | aNic.mPciAddress.miFn;
2512 InsertConfigInteger(pCfg, "NicPciAddress", u32NicPciAddr);
2513 }
2514 if (fOsXGuest && fAudioEnabled)
2515 {
2516 PciBusAddress Address;
2517 if (BusMgr->findPciAddress("hda", 0, Address))
2518 {
2519 uint32_t u32AudioPciAddr = (Address.miDevice << 16) | Address.miFn;
2520 InsertConfigInteger(pCfg, "AudioPciAddress", u32AudioPciAddr);
2521 }
2522 }
2523 InsertConfigInteger(pCfg, "IocPciAddress", uIocPciAddress);
2524 if (chipsetType == ChipsetType_ICH9)
2525 {
2526 InsertConfigInteger(pCfg, "McfgBase", uMcfgBase);
2527 InsertConfigInteger(pCfg, "McfgLength", cbMcfgLength);
2528 }
2529 InsertConfigInteger(pCfg, "HostBusPciAddress", uHbcPciAddress);
2530 InsertConfigInteger(pCfg, "ShowCpu", fShowCpu);
2531 InsertConfigInteger(pCfg, "CpuHotPlug", fCpuHotPlug);
2532
2533 InsertConfigInteger(pCfg, "Serial0IoPortBase", auSerialIoPortBase[0]);
2534 InsertConfigInteger(pCfg, "Serial0Irq", auSerialIrq[0]);
2535
2536 InsertConfigInteger(pCfg, "Serial1IoPortBase", auSerialIoPortBase[1]);
2537 InsertConfigInteger(pCfg, "Serial1Irq", auSerialIrq[1]);
2538
2539 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2540 InsertConfigString(pLunL0, "Driver", "ACPIHost");
2541 InsertConfigNode(pLunL0, "Config", &pCfg);
2542
2543 /* Attach the dummy CPU drivers */
2544 for (ULONG iCpuCurr = 1; iCpuCurr < cCpus; iCpuCurr++)
2545 {
2546 BOOL fCpuAttached = true;
2547
2548 if (fCpuHotPlug)
2549 {
2550 hrc = pMachine->GetCPUStatus(iCpuCurr, &fCpuAttached); H();
2551 }
2552
2553 if (fCpuAttached)
2554 {
2555 InsertConfigNode(pInst, Utf8StrFmt("LUN#%u", iCpuCurr).c_str(), &pLunL0);
2556 InsertConfigString(pLunL0, "Driver", "ACPICpu");
2557 InsertConfigNode(pLunL0, "Config", &pCfg);
2558 }
2559 }
2560 }
2561 }
2562 catch (ConfigError &x)
2563 {
2564 // InsertConfig threw something:
2565 return x.m_vrc;
2566 }
2567
2568#ifdef VBOX_WITH_EXTPACK
2569 /*
2570 * Call the extension pack hooks if everything went well thus far.
2571 */
2572 if (RT_SUCCESS(rc))
2573 {
2574 pAlock->release();
2575 rc = mptrExtPackManager->callAllVmConfigureVmmHooks(this, pVM);
2576 pAlock->acquire();
2577 }
2578#endif
2579
2580 /*
2581 * Apply the CFGM overlay.
2582 */
2583 if (RT_SUCCESS(rc))
2584 rc = configCfgmOverlay(pVM, virtualBox, pMachine);
2585
2586#undef H
2587
2588 /*
2589 * Register VM state change handler.
2590 */
2591 int rc2 = VMR3AtStateRegister(pVM, Console::vmstateChangeCallback, this);
2592 AssertRC(rc2);
2593 if (RT_SUCCESS(rc))
2594 rc = rc2;
2595
2596 /*
2597 * Register VM runtime error handler.
2598 */
2599 rc2 = VMR3AtRuntimeErrorRegister(pVM, Console::setVMRuntimeErrorCallback, this);
2600 AssertRC(rc2);
2601 if (RT_SUCCESS(rc))
2602 rc = rc2;
2603
2604 LogFlowFunc(("vrc = %Rrc\n", rc));
2605 LogFlowFuncLeave();
2606
2607 return rc;
2608}
2609
2610/**
2611 * Applies the CFGM overlay as specified by /VBoxInternal/XXX extra data
2612 * values.
2613 *
2614 * @returns VBox status code.
2615 * @param pVM The VM handle.
2616 * @param pVirtualBox Pointer to the IVirtualBox interface.
2617 * @param pMachine Pointer to the IMachine interface.
2618 */
2619/* static */
2620int Console::configCfgmOverlay(PVM pVM, IVirtualBox *pVirtualBox, IMachine *pMachine)
2621{
2622 /*
2623 * CFGM overlay handling.
2624 *
2625 * Here we check the extra data entries for CFGM values
2626 * and create the nodes and insert the values on the fly. Existing
2627 * values will be removed and reinserted. CFGM is typed, so by default
2628 * we will guess whether it's a string or an integer (byte arrays are
2629 * not currently supported). It's possible to override this autodetection
2630 * by adding "string:", "integer:" or "bytes:" (future).
2631 *
2632 * We first perform a run on global extra data, then on the machine
2633 * extra data to support global settings with local overrides.
2634 */
2635 PCFGMNODE pRoot = CFGMR3GetRoot(pVM);
2636 int rc = VINF_SUCCESS;
2637 try
2638 {
2639 /** @todo add support for removing nodes and byte blobs. */
2640 /*
2641 * Get the next key
2642 */
2643 SafeArray<BSTR> aGlobalExtraDataKeys;
2644 SafeArray<BSTR> aMachineExtraDataKeys;
2645 HRESULT hrc = pVirtualBox->GetExtraDataKeys(ComSafeArrayAsOutParam(aGlobalExtraDataKeys));
2646 AssertMsg(SUCCEEDED(hrc), ("VirtualBox::GetExtraDataKeys failed with %Rhrc\n", hrc));
2647
2648 // remember the no. of global values so we can call the correct method below
2649 size_t cGlobalValues = aGlobalExtraDataKeys.size();
2650
2651 hrc = pMachine->GetExtraDataKeys(ComSafeArrayAsOutParam(aMachineExtraDataKeys));
2652 AssertMsg(SUCCEEDED(hrc), ("VirtualBox::GetExtraDataKeys failed with %Rhrc\n", hrc));
2653
2654 // build a combined list from global keys...
2655 std::list<Utf8Str> llExtraDataKeys;
2656
2657 for (size_t i = 0; i < aGlobalExtraDataKeys.size(); ++i)
2658 llExtraDataKeys.push_back(Utf8Str(aGlobalExtraDataKeys[i]));
2659 // ... and machine keys
2660 for (size_t i = 0; i < aMachineExtraDataKeys.size(); ++i)
2661 llExtraDataKeys.push_back(Utf8Str(aMachineExtraDataKeys[i]));
2662
2663 size_t i2 = 0;
2664 for (std::list<Utf8Str>::const_iterator it = llExtraDataKeys.begin();
2665 it != llExtraDataKeys.end();
2666 ++it, ++i2)
2667 {
2668 const Utf8Str &strKey = *it;
2669
2670 /*
2671 * We only care about keys starting with "VBoxInternal/" (skip "G:" or "M:")
2672 */
2673 if (!strKey.startsWith("VBoxInternal/"))
2674 continue;
2675
2676 const char *pszExtraDataKey = strKey.c_str() + sizeof("VBoxInternal/") - 1;
2677
2678 // get the value
2679 Bstr bstrExtraDataValue;
2680 if (i2 < cGlobalValues)
2681 // this is still one of the global values:
2682 hrc = pVirtualBox->GetExtraData(Bstr(strKey).raw(),
2683 bstrExtraDataValue.asOutParam());
2684 else
2685 hrc = pMachine->GetExtraData(Bstr(strKey).raw(),
2686 bstrExtraDataValue.asOutParam());
2687 if (FAILED(hrc))
2688 LogRel(("Warning: Cannot get extra data key %s, rc = %Rrc\n", strKey.c_str(), hrc));
2689
2690 /*
2691 * The key will be in the format "Node1/Node2/Value" or simply "Value".
2692 * Split the two and get the node, delete the value and create the node
2693 * if necessary.
2694 */
2695 PCFGMNODE pNode;
2696 const char *pszCFGMValueName = strrchr(pszExtraDataKey, '/');
2697 if (pszCFGMValueName)
2698 {
2699 /* terminate the node and advance to the value (Utf8Str might not
2700 offically like this but wtf) */
2701 *(char*)pszCFGMValueName = '\0';
2702 ++pszCFGMValueName;
2703
2704 /* does the node already exist? */
2705 pNode = CFGMR3GetChild(pRoot, pszExtraDataKey);
2706 if (pNode)
2707 CFGMR3RemoveValue(pNode, pszCFGMValueName);
2708 else
2709 {
2710 /* create the node */
2711 rc = CFGMR3InsertNode(pRoot, pszExtraDataKey, &pNode);
2712 if (RT_FAILURE(rc))
2713 {
2714 AssertLogRelMsgRC(rc, ("failed to insert node '%s'\n", pszExtraDataKey));
2715 continue;
2716 }
2717 Assert(pNode);
2718 }
2719 }
2720 else
2721 {
2722 /* root value (no node path). */
2723 pNode = pRoot;
2724 pszCFGMValueName = pszExtraDataKey;
2725 pszExtraDataKey--;
2726 CFGMR3RemoveValue(pNode, pszCFGMValueName);
2727 }
2728
2729 /*
2730 * Now let's have a look at the value.
2731 * Empty strings means that we should remove the value, which we've
2732 * already done above.
2733 */
2734 Utf8Str strCFGMValueUtf8(bstrExtraDataValue);
2735 if (!strCFGMValueUtf8.isEmpty())
2736 {
2737 uint64_t u64Value;
2738
2739 /* check for type prefix first. */
2740 if (!strncmp(strCFGMValueUtf8.c_str(), "string:", sizeof("string:") - 1))
2741 InsertConfigString(pNode, pszCFGMValueName, strCFGMValueUtf8.c_str() + sizeof("string:") - 1);
2742 else if (!strncmp(strCFGMValueUtf8.c_str(), "integer:", sizeof("integer:") - 1))
2743 {
2744 rc = RTStrToUInt64Full(strCFGMValueUtf8.c_str() + sizeof("integer:") - 1, 0, &u64Value);
2745 if (RT_SUCCESS(rc))
2746 rc = CFGMR3InsertInteger(pNode, pszCFGMValueName, u64Value);
2747 }
2748 else if (!strncmp(strCFGMValueUtf8.c_str(), "bytes:", sizeof("bytes:") - 1))
2749 rc = VERR_NOT_IMPLEMENTED;
2750 /* auto detect type. */
2751 else if (RT_SUCCESS(RTStrToUInt64Full(strCFGMValueUtf8.c_str(), 0, &u64Value)))
2752 rc = CFGMR3InsertInteger(pNode, pszCFGMValueName, u64Value);
2753 else
2754 InsertConfigString(pNode, pszCFGMValueName, strCFGMValueUtf8);
2755 AssertLogRelMsgRCBreak(rc, ("failed to insert CFGM value '%s' to key '%s'\n", strCFGMValueUtf8.c_str(), pszExtraDataKey));
2756 }
2757 }
2758 }
2759 catch (ConfigError &x)
2760 {
2761 // InsertConfig threw something:
2762 return x.m_vrc;
2763 }
2764 return rc;
2765}
2766
2767/**
2768 * Ellipsis to va_list wrapper for calling setVMRuntimeErrorCallback.
2769 */
2770/*static*/
2771void Console::setVMRuntimeErrorCallbackF(PVM pVM, void *pvConsole, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, ...)
2772{
2773 va_list va;
2774 va_start(va, pszFormat);
2775 setVMRuntimeErrorCallback(pVM, pvConsole, fFlags, pszErrorId, pszFormat, va);
2776 va_end(va);
2777}
2778
2779/* XXX introduce RT format specifier */
2780static uint64_t formatDiskSize(uint64_t u64Size, const char **pszUnit)
2781{
2782 if (u64Size > INT64_C(5000)*_1G)
2783 {
2784 *pszUnit = "TB";
2785 return u64Size / _1T;
2786 }
2787 else if (u64Size > INT64_C(5000)*_1M)
2788 {
2789 *pszUnit = "GB";
2790 return u64Size / _1G;
2791 }
2792 else
2793 {
2794 *pszUnit = "MB";
2795 return u64Size / _1M;
2796 }
2797}
2798
2799int Console::configMediumAttachment(PCFGMNODE pCtlInst,
2800 const char *pcszDevice,
2801 unsigned uInstance,
2802 StorageBus_T enmBus,
2803 bool fUseHostIOCache,
2804 bool fBuiltinIoCache,
2805 bool fSetupMerge,
2806 unsigned uMergeSource,
2807 unsigned uMergeTarget,
2808 IMediumAttachment *pMediumAtt,
2809 MachineState_T aMachineState,
2810 HRESULT *phrc,
2811 bool fAttachDetach,
2812 bool fForceUnmount,
2813 PVM pVM,
2814 DeviceType_T *paLedDevType)
2815{
2816 // InsertConfig* throws
2817 try
2818 {
2819 int rc = VINF_SUCCESS;
2820 HRESULT hrc;
2821 Bstr bstr;
2822
2823// #define RC_CHECK() AssertMsgReturn(RT_SUCCESS(rc), ("rc=%Rrc\n", rc), rc)
2824#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
2825
2826 LONG lDev;
2827 hrc = pMediumAtt->COMGETTER(Device)(&lDev); H();
2828 LONG lPort;
2829 hrc = pMediumAtt->COMGETTER(Port)(&lPort); H();
2830 DeviceType_T lType;
2831 hrc = pMediumAtt->COMGETTER(Type)(&lType); H();
2832
2833 unsigned uLUN;
2834 PCFGMNODE pLunL0 = NULL;
2835 PCFGMNODE pCfg = NULL;
2836 hrc = Console::convertBusPortDeviceToLun(enmBus, lPort, lDev, uLUN); H();
2837
2838 /* First check if the LUN already exists. */
2839 pLunL0 = CFGMR3GetChildF(pCtlInst, "LUN#%u", uLUN);
2840 if (pLunL0)
2841 {
2842 if (fAttachDetach)
2843 {
2844 if (lType != DeviceType_HardDisk)
2845 {
2846 /* Unmount existing media only for floppy and DVD drives. */
2847 PPDMIBASE pBase;
2848 rc = PDMR3QueryLun(pVM, pcszDevice, uInstance, uLUN, &pBase);
2849 if (RT_FAILURE(rc))
2850 {
2851 if (rc == VERR_PDM_LUN_NOT_FOUND || rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
2852 rc = VINF_SUCCESS;
2853 AssertRC(rc);
2854 }
2855 else
2856 {
2857 PPDMIMOUNT pIMount = PDMIBASE_QUERY_INTERFACE(pBase, PDMIMOUNT);
2858 AssertReturn(pIMount, VERR_INVALID_POINTER);
2859
2860 /* Unmount the media (but do not eject the medium!) */
2861 rc = pIMount->pfnUnmount(pIMount, fForceUnmount, false /*=fEject*/);
2862 if (rc == VERR_PDM_MEDIA_NOT_MOUNTED)
2863 rc = VINF_SUCCESS;
2864 /* for example if the medium is locked */
2865 else if (RT_FAILURE(rc))
2866 return rc;
2867 }
2868 }
2869
2870 rc = PDMR3DeviceDetach(pVM, pcszDevice, uInstance, uLUN, PDM_TACH_FLAGS_NOT_HOT_PLUG);
2871 if (rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
2872 rc = VINF_SUCCESS;
2873 AssertRCReturn(rc, rc);
2874
2875 CFGMR3RemoveNode(pLunL0);
2876 }
2877 else
2878 AssertFailedReturn(VERR_INTERNAL_ERROR);
2879 }
2880
2881 InsertConfigNode(pCtlInst, Utf8StrFmt("LUN#%u", uLUN).c_str(), &pLunL0);
2882
2883 /* SCSI has a another driver between device and block. */
2884 if (enmBus == StorageBus_SCSI || enmBus == StorageBus_SAS)
2885 {
2886 InsertConfigString(pLunL0, "Driver", "SCSI");
2887 InsertConfigNode(pLunL0, "Config", &pCfg);
2888
2889 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
2890 }
2891
2892 ComPtr<IMedium> pMedium;
2893 hrc = pMediumAtt->COMGETTER(Medium)(pMedium.asOutParam()); H();
2894
2895 /*
2896 * 1. Only check this for hard disk images.
2897 * 2. Only check during VM creation and not later, especially not during
2898 * taking an online snapshot!
2899 */
2900 if ( lType == DeviceType_HardDisk
2901 && ( aMachineState == MachineState_Starting
2902 || aMachineState == MachineState_Restoring))
2903 {
2904 /*
2905 * Some sanity checks.
2906 */
2907 ComPtr<IMediumFormat> pMediumFormat;
2908 hrc = pMedium->COMGETTER(MediumFormat)(pMediumFormat.asOutParam()); H();
2909 ULONG uCaps;
2910 hrc = pMediumFormat->COMGETTER(Capabilities)(&uCaps); H();
2911 if (uCaps & MediumFormatCapabilities_File)
2912 {
2913 Bstr strFile;
2914 hrc = pMedium->COMGETTER(Location)(strFile.asOutParam()); H();
2915 Utf8Str utfFile = Utf8Str(strFile);
2916 Bstr strSnap;
2917 ComPtr<IMachine> pMachine = machine();
2918 hrc = pMachine->COMGETTER(SnapshotFolder)(strSnap.asOutParam()); H();
2919 Utf8Str utfSnap = Utf8Str(strSnap);
2920 RTFSTYPE enmFsTypeFile = RTFSTYPE_UNKNOWN;
2921 RTFSTYPE enmFsTypeSnap = RTFSTYPE_UNKNOWN;
2922 int rc2 = RTFsQueryType(utfFile.c_str(), &enmFsTypeFile);
2923 AssertMsgRCReturn(rc2, ("Querying the file type of '%s' failed!\n", utfFile.c_str()), rc2);
2924 /* Ignore the error code. On error, the file system type is still 'unknown' so
2925 * none of the following paths are taken. This can happen for new VMs which
2926 * still don't have a snapshot folder. */
2927 (void)RTFsQueryType(utfSnap.c_str(), &enmFsTypeSnap);
2928 if (!mfSnapshotFolderDiskTypeShown)
2929 {
2930 LogRel(("File system of '%s' (snapshots) is %s\n", utfSnap.c_str(), RTFsTypeName(enmFsTypeSnap)));
2931 mfSnapshotFolderDiskTypeShown = true;
2932 }
2933 LogRel(("File system of '%s' is %s\n", utfFile.c_str(), RTFsTypeName(enmFsTypeFile)));
2934 LONG64 i64Size;
2935 hrc = pMedium->COMGETTER(LogicalSize)(&i64Size); H();
2936#ifdef RT_OS_WINDOWS
2937 if ( enmFsTypeFile == RTFSTYPE_FAT
2938 && i64Size >= _4G)
2939 {
2940 const char *pszUnit;
2941 uint64_t u64Print = formatDiskSize((uint64_t)i64Size, &pszUnit);
2942 setVMRuntimeErrorCallbackF(pVM, this, 0,
2943 "FatPartitionDetected",
2944 N_("The medium '%ls' has a logical size of %RU64%s "
2945 "but the file system the medium is located on seems "
2946 "to be FAT(32) which cannot handle files bigger than 4GB.\n"
2947 "We strongly recommend to put all your virtual disk images and "
2948 "the snapshot folder onto an NTFS partition"),
2949 strFile.raw(), u64Print, pszUnit);
2950 }
2951#else /* !RT_OS_WINDOWS */
2952 if ( enmFsTypeFile == RTFSTYPE_FAT
2953 || enmFsTypeFile == RTFSTYPE_EXT
2954 || enmFsTypeFile == RTFSTYPE_EXT2
2955 || enmFsTypeFile == RTFSTYPE_EXT3
2956 || enmFsTypeFile == RTFSTYPE_EXT4)
2957 {
2958 RTFILE file;
2959 rc = RTFileOpen(&file, utfFile.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
2960 if (RT_SUCCESS(rc))
2961 {
2962 RTFOFF maxSize;
2963 /* Careful: This function will work only on selected local file systems! */
2964 rc = RTFileGetMaxSizeEx(file, &maxSize);
2965 RTFileClose(file);
2966 if ( RT_SUCCESS(rc)
2967 && maxSize > 0
2968 && i64Size > (LONG64)maxSize)
2969 {
2970 const char *pszUnitSiz;
2971 const char *pszUnitMax;
2972 uint64_t u64PrintSiz = formatDiskSize((LONG64)i64Size, &pszUnitSiz);
2973 uint64_t u64PrintMax = formatDiskSize(maxSize, &pszUnitMax);
2974 setVMRuntimeErrorCallbackF(pVM, this, 0,
2975 "FatPartitionDetected", /* <= not exact but ... */
2976 N_("The medium '%ls' has a logical size of %RU64%s "
2977 "but the file system the medium is located on can "
2978 "only handle files up to %RU64%s in theory.\n"
2979 "We strongly recommend to put all your virtual disk "
2980 "images and the snapshot folder onto a proper "
2981 "file system (e.g. ext3) with a sufficient size"),
2982 strFile.raw(), u64PrintSiz, pszUnitSiz, u64PrintMax, pszUnitMax);
2983 }
2984 }
2985 }
2986#endif /* !RT_OS_WINDOWS */
2987
2988 /*
2989 * Snapshot folder:
2990 * Here we test only for a FAT partition as we had to create a dummy file otherwise
2991 */
2992 if ( enmFsTypeSnap == RTFSTYPE_FAT
2993 && i64Size >= _4G
2994 && !mfSnapshotFolderSizeWarningShown)
2995 {
2996 const char *pszUnit;
2997 uint64_t u64Print = formatDiskSize(i64Size, &pszUnit);
2998 setVMRuntimeErrorCallbackF(pVM, this, 0,
2999 "FatPartitionDetected",
3000#ifdef RT_OS_WINDOWS
3001 N_("The snapshot folder of this VM '%ls' seems to be located on "
3002 "a FAT(32) file system. The logical size of the medium '%ls' "
3003 "(%RU64%s) is bigger than the maximum file size this file "
3004 "system can handle (4GB).\n"
3005 "We strongly recommend to put all your virtual disk images and "
3006 "the snapshot folder onto an NTFS partition"),
3007#else
3008 N_("The snapshot folder of this VM '%ls' seems to be located on "
3009 "a FAT(32) file system. The logical size of the medium '%ls' "
3010 "(%RU64%s) is bigger than the maximum file size this file "
3011 "system can handle (4GB).\n"
3012 "We strongly recommend to put all your virtual disk images and "
3013 "the snapshot folder onto a proper file system (e.g. ext3)"),
3014#endif
3015 strSnap.raw(), strFile.raw(), u64Print, pszUnit);
3016 /* Show this particular warning only once */
3017 mfSnapshotFolderSizeWarningShown = true;
3018 }
3019
3020#ifdef RT_OS_LINUX
3021 /*
3022 * Ext4 bug: Check if the host I/O cache is disabled and the disk image is located
3023 * on an ext4 partition. Later we have to check the Linux kernel version!
3024 * This bug apparently applies to the XFS file system as well.
3025 * Linux 2.6.36 is known to be fixed (tested with 2.6.36-rc4).
3026 */
3027
3028 char szOsRelease[128];
3029 rc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szOsRelease, sizeof(szOsRelease));
3030 bool fKernelHasODirectBug = RT_FAILURE(rc)
3031 || (RTStrVersionCompare(szOsRelease, "2.6.36-rc4") < 0);
3032
3033 if ( (uCaps & MediumFormatCapabilities_Asynchronous)
3034 && !fUseHostIOCache
3035 && fKernelHasODirectBug)
3036 {
3037 if ( enmFsTypeFile == RTFSTYPE_EXT4
3038 || enmFsTypeFile == RTFSTYPE_XFS)
3039 {
3040 setVMRuntimeErrorCallbackF(pVM, this, 0,
3041 "Ext4PartitionDetected",
3042 N_("The host I/O cache for at least one controller is disabled "
3043 "and the medium '%ls' for this VM "
3044 "is located on an %s partition. There is a known Linux "
3045 "kernel bug which can lead to the corruption of the virtual "
3046 "disk image under these conditions.\n"
3047 "Either enable the host I/O cache permanently in the VM "
3048 "settings or put the disk image and the snapshot folder "
3049 "onto a different file system.\n"
3050 "The host I/O cache will now be enabled for this medium"),
3051 strFile.raw(), enmFsTypeFile == RTFSTYPE_EXT4 ? "ext4" : "xfs");
3052 fUseHostIOCache = true;
3053 }
3054 else if ( ( enmFsTypeSnap == RTFSTYPE_EXT4
3055 || enmFsTypeSnap == RTFSTYPE_XFS)
3056 && !mfSnapshotFolderExt4WarningShown)
3057 {
3058 setVMRuntimeErrorCallbackF(pVM, this, 0,
3059 "Ext4PartitionDetected",
3060 N_("The host I/O cache for at least one controller is disabled "
3061 "and the snapshot folder for this VM "
3062 "is located on an %s partition. There is a known Linux "
3063 "kernel bug which can lead to the corruption of the virtual "
3064 "disk image under these conditions.\n"
3065 "Either enable the host I/O cache permanently in the VM "
3066 "settings or put the disk image and the snapshot folder "
3067 "onto a different file system.\n"
3068 "The host I/O cache will now be enabled for this medium"),
3069 enmFsTypeSnap == RTFSTYPE_EXT4 ? "ext4" : "xfs");
3070 fUseHostIOCache = true;
3071 mfSnapshotFolderExt4WarningShown = true;
3072 }
3073 }
3074#endif
3075 }
3076 }
3077
3078 BOOL fPassthrough;
3079 hrc = pMediumAtt->COMGETTER(Passthrough)(&fPassthrough); H();
3080
3081 ComObjPtr<IBandwidthGroup> pBwGroup;
3082 Bstr strBwGroup;
3083 hrc = pMediumAtt->COMGETTER(BandwidthGroup)(pBwGroup.asOutParam()); H();
3084
3085 if (!pBwGroup.isNull())
3086 {
3087 hrc = pBwGroup->COMGETTER(Name)(strBwGroup.asOutParam()); H();
3088 }
3089
3090 rc = configMedium(pLunL0,
3091 !!fPassthrough,
3092 lType,
3093 fUseHostIOCache,
3094 fBuiltinIoCache,
3095 fSetupMerge,
3096 uMergeSource,
3097 uMergeTarget,
3098 strBwGroup.isEmpty() ? NULL : Utf8Str(strBwGroup).c_str(),
3099 pMedium,
3100 aMachineState,
3101 phrc);
3102 if (RT_FAILURE(rc))
3103 return rc;
3104
3105 if (fAttachDetach)
3106 {
3107 /* Attach the new driver. */
3108 rc = PDMR3DeviceAttach(pVM, pcszDevice, uInstance, uLUN,
3109 PDM_TACH_FLAGS_NOT_HOT_PLUG, NULL /*ppBase*/);
3110 AssertRCReturn(rc, rc);
3111
3112 /* There is no need to handle removable medium mounting, as we
3113 * unconditionally replace everthing including the block driver level.
3114 * This means the new medium will be picked up automatically. */
3115 }
3116
3117 if (paLedDevType)
3118 paLedDevType[uLUN] = lType;
3119 }
3120 catch (ConfigError &x)
3121 {
3122 // InsertConfig threw something:
3123 return x.m_vrc;
3124 }
3125
3126#undef H
3127
3128 return VINF_SUCCESS;;
3129}
3130
3131int Console::configMedium(PCFGMNODE pLunL0,
3132 bool fPassthrough,
3133 DeviceType_T enmType,
3134 bool fUseHostIOCache,
3135 bool fBuiltinIoCache,
3136 bool fSetupMerge,
3137 unsigned uMergeSource,
3138 unsigned uMergeTarget,
3139 const char *pcszBwGroup,
3140 IMedium *pMedium,
3141 MachineState_T aMachineState,
3142 HRESULT *phrc)
3143{
3144 // InsertConfig* throws
3145 try
3146 {
3147 int rc = VINF_SUCCESS;
3148 HRESULT hrc;
3149 Bstr bstr;
3150 PCFGMNODE pLunL1 = NULL;
3151 PCFGMNODE pCfg = NULL;
3152
3153#define H() \
3154 AssertMsgReturnStmt(SUCCEEDED(hrc), ("hrc=%Rhrc\n", hrc), if (phrc) *phrc = hrc, Global::vboxStatusCodeFromCOM(hrc))
3155
3156
3157 BOOL fHostDrive = FALSE;
3158 MediumType_T mediumType = MediumType_Normal;
3159 if (pMedium)
3160 {
3161 hrc = pMedium->COMGETTER(HostDrive)(&fHostDrive); H();
3162 hrc = pMedium->COMGETTER(Type)(&mediumType); H();
3163 }
3164
3165 if (fHostDrive)
3166 {
3167 Assert(pMedium);
3168 if (enmType == DeviceType_DVD)
3169 {
3170 InsertConfigString(pLunL0, "Driver", "HostDVD");
3171 InsertConfigNode(pLunL0, "Config", &pCfg);
3172
3173 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3174 InsertConfigString(pCfg, "Path", bstr);
3175
3176 InsertConfigInteger(pCfg, "Passthrough", fPassthrough);
3177 }
3178 else if (enmType == DeviceType_Floppy)
3179 {
3180 InsertConfigString(pLunL0, "Driver", "HostFloppy");
3181 InsertConfigNode(pLunL0, "Config", &pCfg);
3182
3183 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3184 InsertConfigString(pCfg, "Path", bstr);
3185 }
3186 }
3187 else
3188 {
3189 InsertConfigString(pLunL0, "Driver", "Block");
3190 InsertConfigNode(pLunL0, "Config", &pCfg);
3191 switch (enmType)
3192 {
3193 case DeviceType_DVD:
3194 InsertConfigString(pCfg, "Type", "DVD");
3195 InsertConfigInteger(pCfg, "Mountable", 1);
3196 break;
3197 case DeviceType_Floppy:
3198 InsertConfigString(pCfg, "Type", "Floppy 1.44");
3199 InsertConfigInteger(pCfg, "Mountable", 1);
3200 break;
3201 case DeviceType_HardDisk:
3202 default:
3203 InsertConfigString(pCfg, "Type", "HardDisk");
3204 InsertConfigInteger(pCfg, "Mountable", 0);
3205 }
3206
3207 if ( pMedium
3208 && ( enmType == DeviceType_DVD
3209 || enmType == DeviceType_Floppy)
3210 )
3211 {
3212 // if this medium represents an ISO image and this image is inaccessible,
3213 // the ignore it instead of causing a failure; this can happen when we
3214 // restore a VM state and the ISO has disappeared, e.g. because the Guest
3215 // Additions were mounted and the user upgraded VirtualBox. Previously
3216 // we failed on startup, but that's not good because the only way out then
3217 // would be to discard the VM state...
3218 MediumState_T mediumState;
3219 hrc = pMedium->RefreshState(&mediumState); H();
3220 if (mediumState == MediumState_Inaccessible)
3221 {
3222 Bstr loc;
3223 hrc = pMedium->COMGETTER(Location)(loc.asOutParam()); H();
3224 setVMRuntimeErrorCallbackF(VMR3GetVM(mpUVM),
3225 this,
3226 0,
3227 "DvdOrFloppyImageInaccessible",
3228 "The image file '%ls' is inaccessible and is being ignored. Please select a different image file for the virtual %s drive.",
3229 loc.raw(),
3230 enmType == DeviceType_DVD ? "DVD" : "floppy");
3231 pMedium = NULL;
3232 }
3233 }
3234
3235 if (pMedium)
3236 {
3237 /* Start with length of parent chain, as the list is reversed */
3238 unsigned uImage = 0;
3239 IMedium *pTmp = pMedium;
3240 while (pTmp)
3241 {
3242 uImage++;
3243 hrc = pTmp->COMGETTER(Parent)(&pTmp); H();
3244 }
3245 /* Index of last image */
3246 uImage--;
3247
3248#if 0 /* Enable for I/O debugging */
3249 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
3250 InsertConfigString(pLunL0, "Driver", "DiskIntegrity");
3251 InsertConfigNode(pLunL0, "Config", &pCfg);
3252 InsertConfigInteger(pCfg, "CheckConsistency", 0);
3253 InsertConfigInteger(pCfg, "CheckDoubleCompletions", 1);
3254#endif
3255
3256 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
3257 InsertConfigString(pLunL1, "Driver", "VD");
3258 InsertConfigNode(pLunL1, "Config", &pCfg);
3259
3260 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3261 InsertConfigString(pCfg, "Path", bstr);
3262
3263 hrc = pMedium->COMGETTER(Format)(bstr.asOutParam()); H();
3264 InsertConfigString(pCfg, "Format", bstr);
3265
3266 if (mediumType == MediumType_Readonly)
3267 InsertConfigInteger(pCfg, "ReadOnly", 1);
3268 else if (enmType == DeviceType_Floppy)
3269 InsertConfigInteger(pCfg, "MaybeReadOnly", 1);
3270
3271 /* Start without exclusive write access to the images. */
3272 /** @todo Live Migration: I don't quite like this, we risk screwing up when
3273 * we're resuming the VM if some 3rd dude have any of the VDIs open
3274 * with write sharing denied. However, if the two VMs are sharing a
3275 * image it really is necessary....
3276 *
3277 * So, on the "lock-media" command, the target teleporter should also
3278 * make DrvVD undo TempReadOnly. It gets interesting if we fail after
3279 * that. Grumble. */
3280 if ( enmType == DeviceType_HardDisk
3281 && ( aMachineState == MachineState_TeleportingIn
3282 || aMachineState == MachineState_FaultTolerantSyncing))
3283 InsertConfigInteger(pCfg, "TempReadOnly", 1);
3284
3285 /* Flag for opening the medium for sharing between VMs. This
3286 * is done at the moment only for the first (and only) medium
3287 * in the chain, as shared media can have no diffs. */
3288 if (mediumType == MediumType_Shareable)
3289 InsertConfigInteger(pCfg, "Shareable", 1);
3290
3291 if (!fUseHostIOCache)
3292 {
3293 InsertConfigInteger(pCfg, "UseNewIo", 1);
3294 /*
3295 * Activate the builtin I/O cache for harddisks only.
3296 * It caches writes only which doesn't make sense for DVD drives
3297 * and just increases the overhead.
3298 */
3299 if ( fBuiltinIoCache
3300 && (enmType == DeviceType_HardDisk))
3301 InsertConfigInteger(pCfg, "BlockCache", 1);
3302 }
3303
3304 if (fSetupMerge)
3305 {
3306 InsertConfigInteger(pCfg, "SetupMerge", 1);
3307 if (uImage == uMergeSource)
3308 InsertConfigInteger(pCfg, "MergeSource", 1);
3309 else if (uImage == uMergeTarget)
3310 InsertConfigInteger(pCfg, "MergeTarget", 1);
3311 }
3312
3313 switch (enmType)
3314 {
3315 case DeviceType_DVD:
3316 InsertConfigString(pCfg, "Type", "DVD");
3317 break;
3318 case DeviceType_Floppy:
3319 InsertConfigString(pCfg, "Type", "Floppy");
3320 break;
3321 case DeviceType_HardDisk:
3322 default:
3323 InsertConfigString(pCfg, "Type", "HardDisk");
3324 }
3325
3326 if (pcszBwGroup)
3327 InsertConfigString(pCfg, "BwGroup", pcszBwGroup);
3328
3329 /* Pass all custom parameters. */
3330 bool fHostIP = true;
3331 SafeArray<BSTR> names;
3332 SafeArray<BSTR> values;
3333 hrc = pMedium->GetProperties(NULL,
3334 ComSafeArrayAsOutParam(names),
3335 ComSafeArrayAsOutParam(values)); H();
3336
3337 if (names.size() != 0)
3338 {
3339 PCFGMNODE pVDC;
3340 InsertConfigNode(pCfg, "VDConfig", &pVDC);
3341 for (size_t ii = 0; ii < names.size(); ++ii)
3342 {
3343 if (values[ii] && *values[ii])
3344 {
3345 Utf8Str name = names[ii];
3346 Utf8Str value = values[ii];
3347 InsertConfigString(pVDC, name.c_str(), value);
3348 if ( name.compare("HostIPStack") == 0
3349 && value.compare("0") == 0)
3350 fHostIP = false;
3351 }
3352 }
3353 }
3354
3355 /* Create an inverted list of parents. */
3356 uImage--;
3357 IMedium *pParentMedium = pMedium;
3358 for (PCFGMNODE pParent = pCfg;; uImage--)
3359 {
3360 hrc = pParentMedium->COMGETTER(Parent)(&pMedium); H();
3361 if (!pMedium)
3362 break;
3363
3364 PCFGMNODE pCur;
3365 InsertConfigNode(pParent, "Parent", &pCur);
3366 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3367 InsertConfigString(pCur, "Path", bstr);
3368
3369 hrc = pMedium->COMGETTER(Format)(bstr.asOutParam()); H();
3370 InsertConfigString(pCur, "Format", bstr);
3371
3372 if (fSetupMerge)
3373 {
3374 if (uImage == uMergeSource)
3375 InsertConfigInteger(pCur, "MergeSource", 1);
3376 else if (uImage == uMergeTarget)
3377 InsertConfigInteger(pCur, "MergeTarget", 1);
3378 }
3379
3380 /* Pass all custom parameters. */
3381 SafeArray<BSTR> aNames;
3382 SafeArray<BSTR> aValues;
3383 hrc = pMedium->GetProperties(NULL,
3384 ComSafeArrayAsOutParam(aNames),
3385 ComSafeArrayAsOutParam(aValues)); H();
3386
3387 if (aNames.size() != 0)
3388 {
3389 PCFGMNODE pVDC;
3390 InsertConfigNode(pCur, "VDConfig", &pVDC);
3391 for (size_t ii = 0; ii < aNames.size(); ++ii)
3392 {
3393 if (aValues[ii] && *aValues[ii])
3394 {
3395 Utf8Str name = aNames[ii];
3396 Utf8Str value = aValues[ii];
3397 InsertConfigString(pVDC, name.c_str(), value);
3398 if ( name.compare("HostIPStack") == 0
3399 && value.compare("0") == 0)
3400 fHostIP = false;
3401 }
3402 }
3403 }
3404
3405 /* next */
3406 pParent = pCur;
3407 pParentMedium = pMedium;
3408 }
3409
3410 /* Custom code: put marker to not use host IP stack to driver
3411 * configuration node. Simplifies life of DrvVD a bit. */
3412 if (!fHostIP)
3413 InsertConfigInteger(pCfg, "HostIPStack", 0);
3414 }
3415 }
3416#undef H
3417 }
3418 catch (ConfigError &x)
3419 {
3420 // InsertConfig threw something:
3421 return x.m_vrc;
3422 }
3423
3424 return VINF_SUCCESS;
3425}
3426
3427/**
3428 * Construct the Network configuration tree
3429 *
3430 * @returns VBox status code.
3431 *
3432 * @param pszDevice The PDM device name.
3433 * @param uInstance The PDM device instance.
3434 * @param uLun The PDM LUN number of the drive.
3435 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
3436 * @param pCfg Configuration node for the device
3437 * @param pLunL0 To store the pointer to the LUN#0.
3438 * @param pInst The instance CFGM node
3439 * @param fAttachDetach To determine if the network attachment should
3440 * be attached/detached after/before
3441 * configuration.
3442 * @param fIgnoreConnectFailure
3443 * True if connection failures should be ignored
3444 * (makes only sense for bridged/host-only networks).
3445 *
3446 * @note Locks this object for writing.
3447 * @thread EMT
3448 */
3449int Console::configNetwork(const char *pszDevice,
3450 unsigned uInstance,
3451 unsigned uLun,
3452 INetworkAdapter *aNetworkAdapter,
3453 PCFGMNODE pCfg,
3454 PCFGMNODE pLunL0,
3455 PCFGMNODE pInst,
3456 bool fAttachDetach,
3457 bool fIgnoreConnectFailure)
3458{
3459 AutoCaller autoCaller(this);
3460 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
3461
3462 // InsertConfig* throws
3463 try
3464 {
3465 int rc = VINF_SUCCESS;
3466 HRESULT hrc;
3467 Bstr bstr;
3468
3469#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
3470
3471 /*
3472 * Locking the object before doing VMR3* calls is quite safe here, since
3473 * we're on EMT. Write lock is necessary because we indirectly modify the
3474 * meAttachmentType member.
3475 */
3476 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3477
3478 PVM pVM = VMR3GetVM(mpUVM); /* We're on an EMT, so this is safe. */
3479
3480 ComPtr<IMachine> pMachine = machine();
3481
3482 ComPtr<IVirtualBox> virtualBox;
3483 hrc = pMachine->COMGETTER(Parent)(virtualBox.asOutParam()); H();
3484
3485 ComPtr<IHost> host;
3486 hrc = virtualBox->COMGETTER(Host)(host.asOutParam()); H();
3487
3488 BOOL fSniffer;
3489 hrc = aNetworkAdapter->COMGETTER(TraceEnabled)(&fSniffer); H();
3490
3491 NetworkAdapterPromiscModePolicy_T enmPromiscModePolicy;
3492 hrc = aNetworkAdapter->COMGETTER(PromiscModePolicy)(&enmPromiscModePolicy); H();
3493 const char *pszPromiscuousGuestPolicy;
3494 switch (enmPromiscModePolicy)
3495 {
3496 case NetworkAdapterPromiscModePolicy_Deny: pszPromiscuousGuestPolicy = "deny"; break;
3497 case NetworkAdapterPromiscModePolicy_AllowNetwork: pszPromiscuousGuestPolicy = "allow-network"; break;
3498 case NetworkAdapterPromiscModePolicy_AllowAll: pszPromiscuousGuestPolicy = "allow-all"; break;
3499 default: AssertFailedReturn(VERR_INTERNAL_ERROR_4);
3500 }
3501
3502 if (fAttachDetach && fSniffer)
3503 {
3504 const char *pszNetDriver = "IntNet";
3505 if (meAttachmentType[uInstance] == NetworkAttachmentType_NAT)
3506 pszNetDriver = "NAT";
3507#if !defined(VBOX_WITH_NETFLT) && defined(RT_OS_LINUX)
3508 if (meAttachmentType[uInstance] == NetworkAttachmentType_Bridged)
3509 pszNetDriver = "HostInterface";
3510#endif
3511
3512 rc = PDMR3DriverDetach(pVM, pszDevice, uInstance, uLun, pszNetDriver, 0, 0 /*fFlags*/);
3513 if (rc == VINF_PDM_NO_DRIVER_ATTACHED_TO_LUN)
3514 rc = VINF_SUCCESS;
3515 AssertLogRelRCReturn(rc, rc);
3516
3517 pLunL0 = CFGMR3GetChildF(pInst, "LUN#%u", uLun);
3518 PCFGMNODE pLunAD = CFGMR3GetChildF(pLunL0, "AttachedDriver");
3519 if (pLunAD)
3520 {
3521 CFGMR3RemoveNode(pLunAD);
3522 }
3523 else
3524 {
3525 CFGMR3RemoveNode(pLunL0);
3526 InsertConfigNode(pInst, "LUN#0", &pLunL0);
3527 InsertConfigString(pLunL0, "Driver", "NetSniffer");
3528 InsertConfigNode(pLunL0, "Config", &pCfg);
3529 hrc = aNetworkAdapter->COMGETTER(TraceFile)(bstr.asOutParam()); H();
3530 if (!bstr.isEmpty()) /* check convention for indicating default file. */
3531 InsertConfigString(pCfg, "File", bstr);
3532 }
3533 }
3534 else if (fAttachDetach && !fSniffer)
3535 {
3536 rc = PDMR3DeviceDetach(pVM, pszDevice, uInstance, uLun, 0 /*fFlags*/);
3537 if (rc == VINF_PDM_NO_DRIVER_ATTACHED_TO_LUN)
3538 rc = VINF_SUCCESS;
3539 AssertLogRelRCReturn(rc, rc);
3540
3541 /* nuke anything which might have been left behind. */
3542 CFGMR3RemoveNode(CFGMR3GetChildF(pInst, "LUN#%u", uLun));
3543 }
3544 else if (!fAttachDetach && fSniffer)
3545 {
3546 /* insert the sniffer filter driver. */
3547 InsertConfigNode(pInst, "LUN#0", &pLunL0);
3548 InsertConfigString(pLunL0, "Driver", "NetSniffer");
3549 InsertConfigNode(pLunL0, "Config", &pCfg);
3550 hrc = aNetworkAdapter->COMGETTER(TraceFile)(bstr.asOutParam()); H();
3551 if (!bstr.isEmpty()) /* check convention for indicating default file. */
3552 InsertConfigString(pCfg, "File", bstr);
3553 }
3554
3555 Bstr networkName, trunkName, trunkType;
3556 NetworkAttachmentType_T eAttachmentType;
3557 hrc = aNetworkAdapter->COMGETTER(AttachmentType)(&eAttachmentType); H();
3558 switch (eAttachmentType)
3559 {
3560 case NetworkAttachmentType_Null:
3561 break;
3562
3563 case NetworkAttachmentType_NAT:
3564 {
3565 ComPtr<INATEngine> natDriver;
3566 hrc = aNetworkAdapter->COMGETTER(NatDriver)(natDriver.asOutParam()); H();
3567 if (fSniffer)
3568 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
3569 else
3570 InsertConfigNode(pInst, "LUN#0", &pLunL0);
3571 InsertConfigString(pLunL0, "Driver", "NAT");
3572 InsertConfigNode(pLunL0, "Config", &pCfg);
3573
3574 /* Configure TFTP prefix and boot filename. */
3575 hrc = virtualBox->COMGETTER(HomeFolder)(bstr.asOutParam()); H();
3576 if (!bstr.isEmpty())
3577 InsertConfigString(pCfg, "TFTPPrefix", Utf8StrFmt("%ls%c%s", bstr.raw(), RTPATH_DELIMITER, "TFTP"));
3578 hrc = pMachine->COMGETTER(Name)(bstr.asOutParam()); H();
3579 InsertConfigString(pCfg, "BootFile", Utf8StrFmt("%ls.pxe", bstr.raw()));
3580
3581 hrc = natDriver->COMGETTER(Network)(bstr.asOutParam()); H();
3582 if (!bstr.isEmpty())
3583 InsertConfigString(pCfg, "Network", bstr);
3584 else
3585 {
3586 ULONG uSlot;
3587 hrc = aNetworkAdapter->COMGETTER(Slot)(&uSlot); H();
3588 InsertConfigString(pCfg, "Network", Utf8StrFmt("10.0.%d.0/24", uSlot+2));
3589 }
3590 hrc = natDriver->COMGETTER(HostIP)(bstr.asOutParam()); H();
3591 if (!bstr.isEmpty())
3592 InsertConfigString(pCfg, "BindIP", bstr);
3593 ULONG mtu = 0;
3594 ULONG sockSnd = 0;
3595 ULONG sockRcv = 0;
3596 ULONG tcpSnd = 0;
3597 ULONG tcpRcv = 0;
3598 hrc = natDriver->GetNetworkSettings(&mtu, &sockSnd, &sockRcv, &tcpSnd, &tcpRcv); H();
3599 if (mtu)
3600 InsertConfigInteger(pCfg, "SlirpMTU", mtu);
3601 if (sockRcv)
3602 InsertConfigInteger(pCfg, "SockRcv", sockRcv);
3603 if (sockSnd)
3604 InsertConfigInteger(pCfg, "SockSnd", sockSnd);
3605 if (tcpRcv)
3606 InsertConfigInteger(pCfg, "TcpRcv", tcpRcv);
3607 if (tcpSnd)
3608 InsertConfigInteger(pCfg, "TcpSnd", tcpSnd);
3609 hrc = natDriver->COMGETTER(TftpPrefix)(bstr.asOutParam()); H();
3610 if (!bstr.isEmpty())
3611 {
3612 RemoveConfigValue(pCfg, "TFTPPrefix");
3613 InsertConfigString(pCfg, "TFTPPrefix", bstr);
3614 }
3615 hrc = natDriver->COMGETTER(TftpBootFile)(bstr.asOutParam()); H();
3616 if (!bstr.isEmpty())
3617 {
3618 RemoveConfigValue(pCfg, "BootFile");
3619 InsertConfigString(pCfg, "BootFile", bstr);
3620 }
3621 hrc = natDriver->COMGETTER(TftpNextServer)(bstr.asOutParam()); H();
3622 if (!bstr.isEmpty())
3623 InsertConfigString(pCfg, "NextServer", bstr);
3624 BOOL fDnsFlag;
3625 hrc = natDriver->COMGETTER(DnsPassDomain)(&fDnsFlag); H();
3626 InsertConfigInteger(pCfg, "PassDomain", fDnsFlag);
3627 hrc = natDriver->COMGETTER(DnsProxy)(&fDnsFlag); H();
3628 InsertConfigInteger(pCfg, "DNSProxy", fDnsFlag);
3629 hrc = natDriver->COMGETTER(DnsUseHostResolver)(&fDnsFlag); H();
3630 InsertConfigInteger(pCfg, "UseHostResolver", fDnsFlag);
3631
3632 ULONG aliasMode;
3633 hrc = natDriver->COMGETTER(AliasMode)(&aliasMode); H();
3634 InsertConfigInteger(pCfg, "AliasMode", aliasMode);
3635
3636 /* port-forwarding */
3637 SafeArray<BSTR> pfs;
3638 hrc = natDriver->COMGETTER(Redirects)(ComSafeArrayAsOutParam(pfs)); H();
3639 PCFGMNODE pPF = NULL; /* /Devices/Dev/.../Config/PF#0/ */
3640 for (unsigned int i = 0; i < pfs.size(); ++i)
3641 {
3642 uint16_t port = 0;
3643 BSTR r = pfs[i];
3644 Utf8Str utf = Utf8Str(r);
3645 Utf8Str strName;
3646 Utf8Str strProto;
3647 Utf8Str strHostPort;
3648 Utf8Str strHostIP;
3649 Utf8Str strGuestPort;
3650 Utf8Str strGuestIP;
3651 size_t pos, ppos;
3652 pos = ppos = 0;
3653#define ITERATE_TO_NEXT_TERM(res, str, pos, ppos) \
3654 do { \
3655 pos = str.find(",", ppos); \
3656 if (pos == Utf8Str::npos) \
3657 { \
3658 Log(( #res " extracting from %s is failed\n", str.c_str())); \
3659 continue; \
3660 } \
3661 res = str.substr(ppos, pos - ppos); \
3662 Log2((#res " %s pos:%d, ppos:%d\n", res.c_str(), pos, ppos)); \
3663 ppos = pos + 1; \
3664 } while (0)
3665 ITERATE_TO_NEXT_TERM(strName, utf, pos, ppos);
3666 ITERATE_TO_NEXT_TERM(strProto, utf, pos, ppos);
3667 ITERATE_TO_NEXT_TERM(strHostIP, utf, pos, ppos);
3668 ITERATE_TO_NEXT_TERM(strHostPort, utf, pos, ppos);
3669 ITERATE_TO_NEXT_TERM(strGuestIP, utf, pos, ppos);
3670 strGuestPort = utf.substr(ppos, utf.length() - ppos);
3671#undef ITERATE_TO_NEXT_TERM
3672
3673 uint32_t proto = strProto.toUInt32();
3674 bool fValid = true;
3675 switch (proto)
3676 {
3677 case NATProtocol_UDP:
3678 strProto = "UDP";
3679 break;
3680 case NATProtocol_TCP:
3681 strProto = "TCP";
3682 break;
3683 default:
3684 fValid = false;
3685 }
3686 /* continue with next rule if no valid proto was passed */
3687 if (!fValid)
3688 continue;
3689
3690 InsertConfigNode(pCfg, strName.c_str(), &pPF);
3691 InsertConfigString(pPF, "Protocol", strProto);
3692
3693 if (!strHostIP.isEmpty())
3694 InsertConfigString(pPF, "BindIP", strHostIP);
3695
3696 if (!strGuestIP.isEmpty())
3697 InsertConfigString(pPF, "GuestIP", strGuestIP);
3698
3699 port = RTStrToUInt16(strHostPort.c_str());
3700 if (port)
3701 InsertConfigInteger(pPF, "HostPort", port);
3702
3703 port = RTStrToUInt16(strGuestPort.c_str());
3704 if (port)
3705 InsertConfigInteger(pPF, "GuestPort", port);
3706 }
3707 break;
3708 }
3709
3710 case NetworkAttachmentType_Bridged:
3711 {
3712#if (defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT)
3713 hrc = attachToTapInterface(aNetworkAdapter);
3714 if (FAILED(hrc))
3715 {
3716 switch (hrc)
3717 {
3718 case VERR_ACCESS_DENIED:
3719 return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
3720 "Failed to open '/dev/net/tun' for read/write access. Please check the "
3721 "permissions of that node. Either run 'chmod 0666 /dev/net/tun' or "
3722 "change the group of that node and make yourself a member of that group. Make "
3723 "sure that these changes are permanent, especially if you are "
3724 "using udev"));
3725 default:
3726 AssertMsgFailed(("Could not attach to host interface! Bad!\n"));
3727 return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
3728 "Failed to initialize Host Interface Networking"));
3729 }
3730 }
3731
3732 Assert((int)maTapFD[uInstance] >= 0);
3733 if ((int)maTapFD[uInstance] >= 0)
3734 {
3735 if (fSniffer)
3736 {
3737 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
3738 }
3739 else
3740 {
3741 InsertConfigNode(pInst, "LUN#0", &pLunL0);
3742 }
3743 InsertConfigString(pLunL0, "Driver", "HostInterface");
3744 InsertConfigNode(pLunL0, "Config", &pCfg);
3745 InsertConfigInteger(pCfg, "FileHandle", maTapFD[uInstance]);
3746 }
3747
3748#elif defined(VBOX_WITH_NETFLT)
3749 /*
3750 * This is the new VBoxNetFlt+IntNet stuff.
3751 */
3752 if (fSniffer)
3753 {
3754 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
3755 }
3756 else
3757 {
3758 InsertConfigNode(pInst, "LUN#0", &pLunL0);
3759 }
3760
3761 Bstr HifName;
3762 hrc = aNetworkAdapter->COMGETTER(HostInterface)(HifName.asOutParam());
3763 if (FAILED(hrc))
3764 {
3765 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(HostInterface) failed, hrc (0x%x)", hrc));
3766 H();
3767 }
3768
3769 Utf8Str HifNameUtf8(HifName);
3770 const char *pszHifName = HifNameUtf8.c_str();
3771
3772# if defined(RT_OS_DARWIN)
3773 /* The name is on the form 'ifX: long name', chop it off at the colon. */
3774 char szTrunk[8];
3775 RTStrCopy(szTrunk, sizeof(szTrunk), pszHifName);
3776 char *pszColon = (char *)memchr(szTrunk, ':', sizeof(szTrunk));
3777 if (!pszColon)
3778 {
3779 /*
3780 * Dynamic changing of attachment causes an attempt to configure
3781 * network with invalid host adapter (as it is must be changed before
3782 * the attachment), calling Detach here will cause a deadlock.
3783 * See #4750.
3784 * hrc = aNetworkAdapter->Detach(); H();
3785 */
3786 return VMSetError(pVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
3787 N_("Malformed host interface networking name '%ls'"),
3788 HifName.raw());
3789 }
3790 *pszColon = '\0';
3791 const char *pszTrunk = szTrunk;
3792
3793# elif defined(RT_OS_SOLARIS)
3794 /* The name is on the form format 'ifX[:1] - long name, chop it off at space. */
3795 char szTrunk[256];
3796 strlcpy(szTrunk, pszHifName, sizeof(szTrunk));
3797 char *pszSpace = (char *)memchr(szTrunk, ' ', sizeof(szTrunk));
3798
3799 /*
3800 * Currently don't bother about malformed names here for the sake of people using
3801 * VBoxManage and setting only the NIC name from there. If there is a space we
3802 * chop it off and proceed, otherwise just use whatever we've got.
3803 */
3804 if (pszSpace)
3805 *pszSpace = '\0';
3806
3807 /* Chop it off at the colon (zone naming eg: e1000g:1 we need only the e1000g) */
3808 char *pszColon = (char *)memchr(szTrunk, ':', sizeof(szTrunk));
3809 if (pszColon)
3810 *pszColon = '\0';
3811
3812 const char *pszTrunk = szTrunk;
3813
3814# elif defined(RT_OS_WINDOWS)
3815 ComPtr<IHostNetworkInterface> hostInterface;
3816 hrc = host->FindHostNetworkInterfaceByName(HifName.raw(),
3817 hostInterface.asOutParam());
3818 if (!SUCCEEDED(hrc))
3819 {
3820 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: FindByName failed, rc=%Rhrc (0x%x)", hrc, hrc));
3821 return VMSetError(pVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
3822 N_("Nonexistent host networking interface, name '%ls'"),
3823 HifName.raw());
3824 }
3825
3826 HostNetworkInterfaceType_T eIfType;
3827 hrc = hostInterface->COMGETTER(InterfaceType)(&eIfType);
3828 if (FAILED(hrc))
3829 {
3830 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(InterfaceType) failed, hrc (0x%x)", hrc));
3831 H();
3832 }
3833
3834 if (eIfType != HostNetworkInterfaceType_Bridged)
3835 {
3836 return VMSetError(pVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
3837 N_("Interface ('%ls') is not a Bridged Adapter interface"),
3838 HifName.raw());
3839 }
3840
3841 hrc = hostInterface->COMGETTER(Id)(bstr.asOutParam());
3842 if (FAILED(hrc))
3843 {
3844 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(Id) failed, hrc (0x%x)", hrc));
3845 H();
3846 }
3847 Guid hostIFGuid(bstr);
3848
3849 INetCfg *pNc;
3850 ComPtr<INetCfgComponent> pAdaptorComponent;
3851 LPWSTR pszApp;
3852
3853 hrc = VBoxNetCfgWinQueryINetCfg(&pNc, FALSE, L"VirtualBox", 10, &pszApp);
3854 Assert(hrc == S_OK);
3855 if (hrc != S_OK)
3856 {
3857 LogRel(("NetworkAttachmentType_Bridged: Failed to get NetCfg, hrc=%Rhrc (0x%x)\n", hrc, hrc));
3858 H();
3859 }
3860
3861 /* get the adapter's INetCfgComponent*/
3862 hrc = VBoxNetCfgWinGetComponentByGuid(pNc, &GUID_DEVCLASS_NET, (GUID*)hostIFGuid.raw(), pAdaptorComponent.asOutParam());
3863 if (hrc != S_OK)
3864 {
3865 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
3866 LogRel(("NetworkAttachmentType_Bridged: VBoxNetCfgWinGetComponentByGuid failed, hrc (0x%x)", hrc));
3867 H();
3868 }
3869#define VBOX_WIN_BINDNAME_PREFIX "\\DEVICE\\"
3870 char szTrunkName[INTNET_MAX_TRUNK_NAME];
3871 char *pszTrunkName = szTrunkName;
3872 wchar_t * pswzBindName;
3873 hrc = pAdaptorComponent->GetBindName(&pswzBindName);
3874 Assert(hrc == S_OK);
3875 if (hrc == S_OK)
3876 {
3877 int cwBindName = (int)wcslen(pswzBindName) + 1;
3878 int cbFullBindNamePrefix = sizeof(VBOX_WIN_BINDNAME_PREFIX);
3879 if (sizeof(szTrunkName) > cbFullBindNamePrefix + cwBindName)
3880 {
3881 strcpy(szTrunkName, VBOX_WIN_BINDNAME_PREFIX);
3882 pszTrunkName += cbFullBindNamePrefix-1;
3883 if (!WideCharToMultiByte(CP_ACP, 0, pswzBindName, cwBindName, pszTrunkName,
3884 sizeof(szTrunkName) - cbFullBindNamePrefix + 1, NULL, NULL))
3885 {
3886 DWORD err = GetLastError();
3887 hrc = HRESULT_FROM_WIN32(err);
3888 AssertMsgFailed(("%hrc=%Rhrc %#x\n", hrc, hrc));
3889 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: WideCharToMultiByte failed, hr=%Rhrc (0x%x) err=%u\n", hrc, hrc, err));
3890 }
3891 }
3892 else
3893 {
3894 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: insufficient szTrunkName buffer space\n"));
3895 /** @todo set appropriate error code */
3896 hrc = E_FAIL;
3897 }
3898
3899 if (hrc != S_OK)
3900 {
3901 AssertFailed();
3902 CoTaskMemFree(pswzBindName);
3903 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
3904 H();
3905 }
3906
3907 /* we're not freeing the bind name since we'll use it later for detecting wireless*/
3908 }
3909 else
3910 {
3911 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
3912 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: VBoxNetCfgWinGetComponentByGuid failed, hrc (0x%x)", hrc));
3913 H();
3914 }
3915
3916 const char *pszTrunk = szTrunkName;
3917 /* we're not releasing the INetCfg stuff here since we use it later to figure out whether it is wireless */
3918
3919# elif defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
3920# if defined(RT_OS_FREEBSD)
3921 /*
3922 * If we bridge to a tap interface open it the `old' direct way.
3923 * This works and performs better than bridging a physical
3924 * interface via the current FreeBSD vboxnetflt implementation.
3925 */
3926 if (!strncmp(pszHifName, "tap", sizeof "tap" - 1)) {
3927 hrc = attachToTapInterface(aNetworkAdapter);
3928 if (FAILED(hrc))
3929 {
3930 switch (hrc)
3931 {
3932 case VERR_ACCESS_DENIED:
3933 return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
3934 "Failed to open '/dev/%s' for read/write access. Please check the "
3935 "permissions of that node, and that the net.link.tap.user_open "
3936 "sysctl is set. Either run 'chmod 0666 /dev/%s' or "
3937 "change the group of that node to vboxusers and make yourself "
3938 "a member of that group. Make sure that these changes are permanent."), pszHifName, pszHifName);
3939 default:
3940 AssertMsgFailed(("Could not attach to tap interface! Bad!\n"));
3941 return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
3942 "Failed to initialize Host Interface Networking"));
3943 }
3944 }
3945
3946 Assert((int)maTapFD[uInstance] >= 0);
3947 if ((int)maTapFD[uInstance] >= 0)
3948 {
3949 InsertConfigString(pLunL0, "Driver", "HostInterface");
3950 InsertConfigNode(pLunL0, "Config", &pCfg);
3951 InsertConfigInteger(pCfg, "FileHandle", maTapFD[uInstance]);
3952 }
3953 break;
3954 }
3955# endif
3956 /** @todo Check for malformed names. */
3957 const char *pszTrunk = pszHifName;
3958
3959 /* Issue a warning if the interface is down */
3960 {
3961 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
3962 if (iSock >= 0)
3963 {
3964 struct ifreq Req;
3965 RT_ZERO(Req);
3966 strncpy(Req.ifr_name, pszHifName, sizeof(Req.ifr_name) - 1);
3967 if (ioctl(iSock, SIOCGIFFLAGS, &Req) >= 0)
3968 if ((Req.ifr_flags & IFF_UP) == 0)
3969 setVMRuntimeErrorCallbackF(pVM, this, 0, "BridgedInterfaceDown",
3970 "Bridged interface %s is down. Guest will not be able to use this interface",
3971 pszHifName);
3972
3973 close(iSock);
3974 }
3975 }
3976
3977# else
3978# error "PORTME (VBOX_WITH_NETFLT)"
3979# endif
3980
3981 InsertConfigString(pLunL0, "Driver", "IntNet");
3982 InsertConfigNode(pLunL0, "Config", &pCfg);
3983 InsertConfigString(pCfg, "Trunk", pszTrunk);
3984 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetFlt);
3985 InsertConfigInteger(pCfg, "IgnoreConnectFailure", (uint64_t)fIgnoreConnectFailure);
3986 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
3987 char szNetwork[INTNET_MAX_NETWORK_NAME];
3988 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszHifName);
3989 InsertConfigString(pCfg, "Network", szNetwork);
3990 networkName = Bstr(szNetwork);
3991 trunkName = Bstr(pszTrunk);
3992 trunkType = Bstr(TRUNKTYPE_NETFLT);
3993
3994# if defined(RT_OS_DARWIN)
3995 /** @todo Come up with a better deal here. Problem is that IHostNetworkInterface is completely useless here. */
3996 if ( strstr(pszHifName, "Wireless")
3997 || strstr(pszHifName, "AirPort" ))
3998 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
3999# elif defined(RT_OS_LINUX)
4000 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
4001 if (iSock >= 0)
4002 {
4003 struct iwreq WRq;
4004
4005 memset(&WRq, 0, sizeof(WRq));
4006 strncpy(WRq.ifr_name, pszHifName, IFNAMSIZ);
4007 bool fSharedMacOnWire = ioctl(iSock, SIOCGIWNAME, &WRq) >= 0;
4008 close(iSock);
4009 if (fSharedMacOnWire)
4010 {
4011 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4012 Log(("Set SharedMacOnWire\n"));
4013 }
4014 else
4015 Log(("Failed to get wireless name\n"));
4016 }
4017 else
4018 Log(("Failed to open wireless socket\n"));
4019# elif defined(RT_OS_FREEBSD)
4020 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
4021 if (iSock >= 0)
4022 {
4023 struct ieee80211req WReq;
4024 uint8_t abData[32];
4025
4026 memset(&WReq, 0, sizeof(WReq));
4027 strncpy(WReq.i_name, pszHifName, sizeof(WReq.i_name));
4028 WReq.i_type = IEEE80211_IOC_SSID;
4029 WReq.i_val = -1;
4030 WReq.i_data = abData;
4031 WReq.i_len = sizeof(abData);
4032
4033 bool fSharedMacOnWire = ioctl(iSock, SIOCG80211, &WReq) >= 0;
4034 close(iSock);
4035 if (fSharedMacOnWire)
4036 {
4037 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4038 Log(("Set SharedMacOnWire\n"));
4039 }
4040 else
4041 Log(("Failed to get wireless name\n"));
4042 }
4043 else
4044 Log(("Failed to open wireless socket\n"));
4045# elif defined(RT_OS_WINDOWS)
4046# define DEVNAME_PREFIX L"\\\\.\\"
4047 /* we are getting the medium type via IOCTL_NDIS_QUERY_GLOBAL_STATS Io Control
4048 * there is a pretty long way till there though since we need to obtain the symbolic link name
4049 * for the adapter device we are going to query given the device Guid */
4050
4051
4052 /* prepend the "\\\\.\\" to the bind name to obtain the link name */
4053
4054 wchar_t FileName[MAX_PATH];
4055 wcscpy(FileName, DEVNAME_PREFIX);
4056 wcscpy((wchar_t*)(((char*)FileName) + sizeof(DEVNAME_PREFIX) - sizeof(FileName[0])), pswzBindName);
4057
4058 /* open the device */
4059 HANDLE hDevice = CreateFile(FileName,
4060 GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
4061 NULL,
4062 OPEN_EXISTING,
4063 FILE_ATTRIBUTE_NORMAL,
4064 NULL);
4065
4066 if (hDevice != INVALID_HANDLE_VALUE)
4067 {
4068 bool fSharedMacOnWire = false;
4069
4070 /* now issue the OID_GEN_PHYSICAL_MEDIUM query */
4071 DWORD Oid = OID_GEN_PHYSICAL_MEDIUM;
4072 NDIS_PHYSICAL_MEDIUM PhMedium;
4073 DWORD cbResult;
4074 if (DeviceIoControl(hDevice,
4075 IOCTL_NDIS_QUERY_GLOBAL_STATS,
4076 &Oid,
4077 sizeof(Oid),
4078 &PhMedium,
4079 sizeof(PhMedium),
4080 &cbResult,
4081 NULL))
4082 {
4083 /* that was simple, now examine PhMedium */
4084 if ( PhMedium == NdisPhysicalMediumWirelessWan
4085 || PhMedium == NdisPhysicalMediumWirelessLan
4086 || PhMedium == NdisPhysicalMediumNative802_11
4087 || PhMedium == NdisPhysicalMediumBluetooth)
4088 fSharedMacOnWire = true;
4089 }
4090 else
4091 {
4092 int winEr = GetLastError();
4093 LogRel(("Console::configNetwork: DeviceIoControl failed, err (0x%x), ignoring\n", winEr));
4094 Assert(winEr == ERROR_INVALID_PARAMETER || winEr == ERROR_NOT_SUPPORTED || winEr == ERROR_BAD_COMMAND);
4095 }
4096 CloseHandle(hDevice);
4097
4098 if (fSharedMacOnWire)
4099 {
4100 Log(("this is a wireless adapter"));
4101 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4102 Log(("Set SharedMacOnWire\n"));
4103 }
4104 else
4105 Log(("this is NOT a wireless adapter"));
4106 }
4107 else
4108 {
4109 int winEr = GetLastError();
4110 AssertLogRelMsgFailed(("Console::configNetwork: CreateFile failed, err (0x%x), ignoring\n", winEr));
4111 }
4112
4113 CoTaskMemFree(pswzBindName);
4114
4115 pAdaptorComponent.setNull();
4116 /* release the pNc finally */
4117 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4118# else
4119 /** @todo PORTME: wireless detection */
4120# endif
4121
4122# if defined(RT_OS_SOLARIS)
4123# if 0 /* bird: this is a bit questionable and might cause more trouble than its worth. */
4124 /* Zone access restriction, don't allow snooping the global zone. */
4125 zoneid_t ZoneId = getzoneid();
4126 if (ZoneId != GLOBAL_ZONEID)
4127 {
4128 InsertConfigInteger(pCfg, "IgnoreAllPromisc", true);
4129 }
4130# endif
4131# endif
4132
4133#elif defined(RT_OS_WINDOWS) /* not defined NetFlt */
4134 /* NOTHING TO DO HERE */
4135#elif defined(RT_OS_LINUX)
4136/// @todo aleksey: is there anything to be done here?
4137#elif defined(RT_OS_FREEBSD)
4138/** @todo FreeBSD: Check out this later (HIF networking). */
4139#else
4140# error "Port me"
4141#endif
4142 break;
4143 }
4144
4145 case NetworkAttachmentType_Internal:
4146 {
4147 hrc = aNetworkAdapter->COMGETTER(InternalNetwork)(bstr.asOutParam()); H();
4148 if (!bstr.isEmpty())
4149 {
4150 if (fSniffer)
4151 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
4152 else
4153 InsertConfigNode(pInst, "LUN#0", &pLunL0);
4154 InsertConfigString(pLunL0, "Driver", "IntNet");
4155 InsertConfigNode(pLunL0, "Config", &pCfg);
4156 InsertConfigString(pCfg, "Network", bstr);
4157 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_WhateverNone);
4158 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
4159 networkName = bstr;
4160 trunkType = Bstr(TRUNKTYPE_WHATEVER);
4161 }
4162 break;
4163 }
4164
4165 case NetworkAttachmentType_HostOnly:
4166 {
4167 if (fSniffer)
4168 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
4169 else
4170 InsertConfigNode(pInst, "LUN#0", &pLunL0);
4171
4172 InsertConfigString(pLunL0, "Driver", "IntNet");
4173 InsertConfigNode(pLunL0, "Config", &pCfg);
4174
4175 Bstr HifName;
4176 hrc = aNetworkAdapter->COMGETTER(HostInterface)(HifName.asOutParam());
4177 if (FAILED(hrc))
4178 {
4179 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(HostInterface) failed, hrc (0x%x)\n", hrc));
4180 H();
4181 }
4182
4183 Utf8Str HifNameUtf8(HifName);
4184 const char *pszHifName = HifNameUtf8.c_str();
4185 ComPtr<IHostNetworkInterface> hostInterface;
4186 rc = host->FindHostNetworkInterfaceByName(HifName.raw(),
4187 hostInterface.asOutParam());
4188 if (!SUCCEEDED(rc))
4189 {
4190 LogRel(("NetworkAttachmentType_HostOnly: FindByName failed, rc (0x%x)\n", rc));
4191 return VMSetError(pVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
4192 N_("Nonexistent host networking interface, name '%ls'"),
4193 HifName.raw());
4194 }
4195
4196 char szNetwork[INTNET_MAX_NETWORK_NAME];
4197 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszHifName);
4198
4199#if defined(RT_OS_WINDOWS)
4200# ifndef VBOX_WITH_NETFLT
4201 hrc = E_NOTIMPL;
4202 LogRel(("NetworkAttachmentType_HostOnly: Not Implemented\n"));
4203 H();
4204# else /* defined VBOX_WITH_NETFLT*/
4205 /** @todo r=bird: Put this in a function. */
4206
4207 HostNetworkInterfaceType_T eIfType;
4208 hrc = hostInterface->COMGETTER(InterfaceType)(&eIfType);
4209 if (FAILED(hrc))
4210 {
4211 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(InterfaceType) failed, hrc (0x%x)\n", hrc));
4212 H();
4213 }
4214
4215 if (eIfType != HostNetworkInterfaceType_HostOnly)
4216 return VMSetError(pVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
4217 N_("Interface ('%ls') is not a Host-Only Adapter interface"),
4218 HifName.raw());
4219
4220 hrc = hostInterface->COMGETTER(Id)(bstr.asOutParam());
4221 if (FAILED(hrc))
4222 {
4223 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(Id) failed, hrc (0x%x)\n", hrc));
4224 H();
4225 }
4226 Guid hostIFGuid(bstr);
4227
4228 INetCfg *pNc;
4229 ComPtr<INetCfgComponent> pAdaptorComponent;
4230 LPWSTR pszApp;
4231 hrc = VBoxNetCfgWinQueryINetCfg(&pNc, FALSE, L"VirtualBox", 10, &pszApp);
4232 Assert(hrc == S_OK);
4233 if (hrc != S_OK)
4234 {
4235 LogRel(("NetworkAttachmentType_HostOnly: Failed to get NetCfg, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4236 H();
4237 }
4238
4239 /* get the adapter's INetCfgComponent*/
4240 hrc = VBoxNetCfgWinGetComponentByGuid(pNc, &GUID_DEVCLASS_NET, (GUID*)hostIFGuid.raw(), pAdaptorComponent.asOutParam());
4241 if (hrc != S_OK)
4242 {
4243 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4244 LogRel(("NetworkAttachmentType_HostOnly: VBoxNetCfgWinGetComponentByGuid failed, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4245 H();
4246 }
4247# define VBOX_WIN_BINDNAME_PREFIX "\\DEVICE\\"
4248 char szTrunkName[INTNET_MAX_TRUNK_NAME];
4249 char *pszTrunkName = szTrunkName;
4250 wchar_t * pswzBindName;
4251 hrc = pAdaptorComponent->GetBindName(&pswzBindName);
4252 Assert(hrc == S_OK);
4253 if (hrc == S_OK)
4254 {
4255 int cwBindName = (int)wcslen(pswzBindName) + 1;
4256 int cbFullBindNamePrefix = sizeof(VBOX_WIN_BINDNAME_PREFIX);
4257 if (sizeof(szTrunkName) > cbFullBindNamePrefix + cwBindName)
4258 {
4259 strcpy(szTrunkName, VBOX_WIN_BINDNAME_PREFIX);
4260 pszTrunkName += cbFullBindNamePrefix-1;
4261 if (!WideCharToMultiByte(CP_ACP, 0, pswzBindName, cwBindName, pszTrunkName,
4262 sizeof(szTrunkName) - cbFullBindNamePrefix + 1, NULL, NULL))
4263 {
4264 DWORD err = GetLastError();
4265 hrc = HRESULT_FROM_WIN32(err);
4266 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: WideCharToMultiByte failed, hr=%Rhrc (0x%x) err=%u\n", hrc, hrc, err));
4267 }
4268 }
4269 else
4270 {
4271 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: insufficient szTrunkName buffer space\n"));
4272 /** @todo set appropriate error code */
4273 hrc = E_FAIL;
4274 }
4275
4276 if (hrc != S_OK)
4277 {
4278 AssertFailed();
4279 CoTaskMemFree(pswzBindName);
4280 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4281 H();
4282 }
4283 }
4284 else
4285 {
4286 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4287 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: VBoxNetCfgWinGetComponentByGuid failed, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4288 H();
4289 }
4290
4291
4292 CoTaskMemFree(pswzBindName);
4293
4294 pAdaptorComponent.setNull();
4295 /* release the pNc finally */
4296 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4297
4298 const char *pszTrunk = szTrunkName;
4299
4300 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetAdp);
4301 InsertConfigString(pCfg, "Trunk", pszTrunk);
4302 InsertConfigString(pCfg, "Network", szNetwork);
4303 InsertConfigInteger(pCfg, "IgnoreConnectFailure", (uint64_t)fIgnoreConnectFailure); /** @todo why is this windows only?? */
4304 networkName = Bstr(szNetwork);
4305 trunkName = Bstr(pszTrunk);
4306 trunkType = TRUNKTYPE_NETADP;
4307# endif /* defined VBOX_WITH_NETFLT*/
4308#elif defined(RT_OS_DARWIN)
4309 InsertConfigString(pCfg, "Trunk", pszHifName);
4310 InsertConfigString(pCfg, "Network", szNetwork);
4311 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetAdp);
4312 networkName = Bstr(szNetwork);
4313 trunkName = Bstr(pszHifName);
4314 trunkType = TRUNKTYPE_NETADP;
4315#else
4316 InsertConfigString(pCfg, "Trunk", pszHifName);
4317 InsertConfigString(pCfg, "Network", szNetwork);
4318 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetFlt);
4319 networkName = Bstr(szNetwork);
4320 trunkName = Bstr(pszHifName);
4321 trunkType = TRUNKTYPE_NETFLT;
4322#endif
4323 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
4324
4325#if !defined(RT_OS_WINDOWS) && defined(VBOX_WITH_NETFLT)
4326
4327 Bstr tmpAddr, tmpMask;
4328
4329 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPAddress",
4330 pszHifName).raw(),
4331 tmpAddr.asOutParam());
4332 if (SUCCEEDED(hrc) && !tmpAddr.isEmpty())
4333 {
4334 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPNetMask",
4335 pszHifName).raw(),
4336 tmpMask.asOutParam());
4337 if (SUCCEEDED(hrc) && !tmpMask.isEmpty())
4338 hrc = hostInterface->EnableStaticIpConfig(tmpAddr.raw(),
4339 tmpMask.raw());
4340 else
4341 hrc = hostInterface->EnableStaticIpConfig(tmpAddr.raw(),
4342 Bstr(VBOXNET_IPV4MASK_DEFAULT).raw());
4343 }
4344 else
4345 {
4346 /* Grab the IP number from the 'vboxnetX' instance number (see netif.h) */
4347 hrc = hostInterface->EnableStaticIpConfig(getDefaultIPv4Address(Bstr(pszHifName)).raw(),
4348 Bstr(VBOXNET_IPV4MASK_DEFAULT).raw());
4349 }
4350
4351 ComAssertComRC(hrc); /** @todo r=bird: Why this isn't fatal? (H()) */
4352
4353 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6Address",
4354 pszHifName).raw(),
4355 tmpAddr.asOutParam());
4356 if (SUCCEEDED(hrc))
4357 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6NetMask", pszHifName).raw(),
4358 tmpMask.asOutParam());
4359 if (SUCCEEDED(hrc) && !tmpAddr.isEmpty() && !tmpMask.isEmpty())
4360 {
4361 hrc = hostInterface->EnableStaticIpConfigV6(tmpAddr.raw(),
4362 Utf8Str(tmpMask).toUInt32());
4363 ComAssertComRC(hrc); /** @todo r=bird: Why this isn't fatal? (H()) */
4364 }
4365#endif
4366 break;
4367 }
4368
4369#if defined(VBOX_WITH_VDE)
4370 case NetworkAttachmentType_VDE:
4371 {
4372 hrc = aNetworkAdapter->COMGETTER(VDENetwork)(bstr.asOutParam()); H();
4373 InsertConfigNode(pInst, "LUN#0", &pLunL0);
4374 InsertConfigString(pLunL0, "Driver", "VDE");
4375 InsertConfigNode(pLunL0, "Config", &pCfg);
4376 if (!bstr.isEmpty())
4377 {
4378 InsertConfigString(pCfg, "Network", bstr);
4379 networkName = bstr;
4380 }
4381 break;
4382 }
4383#endif
4384
4385 default:
4386 AssertMsgFailed(("should not get here!\n"));
4387 break;
4388 }
4389
4390 /*
4391 * Attempt to attach the driver.
4392 */
4393 switch (eAttachmentType)
4394 {
4395 case NetworkAttachmentType_Null:
4396 break;
4397
4398 case NetworkAttachmentType_Bridged:
4399 case NetworkAttachmentType_Internal:
4400 case NetworkAttachmentType_HostOnly:
4401 case NetworkAttachmentType_NAT:
4402#if defined(VBOX_WITH_VDE)
4403 case NetworkAttachmentType_VDE:
4404#endif
4405 {
4406 if (SUCCEEDED(hrc) && SUCCEEDED(rc))
4407 {
4408 if (fAttachDetach)
4409 {
4410 rc = PDMR3DriverAttach(pVM, pszDevice, uInstance, uLun, 0 /*fFlags*/, NULL /* ppBase */);
4411 //AssertRC(rc);
4412 }
4413
4414 {
4415 /** @todo pritesh: get the dhcp server name from the
4416 * previous network configuration and then stop the server
4417 * else it may conflict with the dhcp server running with
4418 * the current attachment type
4419 */
4420 /* Stop the hostonly DHCP Server */
4421 }
4422
4423 if (!networkName.isEmpty())
4424 {
4425 /*
4426 * Until we implement service reference counters DHCP Server will be stopped
4427 * by DHCPServerRunner destructor.
4428 */
4429 ComPtr<IDHCPServer> dhcpServer;
4430 hrc = virtualBox->FindDHCPServerByNetworkName(networkName.raw(),
4431 dhcpServer.asOutParam());
4432 if (SUCCEEDED(hrc))
4433 {
4434 /* there is a DHCP server available for this network */
4435 BOOL fEnabled;
4436 hrc = dhcpServer->COMGETTER(Enabled)(&fEnabled);
4437 if (FAILED(hrc))
4438 {
4439 LogRel(("DHCP svr: COMGETTER(Enabled) failed, hrc (%Rhrc)", hrc));
4440 H();
4441 }
4442
4443 if (fEnabled)
4444 hrc = dhcpServer->Start(networkName.raw(),
4445 trunkName.raw(),
4446 trunkType.raw());
4447 }
4448 else
4449 hrc = S_OK;
4450 }
4451 }
4452
4453 break;
4454 }
4455
4456 default:
4457 AssertMsgFailed(("should not get here!\n"));
4458 break;
4459 }
4460
4461 meAttachmentType[uInstance] = eAttachmentType;
4462 }
4463 catch (ConfigError &x)
4464 {
4465 // InsertConfig threw something:
4466 return x.m_vrc;
4467 }
4468
4469#undef H
4470
4471 return VINF_SUCCESS;
4472}
4473
4474#ifdef VBOX_WITH_GUEST_PROPS
4475/**
4476 * Set an array of guest properties
4477 */
4478static void configSetProperties(VMMDev * const pVMMDev,
4479 void *names,
4480 void *values,
4481 void *timestamps,
4482 void *flags)
4483{
4484 VBOXHGCMSVCPARM parms[4];
4485
4486 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
4487 parms[0].u.pointer.addr = names;
4488 parms[0].u.pointer.size = 0; /* We don't actually care. */
4489 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
4490 parms[1].u.pointer.addr = values;
4491 parms[1].u.pointer.size = 0; /* We don't actually care. */
4492 parms[2].type = VBOX_HGCM_SVC_PARM_PTR;
4493 parms[2].u.pointer.addr = timestamps;
4494 parms[2].u.pointer.size = 0; /* We don't actually care. */
4495 parms[3].type = VBOX_HGCM_SVC_PARM_PTR;
4496 parms[3].u.pointer.addr = flags;
4497 parms[3].u.pointer.size = 0; /* We don't actually care. */
4498
4499 pVMMDev->hgcmHostCall("VBoxGuestPropSvc",
4500 guestProp::SET_PROPS_HOST,
4501 4,
4502 &parms[0]);
4503}
4504
4505/**
4506 * Set a single guest property
4507 */
4508static void configSetProperty(VMMDev * const pVMMDev,
4509 const char *pszName,
4510 const char *pszValue,
4511 const char *pszFlags)
4512{
4513 VBOXHGCMSVCPARM parms[4];
4514
4515 AssertPtrReturnVoid(pszName);
4516 AssertPtrReturnVoid(pszValue);
4517 AssertPtrReturnVoid(pszFlags);
4518 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
4519 parms[0].u.pointer.addr = (void *)pszName;
4520 parms[0].u.pointer.size = strlen(pszName) + 1;
4521 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
4522 parms[1].u.pointer.addr = (void *)pszValue;
4523 parms[1].u.pointer.size = strlen(pszValue) + 1;
4524 parms[2].type = VBOX_HGCM_SVC_PARM_PTR;
4525 parms[2].u.pointer.addr = (void *)pszFlags;
4526 parms[2].u.pointer.size = strlen(pszFlags) + 1;
4527 pVMMDev->hgcmHostCall("VBoxGuestPropSvc", guestProp::SET_PROP_HOST, 3,
4528 &parms[0]);
4529}
4530
4531/**
4532 * Set the global flags value by calling the service
4533 * @returns the status returned by the call to the service
4534 *
4535 * @param pTable the service instance handle
4536 * @param eFlags the flags to set
4537 */
4538int configSetGlobalPropertyFlags(VMMDev * const pVMMDev,
4539 guestProp::ePropFlags eFlags)
4540{
4541 VBOXHGCMSVCPARM paParm;
4542 paParm.setUInt32(eFlags);
4543 int rc = pVMMDev->hgcmHostCall("VBoxGuestPropSvc",
4544 guestProp::SET_GLOBAL_FLAGS_HOST, 1,
4545 &paParm);
4546 if (RT_FAILURE(rc))
4547 {
4548 char szFlags[guestProp::MAX_FLAGS_LEN];
4549 if (RT_FAILURE(writeFlags(eFlags, szFlags)))
4550 Log(("Failed to set the global flags.\n"));
4551 else
4552 Log(("Failed to set the global flags \"%s\".\n", szFlags));
4553 }
4554 return rc;
4555}
4556#endif /* VBOX_WITH_GUEST_PROPS */
4557
4558/**
4559 * Set up the Guest Property service, populate it with properties read from
4560 * the machine XML and set a couple of initial properties.
4561 */
4562/* static */ int Console::configGuestProperties(void *pvConsole)
4563{
4564#ifdef VBOX_WITH_GUEST_PROPS
4565 AssertReturn(pvConsole, VERR_GENERAL_FAILURE);
4566 ComObjPtr<Console> pConsole = static_cast<Console *>(pvConsole);
4567 AssertReturn(pConsole->m_pVMMDev, VERR_GENERAL_FAILURE);
4568
4569 /* Load the service */
4570 int rc = pConsole->m_pVMMDev->hgcmLoadService("VBoxGuestPropSvc", "VBoxGuestPropSvc");
4571
4572 if (RT_FAILURE(rc))
4573 {
4574 LogRel(("VBoxGuestPropSvc is not available. rc = %Rrc\n", rc));
4575 /* That is not a fatal failure. */
4576 rc = VINF_SUCCESS;
4577 }
4578 else
4579 {
4580 /*
4581 * Initialize built-in properties that can be changed and saved.
4582 *
4583 * These are typically transient properties that the guest cannot
4584 * change.
4585 */
4586
4587 /* Sysprep execution by VBoxService. */
4588 configSetProperty(pConsole->m_pVMMDev,
4589 "/VirtualBox/HostGuest/SysprepExec", "",
4590 "TRANSIENT, RDONLYGUEST");
4591 configSetProperty(pConsole->m_pVMMDev,
4592 "/VirtualBox/HostGuest/SysprepArgs", "",
4593 "TRANSIENT, RDONLYGUEST");
4594
4595 /*
4596 * Pull over the properties from the server.
4597 */
4598 SafeArray<BSTR> namesOut;
4599 SafeArray<BSTR> valuesOut;
4600 SafeArray<LONG64> timestampsOut;
4601 SafeArray<BSTR> flagsOut;
4602 HRESULT hrc;
4603 hrc = pConsole->mControl->PullGuestProperties(ComSafeArrayAsOutParam(namesOut),
4604 ComSafeArrayAsOutParam(valuesOut),
4605 ComSafeArrayAsOutParam(timestampsOut),
4606 ComSafeArrayAsOutParam(flagsOut));
4607 AssertMsgReturn(SUCCEEDED(hrc), ("hrc=%Rrc\n", hrc), VERR_GENERAL_FAILURE);
4608 size_t cProps = namesOut.size();
4609 size_t cAlloc = cProps + 1;
4610 if ( valuesOut.size() != cProps
4611 || timestampsOut.size() != cProps
4612 || flagsOut.size() != cProps
4613 )
4614 AssertFailedReturn(VERR_INVALID_PARAMETER);
4615
4616 char **papszNames, **papszValues, **papszFlags;
4617 char szEmpty[] = "";
4618 LONG64 *pai64Timestamps;
4619 papszNames = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
4620 papszValues = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
4621 pai64Timestamps = (LONG64 *)RTMemTmpAllocZ(sizeof(LONG64) * cAlloc);
4622 papszFlags = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
4623 if (papszNames && papszValues && pai64Timestamps && papszFlags)
4624 {
4625 for (unsigned i = 0; RT_SUCCESS(rc) && i < cProps; ++i)
4626 {
4627 AssertPtrReturn(namesOut[i], VERR_INVALID_PARAMETER);
4628 rc = RTUtf16ToUtf8(namesOut[i], &papszNames[i]);
4629 if (RT_FAILURE(rc))
4630 break;
4631 if (valuesOut[i])
4632 rc = RTUtf16ToUtf8(valuesOut[i], &papszValues[i]);
4633 else
4634 papszValues[i] = szEmpty;
4635 if (RT_FAILURE(rc))
4636 break;
4637 pai64Timestamps[i] = timestampsOut[i];
4638 if (flagsOut[i])
4639 rc = RTUtf16ToUtf8(flagsOut[i], &papszFlags[i]);
4640 else
4641 papszFlags[i] = szEmpty;
4642 }
4643 if (RT_SUCCESS(rc))
4644 configSetProperties(pConsole->m_pVMMDev,
4645 (void *)papszNames,
4646 (void *)papszValues,
4647 (void *)pai64Timestamps,
4648 (void *)papszFlags);
4649 for (unsigned i = 0; i < cProps; ++i)
4650 {
4651 RTStrFree(papszNames[i]);
4652 if (valuesOut[i])
4653 RTStrFree(papszValues[i]);
4654 if (flagsOut[i])
4655 RTStrFree(papszFlags[i]);
4656 }
4657 }
4658 else
4659 rc = VERR_NO_MEMORY;
4660 RTMemTmpFree(papszNames);
4661 RTMemTmpFree(papszValues);
4662 RTMemTmpFree(pai64Timestamps);
4663 RTMemTmpFree(papszFlags);
4664 AssertRCReturn(rc, rc);
4665
4666 /*
4667 * These properties have to be set before pulling over the properties
4668 * from the machine XML, to ensure that properties saved in the XML
4669 * will override them.
4670 */
4671 /* Set the VBox version string as a guest property */
4672 configSetProperty(pConsole->m_pVMMDev, "/VirtualBox/HostInfo/VBoxVer",
4673 VBOX_VERSION_STRING, "TRANSIENT, RDONLYGUEST");
4674 /* Set the VBox SVN revision as a guest property */
4675 configSetProperty(pConsole->m_pVMMDev, "/VirtualBox/HostInfo/VBoxRev",
4676 RTBldCfgRevisionStr(), "TRANSIENT, RDONLYGUEST");
4677
4678 /*
4679 * Register the host notification callback
4680 */
4681 HGCMSVCEXTHANDLE hDummy;
4682 HGCMHostRegisterServiceExtension(&hDummy, "VBoxGuestPropSvc",
4683 Console::doGuestPropNotification,
4684 pvConsole);
4685
4686#ifdef VBOX_WITH_GUEST_PROPS_RDONLY_GUEST
4687 rc = configSetGlobalPropertyFlags(pConsole->m_pVMMDev,
4688 guestProp::RDONLYGUEST);
4689 AssertRCReturn(rc, rc);
4690#endif
4691
4692 Log(("Set VBoxGuestPropSvc property store\n"));
4693 }
4694 return VINF_SUCCESS;
4695#else /* !VBOX_WITH_GUEST_PROPS */
4696 return VERR_NOT_SUPPORTED;
4697#endif /* !VBOX_WITH_GUEST_PROPS */
4698}
4699
4700/**
4701 * Set up the Guest Control service.
4702 */
4703/* static */ int Console::configGuestControl(void *pvConsole)
4704{
4705#ifdef VBOX_WITH_GUEST_CONTROL
4706 AssertReturn(pvConsole, VERR_GENERAL_FAILURE);
4707 ComObjPtr<Console> pConsole = static_cast<Console *>(pvConsole);
4708
4709 /* Load the service */
4710 int rc = pConsole->m_pVMMDev->hgcmLoadService("VBoxGuestControlSvc", "VBoxGuestControlSvc");
4711
4712 if (RT_FAILURE(rc))
4713 {
4714 LogRel(("VBoxGuestControlSvc is not available. rc = %Rrc\n", rc));
4715 /* That is not a fatal failure. */
4716 rc = VINF_SUCCESS;
4717 }
4718 else
4719 {
4720 HGCMSVCEXTHANDLE hDummy;
4721 rc = HGCMHostRegisterServiceExtension(&hDummy, "VBoxGuestControlSvc",
4722 &Guest::doGuestCtrlNotification,
4723 pConsole->getGuest());
4724 if (RT_FAILURE(rc))
4725 Log(("Cannot register VBoxGuestControlSvc extension!\n"));
4726 else
4727 Log(("VBoxGuestControlSvc loaded\n"));
4728 }
4729
4730 return rc;
4731#else /* !VBOX_WITH_GUEST_CONTROL */
4732 return VERR_NOT_SUPPORTED;
4733#endif /* !VBOX_WITH_GUEST_CONTROL */
4734}
Note: See TracBrowser for help on using the repository browser.

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