VirtualBox

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

Last change on this file since 48406 was 48406, checked in by vboxsync, 11 years ago

Main,VBoxManage: Implemented IConsole::EmulatedUSB. Removed IMachine::emulatedUSBWebcameraEnabled.

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

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