VirtualBox

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

Last change on this file since 38869 was 38702, checked in by vboxsync, 13 years ago

VSCSI+Main: Fix reporting non rotational medium status + set the CFGM key for SCSI devices

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