VirtualBox

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

Last change on this file since 38399 was 38192, checked in by vboxsync, 14 years ago

Main: bits for debugging cardreader.

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