VirtualBox

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

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

ConsoleImpl2.cpp: Force HW-virt if 64-bit guest. Log force HW-virt decisions and some more.

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