VirtualBox

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

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

Do HMR3Init first in vmR3InitRing3 so the other components can skip raw-mode bits during init.

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