VirtualBox

source: vbox/trunk/src/VBox/Main/ConsoleImpl2.cpp@ 35357

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

VMM, Main: PCI passthrough work

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