VirtualBox

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

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

Change implementation for turning a reset into a power off to prevent the VM from executing while the power down thread is not running

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