VirtualBox

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

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

Main: Clear Console::mpVM on config constructor failure.

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

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