VirtualBox

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

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

RT_STR_TUPLE

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