VirtualBox

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

Last change on this file since 45890 was 45890, checked in by vboxsync, 12 years ago

Main: warnings

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