VirtualBox

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

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

ConsoleImpl2: Fixed some return code confusion, clean-ups.

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

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