VirtualBox

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

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

Main: initialise the PS/2 mouse even if we are not in combination mode.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 214.7 KB
Line 
1/* $Id: ConsoleImpl2.cpp 47419 2013-07-26 11:13:08Z 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 = pMachine->GetHWVirtExProperty(HWVirtExPropertyType_Exclusive, &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_VIDEO
2385 BOOL aEmulatedUSBWebcamEnabled = FALSE;
2386 hrc = pMachine->COMGETTER(EmulatedUSBWebcameraEnabled)(&aEmulatedUSBWebcamEnabled); H();
2387 if (aEmulatedUSBWebcamEnabled)
2388 {
2389 InsertConfigNode(pUsbDevices, "Webcam", &pDev);
2390 InsertConfigNode(pDev, "0", &pInst);
2391 InsertConfigNode(pInst, "Config", &pCfg);
2392 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2393 InsertConfigString(pLunL0, "Driver", "EmWebcam");
2394 InsertConfigNode(pLunL0, "Config", &pCfg);
2395 InsertConfigInteger(pCfg, "Object", (uintptr_t)mEmWebcam);
2396 }
2397#endif
2398
2399#ifdef VBOX_WITH_USB_CARDREADER
2400 BOOL aEmulatedUSBCardReaderEnabled = FALSE;
2401 hrc = pMachine->COMGETTER(EmulatedUSBCardReaderEnabled)(&aEmulatedUSBCardReaderEnabled); H();
2402 if (aEmulatedUSBCardReaderEnabled)
2403 {
2404 InsertConfigNode(pUsbDevices, "CardReader", &pDev);
2405 InsertConfigNode(pDev, "0", &pInst);
2406 InsertConfigNode(pInst, "Config", &pCfg);
2407
2408 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2409# ifdef VBOX_WITH_USB_CARDREADER_TEST
2410 InsertConfigString(pLunL0, "Driver", "DrvDirectCardReader");
2411 InsertConfigNode(pLunL0, "Config", &pCfg);
2412# else
2413 InsertConfigString(pLunL0, "Driver", "UsbCardReader");
2414 InsertConfigNode(pLunL0, "Config", &pCfg);
2415 InsertConfigInteger(pCfg, "Object", (uintptr_t)mUsbCardReader);
2416# endif
2417 }
2418#endif
2419
2420# if 0 /* Virtual MSD*/
2421 InsertConfigNode(pUsbDevices, "Msd", &pDev);
2422 InsertConfigNode(pDev, "0", &pInst);
2423 InsertConfigNode(pInst, "Config", &pCfg);
2424 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2425
2426 InsertConfigString(pLunL0, "Driver", "SCSI");
2427 InsertConfigNode(pLunL0, "Config", &pCfg);
2428
2429 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2430 InsertConfigString(pLunL1, "Driver", "Block");
2431 InsertConfigNode(pLunL1, "Config", &pCfg);
2432 InsertConfigString(pCfg, "Type", "HardDisk");
2433 InsertConfigInteger(pCfg, "Mountable", 0);
2434
2435 InsertConfigNode(pLunL1, "AttachedDriver", &pLunL2);
2436 InsertConfigString(pLunL2, "Driver", "VD");
2437 InsertConfigNode(pLunL2, "Config", &pCfg);
2438 InsertConfigString(pCfg, "Path", "/Volumes/DataHFS/bird/VDIs/linux.vdi");
2439 InsertConfigString(pCfg, "Format", "VDI");
2440# endif
2441
2442 /* Virtual USB Mouse/Tablet */
2443 if ( aPointingHID == PointingHIDType_USBMouse
2444 || aPointingHID == PointingHIDType_ComboMouse
2445 || aPointingHID == PointingHIDType_USBTablet
2446 || aPointingHID == PointingHIDType_USBMultiTouch)
2447 {
2448 InsertConfigNode(pUsbDevices, "HidMouse", &pDev);
2449 InsertConfigNode(pDev, "0", &pInst);
2450 InsertConfigNode(pInst, "Config", &pCfg);
2451
2452 InsertConfigString(pCfg, "Mode", "relative");
2453 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2454 InsertConfigString(pLunL0, "Driver", "MouseQueue");
2455 InsertConfigNode(pLunL0, "Config", &pCfg);
2456 InsertConfigInteger(pCfg, "QueueSize", 128);
2457
2458 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2459 InsertConfigString(pLunL1, "Driver", "MainMouse");
2460 InsertConfigNode(pLunL1, "Config", &pCfg);
2461 InsertConfigInteger(pCfg, "Object", (uintptr_t)pMouse);
2462 }
2463 if ( aPointingHID == PointingHIDType_USBTablet
2464 || aPointingHID == PointingHIDType_USBMultiTouch)
2465 {
2466 InsertConfigNode(pDev, "1", &pInst);
2467 InsertConfigNode(pInst, "Config", &pCfg);
2468
2469 InsertConfigString(pCfg, "Mode", "absolute");
2470 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2471 InsertConfigString(pLunL0, "Driver", "MouseQueue");
2472 InsertConfigNode(pLunL0, "Config", &pCfg);
2473 InsertConfigInteger(pCfg, "QueueSize", 128);
2474
2475 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2476 InsertConfigString(pLunL1, "Driver", "MainMouse");
2477 InsertConfigNode(pLunL1, "Config", &pCfg);
2478 InsertConfigInteger(pCfg, "Object", (uintptr_t)pMouse);
2479 }
2480 if (aPointingHID == PointingHIDType_USBMultiTouch)
2481 {
2482 InsertConfigNode(pDev, "2", &pInst);
2483 InsertConfigNode(pInst, "Config", &pCfg);
2484
2485 InsertConfigString(pCfg, "Mode", "multitouch");
2486 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2487 InsertConfigString(pLunL0, "Driver", "MouseQueue");
2488 InsertConfigNode(pLunL0, "Config", &pCfg);
2489 InsertConfigInteger(pCfg, "QueueSize", 128);
2490
2491 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2492 InsertConfigString(pLunL1, "Driver", "MainMouse");
2493 InsertConfigNode(pLunL1, "Config", &pCfg);
2494 InsertConfigInteger(pCfg, "Object", (uintptr_t)pMouse);
2495 }
2496
2497 /* Virtual USB Keyboard */
2498 KeyboardHIDType_T aKbdHID;
2499 hrc = pMachine->COMGETTER(KeyboardHIDType)(&aKbdHID); H();
2500 if (aKbdHID == KeyboardHIDType_USBKeyboard)
2501 {
2502 InsertConfigNode(pUsbDevices, "HidKeyboard", &pDev);
2503 InsertConfigNode(pDev, "0", &pInst);
2504 InsertConfigNode(pInst, "Config", &pCfg);
2505
2506 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2507 InsertConfigString(pLunL0, "Driver", "KeyboardQueue");
2508 InsertConfigNode(pLunL0, "Config", &pCfg);
2509 InsertConfigInteger(pCfg, "QueueSize", 64);
2510
2511 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2512 InsertConfigString(pLunL1, "Driver", "MainKeyboard");
2513 InsertConfigNode(pLunL1, "Config", &pCfg);
2514 pKeyboard = mKeyboard;
2515 InsertConfigInteger(pCfg, "Object", (uintptr_t)pKeyboard);
2516 }
2517 }
2518
2519 /*
2520 * Clipboard
2521 */
2522 {
2523 ClipboardMode_T mode = ClipboardMode_Disabled;
2524 hrc = pMachine->COMGETTER(ClipboardMode)(&mode); H();
2525
2526 if (/* mode != ClipboardMode_Disabled */ true)
2527 {
2528 /* Load the service */
2529 rc = pVMMDev->hgcmLoadService("VBoxSharedClipboard", "VBoxSharedClipboard");
2530
2531 if (RT_FAILURE(rc))
2532 {
2533 LogRel(("VBoxSharedClipboard is not available. rc = %Rrc\n", rc));
2534 /* That is not a fatal failure. */
2535 rc = VINF_SUCCESS;
2536 }
2537 else
2538 {
2539 changeClipboardMode(mode);
2540
2541 /* Setup the service. */
2542 VBOXHGCMSVCPARM parm;
2543 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
2544 parm.setUInt32(!useHostClipboard());
2545 pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_HEADLESS, 1, &parm);
2546
2547 Log(("Set VBoxSharedClipboard mode\n"));
2548 }
2549 }
2550 }
2551
2552 /*
2553 * HGCM HostChannel
2554 */
2555 {
2556 Bstr value;
2557 hrc = pMachine->GetExtraData(Bstr("HGCM/HostChannel").raw(),
2558 value.asOutParam());
2559
2560 if ( hrc == S_OK
2561 && value == "1")
2562 {
2563 rc = pVMMDev->hgcmLoadService("VBoxHostChannel", "VBoxHostChannel");
2564
2565 if (RT_FAILURE(rc))
2566 {
2567 LogRel(("VBoxHostChannel is not available. rc = %Rrc\n", rc));
2568 /* That is not a fatal failure. */
2569 rc = VINF_SUCCESS;
2570 }
2571 }
2572 }
2573
2574#ifdef VBOX_WITH_DRAG_AND_DROP
2575 /*
2576 * Drag & Drop
2577 */
2578 {
2579 DragAndDropMode_T mode = DragAndDropMode_Disabled;
2580 hrc = pMachine->COMGETTER(DragAndDropMode)(&mode); H();
2581
2582 /* Load the service */
2583 rc = pVMMDev->hgcmLoadService("VBoxDragAndDropSvc", "VBoxDragAndDropSvc");
2584
2585 if (RT_FAILURE(rc))
2586 {
2587 LogRel(("VBoxDragAndDropService is not available. rc = %Rrc\n", rc));
2588 /* That is not a fatal failure. */
2589 rc = VINF_SUCCESS;
2590 }
2591 else
2592 {
2593 HGCMSVCEXTHANDLE hDummy;
2594 rc = HGCMHostRegisterServiceExtension(&hDummy, "VBoxDragAndDropSvc",
2595 &GuestDnD::notifyGuestDragAndDropEvent,
2596 getGuest());
2597 if (RT_FAILURE(rc))
2598 Log(("Cannot register VBoxDragAndDropSvc extension!\n"));
2599 else
2600 {
2601 changeDragAndDropMode(mode);
2602 Log(("VBoxDragAndDropSvc loaded\n"));
2603 }
2604 }
2605 }
2606#endif /* VBOX_WITH_DRAG_AND_DROP */
2607
2608#ifdef VBOX_WITH_CROGL
2609 /*
2610 * crOpenGL
2611 */
2612 {
2613 BOOL fEnabled3D = false;
2614 hrc = pMachine->COMGETTER(Accelerate3DEnabled)(&fEnabled3D); H();
2615
2616 if (fEnabled3D)
2617 {
2618 BOOL fSupports3D = VBoxOglIs3DAccelerationSupported();
2619 if (!fSupports3D)
2620 return VMR3SetError(pUVM, VERR_NOT_AVAILABLE, RT_SRC_POS,
2621 N_("This VM was configured to use 3D acceleration. However, the "
2622 "3D support of the host is not working properly and the "
2623 "VM cannot be started. To fix this problem, either "
2624 "fix the host 3D support (update the host graphics driver?) "
2625 "or disable 3D acceleration in the VM settings"));
2626
2627 /* Load the service */
2628 rc = pVMMDev->hgcmLoadService("VBoxSharedCrOpenGL", "VBoxSharedCrOpenGL");
2629 if (RT_FAILURE(rc))
2630 {
2631 LogRel(("Failed to load Shared OpenGL service %Rrc\n", rc));
2632 /* That is not a fatal failure. */
2633 rc = VINF_SUCCESS;
2634 }
2635 else
2636 {
2637 LogRel(("Shared crOpenGL service loaded.\n"));
2638
2639 /* Setup the service. */
2640 VBOXHGCMSVCPARM parm;
2641 parm.type = VBOX_HGCM_SVC_PARM_PTR;
2642
2643 parm.u.pointer.addr = (IConsole *)(Console *)this;
2644 parm.u.pointer.size = sizeof(IConsole *);
2645
2646 rc = pVMMDev->hgcmHostCall("VBoxSharedCrOpenGL", SHCRGL_HOST_FN_SET_CONSOLE, SHCRGL_CPARMS_SET_CONSOLE, &parm);
2647 if (!RT_SUCCESS(rc))
2648 AssertMsgFailed(("SHCRGL_HOST_FN_SET_CONSOLE failed with %Rrc\n", rc));
2649
2650 parm.u.pointer.addr = pVM;
2651 parm.u.pointer.size = sizeof(pVM);
2652 rc = pVMMDev->hgcmHostCall("VBoxSharedCrOpenGL", SHCRGL_HOST_FN_SET_VM, SHCRGL_CPARMS_SET_VM, &parm);
2653 if (!RT_SUCCESS(rc))
2654 AssertMsgFailed(("SHCRGL_HOST_FN_SET_VM failed with %Rrc\n", rc));
2655 }
2656
2657 }
2658 }
2659#endif
2660
2661#ifdef VBOX_WITH_GUEST_PROPS
2662 /*
2663 * Guest property service
2664 */
2665
2666 rc = configGuestProperties(this, pUVM);
2667#endif /* VBOX_WITH_GUEST_PROPS defined */
2668
2669#ifdef VBOX_WITH_GUEST_CONTROL
2670 /*
2671 * Guest control service
2672 */
2673
2674 rc = configGuestControl(this);
2675#endif /* VBOX_WITH_GUEST_CONTROL defined */
2676
2677 /*
2678 * ACPI
2679 */
2680 BOOL fACPI;
2681 hrc = biosSettings->COMGETTER(ACPIEnabled)(&fACPI); H();
2682 if (fACPI)
2683 {
2684 BOOL fCpuHotPlug = false;
2685 BOOL fShowCpu = fOsXGuest;
2686 /* Always show the CPU leafs when we have multiple VCPUs or when the IO-APIC is enabled.
2687 * The Windows SMP kernel needs a CPU leaf or else its idle loop will burn cpu cycles; the
2688 * intelppm driver refuses to register an idle state handler.
2689 */
2690 if ((cCpus > 1) || fIOAPIC)
2691 fShowCpu = true;
2692
2693 hrc = pMachine->COMGETTER(CPUHotPlugEnabled)(&fCpuHotPlug); H();
2694
2695 InsertConfigNode(pDevices, "acpi", &pDev);
2696 InsertConfigNode(pDev, "0", &pInst);
2697 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2698 InsertConfigNode(pInst, "Config", &pCfg);
2699 hrc = pBusMgr->assignPCIDevice("acpi", pInst); H();
2700
2701 InsertConfigInteger(pCfg, "RamSize", cbRam);
2702 InsertConfigInteger(pCfg, "RamHoleSize", cbRamHole);
2703 InsertConfigInteger(pCfg, "NumCPUs", cCpus);
2704
2705 InsertConfigInteger(pCfg, "IOAPIC", fIOAPIC);
2706 InsertConfigInteger(pCfg, "FdcEnabled", fFdcEnabled);
2707 InsertConfigInteger(pCfg, "HpetEnabled", fHPETEnabled);
2708 InsertConfigInteger(pCfg, "SmcEnabled", fSmcEnabled);
2709 InsertConfigInteger(pCfg, "ShowRtc", fShowRtc);
2710 if (fOsXGuest && !llBootNics.empty())
2711 {
2712 BootNic aNic = llBootNics.front();
2713 uint32_t u32NicPCIAddr = (aNic.mPCIAddress.miDevice << 16) | aNic.mPCIAddress.miFn;
2714 InsertConfigInteger(pCfg, "NicPciAddress", u32NicPCIAddr);
2715 }
2716 if (fOsXGuest && fAudioEnabled)
2717 {
2718 PCIBusAddress Address;
2719 if (pBusMgr->findPCIAddress("hda", 0, Address))
2720 {
2721 uint32_t u32AudioPCIAddr = (Address.miDevice << 16) | Address.miFn;
2722 InsertConfigInteger(pCfg, "AudioPciAddress", u32AudioPCIAddr);
2723 }
2724 }
2725 InsertConfigInteger(pCfg, "IocPciAddress", uIocPCIAddress);
2726 if (chipsetType == ChipsetType_ICH9)
2727 {
2728 InsertConfigInteger(pCfg, "McfgBase", uMcfgBase);
2729 InsertConfigInteger(pCfg, "McfgLength", cbMcfgLength);
2730 }
2731 InsertConfigInteger(pCfg, "HostBusPciAddress", uHbcPCIAddress);
2732 InsertConfigInteger(pCfg, "ShowCpu", fShowCpu);
2733 InsertConfigInteger(pCfg, "CpuHotPlug", fCpuHotPlug);
2734
2735 InsertConfigInteger(pCfg, "Serial0IoPortBase", auSerialIoPortBase[0]);
2736 InsertConfigInteger(pCfg, "Serial0Irq", auSerialIrq[0]);
2737
2738 InsertConfigInteger(pCfg, "Serial1IoPortBase", auSerialIoPortBase[1]);
2739 InsertConfigInteger(pCfg, "Serial1Irq", auSerialIrq[1]);
2740
2741 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2742 InsertConfigString(pLunL0, "Driver", "ACPIHost");
2743 InsertConfigNode(pLunL0, "Config", &pCfg);
2744
2745 /* Attach the dummy CPU drivers */
2746 for (ULONG iCpuCurr = 1; iCpuCurr < cCpus; iCpuCurr++)
2747 {
2748 BOOL fCpuAttached = true;
2749
2750 if (fCpuHotPlug)
2751 {
2752 hrc = pMachine->GetCPUStatus(iCpuCurr, &fCpuAttached); H();
2753 }
2754
2755 if (fCpuAttached)
2756 {
2757 InsertConfigNode(pInst, Utf8StrFmt("LUN#%u", iCpuCurr).c_str(), &pLunL0);
2758 InsertConfigString(pLunL0, "Driver", "ACPICpu");
2759 InsertConfigNode(pLunL0, "Config", &pCfg);
2760 }
2761 }
2762 }
2763
2764 /*
2765 * Configure DBGF (Debug(ger) Facility).
2766 */
2767 {
2768 PCFGMNODE pDbgf;
2769 InsertConfigNode(pRoot, "DBGF", &pDbgf);
2770
2771 /* Paths to search for debug info and such things. */
2772 hrc = pMachine->COMGETTER(SettingsFilePath)(bstr.asOutParam()); H();
2773 Utf8Str strSettingsPath(bstr);
2774 bstr.setNull();
2775 strSettingsPath.stripFilename();
2776
2777 char szHomeDir[RTPATH_MAX];
2778 rc = RTPathUserHome(szHomeDir, sizeof(szHomeDir));
2779 if (RT_FAILURE(rc))
2780 szHomeDir[0] = '\0';
2781
2782 Utf8Str strPath;
2783 strPath.append(strSettingsPath).append("/debug/;");
2784 strPath.append(strSettingsPath).append("/;");
2785 strPath.append(szHomeDir).append("/");
2786
2787 InsertConfigString(pDbgf, "Path", strPath.c_str());
2788
2789 /* Tracing configuration. */
2790 BOOL fTracingEnabled;
2791 hrc = pMachine->COMGETTER(TracingEnabled)(&fTracingEnabled); H();
2792 if (fTracingEnabled)
2793 InsertConfigInteger(pDbgf, "TracingEnabled", 1);
2794
2795 hrc = pMachine->COMGETTER(TracingConfig)(bstr.asOutParam()); H();
2796 if (fTracingEnabled)
2797 InsertConfigString(pDbgf, "TracingConfig", bstr);
2798
2799 BOOL fAllowTracingToAccessVM;
2800 hrc = pMachine->COMGETTER(AllowTracingToAccessVM)(&fAllowTracingToAccessVM); H();
2801 if (fAllowTracingToAccessVM)
2802 InsertConfigInteger(pPDM, "AllowTracingToAccessVM", 1);
2803 }
2804 }
2805 catch (ConfigError &x)
2806 {
2807 // InsertConfig threw something:
2808 return x.m_vrc;
2809 }
2810
2811#ifdef VBOX_WITH_EXTPACK
2812 /*
2813 * Call the extension pack hooks if everything went well thus far.
2814 */
2815 if (RT_SUCCESS(rc))
2816 {
2817 pAlock->release();
2818 rc = mptrExtPackManager->callAllVmConfigureVmmHooks(this, pVM);
2819 pAlock->acquire();
2820 }
2821#endif
2822
2823 /*
2824 * Apply the CFGM overlay.
2825 */
2826 if (RT_SUCCESS(rc))
2827 rc = configCfgmOverlay(pRoot, virtualBox, pMachine);
2828
2829 /*
2830 * Dump all extradata API settings tweaks, both global and per VM.
2831 */
2832 if (RT_SUCCESS(rc))
2833 rc = configDumpAPISettingsTweaks(virtualBox, pMachine);
2834
2835#undef H
2836
2837 pAlock->release(); /* Avoid triggering the lock order inversion check. */
2838
2839 /*
2840 * Register VM state change handler.
2841 */
2842 int rc2 = VMR3AtStateRegister(pUVM, Console::vmstateChangeCallback, this);
2843 AssertRC(rc2);
2844 if (RT_SUCCESS(rc))
2845 rc = rc2;
2846
2847 /*
2848 * Register VM runtime error handler.
2849 */
2850 rc2 = VMR3AtRuntimeErrorRegister(pUVM, Console::setVMRuntimeErrorCallback, this);
2851 AssertRC(rc2);
2852 if (RT_SUCCESS(rc))
2853 rc = rc2;
2854
2855 pAlock->acquire();
2856
2857 LogFlowFunc(("vrc = %Rrc\n", rc));
2858 LogFlowFuncLeave();
2859
2860 return rc;
2861}
2862
2863/**
2864 * Applies the CFGM overlay as specified by VBoxInternal/XXX extra data
2865 * values.
2866 *
2867 * @returns VBox status code.
2868 * @param pRoot The root of the configuration tree.
2869 * @param pVirtualBox Pointer to the IVirtualBox interface.
2870 * @param pMachine Pointer to the IMachine interface.
2871 */
2872/* static */
2873int Console::configCfgmOverlay(PCFGMNODE pRoot, IVirtualBox *pVirtualBox, IMachine *pMachine)
2874{
2875 /*
2876 * CFGM overlay handling.
2877 *
2878 * Here we check the extra data entries for CFGM values
2879 * and create the nodes and insert the values on the fly. Existing
2880 * values will be removed and reinserted. CFGM is typed, so by default
2881 * we will guess whether it's a string or an integer (byte arrays are
2882 * not currently supported). It's possible to override this autodetection
2883 * by adding "string:", "integer:" or "bytes:" (future).
2884 *
2885 * We first perform a run on global extra data, then on the machine
2886 * extra data to support global settings with local overrides.
2887 */
2888 int rc = VINF_SUCCESS;
2889 try
2890 {
2891 /** @todo add support for removing nodes and byte blobs. */
2892 /*
2893 * Get the next key
2894 */
2895 SafeArray<BSTR> aGlobalExtraDataKeys;
2896 SafeArray<BSTR> aMachineExtraDataKeys;
2897 HRESULT hrc = pVirtualBox->GetExtraDataKeys(ComSafeArrayAsOutParam(aGlobalExtraDataKeys));
2898 AssertMsg(SUCCEEDED(hrc), ("VirtualBox::GetExtraDataKeys failed with %Rhrc\n", hrc));
2899
2900 // remember the no. of global values so we can call the correct method below
2901 size_t cGlobalValues = aGlobalExtraDataKeys.size();
2902
2903 hrc = pMachine->GetExtraDataKeys(ComSafeArrayAsOutParam(aMachineExtraDataKeys));
2904 AssertMsg(SUCCEEDED(hrc), ("Machine::GetExtraDataKeys failed with %Rhrc\n", hrc));
2905
2906 // build a combined list from global keys...
2907 std::list<Utf8Str> llExtraDataKeys;
2908
2909 for (size_t i = 0; i < aGlobalExtraDataKeys.size(); ++i)
2910 llExtraDataKeys.push_back(Utf8Str(aGlobalExtraDataKeys[i]));
2911 // ... and machine keys
2912 for (size_t i = 0; i < aMachineExtraDataKeys.size(); ++i)
2913 llExtraDataKeys.push_back(Utf8Str(aMachineExtraDataKeys[i]));
2914
2915 size_t i2 = 0;
2916 for (std::list<Utf8Str>::const_iterator it = llExtraDataKeys.begin();
2917 it != llExtraDataKeys.end();
2918 ++it, ++i2)
2919 {
2920 const Utf8Str &strKey = *it;
2921
2922 /*
2923 * We only care about keys starting with "VBoxInternal/" (skip "G:" or "M:")
2924 */
2925 if (!strKey.startsWith("VBoxInternal/"))
2926 continue;
2927
2928 const char *pszExtraDataKey = strKey.c_str() + sizeof("VBoxInternal/") - 1;
2929
2930 // get the value
2931 Bstr bstrExtraDataValue;
2932 if (i2 < cGlobalValues)
2933 // this is still one of the global values:
2934 hrc = pVirtualBox->GetExtraData(Bstr(strKey).raw(),
2935 bstrExtraDataValue.asOutParam());
2936 else
2937 hrc = pMachine->GetExtraData(Bstr(strKey).raw(),
2938 bstrExtraDataValue.asOutParam());
2939 if (FAILED(hrc))
2940 LogRel(("Warning: Cannot get extra data key %s, rc = %Rrc\n", strKey.c_str(), hrc));
2941
2942 /*
2943 * The key will be in the format "Node1/Node2/Value" or simply "Value".
2944 * Split the two and get the node, delete the value and create the node
2945 * if necessary.
2946 */
2947 PCFGMNODE pNode;
2948 const char *pszCFGMValueName = strrchr(pszExtraDataKey, '/');
2949 if (pszCFGMValueName)
2950 {
2951 /* terminate the node and advance to the value (Utf8Str might not
2952 offically like this but wtf) */
2953 *(char*)pszCFGMValueName = '\0';
2954 ++pszCFGMValueName;
2955
2956 /* does the node already exist? */
2957 pNode = CFGMR3GetChild(pRoot, pszExtraDataKey);
2958 if (pNode)
2959 CFGMR3RemoveValue(pNode, pszCFGMValueName);
2960 else
2961 {
2962 /* create the node */
2963 rc = CFGMR3InsertNode(pRoot, pszExtraDataKey, &pNode);
2964 if (RT_FAILURE(rc))
2965 {
2966 AssertLogRelMsgRC(rc, ("failed to insert node '%s'\n", pszExtraDataKey));
2967 continue;
2968 }
2969 Assert(pNode);
2970 }
2971 }
2972 else
2973 {
2974 /* root value (no node path). */
2975 pNode = pRoot;
2976 pszCFGMValueName = pszExtraDataKey;
2977 pszExtraDataKey--;
2978 CFGMR3RemoveValue(pNode, pszCFGMValueName);
2979 }
2980
2981 /*
2982 * Now let's have a look at the value.
2983 * Empty strings means that we should remove the value, which we've
2984 * already done above.
2985 */
2986 Utf8Str strCFGMValueUtf8(bstrExtraDataValue);
2987 if (!strCFGMValueUtf8.isEmpty())
2988 {
2989 uint64_t u64Value;
2990
2991 /* check for type prefix first. */
2992 if (!strncmp(strCFGMValueUtf8.c_str(), RT_STR_TUPLE("string:")))
2993 InsertConfigString(pNode, pszCFGMValueName, strCFGMValueUtf8.c_str() + sizeof("string:") - 1);
2994 else if (!strncmp(strCFGMValueUtf8.c_str(), RT_STR_TUPLE("integer:")))
2995 {
2996 rc = RTStrToUInt64Full(strCFGMValueUtf8.c_str() + sizeof("integer:") - 1, 0, &u64Value);
2997 if (RT_SUCCESS(rc))
2998 rc = CFGMR3InsertInteger(pNode, pszCFGMValueName, u64Value);
2999 }
3000 else if (!strncmp(strCFGMValueUtf8.c_str(), RT_STR_TUPLE("bytes:")))
3001 {
3002 char const *pszBase64 = strCFGMValueUtf8.c_str() + sizeof("bytes:") - 1;
3003 ssize_t cbValue = RTBase64DecodedSize(pszBase64, NULL);
3004 if (cbValue > 0)
3005 {
3006 void *pvBytes = RTMemTmpAlloc(cbValue);
3007 if (pvBytes)
3008 {
3009 rc = RTBase64Decode(pszBase64, pvBytes, cbValue, NULL, NULL);
3010 if (RT_SUCCESS(rc))
3011 rc = CFGMR3InsertBytes(pNode, pszCFGMValueName, pvBytes, cbValue);
3012 RTMemTmpFree(pvBytes);
3013 }
3014 else
3015 rc = VERR_NO_TMP_MEMORY;
3016 }
3017 else if (cbValue == 0)
3018 rc = CFGMR3InsertBytes(pNode, pszCFGMValueName, NULL, 0);
3019 else
3020 rc = VERR_INVALID_BASE64_ENCODING;
3021 }
3022 /* auto detect type. */
3023 else if (RT_SUCCESS(RTStrToUInt64Full(strCFGMValueUtf8.c_str(), 0, &u64Value)))
3024 rc = CFGMR3InsertInteger(pNode, pszCFGMValueName, u64Value);
3025 else
3026 InsertConfigString(pNode, pszCFGMValueName, strCFGMValueUtf8);
3027 AssertLogRelMsgRCBreak(rc, ("failed to insert CFGM value '%s' to key '%s'\n", strCFGMValueUtf8.c_str(), pszExtraDataKey));
3028 }
3029 }
3030 }
3031 catch (ConfigError &x)
3032 {
3033 // InsertConfig threw something:
3034 return x.m_vrc;
3035 }
3036 return rc;
3037}
3038
3039/**
3040 * Dumps the API settings tweaks as specified by VBoxInternal2/XXX extra data
3041 * values.
3042 *
3043 * @returns VBox status code.
3044 * @param pVirtualBox Pointer to the IVirtualBox interface.
3045 * @param pMachine Pointer to the IMachine interface.
3046 */
3047/* static */
3048int Console::configDumpAPISettingsTweaks(IVirtualBox *pVirtualBox, IMachine *pMachine)
3049{
3050 {
3051 SafeArray<BSTR> aGlobalExtraDataKeys;
3052 HRESULT hrc = pVirtualBox->GetExtraDataKeys(ComSafeArrayAsOutParam(aGlobalExtraDataKeys));
3053 AssertMsg(SUCCEEDED(hrc), ("VirtualBox::GetExtraDataKeys failed with %Rhrc\n", hrc));
3054 bool hasKey = false;
3055 for (size_t i = 0; i < aGlobalExtraDataKeys.size(); i++)
3056 {
3057 Utf8Str strKey(aGlobalExtraDataKeys[i]);
3058 if (!strKey.startsWith("VBoxInternal2/"))
3059 continue;
3060
3061 Bstr bstrValue;
3062 hrc = pVirtualBox->GetExtraData(Bstr(strKey).raw(),
3063 bstrValue.asOutParam());
3064 if (FAILED(hrc))
3065 continue;
3066 if (!hasKey)
3067 LogRel(("Global extradata API settings:\n"));
3068 LogRel((" %s=\"%ls\"\n", strKey.c_str(), bstrValue.raw()));
3069 hasKey = true;
3070 }
3071 }
3072
3073 {
3074 SafeArray<BSTR> aMachineExtraDataKeys;
3075 HRESULT hrc = pMachine->GetExtraDataKeys(ComSafeArrayAsOutParam(aMachineExtraDataKeys));
3076 AssertMsg(SUCCEEDED(hrc), ("Machine::GetExtraDataKeys failed with %Rhrc\n", hrc));
3077 bool hasKey = false;
3078 for (size_t i = 0; i < aMachineExtraDataKeys.size(); i++)
3079 {
3080 Utf8Str strKey(aMachineExtraDataKeys[i]);
3081 if (!strKey.startsWith("VBoxInternal2/"))
3082 continue;
3083
3084 Bstr bstrValue;
3085 hrc = pMachine->GetExtraData(Bstr(strKey).raw(),
3086 bstrValue.asOutParam());
3087 if (FAILED(hrc))
3088 continue;
3089 if (!hasKey)
3090 LogRel(("Per-VM extradata API settings:\n"));
3091 LogRel((" %s=\"%ls\"\n", strKey.c_str(), bstrValue.raw()));
3092 hasKey = true;
3093 }
3094 }
3095
3096 return VINF_SUCCESS;
3097}
3098
3099int Console::configGraphicsController(PCFGMNODE pDevices,
3100 const char *pcszDevice,
3101 BusAssignmentManager *pBusMgr,
3102 const ComPtr<IMachine> &pMachine,
3103 const ComPtr<IBIOSSettings> &biosSettings,
3104 bool fHMEnabled)
3105{
3106 // InsertConfig* throws
3107 try
3108 {
3109 PCFGMNODE pDev, pInst, pCfg, pLunL0;
3110 HRESULT hrc;
3111 Bstr bstr;
3112
3113#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
3114 InsertConfigNode(pDevices, pcszDevice, &pDev);
3115 InsertConfigNode(pDev, "0", &pInst);
3116 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
3117
3118 hrc = pBusMgr->assignPCIDevice(pcszDevice, pInst); H();
3119 InsertConfigNode(pInst, "Config", &pCfg);
3120 ULONG cVRamMBs;
3121 hrc = pMachine->COMGETTER(VRAMSize)(&cVRamMBs); H();
3122 InsertConfigInteger(pCfg, "VRamSize", cVRamMBs * _1M);
3123 ULONG cMonitorCount;
3124 hrc = pMachine->COMGETTER(MonitorCount)(&cMonitorCount); H();
3125 InsertConfigInteger(pCfg, "MonitorCount", cMonitorCount);
3126#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
3127 InsertConfigInteger(pCfg, "R0Enabled", fHMEnabled);
3128#else
3129 NOREF(fHMEnabled);
3130#endif
3131
3132 /* Custom VESA mode list */
3133 unsigned cModes = 0;
3134 for (unsigned iMode = 1; iMode <= 16; ++iMode)
3135 {
3136 char szExtraDataKey[sizeof("CustomVideoModeXX")];
3137 RTStrPrintf(szExtraDataKey, sizeof(szExtraDataKey), "CustomVideoMode%u", iMode);
3138 hrc = pMachine->GetExtraData(Bstr(szExtraDataKey).raw(), bstr.asOutParam()); H();
3139 if (bstr.isEmpty())
3140 break;
3141 InsertConfigString(pCfg, szExtraDataKey, bstr);
3142 ++cModes;
3143 }
3144 InsertConfigInteger(pCfg, "CustomVideoModes", cModes);
3145
3146 /* VESA height reduction */
3147 ULONG ulHeightReduction;
3148 IFramebuffer *pFramebuffer = getDisplay()->getFramebuffer();
3149 if (pFramebuffer)
3150 {
3151 hrc = pFramebuffer->COMGETTER(HeightReduction)(&ulHeightReduction); H();
3152 }
3153 else
3154 {
3155 /* If framebuffer is not available, there is no height reduction. */
3156 ulHeightReduction = 0;
3157 }
3158 InsertConfigInteger(pCfg, "HeightReduction", ulHeightReduction);
3159
3160 /*
3161 * BIOS logo
3162 */
3163 BOOL fFadeIn;
3164 hrc = biosSettings->COMGETTER(LogoFadeIn)(&fFadeIn); H();
3165 InsertConfigInteger(pCfg, "FadeIn", fFadeIn ? 1 : 0);
3166 BOOL fFadeOut;
3167 hrc = biosSettings->COMGETTER(LogoFadeOut)(&fFadeOut); H();
3168 InsertConfigInteger(pCfg, "FadeOut", fFadeOut ? 1: 0);
3169 ULONG logoDisplayTime;
3170 hrc = biosSettings->COMGETTER(LogoDisplayTime)(&logoDisplayTime); H();
3171 InsertConfigInteger(pCfg, "LogoTime", logoDisplayTime);
3172 Bstr logoImagePath;
3173 hrc = biosSettings->COMGETTER(LogoImagePath)(logoImagePath.asOutParam()); H();
3174 InsertConfigString(pCfg, "LogoFile", Utf8Str(!logoImagePath.isEmpty() ? logoImagePath : "") );
3175
3176 /*
3177 * Boot menu
3178 */
3179 BIOSBootMenuMode_T eBootMenuMode;
3180 int iShowBootMenu;
3181 biosSettings->COMGETTER(BootMenuMode)(&eBootMenuMode);
3182 switch (eBootMenuMode)
3183 {
3184 case BIOSBootMenuMode_Disabled: iShowBootMenu = 0; break;
3185 case BIOSBootMenuMode_MenuOnly: iShowBootMenu = 1; break;
3186 default: iShowBootMenu = 2; break;
3187 }
3188 InsertConfigInteger(pCfg, "ShowBootMenu", iShowBootMenu);
3189
3190 /* Attach the display. */
3191 InsertConfigNode(pInst, "LUN#0", &pLunL0);
3192 InsertConfigString(pLunL0, "Driver", "MainDisplay");
3193 InsertConfigNode(pLunL0, "Config", &pCfg);
3194 Display *pDisplay = mDisplay;
3195 InsertConfigInteger(pCfg, "Object", (uintptr_t)pDisplay);
3196 }
3197 catch (ConfigError &x)
3198 {
3199 // InsertConfig threw something:
3200 return x.m_vrc;
3201 }
3202
3203#undef H
3204
3205 return VINF_SUCCESS;
3206}
3207
3208
3209/**
3210 * Ellipsis to va_list wrapper for calling setVMRuntimeErrorCallback.
3211 */
3212void Console::setVMRuntimeErrorCallbackF(uint32_t fFlags, const char *pszErrorId, const char *pszFormat, ...)
3213{
3214 va_list va;
3215 va_start(va, pszFormat);
3216 setVMRuntimeErrorCallback(NULL, this, fFlags, pszErrorId, pszFormat, va);
3217 va_end(va);
3218}
3219
3220/* XXX introduce RT format specifier */
3221static uint64_t formatDiskSize(uint64_t u64Size, const char **pszUnit)
3222{
3223 if (u64Size > INT64_C(5000)*_1G)
3224 {
3225 *pszUnit = "TB";
3226 return u64Size / _1T;
3227 }
3228 else if (u64Size > INT64_C(5000)*_1M)
3229 {
3230 *pszUnit = "GB";
3231 return u64Size / _1G;
3232 }
3233 else
3234 {
3235 *pszUnit = "MB";
3236 return u64Size / _1M;
3237 }
3238}
3239
3240int Console::configMediumAttachment(PCFGMNODE pCtlInst,
3241 const char *pcszDevice,
3242 unsigned uInstance,
3243 StorageBus_T enmBus,
3244 bool fUseHostIOCache,
3245 bool fBuiltinIOCache,
3246 bool fSetupMerge,
3247 unsigned uMergeSource,
3248 unsigned uMergeTarget,
3249 IMediumAttachment *pMediumAtt,
3250 MachineState_T aMachineState,
3251 HRESULT *phrc,
3252 bool fAttachDetach,
3253 bool fForceUnmount,
3254 bool fHotplug,
3255 PUVM pUVM,
3256 DeviceType_T *paLedDevType)
3257{
3258 // InsertConfig* throws
3259 try
3260 {
3261 int rc = VINF_SUCCESS;
3262 HRESULT hrc;
3263 Bstr bstr;
3264
3265// #define RC_CHECK() AssertMsgReturn(RT_SUCCESS(rc), ("rc=%Rrc\n", rc), rc)
3266#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
3267
3268 LONG lDev;
3269 hrc = pMediumAtt->COMGETTER(Device)(&lDev); H();
3270 LONG lPort;
3271 hrc = pMediumAtt->COMGETTER(Port)(&lPort); H();
3272 DeviceType_T lType;
3273 hrc = pMediumAtt->COMGETTER(Type)(&lType); H();
3274 BOOL fNonRotational;
3275 hrc = pMediumAtt->COMGETTER(NonRotational)(&fNonRotational); H();
3276 BOOL fDiscard;
3277 hrc = pMediumAtt->COMGETTER(Discard)(&fDiscard); H();
3278
3279 unsigned uLUN;
3280 PCFGMNODE pLunL0 = NULL;
3281 hrc = Console::convertBusPortDeviceToLun(enmBus, lPort, lDev, uLUN); H();
3282
3283 /* First check if the LUN already exists. */
3284 pLunL0 = CFGMR3GetChildF(pCtlInst, "LUN#%u", uLUN);
3285 if (pLunL0)
3286 {
3287 if (fAttachDetach)
3288 {
3289 if (lType != DeviceType_HardDisk)
3290 {
3291 /* Unmount existing media only for floppy and DVD drives. */
3292 PPDMIBASE pBase;
3293 rc = PDMR3QueryLun(pUVM, pcszDevice, uInstance, uLUN, &pBase);
3294 if (RT_FAILURE(rc))
3295 {
3296 if (rc == VERR_PDM_LUN_NOT_FOUND || rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
3297 rc = VINF_SUCCESS;
3298 AssertRC(rc);
3299 }
3300 else
3301 {
3302 PPDMIMOUNT pIMount = PDMIBASE_QUERY_INTERFACE(pBase, PDMIMOUNT);
3303 AssertReturn(pIMount, VERR_INVALID_POINTER);
3304
3305 /* Unmount the media (but do not eject the medium!) */
3306 rc = pIMount->pfnUnmount(pIMount, fForceUnmount, false /*=fEject*/);
3307 if (rc == VERR_PDM_MEDIA_NOT_MOUNTED)
3308 rc = VINF_SUCCESS;
3309 /* for example if the medium is locked */
3310 else if (RT_FAILURE(rc))
3311 return rc;
3312 }
3313 }
3314
3315 rc = PDMR3DeviceDetach(pUVM, pcszDevice, uInstance, uLUN, fHotplug ? 0 : PDM_TACH_FLAGS_NOT_HOT_PLUG);
3316 if (rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
3317 rc = VINF_SUCCESS;
3318 AssertRCReturn(rc, rc);
3319
3320 CFGMR3RemoveNode(pLunL0);
3321 }
3322 else
3323 AssertFailedReturn(VERR_INTERNAL_ERROR);
3324 }
3325
3326 InsertConfigNode(pCtlInst, Utf8StrFmt("LUN#%u", uLUN).c_str(), &pLunL0);
3327
3328 PCFGMNODE pCfg = CFGMR3GetChild(pCtlInst, "Config");
3329 if (pCfg)
3330 {
3331 if (!strcmp(pcszDevice, "piix3ide"))
3332 {
3333 PCFGMNODE pDrive = CFGMR3GetChild(pCfg, g_apszIDEDrives[uLUN]);
3334 if (!pDrive)
3335 InsertConfigNode(pCfg, g_apszIDEDrives[uLUN], &pDrive);
3336 /* Don't use the RemoveConfigValue wrapper above, as we don't
3337 * know if the leaf is present or not. */
3338 CFGMR3RemoveValue(pDrive, "NonRotationalMedium");
3339 InsertConfigInteger(pDrive, "NonRotationalMedium", !!fNonRotational);
3340 }
3341 else if (!strcmp(pcszDevice, "ahci"))
3342 {
3343 Utf8Str strPort = Utf8StrFmt("Port%u", uLUN);
3344 PCFGMNODE pDrive = CFGMR3GetChild(pCfg, strPort.c_str());
3345 if (!pDrive)
3346 InsertConfigNode(pCfg, strPort.c_str(), &pDrive);
3347 /* Don't use the RemoveConfigValue wrapper above, as we don't
3348 * know if the leaf is present or not. */
3349 CFGMR3RemoveValue(pDrive, "NonRotationalMedium");
3350 InsertConfigInteger(pDrive, "NonRotationalMedium", !!fNonRotational);
3351 }
3352 }
3353
3354 Utf8Str devicePath = Utf8StrFmt("%s/%u/LUN#%u", pcszDevice, uInstance, uLUN);
3355 mapMediumAttachments[devicePath] = pMediumAtt;
3356
3357 /* SCSI has a another driver between device and block. */
3358 if (enmBus == StorageBus_SCSI || enmBus == StorageBus_SAS)
3359 {
3360 InsertConfigString(pLunL0, "Driver", "SCSI");
3361 PCFGMNODE pL1Cfg = NULL;
3362 InsertConfigNode(pLunL0, "Config", &pL1Cfg);
3363 InsertConfigInteger(pL1Cfg, "NonRotationalMedium", !!fNonRotational);
3364
3365 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
3366 }
3367
3368 ComPtr<IMedium> pMedium;
3369 hrc = pMediumAtt->COMGETTER(Medium)(pMedium.asOutParam()); H();
3370
3371 /*
3372 * 1. Only check this for hard disk images.
3373 * 2. Only check during VM creation and not later, especially not during
3374 * taking an online snapshot!
3375 */
3376 if ( lType == DeviceType_HardDisk
3377 && ( aMachineState == MachineState_Starting
3378 || aMachineState == MachineState_Restoring))
3379 {
3380 /*
3381 * Some sanity checks.
3382 */
3383 ComPtr<IMediumFormat> pMediumFormat;
3384 hrc = pMedium->COMGETTER(MediumFormat)(pMediumFormat.asOutParam()); H();
3385 ULONG uCaps = 0;
3386 com::SafeArray <MediumFormatCapabilities_T> mediumFormatCap;
3387 hrc = pMediumFormat->COMGETTER(Capabilities)(ComSafeArrayAsOutParam(mediumFormatCap)); H();
3388
3389 for (ULONG j = 0; j < mediumFormatCap.size(); j++)
3390 uCaps |= mediumFormatCap[j];
3391
3392 if (uCaps & MediumFormatCapabilities_File)
3393 {
3394 Bstr strFile;
3395 hrc = pMedium->COMGETTER(Location)(strFile.asOutParam()); H();
3396 Utf8Str utfFile = Utf8Str(strFile);
3397 Bstr strSnap;
3398 ComPtr<IMachine> pMachine = machine();
3399 hrc = pMachine->COMGETTER(SnapshotFolder)(strSnap.asOutParam()); H();
3400 Utf8Str utfSnap = Utf8Str(strSnap);
3401 RTFSTYPE enmFsTypeFile = RTFSTYPE_UNKNOWN;
3402 RTFSTYPE enmFsTypeSnap = RTFSTYPE_UNKNOWN;
3403 int rc2 = RTFsQueryType(utfFile.c_str(), &enmFsTypeFile);
3404 AssertMsgRCReturn(rc2, ("Querying the file type of '%s' failed!\n", utfFile.c_str()), rc2);
3405 /* Ignore the error code. On error, the file system type is still 'unknown' so
3406 * none of the following paths are taken. This can happen for new VMs which
3407 * still don't have a snapshot folder. */
3408 (void)RTFsQueryType(utfSnap.c_str(), &enmFsTypeSnap);
3409 if (!mfSnapshotFolderDiskTypeShown)
3410 {
3411 LogRel(("File system of '%s' (snapshots) is %s\n",
3412 utfSnap.c_str(), RTFsTypeName(enmFsTypeSnap)));
3413 mfSnapshotFolderDiskTypeShown = true;
3414 }
3415 LogRel(("File system of '%s' is %s\n", utfFile.c_str(), RTFsTypeName(enmFsTypeFile)));
3416 LONG64 i64Size;
3417 hrc = pMedium->COMGETTER(LogicalSize)(&i64Size); H();
3418#ifdef RT_OS_WINDOWS
3419 if ( enmFsTypeFile == RTFSTYPE_FAT
3420 && i64Size >= _4G)
3421 {
3422 const char *pszUnit;
3423 uint64_t u64Print = formatDiskSize((uint64_t)i64Size, &pszUnit);
3424 setVMRuntimeErrorCallbackF(0, "FatPartitionDetected",
3425 N_("The medium '%ls' has a logical size of %RU64%s "
3426 "but the file system the medium is located on seems "
3427 "to be FAT(32) which cannot handle files bigger than 4GB.\n"
3428 "We strongly recommend to put all your virtual disk images and "
3429 "the snapshot folder onto an NTFS partition"),
3430 strFile.raw(), u64Print, pszUnit);
3431 }
3432#else /* !RT_OS_WINDOWS */
3433 if ( enmFsTypeFile == RTFSTYPE_FAT
3434 || enmFsTypeFile == RTFSTYPE_EXT
3435 || enmFsTypeFile == RTFSTYPE_EXT2
3436 || enmFsTypeFile == RTFSTYPE_EXT3
3437 || enmFsTypeFile == RTFSTYPE_EXT4)
3438 {
3439 RTFILE file;
3440 rc = RTFileOpen(&file, utfFile.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
3441 if (RT_SUCCESS(rc))
3442 {
3443 RTFOFF maxSize;
3444 /* Careful: This function will work only on selected local file systems! */
3445 rc = RTFileGetMaxSizeEx(file, &maxSize);
3446 RTFileClose(file);
3447 if ( RT_SUCCESS(rc)
3448 && maxSize > 0
3449 && i64Size > (LONG64)maxSize)
3450 {
3451 const char *pszUnitSiz;
3452 const char *pszUnitMax;
3453 uint64_t u64PrintSiz = formatDiskSize((LONG64)i64Size, &pszUnitSiz);
3454 uint64_t u64PrintMax = formatDiskSize(maxSize, &pszUnitMax);
3455 setVMRuntimeErrorCallbackF(0, "FatPartitionDetected", /* <= not exact but ... */
3456 N_("The medium '%ls' has a logical size of %RU64%s "
3457 "but the file system the medium is located on can "
3458 "only handle files up to %RU64%s in theory.\n"
3459 "We strongly recommend to put all your virtual disk "
3460 "images and the snapshot folder onto a proper "
3461 "file system (e.g. ext3) with a sufficient size"),
3462 strFile.raw(), u64PrintSiz, pszUnitSiz, u64PrintMax, pszUnitMax);
3463 }
3464 }
3465 }
3466#endif /* !RT_OS_WINDOWS */
3467
3468 /*
3469 * Snapshot folder:
3470 * Here we test only for a FAT partition as we had to create a dummy file otherwise
3471 */
3472 if ( enmFsTypeSnap == RTFSTYPE_FAT
3473 && i64Size >= _4G
3474 && !mfSnapshotFolderSizeWarningShown)
3475 {
3476 const char *pszUnit;
3477 uint64_t u64Print = formatDiskSize(i64Size, &pszUnit);
3478 setVMRuntimeErrorCallbackF(0, "FatPartitionDetected",
3479#ifdef RT_OS_WINDOWS
3480 N_("The snapshot folder of this VM '%ls' seems to be located on "
3481 "a FAT(32) file system. The logical size of the medium '%ls' "
3482 "(%RU64%s) is bigger than the maximum file size this file "
3483 "system can handle (4GB).\n"
3484 "We strongly recommend to put all your virtual disk images and "
3485 "the snapshot folder onto an NTFS partition"),
3486#else
3487 N_("The snapshot folder of this VM '%ls' seems to be located on "
3488 "a FAT(32) file system. The logical size of the medium '%ls' "
3489 "(%RU64%s) is bigger than the maximum file size this file "
3490 "system can handle (4GB).\n"
3491 "We strongly recommend to put all your virtual disk images and "
3492 "the snapshot folder onto a proper file system (e.g. ext3)"),
3493#endif
3494 strSnap.raw(), strFile.raw(), u64Print, pszUnit);
3495 /* Show this particular warning only once */
3496 mfSnapshotFolderSizeWarningShown = true;
3497 }
3498
3499#ifdef RT_OS_LINUX
3500 /*
3501 * Ext4 bug: Check if the host I/O cache is disabled and the disk image is located
3502 * on an ext4 partition. Later we have to check the Linux kernel version!
3503 * This bug apparently applies to the XFS file system as well.
3504 * Linux 2.6.36 is known to be fixed (tested with 2.6.36-rc4).
3505 */
3506
3507 char szOsRelease[128];
3508 rc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szOsRelease, sizeof(szOsRelease));
3509 bool fKernelHasODirectBug = RT_FAILURE(rc)
3510 || (RTStrVersionCompare(szOsRelease, "2.6.36-rc4") < 0);
3511
3512 if ( (uCaps & MediumFormatCapabilities_Asynchronous)
3513 && !fUseHostIOCache
3514 && fKernelHasODirectBug)
3515 {
3516 if ( enmFsTypeFile == RTFSTYPE_EXT4
3517 || enmFsTypeFile == RTFSTYPE_XFS)
3518 {
3519 setVMRuntimeErrorCallbackF(0, "Ext4PartitionDetected",
3520 N_("The host I/O cache for at least one controller is disabled "
3521 "and the medium '%ls' for this VM "
3522 "is located on an %s partition. There is a known Linux "
3523 "kernel bug which can lead to the corruption of the virtual "
3524 "disk image under these conditions.\n"
3525 "Either enable the host I/O cache permanently in the VM "
3526 "settings or put the disk image and the snapshot folder "
3527 "onto a different file system.\n"
3528 "The host I/O cache will now be enabled for this medium"),
3529 strFile.raw(), enmFsTypeFile == RTFSTYPE_EXT4 ? "ext4" : "xfs");
3530 fUseHostIOCache = true;
3531 }
3532 else if ( ( enmFsTypeSnap == RTFSTYPE_EXT4
3533 || enmFsTypeSnap == RTFSTYPE_XFS)
3534 && !mfSnapshotFolderExt4WarningShown)
3535 {
3536 setVMRuntimeErrorCallbackF(0, "Ext4PartitionDetected",
3537 N_("The host I/O cache for at least one controller is disabled "
3538 "and the snapshot folder for this VM "
3539 "is located on an %s partition. There is a known Linux "
3540 "kernel bug which can lead to the corruption of the virtual "
3541 "disk image under these conditions.\n"
3542 "Either enable the host I/O cache permanently in the VM "
3543 "settings or put the disk image and the snapshot folder "
3544 "onto a different file system.\n"
3545 "The host I/O cache will now be enabled for this medium"),
3546 enmFsTypeSnap == RTFSTYPE_EXT4 ? "ext4" : "xfs");
3547 fUseHostIOCache = true;
3548 mfSnapshotFolderExt4WarningShown = true;
3549 }
3550 }
3551#endif
3552 }
3553 }
3554
3555 if ( pMedium
3556 && ( lType == DeviceType_DVD
3557 || lType == DeviceType_Floppy))
3558 {
3559 /*
3560 * Informative logging.
3561 */
3562 ComPtr<IMediumFormat> pMediumFormat;
3563 hrc = pMedium->COMGETTER(MediumFormat)(pMediumFormat.asOutParam()); H();
3564 ULONG uCaps = 0;
3565 com::SafeArray <MediumFormatCapabilities_T> mediumFormatCap;
3566 hrc = pMediumFormat->COMGETTER(Capabilities)(ComSafeArrayAsOutParam(mediumFormatCap)); H();
3567
3568 for (ULONG j = 0; j < mediumFormatCap.size(); j++)
3569 uCaps |= mediumFormatCap[j];
3570
3571 if (uCaps & MediumFormatCapabilities_File)
3572 {
3573 Bstr strFile;
3574 hrc = pMedium->COMGETTER(Location)(strFile.asOutParam()); H();
3575 Utf8Str utfFile = Utf8Str(strFile);
3576 RTFSTYPE enmFsTypeFile = RTFSTYPE_UNKNOWN;
3577 (void)RTFsQueryType(utfFile.c_str(), &enmFsTypeFile);
3578 LogRel(("File system of '%s' (%s) is %s\n",
3579 utfFile.c_str(), lType == DeviceType_DVD ? "DVD" : "Floppy",
3580 RTFsTypeName(enmFsTypeFile)));
3581 }
3582 }
3583
3584 BOOL fPassthrough;
3585 hrc = pMediumAtt->COMGETTER(Passthrough)(&fPassthrough); H();
3586
3587 ComObjPtr<IBandwidthGroup> pBwGroup;
3588 Bstr strBwGroup;
3589 hrc = pMediumAtt->COMGETTER(BandwidthGroup)(pBwGroup.asOutParam()); H();
3590
3591 if (!pBwGroup.isNull())
3592 {
3593 hrc = pBwGroup->COMGETTER(Name)(strBwGroup.asOutParam()); H();
3594 }
3595
3596 rc = configMedium(pLunL0,
3597 !!fPassthrough,
3598 lType,
3599 fUseHostIOCache,
3600 fBuiltinIOCache,
3601 fSetupMerge,
3602 uMergeSource,
3603 uMergeTarget,
3604 strBwGroup.isEmpty() ? NULL : Utf8Str(strBwGroup).c_str(),
3605 !!fDiscard,
3606 pMedium,
3607 aMachineState,
3608 phrc);
3609 if (RT_FAILURE(rc))
3610 return rc;
3611
3612 if (fAttachDetach)
3613 {
3614 /* Attach the new driver. */
3615 rc = PDMR3DeviceAttach(pUVM, pcszDevice, uInstance, uLUN,
3616 fHotplug ? 0 : PDM_TACH_FLAGS_NOT_HOT_PLUG, NULL /*ppBase*/);
3617 AssertRCReturn(rc, rc);
3618
3619 /* There is no need to handle removable medium mounting, as we
3620 * unconditionally replace everthing including the block driver level.
3621 * This means the new medium will be picked up automatically. */
3622 }
3623
3624 if (paLedDevType)
3625 paLedDevType[uLUN] = lType;
3626 }
3627 catch (ConfigError &x)
3628 {
3629 // InsertConfig threw something:
3630 return x.m_vrc;
3631 }
3632
3633#undef H
3634
3635 return VINF_SUCCESS;
3636}
3637
3638int Console::configMedium(PCFGMNODE pLunL0,
3639 bool fPassthrough,
3640 DeviceType_T enmType,
3641 bool fUseHostIOCache,
3642 bool fBuiltinIOCache,
3643 bool fSetupMerge,
3644 unsigned uMergeSource,
3645 unsigned uMergeTarget,
3646 const char *pcszBwGroup,
3647 bool fDiscard,
3648 IMedium *pMedium,
3649 MachineState_T aMachineState,
3650 HRESULT *phrc)
3651{
3652 // InsertConfig* throws
3653 try
3654 {
3655 int rc = VINF_SUCCESS;
3656 HRESULT hrc;
3657 Bstr bstr;
3658 PCFGMNODE pLunL1 = NULL;
3659 PCFGMNODE pCfg = NULL;
3660
3661#define H() \
3662 AssertMsgReturnStmt(SUCCEEDED(hrc), ("hrc=%Rhrc\n", hrc), if (phrc) *phrc = hrc, Global::vboxStatusCodeFromCOM(hrc))
3663
3664
3665 BOOL fHostDrive = FALSE;
3666 MediumType_T mediumType = MediumType_Normal;
3667 if (pMedium)
3668 {
3669 hrc = pMedium->COMGETTER(HostDrive)(&fHostDrive); H();
3670 hrc = pMedium->COMGETTER(Type)(&mediumType); H();
3671 }
3672
3673 if (fHostDrive)
3674 {
3675 Assert(pMedium);
3676 if (enmType == DeviceType_DVD)
3677 {
3678 InsertConfigString(pLunL0, "Driver", "HostDVD");
3679 InsertConfigNode(pLunL0, "Config", &pCfg);
3680
3681 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3682 InsertConfigString(pCfg, "Path", bstr);
3683
3684 InsertConfigInteger(pCfg, "Passthrough", fPassthrough);
3685 }
3686 else if (enmType == DeviceType_Floppy)
3687 {
3688 InsertConfigString(pLunL0, "Driver", "HostFloppy");
3689 InsertConfigNode(pLunL0, "Config", &pCfg);
3690
3691 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3692 InsertConfigString(pCfg, "Path", bstr);
3693 }
3694 }
3695 else
3696 {
3697 InsertConfigString(pLunL0, "Driver", "Block");
3698 InsertConfigNode(pLunL0, "Config", &pCfg);
3699 switch (enmType)
3700 {
3701 case DeviceType_DVD:
3702 InsertConfigString(pCfg, "Type", "DVD");
3703 InsertConfigInteger(pCfg, "Mountable", 1);
3704 break;
3705 case DeviceType_Floppy:
3706 InsertConfigString(pCfg, "Type", "Floppy 1.44");
3707 InsertConfigInteger(pCfg, "Mountable", 1);
3708 break;
3709 case DeviceType_HardDisk:
3710 default:
3711 InsertConfigString(pCfg, "Type", "HardDisk");
3712 InsertConfigInteger(pCfg, "Mountable", 0);
3713 }
3714
3715 if ( pMedium
3716 && ( enmType == DeviceType_DVD
3717 || enmType == DeviceType_Floppy)
3718 )
3719 {
3720 // if this medium represents an ISO image and this image is inaccessible,
3721 // the ignore it instead of causing a failure; this can happen when we
3722 // restore a VM state and the ISO has disappeared, e.g. because the Guest
3723 // Additions were mounted and the user upgraded VirtualBox. Previously
3724 // we failed on startup, but that's not good because the only way out then
3725 // would be to discard the VM state...
3726 MediumState_T mediumState;
3727 hrc = pMedium->RefreshState(&mediumState); H();
3728 if (mediumState == MediumState_Inaccessible)
3729 {
3730 Bstr loc;
3731 hrc = pMedium->COMGETTER(Location)(loc.asOutParam()); H();
3732 setVMRuntimeErrorCallbackF(0, "DvdOrFloppyImageInaccessible",
3733 "The image file '%ls' is inaccessible and is being ignored. Please select a different image file for the virtual %s drive.",
3734 loc.raw(),
3735 enmType == DeviceType_DVD ? "DVD" : "floppy");
3736 pMedium = NULL;
3737 }
3738 }
3739
3740 if (pMedium)
3741 {
3742 /* Start with length of parent chain, as the list is reversed */
3743 unsigned uImage = 0;
3744 IMedium *pTmp = pMedium;
3745 while (pTmp)
3746 {
3747 uImage++;
3748 hrc = pTmp->COMGETTER(Parent)(&pTmp); H();
3749 }
3750 /* Index of last image */
3751 uImage--;
3752
3753#if 0 /* Enable for I/O debugging */
3754 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
3755 InsertConfigString(pLunL0, "Driver", "DiskIntegrity");
3756 InsertConfigNode(pLunL0, "Config", &pCfg);
3757 InsertConfigInteger(pCfg, "CheckConsistency", 0);
3758 InsertConfigInteger(pCfg, "CheckDoubleCompletions", 1);
3759#endif
3760
3761 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
3762 InsertConfigString(pLunL1, "Driver", "VD");
3763 InsertConfigNode(pLunL1, "Config", &pCfg);
3764
3765 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3766 InsertConfigString(pCfg, "Path", bstr);
3767
3768 hrc = pMedium->COMGETTER(Format)(bstr.asOutParam()); H();
3769 InsertConfigString(pCfg, "Format", bstr);
3770
3771 if (mediumType == MediumType_Readonly)
3772 InsertConfigInteger(pCfg, "ReadOnly", 1);
3773 else if (enmType == DeviceType_Floppy)
3774 InsertConfigInteger(pCfg, "MaybeReadOnly", 1);
3775
3776 /* Start without exclusive write access to the images. */
3777 /** @todo Live Migration: I don't quite like this, we risk screwing up when
3778 * we're resuming the VM if some 3rd dude have any of the VDIs open
3779 * with write sharing denied. However, if the two VMs are sharing a
3780 * image it really is necessary....
3781 *
3782 * So, on the "lock-media" command, the target teleporter should also
3783 * make DrvVD undo TempReadOnly. It gets interesting if we fail after
3784 * that. Grumble. */
3785 if ( enmType == DeviceType_HardDisk
3786 && ( aMachineState == MachineState_TeleportingIn
3787 || aMachineState == MachineState_FaultTolerantSyncing))
3788 InsertConfigInteger(pCfg, "TempReadOnly", 1);
3789
3790 /* Flag for opening the medium for sharing between VMs. This
3791 * is done at the moment only for the first (and only) medium
3792 * in the chain, as shared media can have no diffs. */
3793 if (mediumType == MediumType_Shareable)
3794 InsertConfigInteger(pCfg, "Shareable", 1);
3795
3796 if (!fUseHostIOCache)
3797 {
3798 InsertConfigInteger(pCfg, "UseNewIo", 1);
3799 /*
3800 * Activate the builtin I/O cache for harddisks only.
3801 * It caches writes only which doesn't make sense for DVD drives
3802 * and just increases the overhead.
3803 */
3804 if ( fBuiltinIOCache
3805 && (enmType == DeviceType_HardDisk))
3806 InsertConfigInteger(pCfg, "BlockCache", 1);
3807 }
3808
3809 if (fSetupMerge)
3810 {
3811 InsertConfigInteger(pCfg, "SetupMerge", 1);
3812 if (uImage == uMergeSource)
3813 InsertConfigInteger(pCfg, "MergeSource", 1);
3814 else if (uImage == uMergeTarget)
3815 InsertConfigInteger(pCfg, "MergeTarget", 1);
3816 }
3817
3818 switch (enmType)
3819 {
3820 case DeviceType_DVD:
3821 InsertConfigString(pCfg, "Type", "DVD");
3822 break;
3823 case DeviceType_Floppy:
3824 InsertConfigString(pCfg, "Type", "Floppy");
3825 break;
3826 case DeviceType_HardDisk:
3827 default:
3828 InsertConfigString(pCfg, "Type", "HardDisk");
3829 }
3830
3831 if (pcszBwGroup)
3832 InsertConfigString(pCfg, "BwGroup", pcszBwGroup);
3833
3834 if (fDiscard)
3835 InsertConfigInteger(pCfg, "Discard", 1);
3836
3837 /* Pass all custom parameters. */
3838 bool fHostIP = true;
3839 SafeArray<BSTR> names;
3840 SafeArray<BSTR> values;
3841 hrc = pMedium->GetProperties(Bstr().raw(),
3842 ComSafeArrayAsOutParam(names),
3843 ComSafeArrayAsOutParam(values)); H();
3844
3845 if (names.size() != 0)
3846 {
3847 PCFGMNODE pVDC;
3848 InsertConfigNode(pCfg, "VDConfig", &pVDC);
3849 for (size_t ii = 0; ii < names.size(); ++ii)
3850 {
3851 if (values[ii] && *values[ii])
3852 {
3853 Utf8Str name = names[ii];
3854 Utf8Str value = values[ii];
3855 InsertConfigString(pVDC, name.c_str(), value);
3856 if ( name.compare("HostIPStack") == 0
3857 && value.compare("0") == 0)
3858 fHostIP = false;
3859 }
3860 }
3861 }
3862
3863 /* Create an inverted list of parents. */
3864 uImage--;
3865 IMedium *pParentMedium = pMedium;
3866 for (PCFGMNODE pParent = pCfg;; uImage--)
3867 {
3868 hrc = pParentMedium->COMGETTER(Parent)(&pMedium); H();
3869 if (!pMedium)
3870 break;
3871
3872 PCFGMNODE pCur;
3873 InsertConfigNode(pParent, "Parent", &pCur);
3874 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3875 InsertConfigString(pCur, "Path", bstr);
3876
3877 hrc = pMedium->COMGETTER(Format)(bstr.asOutParam()); H();
3878 InsertConfigString(pCur, "Format", bstr);
3879
3880 if (fSetupMerge)
3881 {
3882 if (uImage == uMergeSource)
3883 InsertConfigInteger(pCur, "MergeSource", 1);
3884 else if (uImage == uMergeTarget)
3885 InsertConfigInteger(pCur, "MergeTarget", 1);
3886 }
3887
3888 /* Pass all custom parameters. */
3889 SafeArray<BSTR> aNames;
3890 SafeArray<BSTR> aValues;
3891 hrc = pMedium->GetProperties(NULL,
3892 ComSafeArrayAsOutParam(aNames),
3893 ComSafeArrayAsOutParam(aValues)); H();
3894
3895 if (aNames.size() != 0)
3896 {
3897 PCFGMNODE pVDC;
3898 InsertConfigNode(pCur, "VDConfig", &pVDC);
3899 for (size_t ii = 0; ii < aNames.size(); ++ii)
3900 {
3901 if (aValues[ii] && *aValues[ii])
3902 {
3903 Utf8Str name = aNames[ii];
3904 Utf8Str value = aValues[ii];
3905 InsertConfigString(pVDC, name.c_str(), value);
3906 if ( name.compare("HostIPStack") == 0
3907 && value.compare("0") == 0)
3908 fHostIP = false;
3909 }
3910 }
3911 }
3912
3913 /* next */
3914 pParent = pCur;
3915 pParentMedium = pMedium;
3916 }
3917
3918 /* Custom code: put marker to not use host IP stack to driver
3919 * configuration node. Simplifies life of DrvVD a bit. */
3920 if (!fHostIP)
3921 InsertConfigInteger(pCfg, "HostIPStack", 0);
3922 }
3923 }
3924#undef H
3925 }
3926 catch (ConfigError &x)
3927 {
3928 // InsertConfig threw something:
3929 return x.m_vrc;
3930 }
3931
3932 return VINF_SUCCESS;
3933}
3934
3935/**
3936 * Construct the Network configuration tree
3937 *
3938 * @returns VBox status code.
3939 *
3940 * @param pszDevice The PDM device name.
3941 * @param uInstance The PDM device instance.
3942 * @param uLun The PDM LUN number of the drive.
3943 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
3944 * @param pCfg Configuration node for the device
3945 * @param pLunL0 To store the pointer to the LUN#0.
3946 * @param pInst The instance CFGM node
3947 * @param fAttachDetach To determine if the network attachment should
3948 * be attached/detached after/before
3949 * configuration.
3950 * @param fIgnoreConnectFailure
3951 * True if connection failures should be ignored
3952 * (makes only sense for bridged/host-only networks).
3953 *
3954 * @note Locks this object for writing.
3955 * @thread EMT
3956 */
3957int Console::configNetwork(const char *pszDevice,
3958 unsigned uInstance,
3959 unsigned uLun,
3960 INetworkAdapter *aNetworkAdapter,
3961 PCFGMNODE pCfg,
3962 PCFGMNODE pLunL0,
3963 PCFGMNODE pInst,
3964 bool fAttachDetach,
3965 bool fIgnoreConnectFailure)
3966{
3967 AutoCaller autoCaller(this);
3968 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
3969
3970 // InsertConfig* throws
3971 try
3972 {
3973 int rc = VINF_SUCCESS;
3974 HRESULT hrc;
3975 Bstr bstr;
3976
3977#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
3978
3979 /*
3980 * Locking the object before doing VMR3* calls is quite safe here, since
3981 * we're on EMT. Write lock is necessary because we indirectly modify the
3982 * meAttachmentType member.
3983 */
3984 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3985
3986 ComPtr<IMachine> pMachine = machine();
3987
3988 ComPtr<IVirtualBox> virtualBox;
3989 hrc = pMachine->COMGETTER(Parent)(virtualBox.asOutParam()); H();
3990
3991 ComPtr<IHost> host;
3992 hrc = virtualBox->COMGETTER(Host)(host.asOutParam()); H();
3993
3994 BOOL fSniffer;
3995 hrc = aNetworkAdapter->COMGETTER(TraceEnabled)(&fSniffer); H();
3996
3997 NetworkAdapterPromiscModePolicy_T enmPromiscModePolicy;
3998 hrc = aNetworkAdapter->COMGETTER(PromiscModePolicy)(&enmPromiscModePolicy); H();
3999 const char *pszPromiscuousGuestPolicy;
4000 switch (enmPromiscModePolicy)
4001 {
4002 case NetworkAdapterPromiscModePolicy_Deny: pszPromiscuousGuestPolicy = "deny"; break;
4003 case NetworkAdapterPromiscModePolicy_AllowNetwork: pszPromiscuousGuestPolicy = "allow-network"; break;
4004 case NetworkAdapterPromiscModePolicy_AllowAll: pszPromiscuousGuestPolicy = "allow-all"; break;
4005 default: AssertFailedReturn(VERR_INTERNAL_ERROR_4);
4006 }
4007
4008 if (fAttachDetach)
4009 {
4010 rc = PDMR3DeviceDetach(mpUVM, pszDevice, uInstance, uLun, 0 /*fFlags*/);
4011 if (rc == VINF_PDM_NO_DRIVER_ATTACHED_TO_LUN)
4012 rc = VINF_SUCCESS;
4013 AssertLogRelRCReturn(rc, rc);
4014
4015 /* nuke anything which might have been left behind. */
4016 CFGMR3RemoveNode(CFGMR3GetChildF(pInst, "LUN#%u", uLun));
4017 }
4018
4019#ifdef VBOX_WITH_NETSHAPER
4020 ComObjPtr<IBandwidthGroup> pBwGroup;
4021 Bstr strBwGroup;
4022 hrc = aNetworkAdapter->COMGETTER(BandwidthGroup)(pBwGroup.asOutParam()); H();
4023
4024 if (!pBwGroup.isNull())
4025 {
4026 hrc = pBwGroup->COMGETTER(Name)(strBwGroup.asOutParam()); H();
4027 }
4028#endif /* VBOX_WITH_NETSHAPER */
4029
4030 Utf8Str strNetDriver;
4031
4032
4033 InsertConfigNode(pInst, "LUN#0", &pLunL0);
4034
4035#ifdef VBOX_WITH_NETSHAPER
4036 if (!strBwGroup.isEmpty())
4037 {
4038 InsertConfigString(pLunL0, "Driver", "NetShaper");
4039 InsertConfigNode(pLunL0, "Config", &pCfg);
4040 InsertConfigString(pCfg, "BwGroup", strBwGroup);
4041 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
4042 }
4043#endif /* VBOX_WITH_NETSHAPER */
4044
4045 if (fSniffer)
4046 {
4047 InsertConfigString(pLunL0, "Driver", "NetSniffer");
4048 InsertConfigNode(pLunL0, "Config", &pCfg);
4049 hrc = aNetworkAdapter->COMGETTER(TraceFile)(bstr.asOutParam()); H();
4050 if (!bstr.isEmpty()) /* check convention for indicating default file. */
4051 InsertConfigString(pCfg, "File", bstr);
4052 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
4053 }
4054
4055
4056 Bstr networkName, trunkName, trunkType;
4057 NetworkAttachmentType_T eAttachmentType;
4058 hrc = aNetworkAdapter->COMGETTER(AttachmentType)(&eAttachmentType); H();
4059 switch (eAttachmentType)
4060 {
4061 case NetworkAttachmentType_Null:
4062 break;
4063
4064 case NetworkAttachmentType_NAT:
4065 {
4066 ComPtr<INATEngine> natEngine;
4067 hrc = aNetworkAdapter->COMGETTER(NATEngine)(natEngine.asOutParam()); H();
4068 InsertConfigString(pLunL0, "Driver", "NAT");
4069 InsertConfigNode(pLunL0, "Config", &pCfg);
4070
4071 /* Configure TFTP prefix and boot filename. */
4072 hrc = virtualBox->COMGETTER(HomeFolder)(bstr.asOutParam()); H();
4073 if (!bstr.isEmpty())
4074 InsertConfigString(pCfg, "TFTPPrefix", Utf8StrFmt("%ls%c%s", bstr.raw(), RTPATH_DELIMITER, "TFTP"));
4075 hrc = pMachine->COMGETTER(Name)(bstr.asOutParam()); H();
4076 InsertConfigString(pCfg, "BootFile", Utf8StrFmt("%ls.pxe", bstr.raw()));
4077
4078 hrc = natEngine->COMGETTER(Network)(bstr.asOutParam()); H();
4079 if (!bstr.isEmpty())
4080 InsertConfigString(pCfg, "Network", bstr);
4081 else
4082 {
4083 ULONG uSlot;
4084 hrc = aNetworkAdapter->COMGETTER(Slot)(&uSlot); H();
4085 InsertConfigString(pCfg, "Network", Utf8StrFmt("10.0.%d.0/24", uSlot+2));
4086 }
4087 hrc = natEngine->COMGETTER(HostIP)(bstr.asOutParam()); H();
4088 if (!bstr.isEmpty())
4089 InsertConfigString(pCfg, "BindIP", bstr);
4090 ULONG mtu = 0;
4091 ULONG sockSnd = 0;
4092 ULONG sockRcv = 0;
4093 ULONG tcpSnd = 0;
4094 ULONG tcpRcv = 0;
4095 hrc = natEngine->GetNetworkSettings(&mtu, &sockSnd, &sockRcv, &tcpSnd, &tcpRcv); H();
4096 if (mtu)
4097 InsertConfigInteger(pCfg, "SlirpMTU", mtu);
4098 if (sockRcv)
4099 InsertConfigInteger(pCfg, "SockRcv", sockRcv);
4100 if (sockSnd)
4101 InsertConfigInteger(pCfg, "SockSnd", sockSnd);
4102 if (tcpRcv)
4103 InsertConfigInteger(pCfg, "TcpRcv", tcpRcv);
4104 if (tcpSnd)
4105 InsertConfigInteger(pCfg, "TcpSnd", tcpSnd);
4106 hrc = natEngine->COMGETTER(TFTPPrefix)(bstr.asOutParam()); H();
4107 if (!bstr.isEmpty())
4108 {
4109 RemoveConfigValue(pCfg, "TFTPPrefix");
4110 InsertConfigString(pCfg, "TFTPPrefix", bstr);
4111 }
4112 hrc = natEngine->COMGETTER(TFTPBootFile)(bstr.asOutParam()); H();
4113 if (!bstr.isEmpty())
4114 {
4115 RemoveConfigValue(pCfg, "BootFile");
4116 InsertConfigString(pCfg, "BootFile", bstr);
4117 }
4118 hrc = natEngine->COMGETTER(TFTPNextServer)(bstr.asOutParam()); H();
4119 if (!bstr.isEmpty())
4120 InsertConfigString(pCfg, "NextServer", bstr);
4121 BOOL fDNSFlag;
4122 hrc = natEngine->COMGETTER(DNSPassDomain)(&fDNSFlag); H();
4123 InsertConfigInteger(pCfg, "PassDomain", fDNSFlag);
4124 hrc = natEngine->COMGETTER(DNSProxy)(&fDNSFlag); H();
4125 InsertConfigInteger(pCfg, "DNSProxy", fDNSFlag);
4126 hrc = natEngine->COMGETTER(DNSUseHostResolver)(&fDNSFlag); H();
4127 InsertConfigInteger(pCfg, "UseHostResolver", fDNSFlag);
4128
4129 ULONG aliasMode;
4130 hrc = natEngine->COMGETTER(AliasMode)(&aliasMode); H();
4131 InsertConfigInteger(pCfg, "AliasMode", aliasMode);
4132
4133 /* port-forwarding */
4134 SafeArray<BSTR> pfs;
4135 hrc = natEngine->COMGETTER(Redirects)(ComSafeArrayAsOutParam(pfs)); H();
4136 PCFGMNODE pPF = NULL; /* /Devices/Dev/.../Config/PF#0/ */
4137 for (unsigned int i = 0; i < pfs.size(); ++i)
4138 {
4139 uint16_t port = 0;
4140 BSTR r = pfs[i];
4141 Utf8Str utf = Utf8Str(r);
4142 Utf8Str strName;
4143 Utf8Str strProto;
4144 Utf8Str strHostPort;
4145 Utf8Str strHostIP;
4146 Utf8Str strGuestPort;
4147 Utf8Str strGuestIP;
4148 size_t pos, ppos;
4149 pos = ppos = 0;
4150#define ITERATE_TO_NEXT_TERM(res, str, pos, ppos) \
4151 do { \
4152 pos = str.find(",", ppos); \
4153 if (pos == Utf8Str::npos) \
4154 { \
4155 Log(( #res " extracting from %s is failed\n", str.c_str())); \
4156 continue; \
4157 } \
4158 res = str.substr(ppos, pos - ppos); \
4159 Log2((#res " %s pos:%d, ppos:%d\n", res.c_str(), pos, ppos)); \
4160 ppos = pos + 1; \
4161 } while (0)
4162 ITERATE_TO_NEXT_TERM(strName, utf, pos, ppos);
4163 ITERATE_TO_NEXT_TERM(strProto, utf, pos, ppos);
4164 ITERATE_TO_NEXT_TERM(strHostIP, utf, pos, ppos);
4165 ITERATE_TO_NEXT_TERM(strHostPort, utf, pos, ppos);
4166 ITERATE_TO_NEXT_TERM(strGuestIP, utf, pos, ppos);
4167 strGuestPort = utf.substr(ppos, utf.length() - ppos);
4168#undef ITERATE_TO_NEXT_TERM
4169
4170 uint32_t proto = strProto.toUInt32();
4171 bool fValid = true;
4172 switch (proto)
4173 {
4174 case NATProtocol_UDP:
4175 strProto = "UDP";
4176 break;
4177 case NATProtocol_TCP:
4178 strProto = "TCP";
4179 break;
4180 default:
4181 fValid = false;
4182 }
4183 /* continue with next rule if no valid proto was passed */
4184 if (!fValid)
4185 continue;
4186
4187 InsertConfigNode(pCfg, strName.c_str(), &pPF);
4188 InsertConfigString(pPF, "Protocol", strProto);
4189
4190 if (!strHostIP.isEmpty())
4191 InsertConfigString(pPF, "BindIP", strHostIP);
4192
4193 if (!strGuestIP.isEmpty())
4194 InsertConfigString(pPF, "GuestIP", strGuestIP);
4195
4196 port = RTStrToUInt16(strHostPort.c_str());
4197 if (port)
4198 InsertConfigInteger(pPF, "HostPort", port);
4199
4200 port = RTStrToUInt16(strGuestPort.c_str());
4201 if (port)
4202 InsertConfigInteger(pPF, "GuestPort", port);
4203 }
4204 break;
4205 }
4206
4207 case NetworkAttachmentType_Bridged:
4208 {
4209#if (defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT)
4210 hrc = attachToTapInterface(aNetworkAdapter);
4211 if (FAILED(hrc))
4212 {
4213 switch (hrc)
4214 {
4215 case VERR_ACCESS_DENIED:
4216 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4217 "Failed to open '/dev/net/tun' for read/write access. Please check the "
4218 "permissions of that node. Either run 'chmod 0666 /dev/net/tun' or "
4219 "change the group of that node and make yourself a member of that group. Make "
4220 "sure that these changes are permanent, especially if you are "
4221 "using udev"));
4222 default:
4223 AssertMsgFailed(("Could not attach to host interface! Bad!\n"));
4224 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4225 "Failed to initialize Host Interface Networking"));
4226 }
4227 }
4228
4229 Assert((int)maTapFD[uInstance] >= 0);
4230 if ((int)maTapFD[uInstance] >= 0)
4231 {
4232 InsertConfigString(pLunL0, "Driver", "HostInterface");
4233 InsertConfigNode(pLunL0, "Config", &pCfg);
4234 InsertConfigInteger(pCfg, "FileHandle", maTapFD[uInstance]);
4235 }
4236
4237#elif defined(VBOX_WITH_NETFLT)
4238 /*
4239 * This is the new VBoxNetFlt+IntNet stuff.
4240 */
4241 Bstr BridgedIfName;
4242 hrc = aNetworkAdapter->COMGETTER(BridgedInterface)(BridgedIfName.asOutParam());
4243 if (FAILED(hrc))
4244 {
4245 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(BridgedInterface) failed, hrc (0x%x)\n", hrc));
4246 H();
4247 }
4248
4249 Utf8Str BridgedIfNameUtf8(BridgedIfName);
4250 const char *pszBridgedIfName = BridgedIfNameUtf8.c_str();
4251
4252# if defined(RT_OS_DARWIN)
4253 /* The name is on the form 'ifX: long name', chop it off at the colon. */
4254 char szTrunk[8];
4255 RTStrCopy(szTrunk, sizeof(szTrunk), pszBridgedIfName);
4256 char *pszColon = (char *)memchr(szTrunk, ':', sizeof(szTrunk));
4257// Quick fix for @bugref{5633}
4258// if (!pszColon)
4259// {
4260// /*
4261// * Dynamic changing of attachment causes an attempt to configure
4262// * network with invalid host adapter (as it is must be changed before
4263// * the attachment), calling Detach here will cause a deadlock.
4264// * See @bugref{4750}.
4265// * hrc = aNetworkAdapter->Detach(); H();
4266// */
4267// return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4268// N_("Malformed host interface networking name '%ls'"),
4269// BridgedIfName.raw());
4270// }
4271 if (pszColon)
4272 *pszColon = '\0';
4273 const char *pszTrunk = szTrunk;
4274
4275# elif defined(RT_OS_SOLARIS)
4276 /* The name is on the form format 'ifX[:1] - long name, chop it off at space. */
4277 char szTrunk[256];
4278 strlcpy(szTrunk, pszBridgedIfName, sizeof(szTrunk));
4279 char *pszSpace = (char *)memchr(szTrunk, ' ', sizeof(szTrunk));
4280
4281 /*
4282 * Currently don't bother about malformed names here for the sake of people using
4283 * VBoxManage and setting only the NIC name from there. If there is a space we
4284 * chop it off and proceed, otherwise just use whatever we've got.
4285 */
4286 if (pszSpace)
4287 *pszSpace = '\0';
4288
4289 /* Chop it off at the colon (zone naming eg: e1000g:1 we need only the e1000g) */
4290 char *pszColon = (char *)memchr(szTrunk, ':', sizeof(szTrunk));
4291 if (pszColon)
4292 *pszColon = '\0';
4293
4294 const char *pszTrunk = szTrunk;
4295
4296# elif defined(RT_OS_WINDOWS)
4297 ComPtr<IHostNetworkInterface> hostInterface;
4298 hrc = host->FindHostNetworkInterfaceByName(BridgedIfName.raw(),
4299 hostInterface.asOutParam());
4300 if (!SUCCEEDED(hrc))
4301 {
4302 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: FindByName failed, rc=%Rhrc (0x%x)", hrc, hrc));
4303 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4304 N_("Nonexistent host networking interface, name '%ls'"),
4305 BridgedIfName.raw());
4306 }
4307
4308 HostNetworkInterfaceType_T eIfType;
4309 hrc = hostInterface->COMGETTER(InterfaceType)(&eIfType);
4310 if (FAILED(hrc))
4311 {
4312 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(InterfaceType) failed, hrc (0x%x)\n", hrc));
4313 H();
4314 }
4315
4316 if (eIfType != HostNetworkInterfaceType_Bridged)
4317 {
4318 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4319 N_("Interface ('%ls') is not a Bridged Adapter interface"),
4320 BridgedIfName.raw());
4321 }
4322
4323 hrc = hostInterface->COMGETTER(Id)(bstr.asOutParam());
4324 if (FAILED(hrc))
4325 {
4326 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(Id) failed, hrc (0x%x)\n", hrc));
4327 H();
4328 }
4329 Guid hostIFGuid(bstr);
4330
4331 INetCfg *pNc;
4332 ComPtr<INetCfgComponent> pAdaptorComponent;
4333 LPWSTR pszApp;
4334
4335 hrc = VBoxNetCfgWinQueryINetCfg(&pNc, FALSE, L"VirtualBox", 10, &pszApp);
4336 Assert(hrc == S_OK);
4337 if (hrc != S_OK)
4338 {
4339 LogRel(("NetworkAttachmentType_Bridged: Failed to get NetCfg, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4340 H();
4341 }
4342
4343 /* get the adapter's INetCfgComponent*/
4344 hrc = VBoxNetCfgWinGetComponentByGuid(pNc, &GUID_DEVCLASS_NET, (GUID*)hostIFGuid.raw(), pAdaptorComponent.asOutParam());
4345 if (hrc != S_OK)
4346 {
4347 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4348 LogRel(("NetworkAttachmentType_Bridged: VBoxNetCfgWinGetComponentByGuid failed, hrc (0x%x)\n", hrc));
4349 H();
4350 }
4351#define VBOX_WIN_BINDNAME_PREFIX "\\DEVICE\\"
4352 char szTrunkName[INTNET_MAX_TRUNK_NAME];
4353 char *pszTrunkName = szTrunkName;
4354 wchar_t * pswzBindName;
4355 hrc = pAdaptorComponent->GetBindName(&pswzBindName);
4356 Assert(hrc == S_OK);
4357 if (hrc == S_OK)
4358 {
4359 int cwBindName = (int)wcslen(pswzBindName) + 1;
4360 int cbFullBindNamePrefix = sizeof(VBOX_WIN_BINDNAME_PREFIX);
4361 if (sizeof(szTrunkName) > cbFullBindNamePrefix + cwBindName)
4362 {
4363 strcpy(szTrunkName, VBOX_WIN_BINDNAME_PREFIX);
4364 pszTrunkName += cbFullBindNamePrefix-1;
4365 if (!WideCharToMultiByte(CP_ACP, 0, pswzBindName, cwBindName, pszTrunkName,
4366 sizeof(szTrunkName) - cbFullBindNamePrefix + 1, NULL, NULL))
4367 {
4368 DWORD err = GetLastError();
4369 hrc = HRESULT_FROM_WIN32(err);
4370 AssertMsgFailed(("%hrc=%Rhrc %#x\n", hrc, hrc));
4371 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: WideCharToMultiByte failed, hr=%Rhrc (0x%x) err=%u\n", hrc, hrc, err));
4372 }
4373 }
4374 else
4375 {
4376 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: insufficient szTrunkName buffer space\n"));
4377 /** @todo set appropriate error code */
4378 hrc = E_FAIL;
4379 }
4380
4381 if (hrc != S_OK)
4382 {
4383 AssertFailed();
4384 CoTaskMemFree(pswzBindName);
4385 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4386 H();
4387 }
4388
4389 /* we're not freeing the bind name since we'll use it later for detecting wireless*/
4390 }
4391 else
4392 {
4393 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4394 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: VBoxNetCfgWinGetComponentByGuid failed, hrc (0x%x)", hrc));
4395 H();
4396 }
4397
4398 const char *pszTrunk = szTrunkName;
4399 /* we're not releasing the INetCfg stuff here since we use it later to figure out whether it is wireless */
4400
4401# elif defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
4402# if defined(RT_OS_FREEBSD)
4403 /*
4404 * If we bridge to a tap interface open it the `old' direct way.
4405 * This works and performs better than bridging a physical
4406 * interface via the current FreeBSD vboxnetflt implementation.
4407 */
4408 if (!strncmp(pszBridgedIfName, RT_STR_TUPLE("tap"))) {
4409 hrc = attachToTapInterface(aNetworkAdapter);
4410 if (FAILED(hrc))
4411 {
4412 switch (hrc)
4413 {
4414 case VERR_ACCESS_DENIED:
4415 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4416 "Failed to open '/dev/%s' for read/write access. Please check the "
4417 "permissions of that node, and that the net.link.tap.user_open "
4418 "sysctl is set. Either run 'chmod 0666 /dev/%s' or "
4419 "change the group of that node to vboxusers and make yourself "
4420 "a member of that group. Make sure that these changes are permanent."), pszBridgedIfName, pszBridgedIfName);
4421 default:
4422 AssertMsgFailed(("Could not attach to tap interface! Bad!\n"));
4423 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4424 "Failed to initialize Host Interface Networking"));
4425 }
4426 }
4427
4428 Assert((int)maTapFD[uInstance] >= 0);
4429 if ((int)maTapFD[uInstance] >= 0)
4430 {
4431 InsertConfigString(pLunL0, "Driver", "HostInterface");
4432 InsertConfigNode(pLunL0, "Config", &pCfg);
4433 InsertConfigInteger(pCfg, "FileHandle", maTapFD[uInstance]);
4434 }
4435 break;
4436 }
4437# endif
4438 /** @todo Check for malformed names. */
4439 const char *pszTrunk = pszBridgedIfName;
4440
4441 /* Issue a warning if the interface is down */
4442 {
4443 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
4444 if (iSock >= 0)
4445 {
4446 struct ifreq Req;
4447 RT_ZERO(Req);
4448 RTStrCopy(Req.ifr_name, sizeof(Req.ifr_name), pszBridgedIfName);
4449 if (ioctl(iSock, SIOCGIFFLAGS, &Req) >= 0)
4450 if ((Req.ifr_flags & IFF_UP) == 0)
4451 setVMRuntimeErrorCallbackF(0, "BridgedInterfaceDown",
4452 N_("Bridged interface %s is down. Guest will not be able to use this interface"),
4453 pszBridgedIfName);
4454
4455 close(iSock);
4456 }
4457 }
4458
4459# else
4460# error "PORTME (VBOX_WITH_NETFLT)"
4461# endif
4462
4463 InsertConfigString(pLunL0, "Driver", "IntNet");
4464 InsertConfigNode(pLunL0, "Config", &pCfg);
4465 InsertConfigString(pCfg, "Trunk", pszTrunk);
4466 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetFlt);
4467 InsertConfigInteger(pCfg, "IgnoreConnectFailure", (uint64_t)fIgnoreConnectFailure);
4468 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
4469 char szNetwork[INTNET_MAX_NETWORK_NAME];
4470
4471#if defined(RT_OS_SOLARIS) || defined(RT_OS_DARWIN)
4472 /*
4473 * 'pszTrunk' contains just the interface name required in ring-0, while 'pszBridgedIfName' contains
4474 * interface name + optional description. We must not pass any description to the VM as it can differ
4475 * for the same interface name, eg: "nge0 - ethernet" (GUI) vs "nge0" (VBoxManage).
4476 */
4477 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszTrunk);
4478#else
4479 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszBridgedIfName);
4480#endif
4481 InsertConfigString(pCfg, "Network", szNetwork);
4482 networkName = Bstr(szNetwork);
4483 trunkName = Bstr(pszTrunk);
4484 trunkType = Bstr(TRUNKTYPE_NETFLT);
4485
4486# if defined(RT_OS_DARWIN)
4487 /** @todo Come up with a better deal here. Problem is that IHostNetworkInterface is completely useless here. */
4488 if ( strstr(pszBridgedIfName, "Wireless")
4489 || strstr(pszBridgedIfName, "AirPort" ))
4490 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4491# elif defined(RT_OS_LINUX)
4492 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
4493 if (iSock >= 0)
4494 {
4495 struct iwreq WRq;
4496
4497 RT_ZERO(WRq);
4498 strncpy(WRq.ifr_name, pszBridgedIfName, IFNAMSIZ);
4499 bool fSharedMacOnWire = ioctl(iSock, SIOCGIWNAME, &WRq) >= 0;
4500 close(iSock);
4501 if (fSharedMacOnWire)
4502 {
4503 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4504 Log(("Set SharedMacOnWire\n"));
4505 }
4506 else
4507 Log(("Failed to get wireless name\n"));
4508 }
4509 else
4510 Log(("Failed to open wireless socket\n"));
4511# elif defined(RT_OS_FREEBSD)
4512 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
4513 if (iSock >= 0)
4514 {
4515 struct ieee80211req WReq;
4516 uint8_t abData[32];
4517
4518 RT_ZERO(WReq);
4519 strncpy(WReq.i_name, pszBridgedIfName, sizeof(WReq.i_name));
4520 WReq.i_type = IEEE80211_IOC_SSID;
4521 WReq.i_val = -1;
4522 WReq.i_data = abData;
4523 WReq.i_len = sizeof(abData);
4524
4525 bool fSharedMacOnWire = ioctl(iSock, SIOCG80211, &WReq) >= 0;
4526 close(iSock);
4527 if (fSharedMacOnWire)
4528 {
4529 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4530 Log(("Set SharedMacOnWire\n"));
4531 }
4532 else
4533 Log(("Failed to get wireless name\n"));
4534 }
4535 else
4536 Log(("Failed to open wireless socket\n"));
4537# elif defined(RT_OS_WINDOWS)
4538# define DEVNAME_PREFIX L"\\\\.\\"
4539 /* we are getting the medium type via IOCTL_NDIS_QUERY_GLOBAL_STATS Io Control
4540 * there is a pretty long way till there though since we need to obtain the symbolic link name
4541 * for the adapter device we are going to query given the device Guid */
4542
4543
4544 /* prepend the "\\\\.\\" to the bind name to obtain the link name */
4545
4546 wchar_t FileName[MAX_PATH];
4547 wcscpy(FileName, DEVNAME_PREFIX);
4548 wcscpy((wchar_t*)(((char*)FileName) + sizeof(DEVNAME_PREFIX) - sizeof(FileName[0])), pswzBindName);
4549
4550 /* open the device */
4551 HANDLE hDevice = CreateFile(FileName,
4552 GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
4553 NULL,
4554 OPEN_EXISTING,
4555 FILE_ATTRIBUTE_NORMAL,
4556 NULL);
4557
4558 if (hDevice != INVALID_HANDLE_VALUE)
4559 {
4560 bool fSharedMacOnWire = false;
4561
4562 /* now issue the OID_GEN_PHYSICAL_MEDIUM query */
4563 DWORD Oid = OID_GEN_PHYSICAL_MEDIUM;
4564 NDIS_PHYSICAL_MEDIUM PhMedium;
4565 DWORD cbResult;
4566 if (DeviceIoControl(hDevice,
4567 IOCTL_NDIS_QUERY_GLOBAL_STATS,
4568 &Oid,
4569 sizeof(Oid),
4570 &PhMedium,
4571 sizeof(PhMedium),
4572 &cbResult,
4573 NULL))
4574 {
4575 /* that was simple, now examine PhMedium */
4576 if ( PhMedium == NdisPhysicalMediumWirelessWan
4577 || PhMedium == NdisPhysicalMediumWirelessLan
4578 || PhMedium == NdisPhysicalMediumNative802_11
4579 || PhMedium == NdisPhysicalMediumBluetooth)
4580 fSharedMacOnWire = true;
4581 }
4582 else
4583 {
4584 int winEr = GetLastError();
4585 LogRel(("Console::configNetwork: DeviceIoControl failed, err (0x%x), ignoring\n", winEr));
4586 Assert(winEr == ERROR_INVALID_PARAMETER || winEr == ERROR_NOT_SUPPORTED || winEr == ERROR_BAD_COMMAND);
4587 }
4588 CloseHandle(hDevice);
4589
4590 if (fSharedMacOnWire)
4591 {
4592 Log(("this is a wireless adapter"));
4593 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4594 Log(("Set SharedMacOnWire\n"));
4595 }
4596 else
4597 Log(("this is NOT a wireless adapter"));
4598 }
4599 else
4600 {
4601 int winEr = GetLastError();
4602 AssertLogRelMsgFailed(("Console::configNetwork: CreateFile failed, err (0x%x), ignoring\n", winEr));
4603 }
4604
4605 CoTaskMemFree(pswzBindName);
4606
4607 pAdaptorComponent.setNull();
4608 /* release the pNc finally */
4609 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4610# else
4611 /** @todo PORTME: wireless detection */
4612# endif
4613
4614# if defined(RT_OS_SOLARIS)
4615# if 0 /* bird: this is a bit questionable and might cause more trouble than its worth. */
4616 /* Zone access restriction, don't allow snooping the global zone. */
4617 zoneid_t ZoneId = getzoneid();
4618 if (ZoneId != GLOBAL_ZONEID)
4619 {
4620 InsertConfigInteger(pCfg, "IgnoreAllPromisc", true);
4621 }
4622# endif
4623# endif
4624
4625#elif defined(RT_OS_WINDOWS) /* not defined NetFlt */
4626 /* NOTHING TO DO HERE */
4627#elif defined(RT_OS_LINUX)
4628/// @todo aleksey: is there anything to be done here?
4629#elif defined(RT_OS_FREEBSD)
4630/** @todo FreeBSD: Check out this later (HIF networking). */
4631#else
4632# error "Port me"
4633#endif
4634 break;
4635 }
4636
4637 case NetworkAttachmentType_Internal:
4638 {
4639 hrc = aNetworkAdapter->COMGETTER(InternalNetwork)(bstr.asOutParam()); H();
4640 if (!bstr.isEmpty())
4641 {
4642 InsertConfigString(pLunL0, "Driver", "IntNet");
4643 InsertConfigNode(pLunL0, "Config", &pCfg);
4644 InsertConfigString(pCfg, "Network", bstr);
4645 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_WhateverNone);
4646 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
4647 networkName = bstr;
4648 trunkType = Bstr(TRUNKTYPE_WHATEVER);
4649 }
4650 break;
4651 }
4652
4653 case NetworkAttachmentType_HostOnly:
4654 {
4655 InsertConfigString(pLunL0, "Driver", "IntNet");
4656 InsertConfigNode(pLunL0, "Config", &pCfg);
4657
4658 Bstr HostOnlyName;
4659 hrc = aNetworkAdapter->COMGETTER(HostOnlyInterface)(HostOnlyName.asOutParam());
4660 if (FAILED(hrc))
4661 {
4662 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(HostOnlyInterface) failed, hrc (0x%x)\n", hrc));
4663 H();
4664 }
4665
4666 Utf8Str HostOnlyNameUtf8(HostOnlyName);
4667 const char *pszHostOnlyName = HostOnlyNameUtf8.c_str();
4668 ComPtr<IHostNetworkInterface> hostInterface;
4669 rc = host->FindHostNetworkInterfaceByName(HostOnlyName.raw(),
4670 hostInterface.asOutParam());
4671 if (!SUCCEEDED(rc))
4672 {
4673 LogRel(("NetworkAttachmentType_HostOnly: FindByName failed, rc (0x%x)\n", rc));
4674 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4675 N_("Nonexistent host networking interface, name '%ls'"),
4676 HostOnlyName.raw());
4677 }
4678
4679 char szNetwork[INTNET_MAX_NETWORK_NAME];
4680 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszHostOnlyName);
4681
4682#if defined(RT_OS_WINDOWS)
4683# ifndef VBOX_WITH_NETFLT
4684 hrc = E_NOTIMPL;
4685 LogRel(("NetworkAttachmentType_HostOnly: Not Implemented\n"));
4686 H();
4687# else /* defined VBOX_WITH_NETFLT*/
4688 /** @todo r=bird: Put this in a function. */
4689
4690 HostNetworkInterfaceType_T eIfType;
4691 hrc = hostInterface->COMGETTER(InterfaceType)(&eIfType);
4692 if (FAILED(hrc))
4693 {
4694 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(InterfaceType) failed, hrc (0x%x)\n", hrc));
4695 H();
4696 }
4697
4698 if (eIfType != HostNetworkInterfaceType_HostOnly)
4699 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4700 N_("Interface ('%ls') is not a Host-Only Adapter interface"),
4701 HostOnlyName.raw());
4702
4703 hrc = hostInterface->COMGETTER(Id)(bstr.asOutParam());
4704 if (FAILED(hrc))
4705 {
4706 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(Id) failed, hrc (0x%x)\n", hrc));
4707 H();
4708 }
4709 Guid hostIFGuid(bstr);
4710
4711 INetCfg *pNc;
4712 ComPtr<INetCfgComponent> pAdaptorComponent;
4713 LPWSTR pszApp;
4714 hrc = VBoxNetCfgWinQueryINetCfg(&pNc, FALSE, L"VirtualBox", 10, &pszApp);
4715 Assert(hrc == S_OK);
4716 if (hrc != S_OK)
4717 {
4718 LogRel(("NetworkAttachmentType_HostOnly: Failed to get NetCfg, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4719 H();
4720 }
4721
4722 /* get the adapter's INetCfgComponent*/
4723 hrc = VBoxNetCfgWinGetComponentByGuid(pNc, &GUID_DEVCLASS_NET, (GUID*)hostIFGuid.raw(), pAdaptorComponent.asOutParam());
4724 if (hrc != S_OK)
4725 {
4726 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4727 LogRel(("NetworkAttachmentType_HostOnly: VBoxNetCfgWinGetComponentByGuid failed, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4728 H();
4729 }
4730# define VBOX_WIN_BINDNAME_PREFIX "\\DEVICE\\"
4731 char szTrunkName[INTNET_MAX_TRUNK_NAME];
4732 char *pszTrunkName = szTrunkName;
4733 wchar_t * pswzBindName;
4734 hrc = pAdaptorComponent->GetBindName(&pswzBindName);
4735 Assert(hrc == S_OK);
4736 if (hrc == S_OK)
4737 {
4738 int cwBindName = (int)wcslen(pswzBindName) + 1;
4739 int cbFullBindNamePrefix = sizeof(VBOX_WIN_BINDNAME_PREFIX);
4740 if (sizeof(szTrunkName) > cbFullBindNamePrefix + cwBindName)
4741 {
4742 strcpy(szTrunkName, VBOX_WIN_BINDNAME_PREFIX);
4743 pszTrunkName += cbFullBindNamePrefix-1;
4744 if (!WideCharToMultiByte(CP_ACP, 0, pswzBindName, cwBindName, pszTrunkName,
4745 sizeof(szTrunkName) - cbFullBindNamePrefix + 1, NULL, NULL))
4746 {
4747 DWORD err = GetLastError();
4748 hrc = HRESULT_FROM_WIN32(err);
4749 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: WideCharToMultiByte failed, hr=%Rhrc (0x%x) err=%u\n", hrc, hrc, err));
4750 }
4751 }
4752 else
4753 {
4754 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: insufficient szTrunkName buffer space\n"));
4755 /** @todo set appropriate error code */
4756 hrc = E_FAIL;
4757 }
4758
4759 if (hrc != S_OK)
4760 {
4761 AssertFailed();
4762 CoTaskMemFree(pswzBindName);
4763 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4764 H();
4765 }
4766 }
4767 else
4768 {
4769 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4770 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: VBoxNetCfgWinGetComponentByGuid failed, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4771 H();
4772 }
4773
4774
4775 CoTaskMemFree(pswzBindName);
4776
4777 pAdaptorComponent.setNull();
4778 /* release the pNc finally */
4779 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4780
4781 const char *pszTrunk = szTrunkName;
4782
4783 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetAdp);
4784 InsertConfigString(pCfg, "Trunk", pszTrunk);
4785 InsertConfigString(pCfg, "Network", szNetwork);
4786 InsertConfigInteger(pCfg, "IgnoreConnectFailure", (uint64_t)fIgnoreConnectFailure); /** @todo why is this windows only?? */
4787 networkName = Bstr(szNetwork);
4788 trunkName = Bstr(pszTrunk);
4789 trunkType = TRUNKTYPE_NETADP;
4790# endif /* defined VBOX_WITH_NETFLT*/
4791#elif defined(RT_OS_DARWIN)
4792 InsertConfigString(pCfg, "Trunk", pszHostOnlyName);
4793 InsertConfigString(pCfg, "Network", szNetwork);
4794 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetAdp);
4795 networkName = Bstr(szNetwork);
4796 trunkName = Bstr(pszHostOnlyName);
4797 trunkType = TRUNKTYPE_NETADP;
4798#else
4799 InsertConfigString(pCfg, "Trunk", pszHostOnlyName);
4800 InsertConfigString(pCfg, "Network", szNetwork);
4801 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetFlt);
4802 networkName = Bstr(szNetwork);
4803 trunkName = Bstr(pszHostOnlyName);
4804 trunkType = TRUNKTYPE_NETFLT;
4805#endif
4806 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
4807
4808#if !defined(RT_OS_WINDOWS) && defined(VBOX_WITH_NETFLT)
4809
4810 Bstr tmpAddr, tmpMask;
4811
4812 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPAddress",
4813 pszHostOnlyName).raw(),
4814 tmpAddr.asOutParam());
4815 if (SUCCEEDED(hrc) && !tmpAddr.isEmpty())
4816 {
4817 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPNetMask",
4818 pszHostOnlyName).raw(),
4819 tmpMask.asOutParam());
4820 if (SUCCEEDED(hrc) && !tmpMask.isEmpty())
4821 hrc = hostInterface->EnableStaticIPConfig(tmpAddr.raw(),
4822 tmpMask.raw());
4823 else
4824 hrc = hostInterface->EnableStaticIPConfig(tmpAddr.raw(),
4825 Bstr(VBOXNET_IPV4MASK_DEFAULT).raw());
4826 }
4827 else
4828 {
4829 /* Grab the IP number from the 'vboxnetX' instance number (see netif.h) */
4830 hrc = hostInterface->EnableStaticIPConfig(getDefaultIPv4Address(Bstr(pszHostOnlyName)).raw(),
4831 Bstr(VBOXNET_IPV4MASK_DEFAULT).raw());
4832 }
4833
4834 ComAssertComRC(hrc); /** @todo r=bird: Why this isn't fatal? (H()) */
4835
4836 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6Address",
4837 pszHostOnlyName).raw(),
4838 tmpAddr.asOutParam());
4839 if (SUCCEEDED(hrc))
4840 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6NetMask", pszHostOnlyName).raw(),
4841 tmpMask.asOutParam());
4842 if (SUCCEEDED(hrc) && !tmpAddr.isEmpty() && !tmpMask.isEmpty())
4843 {
4844 hrc = hostInterface->EnableStaticIPConfigV6(tmpAddr.raw(),
4845 Utf8Str(tmpMask).toUInt32());
4846 ComAssertComRC(hrc); /** @todo r=bird: Why this isn't fatal? (H()) */
4847 }
4848#endif
4849 break;
4850 }
4851
4852 case NetworkAttachmentType_Generic:
4853 {
4854 hrc = aNetworkAdapter->COMGETTER(GenericDriver)(bstr.asOutParam()); H();
4855 SafeArray<BSTR> names;
4856 SafeArray<BSTR> values;
4857 hrc = aNetworkAdapter->GetProperties(Bstr().raw(),
4858 ComSafeArrayAsOutParam(names),
4859 ComSafeArrayAsOutParam(values)); H();
4860
4861 InsertConfigString(pLunL0, "Driver", bstr);
4862 InsertConfigNode(pLunL0, "Config", &pCfg);
4863 for (size_t ii = 0; ii < names.size(); ++ii)
4864 {
4865 if (values[ii] && *values[ii])
4866 {
4867 Utf8Str name = names[ii];
4868 Utf8Str value = values[ii];
4869 InsertConfigString(pCfg, name.c_str(), value);
4870 }
4871 }
4872 break;
4873 }
4874
4875 default:
4876 AssertMsgFailed(("should not get here!\n"));
4877 break;
4878 }
4879
4880 /*
4881 * Attempt to attach the driver.
4882 */
4883 switch (eAttachmentType)
4884 {
4885 case NetworkAttachmentType_Null:
4886 break;
4887
4888 case NetworkAttachmentType_Bridged:
4889 case NetworkAttachmentType_Internal:
4890 case NetworkAttachmentType_HostOnly:
4891 case NetworkAttachmentType_NAT:
4892 case NetworkAttachmentType_Generic:
4893 {
4894 if (SUCCEEDED(hrc) && SUCCEEDED(rc))
4895 {
4896 if (fAttachDetach)
4897 {
4898 rc = PDMR3DriverAttach(mpUVM, pszDevice, uInstance, uLun, 0 /*fFlags*/, NULL /* ppBase */);
4899 //AssertRC(rc);
4900 }
4901
4902 {
4903 /** @todo pritesh: get the dhcp server name from the
4904 * previous network configuration and then stop the server
4905 * else it may conflict with the dhcp server running with
4906 * the current attachment type
4907 */
4908 /* Stop the hostonly DHCP Server */
4909 }
4910
4911 if (!networkName.isEmpty())
4912 {
4913 /*
4914 * Until we implement service reference counters DHCP Server will be stopped
4915 * by DHCPServerRunner destructor.
4916 */
4917 ComPtr<IDHCPServer> dhcpServer;
4918 hrc = virtualBox->FindDHCPServerByNetworkName(networkName.raw(),
4919 dhcpServer.asOutParam());
4920 if (SUCCEEDED(hrc))
4921 {
4922 /* there is a DHCP server available for this network */
4923 BOOL fEnabledDhcp;
4924 hrc = dhcpServer->COMGETTER(Enabled)(&fEnabledDhcp);
4925 if (FAILED(hrc))
4926 {
4927 LogRel(("DHCP svr: COMGETTER(Enabled) failed, hrc (%Rhrc)\n", hrc));
4928 H();
4929 }
4930
4931 if (fEnabledDhcp)
4932 hrc = dhcpServer->Start(networkName.raw(),
4933 trunkName.raw(),
4934 trunkType.raw());
4935 }
4936 else
4937 hrc = S_OK;
4938 }
4939 }
4940
4941 break;
4942 }
4943
4944 default:
4945 AssertMsgFailed(("should not get here!\n"));
4946 break;
4947 }
4948
4949 meAttachmentType[uInstance] = eAttachmentType;
4950 }
4951 catch (ConfigError &x)
4952 {
4953 // InsertConfig threw something:
4954 return x.m_vrc;
4955 }
4956
4957#undef H
4958
4959 return VINF_SUCCESS;
4960}
4961
4962#ifdef VBOX_WITH_GUEST_PROPS
4963/**
4964 * Set an array of guest properties
4965 */
4966static void configSetProperties(VMMDev * const pVMMDev,
4967 void *names,
4968 void *values,
4969 void *timestamps,
4970 void *flags)
4971{
4972 VBOXHGCMSVCPARM parms[4];
4973
4974 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
4975 parms[0].u.pointer.addr = names;
4976 parms[0].u.pointer.size = 0; /* We don't actually care. */
4977 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
4978 parms[1].u.pointer.addr = values;
4979 parms[1].u.pointer.size = 0; /* We don't actually care. */
4980 parms[2].type = VBOX_HGCM_SVC_PARM_PTR;
4981 parms[2].u.pointer.addr = timestamps;
4982 parms[2].u.pointer.size = 0; /* We don't actually care. */
4983 parms[3].type = VBOX_HGCM_SVC_PARM_PTR;
4984 parms[3].u.pointer.addr = flags;
4985 parms[3].u.pointer.size = 0; /* We don't actually care. */
4986
4987 pVMMDev->hgcmHostCall("VBoxGuestPropSvc",
4988 guestProp::SET_PROPS_HOST,
4989 4,
4990 &parms[0]);
4991}
4992
4993/**
4994 * Set a single guest property
4995 */
4996static void configSetProperty(VMMDev * const pVMMDev,
4997 const char *pszName,
4998 const char *pszValue,
4999 const char *pszFlags)
5000{
5001 VBOXHGCMSVCPARM parms[4];
5002
5003 AssertPtrReturnVoid(pszName);
5004 AssertPtrReturnVoid(pszValue);
5005 AssertPtrReturnVoid(pszFlags);
5006 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
5007 parms[0].u.pointer.addr = (void *)pszName;
5008 parms[0].u.pointer.size = (uint32_t)strlen(pszName) + 1;
5009 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
5010 parms[1].u.pointer.addr = (void *)pszValue;
5011 parms[1].u.pointer.size = (uint32_t)strlen(pszValue) + 1;
5012 parms[2].type = VBOX_HGCM_SVC_PARM_PTR;
5013 parms[2].u.pointer.addr = (void *)pszFlags;
5014 parms[2].u.pointer.size = (uint32_t)strlen(pszFlags) + 1;
5015 pVMMDev->hgcmHostCall("VBoxGuestPropSvc", guestProp::SET_PROP_HOST, 3,
5016 &parms[0]);
5017}
5018
5019/**
5020 * Set the global flags value by calling the service
5021 * @returns the status returned by the call to the service
5022 *
5023 * @param pTable the service instance handle
5024 * @param eFlags the flags to set
5025 */
5026int configSetGlobalPropertyFlags(VMMDev * const pVMMDev,
5027 guestProp::ePropFlags eFlags)
5028{
5029 VBOXHGCMSVCPARM paParm;
5030 paParm.setUInt32(eFlags);
5031 int rc = pVMMDev->hgcmHostCall("VBoxGuestPropSvc",
5032 guestProp::SET_GLOBAL_FLAGS_HOST, 1,
5033 &paParm);
5034 if (RT_FAILURE(rc))
5035 {
5036 char szFlags[guestProp::MAX_FLAGS_LEN];
5037 if (RT_FAILURE(writeFlags(eFlags, szFlags)))
5038 Log(("Failed to set the global flags.\n"));
5039 else
5040 Log(("Failed to set the global flags \"%s\".\n", szFlags));
5041 }
5042 return rc;
5043}
5044#endif /* VBOX_WITH_GUEST_PROPS */
5045
5046/**
5047 * Set up the Guest Property service, populate it with properties read from
5048 * the machine XML and set a couple of initial properties.
5049 */
5050/* static */ int Console::configGuestProperties(void *pvConsole, PUVM pUVM)
5051{
5052#ifdef VBOX_WITH_GUEST_PROPS
5053 AssertReturn(pvConsole, VERR_GENERAL_FAILURE);
5054 ComObjPtr<Console> pConsole = static_cast<Console *>(pvConsole);
5055 AssertReturn(pConsole->m_pVMMDev, VERR_GENERAL_FAILURE);
5056
5057 /* Load the service */
5058 int rc = pConsole->m_pVMMDev->hgcmLoadService("VBoxGuestPropSvc", "VBoxGuestPropSvc");
5059
5060 if (RT_FAILURE(rc))
5061 {
5062 LogRel(("VBoxGuestPropSvc is not available. rc = %Rrc\n", rc));
5063 /* That is not a fatal failure. */
5064 rc = VINF_SUCCESS;
5065 }
5066 else
5067 {
5068 /*
5069 * Initialize built-in properties that can be changed and saved.
5070 *
5071 * These are typically transient properties that the guest cannot
5072 * change.
5073 */
5074
5075 {
5076 VBOXHGCMSVCPARM Params[2];
5077 int rc2 = pConsole->m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", guestProp::GET_DBGF_INFO_FN, 2, &Params[0]);
5078 if (RT_SUCCESS(rc2))
5079 {
5080 PFNDBGFHANDLEREXT pfnHandler = (PFNDBGFHANDLEREXT)(uintptr_t)Params[0].u.pointer.addr;
5081 void *pService = (void*)Params[1].u.pointer.addr;
5082 DBGFR3InfoRegisterExternal(pUVM, "guestprops", "Display the guest properties", pfnHandler, pService);
5083 }
5084 }
5085
5086 /* Sysprep execution by VBoxService. */
5087 configSetProperty(pConsole->m_pVMMDev,
5088 "/VirtualBox/HostGuest/SysprepExec", "",
5089 "TRANSIENT, RDONLYGUEST");
5090 configSetProperty(pConsole->m_pVMMDev,
5091 "/VirtualBox/HostGuest/SysprepArgs", "",
5092 "TRANSIENT, RDONLYGUEST");
5093
5094 /*
5095 * Pull over the properties from the server.
5096 */
5097 SafeArray<BSTR> namesOut;
5098 SafeArray<BSTR> valuesOut;
5099 SafeArray<LONG64> timestampsOut;
5100 SafeArray<BSTR> flagsOut;
5101 HRESULT hrc;
5102 hrc = pConsole->mControl->PullGuestProperties(ComSafeArrayAsOutParam(namesOut),
5103 ComSafeArrayAsOutParam(valuesOut),
5104 ComSafeArrayAsOutParam(timestampsOut),
5105 ComSafeArrayAsOutParam(flagsOut));
5106 AssertMsgReturn(SUCCEEDED(hrc), ("hrc=%Rrc\n", hrc), VERR_GENERAL_FAILURE);
5107 size_t cProps = namesOut.size();
5108 size_t cAlloc = cProps + 1;
5109 if ( valuesOut.size() != cProps
5110 || timestampsOut.size() != cProps
5111 || flagsOut.size() != cProps
5112 )
5113 AssertFailedReturn(VERR_INVALID_PARAMETER);
5114
5115 char **papszNames, **papszValues, **papszFlags;
5116 char szEmpty[] = "";
5117 LONG64 *pai64Timestamps;
5118 papszNames = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
5119 papszValues = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
5120 pai64Timestamps = (LONG64 *)RTMemTmpAllocZ(sizeof(LONG64) * cAlloc);
5121 papszFlags = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
5122 if (papszNames && papszValues && pai64Timestamps && papszFlags)
5123 {
5124 for (unsigned i = 0; RT_SUCCESS(rc) && i < cProps; ++i)
5125 {
5126 AssertPtrReturn(namesOut[i], VERR_INVALID_PARAMETER);
5127 rc = RTUtf16ToUtf8(namesOut[i], &papszNames[i]);
5128 if (RT_FAILURE(rc))
5129 break;
5130 if (valuesOut[i])
5131 rc = RTUtf16ToUtf8(valuesOut[i], &papszValues[i]);
5132 else
5133 papszValues[i] = szEmpty;
5134 if (RT_FAILURE(rc))
5135 break;
5136 pai64Timestamps[i] = timestampsOut[i];
5137 if (flagsOut[i])
5138 rc = RTUtf16ToUtf8(flagsOut[i], &papszFlags[i]);
5139 else
5140 papszFlags[i] = szEmpty;
5141 }
5142 if (RT_SUCCESS(rc))
5143 configSetProperties(pConsole->m_pVMMDev,
5144 (void *)papszNames,
5145 (void *)papszValues,
5146 (void *)pai64Timestamps,
5147 (void *)papszFlags);
5148 for (unsigned i = 0; i < cProps; ++i)
5149 {
5150 RTStrFree(papszNames[i]);
5151 if (valuesOut[i])
5152 RTStrFree(papszValues[i]);
5153 if (flagsOut[i])
5154 RTStrFree(papszFlags[i]);
5155 }
5156 }
5157 else
5158 rc = VERR_NO_MEMORY;
5159 RTMemTmpFree(papszNames);
5160 RTMemTmpFree(papszValues);
5161 RTMemTmpFree(pai64Timestamps);
5162 RTMemTmpFree(papszFlags);
5163 AssertRCReturn(rc, rc);
5164
5165 /*
5166 * These properties have to be set before pulling over the properties
5167 * from the machine XML, to ensure that properties saved in the XML
5168 * will override them.
5169 */
5170 /* Set the raw VBox version string as a guest property. Used for host/guest
5171 * version comparison. */
5172 configSetProperty(pConsole->m_pVMMDev, "/VirtualBox/HostInfo/VBoxVer",
5173 VBOX_VERSION_STRING_RAW, "TRANSIENT, RDONLYGUEST");
5174 /* Set the full VBox version string as a guest property. Can contain vendor-specific
5175 * information/branding and/or pre-release tags. */
5176 configSetProperty(pConsole->m_pVMMDev, "/VirtualBox/HostInfo/VBoxVerExt",
5177 VBOX_VERSION_STRING, "TRANSIENT, RDONLYGUEST");
5178 /* Set the VBox SVN revision as a guest property */
5179 configSetProperty(pConsole->m_pVMMDev, "/VirtualBox/HostInfo/VBoxRev",
5180 RTBldCfgRevisionStr(), "TRANSIENT, RDONLYGUEST");
5181
5182 /*
5183 * Register the host notification callback
5184 */
5185 HGCMSVCEXTHANDLE hDummy;
5186 HGCMHostRegisterServiceExtension(&hDummy, "VBoxGuestPropSvc",
5187 Console::doGuestPropNotification,
5188 pvConsole);
5189
5190#ifdef VBOX_WITH_GUEST_PROPS_RDONLY_GUEST
5191 rc = configSetGlobalPropertyFlags(pConsole->m_pVMMDev,
5192 guestProp::RDONLYGUEST);
5193 AssertRCReturn(rc, rc);
5194#endif
5195
5196 Log(("Set VBoxGuestPropSvc property store\n"));
5197 }
5198 return VINF_SUCCESS;
5199#else /* !VBOX_WITH_GUEST_PROPS */
5200 return VERR_NOT_SUPPORTED;
5201#endif /* !VBOX_WITH_GUEST_PROPS */
5202}
5203
5204/**
5205 * Set up the Guest Control service.
5206 */
5207/* static */ int Console::configGuestControl(void *pvConsole)
5208{
5209#ifdef VBOX_WITH_GUEST_CONTROL
5210 AssertReturn(pvConsole, VERR_GENERAL_FAILURE);
5211 ComObjPtr<Console> pConsole = static_cast<Console *>(pvConsole);
5212
5213 /* Load the service */
5214 int rc = pConsole->m_pVMMDev->hgcmLoadService("VBoxGuestControlSvc", "VBoxGuestControlSvc");
5215
5216 if (RT_FAILURE(rc))
5217 {
5218 LogRel(("VBoxGuestControlSvc is not available. rc = %Rrc\n", rc));
5219 /* That is not a fatal failure. */
5220 rc = VINF_SUCCESS;
5221 }
5222 else
5223 {
5224 HGCMSVCEXTHANDLE hDummy;
5225 rc = HGCMHostRegisterServiceExtension(&hDummy, "VBoxGuestControlSvc",
5226 &Guest::notifyCtrlDispatcher,
5227 pConsole->getGuest());
5228 if (RT_FAILURE(rc))
5229 Log(("Cannot register VBoxGuestControlSvc extension!\n"));
5230 else
5231 Log(("VBoxGuestControlSvc loaded\n"));
5232 }
5233
5234 return rc;
5235#else /* !VBOX_WITH_GUEST_CONTROL */
5236 return VERR_NOT_SUPPORTED;
5237#endif /* !VBOX_WITH_GUEST_CONTROL */
5238}
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