VirtualBox

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

Last change on this file since 46969 was 46969, checked in by vboxsync, 11 years ago

backed out r86967,r86968,r86969,r86970,r86971,r86972,r86973,r86975,r86976.
will fix build locally.

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