VirtualBox

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

Last change on this file since 35757 was 35753, checked in by vboxsync, 14 years ago

various nits.

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