VirtualBox

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

Last change on this file since 56088 was 56088, checked in by vboxsync, 10 years ago

pr6522. First part: added logic which allows to read\save audio properties in form key=value in VM xml setting file

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette