VirtualBox

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

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

Main/Console: OSX fix

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