VirtualBox

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

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

HPET: cleanup, ICH9-specific HPET behavior

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