VirtualBox

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

Last change on this file since 39450 was 39450, checked in by vboxsync, 13 years ago

Main: initial DnD support

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

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