VirtualBox

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

Last change on this file since 35722 was 35689, checked in by vboxsync, 14 years ago

Main: one more

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 192.4 KB
Line 
1/* $Id: ConsoleImpl2.cpp 35689 2011-01-24 16:13:19Z 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(pRoot, "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 InsertConfigNode(pDevices, "serial", &pDev);
1827 for (ULONG ulInstance = 0; ulInstance < SchemaDefs::SerialPortCount; ++ulInstance)
1828 {
1829 ComPtr<ISerialPort> serialPort;
1830 hrc = pMachine->GetSerialPort(ulInstance, serialPort.asOutParam()); H();
1831 BOOL fEnabled = FALSE;
1832 if (serialPort)
1833 hrc = serialPort->COMGETTER(Enabled)(&fEnabled); H();
1834 if (!fEnabled)
1835 continue;
1836
1837 InsertConfigNode(pDev, Utf8StrFmt("%u", ulInstance).c_str(), &pInst);
1838 InsertConfigNode(pInst, "Config", &pCfg);
1839
1840 ULONG ulIRQ;
1841 hrc = serialPort->COMGETTER(IRQ)(&ulIRQ); H();
1842 InsertConfigInteger(pCfg, "IRQ", ulIRQ);
1843 ULONG ulIOBase;
1844 hrc = serialPort->COMGETTER(IOBase)(&ulIOBase); H();
1845 InsertConfigInteger(pCfg, "IOBase", ulIOBase);
1846 BOOL fServer;
1847 hrc = serialPort->COMGETTER(Server)(&fServer); H();
1848 hrc = serialPort->COMGETTER(Path)(bstr.asOutParam()); H();
1849 PortMode_T eHostMode;
1850 hrc = serialPort->COMGETTER(HostMode)(&eHostMode); H();
1851 if (eHostMode != PortMode_Disconnected)
1852 {
1853 InsertConfigNode(pInst, "LUN#0", &pLunL0);
1854 if (eHostMode == PortMode_HostPipe)
1855 {
1856 InsertConfigString(pLunL0, "Driver", "Char");
1857 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
1858 InsertConfigString(pLunL1, "Driver", "NamedPipe");
1859 InsertConfigNode(pLunL1, "Config", &pLunL2);
1860 InsertConfigString(pLunL2, "Location", bstr);
1861 InsertConfigInteger(pLunL2, "IsServer", fServer);
1862 }
1863 else if (eHostMode == PortMode_HostDevice)
1864 {
1865 InsertConfigString(pLunL0, "Driver", "Host Serial");
1866 InsertConfigNode(pLunL0, "Config", &pLunL1);
1867 InsertConfigString(pLunL1, "DevicePath", bstr);
1868 }
1869 else if (eHostMode == PortMode_RawFile)
1870 {
1871 InsertConfigString(pLunL0, "Driver", "Char");
1872 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
1873 InsertConfigString(pLunL1, "Driver", "RawFile");
1874 InsertConfigNode(pLunL1, "Config", &pLunL2);
1875 InsertConfigString(pLunL2, "Location", bstr);
1876 }
1877 }
1878 }
1879
1880 /*
1881 * Parallel (LPT) Ports
1882 */
1883 InsertConfigNode(pDevices, "parallel", &pDev);
1884 for (ULONG ulInstance = 0; ulInstance < SchemaDefs::ParallelPortCount; ++ulInstance)
1885 {
1886 ComPtr<IParallelPort> parallelPort;
1887 hrc = pMachine->GetParallelPort(ulInstance, parallelPort.asOutParam()); H();
1888 BOOL fEnabled = FALSE;
1889 if (parallelPort)
1890 {
1891 hrc = parallelPort->COMGETTER(Enabled)(&fEnabled); H();
1892 }
1893 if (!fEnabled)
1894 continue;
1895
1896 InsertConfigNode(pDev, Utf8StrFmt("%u", ulInstance).c_str(), &pInst);
1897 InsertConfigNode(pInst, "Config", &pCfg);
1898
1899 ULONG ulIRQ;
1900 hrc = parallelPort->COMGETTER(IRQ)(&ulIRQ); H();
1901 InsertConfigInteger(pCfg, "IRQ", ulIRQ);
1902 ULONG ulIOBase;
1903 hrc = parallelPort->COMGETTER(IOBase)(&ulIOBase); H();
1904 InsertConfigInteger(pCfg, "IOBase", ulIOBase);
1905 InsertConfigNode(pInst, "LUN#0", &pLunL0);
1906 InsertConfigString(pLunL0, "Driver", "HostParallel");
1907 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
1908 hrc = parallelPort->COMGETTER(Path)(bstr.asOutParam()); H();
1909 InsertConfigString(pLunL1, "DevicePath", bstr);
1910 }
1911
1912 /*
1913 * VMM Device
1914 */
1915 InsertConfigNode(pDevices, "VMMDev", &pDev);
1916 InsertConfigNode(pDev, "0", &pInst);
1917 InsertConfigNode(pInst, "Config", &pCfg);
1918 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1919 hrc = BusMgr->assignPciDevice("VMMDev", pInst); H();
1920
1921 Bstr hwVersion;
1922 hrc = pMachine->COMGETTER(HardwareVersion)(hwVersion.asOutParam()); H();
1923 InsertConfigInteger(pCfg, "RamSize", cbRam);
1924 if (hwVersion.compare(Bstr("1").raw()) == 0) /* <= 2.0.x */
1925 InsertConfigInteger(pCfg, "HeapEnabled", 0);
1926 Bstr snapshotFolder;
1927 hrc = pMachine->COMGETTER(SnapshotFolder)(snapshotFolder.asOutParam()); H();
1928 InsertConfigString(pCfg, "GuestCoreDumpDir", snapshotFolder);
1929
1930 /* the VMM device's Main driver */
1931 InsertConfigNode(pInst, "LUN#0", &pLunL0);
1932 InsertConfigString(pLunL0, "Driver", "HGCM");
1933 InsertConfigNode(pLunL0, "Config", &pCfg);
1934 InsertConfigInteger(pCfg, "Object", (uintptr_t)pVMMDev);
1935
1936 /*
1937 * Attach the status driver.
1938 */
1939 InsertConfigNode(pInst, "LUN#999", &pLunL0);
1940 InsertConfigString(pLunL0, "Driver", "MainStatus");
1941 InsertConfigNode(pLunL0, "Config", &pCfg);
1942 InsertConfigInteger(pCfg, "papLeds", (uintptr_t)&pConsole->mapSharedFolderLed);
1943 InsertConfigInteger(pCfg, "First", 0);
1944 InsertConfigInteger(pCfg, "Last", 0);
1945
1946 /*
1947 * Audio Sniffer Device
1948 */
1949 InsertConfigNode(pDevices, "AudioSniffer", &pDev);
1950 InsertConfigNode(pDev, "0", &pInst);
1951 InsertConfigNode(pInst, "Config", &pCfg);
1952
1953 /* the Audio Sniffer device's Main driver */
1954 InsertConfigNode(pInst, "LUN#0", &pLunL0);
1955 InsertConfigString(pLunL0, "Driver", "MainAudioSniffer");
1956 InsertConfigNode(pLunL0, "Config", &pCfg);
1957 AudioSniffer *pAudioSniffer = pConsole->mAudioSniffer;
1958 InsertConfigInteger(pCfg, "Object", (uintptr_t)pAudioSniffer);
1959
1960 /*
1961 * AC'97 ICH / SoundBlaster16 audio / Intel HD Audio
1962 */
1963 BOOL fAudioEnabled;
1964 ComPtr<IAudioAdapter> audioAdapter;
1965 hrc = pMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam()); H();
1966 if (audioAdapter)
1967 hrc = audioAdapter->COMGETTER(Enabled)(&fAudioEnabled); H();
1968
1969 if (fAudioEnabled)
1970 {
1971 AudioControllerType_T audioController;
1972 hrc = audioAdapter->COMGETTER(AudioController)(&audioController); H();
1973 switch (audioController)
1974 {
1975 case AudioControllerType_AC97:
1976 {
1977 /* default: ICH AC97 */
1978 InsertConfigNode(pDevices, "ichac97", &pDev);
1979 InsertConfigNode(pDev, "0", &pInst);
1980 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1981 hrc = BusMgr->assignPciDevice("ichac97", pInst); H();
1982 InsertConfigNode(pInst, "Config", &pCfg);
1983 break;
1984 }
1985 case AudioControllerType_SB16:
1986 {
1987 /* legacy SoundBlaster16 */
1988 InsertConfigNode(pDevices, "sb16", &pDev);
1989 InsertConfigNode(pDev, "0", &pInst);
1990 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
1991 InsertConfigNode(pInst, "Config", &pCfg);
1992 InsertConfigInteger(pCfg, "IRQ", 5);
1993 InsertConfigInteger(pCfg, "DMA", 1);
1994 InsertConfigInteger(pCfg, "DMA16", 5);
1995 InsertConfigInteger(pCfg, "Port", 0x220);
1996 InsertConfigInteger(pCfg, "Version", 0x0405);
1997 break;
1998 }
1999 case AudioControllerType_HDA:
2000 {
2001 /* Intel HD Audio */
2002 InsertConfigNode(pDevices, "hda", &pDev);
2003 InsertConfigNode(pDev, "0", &pInst);
2004 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2005 hrc = BusMgr->assignPciDevice("hda", pInst); H();
2006 InsertConfigNode(pInst, "Config", &pCfg);
2007 }
2008 }
2009
2010 /* the Audio driver */
2011 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2012 InsertConfigString(pLunL0, "Driver", "AUDIO");
2013 InsertConfigNode(pLunL0, "Config", &pCfg);
2014
2015 AudioDriverType_T audioDriver;
2016 hrc = audioAdapter->COMGETTER(AudioDriver)(&audioDriver); H();
2017 switch (audioDriver)
2018 {
2019 case AudioDriverType_Null:
2020 {
2021 InsertConfigString(pCfg, "AudioDriver", "null");
2022 break;
2023 }
2024#ifdef RT_OS_WINDOWS
2025#ifdef VBOX_WITH_WINMM
2026 case AudioDriverType_WinMM:
2027 {
2028 InsertConfigString(pCfg, "AudioDriver", "winmm");
2029 break;
2030 }
2031#endif
2032 case AudioDriverType_DirectSound:
2033 {
2034 InsertConfigString(pCfg, "AudioDriver", "dsound");
2035 break;
2036 }
2037#endif /* RT_OS_WINDOWS */
2038#ifdef RT_OS_SOLARIS
2039 case AudioDriverType_SolAudio:
2040 {
2041 InsertConfigString(pCfg, "AudioDriver", "solaudio");
2042 break;
2043 }
2044#endif
2045#ifdef RT_OS_LINUX
2046# ifdef VBOX_WITH_ALSA
2047 case AudioDriverType_ALSA:
2048 {
2049 InsertConfigString(pCfg, "AudioDriver", "alsa");
2050 break;
2051 }
2052# endif
2053# ifdef VBOX_WITH_PULSE
2054 case AudioDriverType_Pulse:
2055 {
2056 InsertConfigString(pCfg, "AudioDriver", "pulse");
2057 break;
2058 }
2059# endif
2060#endif /* RT_OS_LINUX */
2061#if defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD) || defined(VBOX_WITH_SOLARIS_OSS)
2062 case AudioDriverType_OSS:
2063 {
2064 InsertConfigString(pCfg, "AudioDriver", "oss");
2065 break;
2066 }
2067#endif
2068#ifdef RT_OS_FREEBSD
2069# ifdef VBOX_WITH_PULSE
2070 case AudioDriverType_Pulse:
2071 {
2072 InsertConfigString(pCfg, "AudioDriver", "pulse");
2073 break;
2074 }
2075# endif
2076#endif
2077#ifdef RT_OS_DARWIN
2078 case AudioDriverType_CoreAudio:
2079 {
2080 InsertConfigString(pCfg, "AudioDriver", "coreaudio");
2081 break;
2082 }
2083#endif
2084 }
2085 hrc = pMachine->COMGETTER(Name)(bstr.asOutParam()); H();
2086 InsertConfigString(pCfg, "StreamName", bstr);
2087 }
2088
2089 /*
2090 * The USB Controller.
2091 */
2092 ComPtr<IUSBController> USBCtlPtr;
2093 hrc = pMachine->COMGETTER(USBController)(USBCtlPtr.asOutParam());
2094 if (USBCtlPtr)
2095 {
2096 BOOL fOhciEnabled;
2097 hrc = USBCtlPtr->COMGETTER(Enabled)(&fOhciEnabled); H();
2098 if (fOhciEnabled)
2099 {
2100 InsertConfigNode(pDevices, "usb-ohci", &pDev);
2101 InsertConfigNode(pDev, "0", &pInst);
2102 InsertConfigNode(pInst, "Config", &pCfg);
2103 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2104 hrc = BusMgr->assignPciDevice("usb-ohci", pInst); H();
2105 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2106 InsertConfigString(pLunL0, "Driver", "VUSBRootHub");
2107 InsertConfigNode(pLunL0, "Config", &pCfg);
2108
2109 /*
2110 * Attach the status driver.
2111 */
2112 InsertConfigNode(pInst, "LUN#999", &pLunL0);
2113 InsertConfigString(pLunL0, "Driver", "MainStatus");
2114 InsertConfigNode(pLunL0, "Config", &pCfg);
2115 InsertConfigInteger(pCfg, "papLeds", (uintptr_t)&pConsole->mapUSBLed[0]);
2116 InsertConfigInteger(pCfg, "First", 0);
2117 InsertConfigInteger(pCfg, "Last", 0);
2118
2119#ifdef VBOX_WITH_EHCI
2120 BOOL fEhciEnabled;
2121 hrc = USBCtlPtr->COMGETTER(EnabledEhci)(&fEhciEnabled); H();
2122 if (fEhciEnabled)
2123 {
2124 /*
2125 * USB 2.0 is only available if the proper ExtPack is installed.
2126 *
2127 * Note. Configuring EHCI here and providing messages about
2128 * the missing extpack isn't exactly clean, but it is a
2129 * necessary evil to patch over legacy compatability issues
2130 * introduced by the new distribution model.
2131 */
2132 static const char *s_pszUsbExtPackName = "Oracle VM VirtualBox Extension Pack";
2133# ifdef VBOX_WITH_EXTPACK
2134 if (pConsole->mptrExtPackManager->isExtPackUsable(s_pszUsbExtPackName))
2135# endif
2136 {
2137 InsertConfigNode(pDevices, "usb-ehci", &pDev);
2138 InsertConfigNode(pDev, "0", &pInst);
2139 InsertConfigNode(pInst, "Config", &pCfg);
2140 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2141 hrc = BusMgr->assignPciDevice("usb-ehci", pInst); H();
2142
2143 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2144 InsertConfigString(pLunL0, "Driver", "VUSBRootHub");
2145 InsertConfigNode(pLunL0, "Config", &pCfg);
2146
2147 /*
2148 * Attach the status driver.
2149 */
2150 InsertConfigNode(pInst, "LUN#999", &pLunL0);
2151 InsertConfigString(pLunL0, "Driver", "MainStatus");
2152 InsertConfigNode(pLunL0, "Config", &pCfg);
2153 InsertConfigInteger(pCfg, "papLeds", (uintptr_t)&pConsole->mapUSBLed[1]);
2154 InsertConfigInteger(pCfg, "First", 0);
2155 InsertConfigInteger(pCfg, "Last", 0);
2156 }
2157# ifdef VBOX_WITH_EXTPACK
2158 else
2159 {
2160 /* Fatal if a saved state is being restored, otherwise ignorable. */
2161 if (pConsole->mMachineState == MachineState_Restoring)
2162 return VMSetError(pVM, VERR_NOT_FOUND, RT_SRC_POS,
2163 N_("Implementation of the USB 2.0 controller not found!\n"
2164 "Because the USB 2.0 controller state is part of the saved "
2165 "VM state, the VM cannot be started. To fix "
2166 "this problem, either install the '%s' or disable USB 2.0 "
2167 "support in the VM settings"),
2168 s_pszUsbExtPackName);
2169 setVMRuntimeErrorCallbackF(pVM, pConsole, 0, "ExtPackNoEhci",
2170 N_("Implementation of the USB 2.0 controller not found!\n"
2171 "The device will be disabled. You can ignore this warning "
2172 "but there will be no USB 2.0 support in your VM. To fix "
2173 "this issue, either install the '%s' or disable USB 2.0 "
2174 "support in the VM settings"),
2175 s_pszUsbExtPackName);
2176 }
2177# endif
2178 }
2179#endif
2180
2181 /*
2182 * Virtual USB Devices.
2183 */
2184 PCFGMNODE pUsbDevices = NULL;
2185 InsertConfigNode(pRoot, "USB", &pUsbDevices);
2186
2187#ifdef VBOX_WITH_USB
2188 {
2189 /*
2190 * Global USB options, currently unused as we'll apply the 2.0 -> 1.1 morphing
2191 * on a per device level now.
2192 */
2193 InsertConfigNode(pUsbDevices, "USBProxy", &pCfg);
2194 InsertConfigNode(pCfg, "GlobalConfig", &pCfg);
2195 // This globally enables the 2.0 -> 1.1 device morphing of proxied devices to keep windows quiet.
2196 //InsertConfigInteger(pCfg, "Force11Device", true);
2197 // The following breaks stuff, but it makes MSDs work in vista. (I include it here so
2198 // that it's documented somewhere.) Users needing it can use:
2199 // VBoxManage setextradata "myvm" "VBoxInternal/USB/USBProxy/GlobalConfig/Force11PacketSize" 1
2200 //InsertConfigInteger(pCfg, "Force11PacketSize", true);
2201 }
2202#endif
2203
2204# if 0 /* Virtual MSD*/
2205
2206 InsertConfigNode(pUsbDevices, "Msd", &pDev);
2207 InsertConfigNode(pDev, "0", &pInst);
2208 InsertConfigNode(pInst, "Config", &pCfg);
2209 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2210
2211 InsertConfigString(pLunL0, "Driver", "SCSI");
2212 InsertConfigNode(pLunL0, "Config", &pCfg);
2213
2214 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2215 InsertConfigString(pLunL1, "Driver", "Block");
2216 InsertConfigNode(pLunL1, "Config", &pCfg);
2217 InsertConfigString(pCfg, "Type", "HardDisk");
2218 InsertConfigInteger(pCfg, "Mountable", 0);
2219
2220 InsertConfigNode(pLunL1, "AttachedDriver", &pLunL2);
2221 InsertConfigString(pLunL2, "Driver", "VD");
2222 InsertConfigNode(pLunL2, "Config", &pCfg);
2223 InsertConfigString(pCfg, "Path", "/Volumes/DataHFS/bird/VDIs/linux.vdi");
2224 InsertConfigString(pCfg, "Format", "VDI");
2225# endif
2226
2227 /* Virtual USB Mouse/Tablet */
2228 PointingHidType_T aPointingHid;
2229 hrc = pMachine->COMGETTER(PointingHidType)(&aPointingHid); H();
2230 if (aPointingHid == PointingHidType_USBMouse || aPointingHid == PointingHidType_USBTablet)
2231 {
2232 InsertConfigNode(pUsbDevices, "HidMouse", &pDev);
2233 InsertConfigNode(pDev, "0", &pInst);
2234 InsertConfigNode(pInst, "Config", &pCfg);
2235
2236 if (aPointingHid == PointingHidType_USBTablet)
2237 {
2238 InsertConfigInteger(pCfg, "Absolute", 1);
2239 }
2240 else
2241 {
2242 InsertConfigInteger(pCfg, "Absolute", 0);
2243 }
2244 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2245 InsertConfigString(pLunL0, "Driver", "MouseQueue");
2246 InsertConfigNode(pLunL0, "Config", &pCfg);
2247 InsertConfigInteger(pCfg, "QueueSize", 128);
2248
2249 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2250 InsertConfigString(pLunL1, "Driver", "MainMouse");
2251 InsertConfigNode(pLunL1, "Config", &pCfg);
2252 pMouse = pConsole->mMouse;
2253 InsertConfigInteger(pCfg, "Object", (uintptr_t)pMouse);
2254 }
2255
2256 /* Virtual USB Keyboard */
2257 KeyboardHidType_T aKbdHid;
2258 hrc = pMachine->COMGETTER(KeyboardHidType)(&aKbdHid); H();
2259 if (aKbdHid == KeyboardHidType_USBKeyboard)
2260 {
2261 InsertConfigNode(pUsbDevices, "HidKeyboard", &pDev);
2262 InsertConfigNode(pDev, "0", &pInst);
2263 InsertConfigNode(pInst, "Config", &pCfg);
2264
2265 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2266 InsertConfigString(pLunL0, "Driver", "KeyboardQueue");
2267 InsertConfigNode(pLunL0, "Config", &pCfg);
2268 InsertConfigInteger(pCfg, "QueueSize", 64);
2269
2270 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
2271 InsertConfigString(pLunL1, "Driver", "MainKeyboard");
2272 InsertConfigNode(pLunL1, "Config", &pCfg);
2273 pKeyboard = pConsole->mKeyboard;
2274 InsertConfigInteger(pCfg, "Object", (uintptr_t)pKeyboard);
2275 }
2276 }
2277 }
2278
2279 /*
2280 * Clipboard
2281 */
2282 {
2283 ClipboardMode_T mode = ClipboardMode_Disabled;
2284 hrc = pMachine->COMGETTER(ClipboardMode)(&mode); H();
2285
2286 if (mode != ClipboardMode_Disabled)
2287 {
2288 /* Load the service */
2289 rc = pVMMDev->hgcmLoadService("VBoxSharedClipboard", "VBoxSharedClipboard");
2290
2291 if (RT_FAILURE(rc))
2292 {
2293 LogRel(("VBoxSharedClipboard is not available. rc = %Rrc\n", rc));
2294 /* That is not a fatal failure. */
2295 rc = VINF_SUCCESS;
2296 }
2297 else
2298 {
2299 /* Setup the service. */
2300 VBOXHGCMSVCPARM parm;
2301
2302 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
2303
2304 switch (mode)
2305 {
2306 default:
2307 case ClipboardMode_Disabled:
2308 {
2309 LogRel(("VBoxSharedClipboard mode: Off\n"));
2310 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_OFF;
2311 break;
2312 }
2313 case ClipboardMode_GuestToHost:
2314 {
2315 LogRel(("VBoxSharedClipboard mode: Guest to Host\n"));
2316 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_GUEST_TO_HOST;
2317 break;
2318 }
2319 case ClipboardMode_HostToGuest:
2320 {
2321 LogRel(("VBoxSharedClipboard mode: Host to Guest\n"));
2322 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_HOST_TO_GUEST;
2323 break;
2324 }
2325 case ClipboardMode_Bidirectional:
2326 {
2327 LogRel(("VBoxSharedClipboard mode: Bidirectional\n"));
2328 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_BIDIRECTIONAL;
2329 break;
2330 }
2331 }
2332
2333 pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE, 1, &parm);
2334
2335 Log(("Set VBoxSharedClipboard mode\n"));
2336 }
2337 }
2338 }
2339
2340#ifdef VBOX_WITH_CROGL
2341 /*
2342 * crOpenGL
2343 */
2344 {
2345 BOOL fEnabled = false;
2346 hrc = pMachine->COMGETTER(Accelerate3DEnabled)(&fEnabled); H();
2347
2348 if (fEnabled)
2349 {
2350 /* Load the service */
2351 rc = pVMMDev->hgcmLoadService("VBoxSharedCrOpenGL", "VBoxSharedCrOpenGL");
2352 if (RT_FAILURE(rc))
2353 {
2354 LogRel(("Failed to load Shared OpenGL service %Rrc\n", rc));
2355 /* That is not a fatal failure. */
2356 rc = VINF_SUCCESS;
2357 }
2358 else
2359 {
2360 LogRel(("Shared crOpenGL service loaded.\n"));
2361
2362 /* Setup the service. */
2363 VBOXHGCMSVCPARM parm;
2364 parm.type = VBOX_HGCM_SVC_PARM_PTR;
2365
2366 parm.u.pointer.addr = (IConsole*) (Console*) pConsole;
2367 parm.u.pointer.size = sizeof(IConsole *);
2368
2369 rc = pVMMDev->hgcmHostCall("VBoxSharedCrOpenGL", SHCRGL_HOST_FN_SET_CONSOLE, SHCRGL_CPARMS_SET_CONSOLE, &parm);
2370 if (!RT_SUCCESS(rc))
2371 AssertMsgFailed(("SHCRGL_HOST_FN_SET_CONSOLE failed with %Rrc\n", rc));
2372
2373 parm.u.pointer.addr = pVM;
2374 parm.u.pointer.size = sizeof(pVM);
2375 rc = pVMMDev->hgcmHostCall("VBoxSharedCrOpenGL", SHCRGL_HOST_FN_SET_VM, SHCRGL_CPARMS_SET_VM, &parm);
2376 if (!RT_SUCCESS(rc))
2377 AssertMsgFailed(("SHCRGL_HOST_FN_SET_VM failed with %Rrc\n", rc));
2378 }
2379
2380 }
2381 }
2382#endif
2383
2384#ifdef VBOX_WITH_GUEST_PROPS
2385 /*
2386 * Guest property service
2387 */
2388
2389 rc = configGuestProperties(pConsole);
2390#endif /* VBOX_WITH_GUEST_PROPS defined */
2391
2392#ifdef VBOX_WITH_GUEST_CONTROL
2393 /*
2394 * Guest control service
2395 */
2396
2397 rc = configGuestControl(pConsole);
2398#endif /* VBOX_WITH_GUEST_CONTROL defined */
2399
2400 /*
2401 * ACPI
2402 */
2403 BOOL fACPI;
2404 hrc = biosSettings->COMGETTER(ACPIEnabled)(&fACPI); H();
2405 if (fACPI)
2406 {
2407 BOOL fCpuHotPlug = false;
2408 BOOL fShowCpu = fOsXGuest;
2409 /* Always show the CPU leafs when we have multiple VCPUs or when the IO-APIC is enabled.
2410 * The Windows SMP kernel needs a CPU leaf or else its idle loop will burn cpu cycles; the
2411 * intelppm driver refuses to register an idle state handler.
2412 */
2413 if ((cCpus > 1) || fIOAPIC)
2414 fShowCpu = true;
2415
2416 hrc = pMachine->COMGETTER(CPUHotPlugEnabled)(&fCpuHotPlug); H();
2417
2418 InsertConfigNode(pDevices, "acpi", &pDev);
2419 InsertConfigNode(pDev, "0", &pInst);
2420 InsertConfigInteger(pInst, "Trusted", 1); /* boolean */
2421 InsertConfigNode(pInst, "Config", &pCfg);
2422 hrc = BusMgr->assignPciDevice("acpi", pInst); H();
2423
2424 InsertConfigInteger(pCfg, "RamSize", cbRam);
2425 InsertConfigInteger(pCfg, "RamHoleSize", cbRamHole);
2426 InsertConfigInteger(pCfg, "NumCPUs", cCpus);
2427
2428 InsertConfigInteger(pCfg, "IOAPIC", fIOAPIC);
2429 InsertConfigInteger(pCfg, "FdcEnabled", fFdcEnabled);
2430 InsertConfigInteger(pCfg, "HpetEnabled", fHpetEnabled);
2431 InsertConfigInteger(pCfg, "SmcEnabled", fSmcEnabled);
2432 InsertConfigInteger(pCfg, "ShowRtc", fShowRtc);
2433 if (fOsXGuest && !llBootNics.empty())
2434 {
2435 BootNic aNic = llBootNics.front();
2436 uint32_t u32NicPciAddr = (aNic.mPciAddress.iDevice << 16) | aNic.mPciAddress.iFn;
2437 InsertConfigInteger(pCfg, "NicPciAddress", u32NicPciAddr);
2438 }
2439 if (fOsXGuest && fAudioEnabled)
2440 {
2441 PciBusAddress Address;
2442 if (BusMgr->findPciAddress("hda", 0, Address))
2443 {
2444 uint32_t u32AudioPciAddr = (Address.iDevice << 16) | Address.iFn;
2445 InsertConfigInteger(pCfg, "AudioPciAddress", u32AudioPciAddr);
2446 }
2447 }
2448 InsertConfigInteger(pCfg, "IocPciAddress", u32IocPciAddress);
2449 if (chipsetType == ChipsetType_ICH9)
2450 {
2451 InsertConfigInteger(pCfg, "McfgBase", u64McfgBase);
2452 InsertConfigInteger(pCfg, "McfgLength", u32McfgLength);
2453 }
2454 InsertConfigInteger(pCfg, "HostBusPciAddress", u32HbcPciAddress);
2455 InsertConfigInteger(pCfg, "ShowCpu", fShowCpu);
2456 InsertConfigInteger(pCfg, "CpuHotPlug", fCpuHotPlug);
2457
2458 InsertConfigNode(pInst, "LUN#0", &pLunL0);
2459 InsertConfigString(pLunL0, "Driver", "ACPIHost");
2460 InsertConfigNode(pLunL0, "Config", &pCfg);
2461
2462 /* Attach the dummy CPU drivers */
2463 for (ULONG iCpuCurr = 1; iCpuCurr < cCpus; iCpuCurr++)
2464 {
2465 BOOL fCpuAttached = true;
2466
2467 if (fCpuHotPlug)
2468 {
2469 hrc = pMachine->GetCPUStatus(iCpuCurr, &fCpuAttached); H();
2470 }
2471
2472 if (fCpuAttached)
2473 {
2474 InsertConfigNode(pInst, Utf8StrFmt("LUN#%u", iCpuCurr).c_str(), &pLunL0);
2475 InsertConfigString(pLunL0, "Driver", "ACPICpu");
2476 InsertConfigNode(pLunL0, "Config", &pCfg);
2477 }
2478 }
2479 }
2480 }
2481 catch (ConfigError &x)
2482 {
2483 // InsertConfig threw something:
2484 return x.m_vrc;
2485 }
2486
2487#ifdef VBOX_WITH_EXTPACK
2488 /*
2489 * Call the extension pack hooks if everything went well thus far.
2490 */
2491 if (RT_SUCCESS(rc))
2492 {
2493 alock.release();
2494 rc = pConsole->mptrExtPackManager->callAllVmConfigureVmmHooks(pConsole, pVM);
2495 alock.acquire();
2496 }
2497#endif
2498
2499 /*
2500 * Apply the CFGM overlay.
2501 */
2502 if (RT_SUCCESS(rc))
2503 rc = pConsole->configCfgmOverlay(pVM, virtualBox, pMachine);
2504
2505#undef H
2506
2507 /*
2508 * Register VM state change handler.
2509 */
2510 int rc2 = VMR3AtStateRegister(pVM, Console::vmstateChangeCallback, pConsole);
2511 AssertRC(rc2);
2512 if (RT_SUCCESS(rc))
2513 rc = rc2;
2514
2515 /*
2516 * Register VM runtime error handler.
2517 */
2518 rc2 = VMR3AtRuntimeErrorRegister(pVM, Console::setVMRuntimeErrorCallback, pConsole);
2519 AssertRC(rc2);
2520 if (RT_SUCCESS(rc))
2521 rc = rc2;
2522
2523 LogFlowFunc(("vrc = %Rrc\n", rc));
2524 LogFlowFuncLeave();
2525
2526 return rc;
2527}
2528
2529/**
2530 * Applies the CFGM overlay as specified by /VBoxInternal/XXX extra data
2531 * values.
2532 *
2533 * @returns VBox status code.
2534 * @param pVM The VM handle.
2535 * @param pVirtualBox Pointer to the IVirtualBox interface.
2536 * @param pMachine Pointer to the IMachine interface.
2537 */
2538/* static */
2539int Console::configCfgmOverlay(PVM pVM, IVirtualBox *pVirtualBox, IMachine *pMachine)
2540{
2541 /*
2542 * CFGM overlay handling.
2543 *
2544 * Here we check the extra data entries for CFGM values
2545 * and create the nodes and insert the values on the fly. Existing
2546 * values will be removed and reinserted. CFGM is typed, so by default
2547 * we will guess whether it's a string or an integer (byte arrays are
2548 * not currently supported). It's possible to override this autodetection
2549 * by adding "string:", "integer:" or "bytes:" (future).
2550 *
2551 * We first perform a run on global extra data, then on the machine
2552 * extra data to support global settings with local overrides.
2553 */
2554 PCFGMNODE pRoot = CFGMR3GetRoot(pVM);
2555 int rc = VINF_SUCCESS;
2556 try
2557 {
2558 /** @todo add support for removing nodes and byte blobs. */
2559 /*
2560 * Get the next key
2561 */
2562 SafeArray<BSTR> aGlobalExtraDataKeys;
2563 SafeArray<BSTR> aMachineExtraDataKeys;
2564 HRESULT hrc = pVirtualBox->GetExtraDataKeys(ComSafeArrayAsOutParam(aGlobalExtraDataKeys));
2565 AssertMsg(SUCCEEDED(hrc), ("VirtualBox::GetExtraDataKeys failed with %Rhrc\n", hrc));
2566
2567 // remember the no. of global values so we can call the correct method below
2568 size_t cGlobalValues = aGlobalExtraDataKeys.size();
2569
2570 hrc = pMachine->GetExtraDataKeys(ComSafeArrayAsOutParam(aMachineExtraDataKeys));
2571 AssertMsg(SUCCEEDED(hrc), ("VirtualBox::GetExtraDataKeys failed with %Rhrc\n", hrc));
2572
2573 // build a combined list from global keys...
2574 std::list<Utf8Str> llExtraDataKeys;
2575
2576 for (size_t i = 0; i < aGlobalExtraDataKeys.size(); ++i)
2577 llExtraDataKeys.push_back(Utf8Str(aGlobalExtraDataKeys[i]));
2578 // ... and machine keys
2579 for (size_t i = 0; i < aMachineExtraDataKeys.size(); ++i)
2580 llExtraDataKeys.push_back(Utf8Str(aMachineExtraDataKeys[i]));
2581
2582 size_t i2 = 0;
2583 for (std::list<Utf8Str>::const_iterator it = llExtraDataKeys.begin();
2584 it != llExtraDataKeys.end();
2585 ++it, ++i2)
2586 {
2587 const Utf8Str &strKey = *it;
2588
2589 /*
2590 * We only care about keys starting with "VBoxInternal/" (skip "G:" or "M:")
2591 */
2592 if (!strKey.startsWith("VBoxInternal/"))
2593 continue;
2594
2595 const char *pszExtraDataKey = strKey.c_str() + sizeof("VBoxInternal/") - 1;
2596
2597 // get the value
2598 Bstr bstrExtraDataValue;
2599 if (i2 < cGlobalValues)
2600 // this is still one of the global values:
2601 hrc = pVirtualBox->GetExtraData(Bstr(strKey).raw(),
2602 bstrExtraDataValue.asOutParam());
2603 else
2604 hrc = pMachine->GetExtraData(Bstr(strKey).raw(),
2605 bstrExtraDataValue.asOutParam());
2606 if (FAILED(hrc))
2607 LogRel(("Warning: Cannot get extra data key %s, rc = %Rrc\n", strKey.c_str(), hrc));
2608
2609 /*
2610 * The key will be in the format "Node1/Node2/Value" or simply "Value".
2611 * Split the two and get the node, delete the value and create the node
2612 * if necessary.
2613 */
2614 PCFGMNODE pNode;
2615 const char *pszCFGMValueName = strrchr(pszExtraDataKey, '/');
2616 if (pszCFGMValueName)
2617 {
2618 /* terminate the node and advance to the value (Utf8Str might not
2619 offically like this but wtf) */
2620 *(char*)pszCFGMValueName = '\0';
2621 ++pszCFGMValueName;
2622
2623 /* does the node already exist? */
2624 pNode = CFGMR3GetChild(pRoot, pszExtraDataKey);
2625 if (pNode)
2626 CFGMR3RemoveValue(pNode, pszCFGMValueName);
2627 else
2628 {
2629 /* create the node */
2630 rc = CFGMR3InsertNode(pRoot, pszExtraDataKey, &pNode);
2631 if (RT_FAILURE(rc))
2632 {
2633 AssertLogRelMsgRC(rc, ("failed to insert node '%s'\n", pszExtraDataKey));
2634 continue;
2635 }
2636 Assert(pNode);
2637 }
2638 }
2639 else
2640 {
2641 /* root value (no node path). */
2642 pNode = pRoot;
2643 pszCFGMValueName = pszExtraDataKey;
2644 pszExtraDataKey--;
2645 CFGMR3RemoveValue(pNode, pszCFGMValueName);
2646 }
2647
2648 /*
2649 * Now let's have a look at the value.
2650 * Empty strings means that we should remove the value, which we've
2651 * already done above.
2652 */
2653 Utf8Str strCFGMValueUtf8(bstrExtraDataValue);
2654 if (!strCFGMValueUtf8.isEmpty())
2655 {
2656 uint64_t u64Value;
2657
2658 /* check for type prefix first. */
2659 if (!strncmp(strCFGMValueUtf8.c_str(), "string:", sizeof("string:") - 1))
2660 InsertConfigString(pNode, pszCFGMValueName, strCFGMValueUtf8.c_str() + sizeof("string:") - 1);
2661 else if (!strncmp(strCFGMValueUtf8.c_str(), "integer:", sizeof("integer:") - 1))
2662 {
2663 rc = RTStrToUInt64Full(strCFGMValueUtf8.c_str() + sizeof("integer:") - 1, 0, &u64Value);
2664 if (RT_SUCCESS(rc))
2665 rc = CFGMR3InsertInteger(pNode, pszCFGMValueName, u64Value);
2666 }
2667 else if (!strncmp(strCFGMValueUtf8.c_str(), "bytes:", sizeof("bytes:") - 1))
2668 rc = VERR_NOT_IMPLEMENTED;
2669 /* auto detect type. */
2670 else if (RT_SUCCESS(RTStrToUInt64Full(strCFGMValueUtf8.c_str(), 0, &u64Value)))
2671 rc = CFGMR3InsertInteger(pNode, pszCFGMValueName, u64Value);
2672 else
2673 InsertConfigString(pNode, pszCFGMValueName, strCFGMValueUtf8);
2674 AssertLogRelMsgRCBreak(rc, ("failed to insert CFGM value '%s' to key '%s'\n", strCFGMValueUtf8.c_str(), pszExtraDataKey));
2675 }
2676 }
2677 }
2678 catch (ConfigError &x)
2679 {
2680 // InsertConfig threw something:
2681 return x.m_vrc;
2682 }
2683 return rc;
2684}
2685
2686/**
2687 * Ellipsis to va_list wrapper for calling setVMRuntimeErrorCallback.
2688 */
2689/*static*/
2690void Console::setVMRuntimeErrorCallbackF(PVM pVM, void *pvConsole, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, ...)
2691{
2692 va_list va;
2693 va_start(va, pszFormat);
2694 setVMRuntimeErrorCallback(pVM, pvConsole, fFlags, pszErrorId, pszFormat, va);
2695 va_end(va);
2696}
2697
2698/* XXX introduce RT format specifier */
2699static uint64_t formatDiskSize(uint64_t u64Size, const char **pszUnit)
2700{
2701 if (u64Size > INT64_C(5000)*_1G)
2702 {
2703 *pszUnit = "TB";
2704 return u64Size / _1T;
2705 }
2706 else if (u64Size > INT64_C(5000)*_1M)
2707 {
2708 *pszUnit = "GB";
2709 return u64Size / _1G;
2710 }
2711 else
2712 {
2713 *pszUnit = "MB";
2714 return u64Size / _1M;
2715 }
2716}
2717
2718int Console::configMediumAttachment(PCFGMNODE pCtlInst,
2719 const char *pcszDevice,
2720 unsigned uInstance,
2721 StorageBus_T enmBus,
2722 bool fUseHostIOCache,
2723 bool fBuiltinIoCache,
2724 bool fSetupMerge,
2725 unsigned uMergeSource,
2726 unsigned uMergeTarget,
2727 IMediumAttachment *pMediumAtt,
2728 MachineState_T aMachineState,
2729 HRESULT *phrc,
2730 bool fAttachDetach,
2731 bool fForceUnmount,
2732 PVM pVM,
2733 DeviceType_T *paLedDevType)
2734{
2735 // InsertConfig* throws
2736 try
2737 {
2738 int rc = VINF_SUCCESS;
2739 HRESULT hrc;
2740 Bstr bstr;
2741
2742// #define RC_CHECK() AssertMsgReturn(RT_SUCCESS(rc), ("rc=%Rrc\n", rc), rc)
2743#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
2744
2745 LONG lDev;
2746 hrc = pMediumAtt->COMGETTER(Device)(&lDev); H();
2747 LONG lPort;
2748 hrc = pMediumAtt->COMGETTER(Port)(&lPort); H();
2749 DeviceType_T lType;
2750 hrc = pMediumAtt->COMGETTER(Type)(&lType); H();
2751
2752 unsigned uLUN;
2753 PCFGMNODE pLunL0 = NULL;
2754 PCFGMNODE pCfg = NULL;
2755 hrc = Console::convertBusPortDeviceToLun(enmBus, lPort, lDev, uLUN); H();
2756
2757 /* First check if the LUN already exists. */
2758 pLunL0 = CFGMR3GetChildF(pCtlInst, "LUN#%u", uLUN);
2759 if (pLunL0)
2760 {
2761 if (fAttachDetach)
2762 {
2763 if (lType != DeviceType_HardDisk)
2764 {
2765 /* Unmount existing media only for floppy and DVD drives. */
2766 PPDMIBASE pBase;
2767 rc = PDMR3QueryLun(pVM, pcszDevice, uInstance, uLUN, &pBase);
2768 if (RT_FAILURE(rc))
2769 {
2770 if (rc == VERR_PDM_LUN_NOT_FOUND || rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
2771 rc = VINF_SUCCESS;
2772 AssertRC(rc);
2773 }
2774 else
2775 {
2776 PPDMIMOUNT pIMount = PDMIBASE_QUERY_INTERFACE(pBase, PDMIMOUNT);
2777 AssertReturn(pIMount, VERR_INVALID_POINTER);
2778
2779 /* Unmount the media (but do not eject the medium!) */
2780 rc = pIMount->pfnUnmount(pIMount, fForceUnmount, false /*=fEject*/);
2781 if (rc == VERR_PDM_MEDIA_NOT_MOUNTED)
2782 rc = VINF_SUCCESS;
2783 /* for example if the medium is locked */
2784 else if (RT_FAILURE(rc))
2785 return rc;
2786 }
2787 }
2788
2789 rc = PDMR3DeviceDetach(pVM, pcszDevice, 0, uLUN, PDM_TACH_FLAGS_NOT_HOT_PLUG);
2790 if (rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
2791 rc = VINF_SUCCESS;
2792 AssertMsgReturn(RT_SUCCESS(rc), ("rc=%Rrc\n", rc), rc);
2793
2794 CFGMR3RemoveNode(pLunL0);
2795 }
2796 else
2797 AssertFailedReturn(VERR_INTERNAL_ERROR);
2798 }
2799
2800 InsertConfigNode(pCtlInst, Utf8StrFmt("LUN#%u", uLUN).c_str(), &pLunL0);
2801
2802 /* SCSI has a another driver between device and block. */
2803 if (enmBus == StorageBus_SCSI || enmBus == StorageBus_SAS)
2804 {
2805 InsertConfigString(pLunL0, "Driver", "SCSI");
2806 InsertConfigNode(pLunL0, "Config", &pCfg);
2807
2808 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
2809 }
2810
2811 ComPtr<IMedium> pMedium;
2812 hrc = pMediumAtt->COMGETTER(Medium)(pMedium.asOutParam()); H();
2813
2814 /*
2815 * 1. Only check this for hard disk images.
2816 * 2. Only check during VM creation and not later, especially not during
2817 * taking an online snapshot!
2818 */
2819 if ( lType == DeviceType_HardDisk
2820 && ( aMachineState == MachineState_Starting
2821 || aMachineState == MachineState_Restoring))
2822 {
2823 /*
2824 * Some sanity checks.
2825 */
2826 ComPtr<IMediumFormat> pMediumFormat;
2827 hrc = pMedium->COMGETTER(MediumFormat)(pMediumFormat.asOutParam()); H();
2828 ULONG uCaps;
2829 hrc = pMediumFormat->COMGETTER(Capabilities)(&uCaps); H();
2830 if (uCaps & MediumFormatCapabilities_File)
2831 {
2832 Bstr strFile;
2833 hrc = pMedium->COMGETTER(Location)(strFile.asOutParam()); H();
2834 Utf8Str utfFile = Utf8Str(strFile);
2835 Bstr strSnap;
2836 ComPtr<IMachine> pMachine = machine();
2837 hrc = pMachine->COMGETTER(SnapshotFolder)(strSnap.asOutParam()); H();
2838 Utf8Str utfSnap = Utf8Str(strSnap);
2839 RTFSTYPE enmFsTypeFile = RTFSTYPE_UNKNOWN;
2840 RTFSTYPE enmFsTypeSnap = RTFSTYPE_UNKNOWN;
2841 int rc2 = RTFsQueryType(utfFile.c_str(), &enmFsTypeFile);
2842 AssertMsgRCReturn(rc2, ("Querying the file type of '%s' failed!\n", utfFile.c_str()), rc2);
2843 /* Ignore the error code. On error, the file system type is still 'unknown' so
2844 * none of the following paths are taken. This can happen for new VMs which
2845 * still don't have a snapshot folder. */
2846 (void)RTFsQueryType(utfSnap.c_str(), &enmFsTypeSnap);
2847 if (!mfSnapshotFolderDiskTypeShown)
2848 {
2849 LogRel(("File system of '%s' (snapshots) is %s\n", utfSnap.c_str(), RTFsTypeName(enmFsTypeSnap)));
2850 mfSnapshotFolderDiskTypeShown = true;
2851 }
2852 LogRel(("File system of '%s' is %s\n", utfFile.c_str(), RTFsTypeName(enmFsTypeFile)));
2853 LONG64 i64Size;
2854 hrc = pMedium->COMGETTER(LogicalSize)(&i64Size); H();
2855#ifdef RT_OS_WINDOWS
2856 if ( enmFsTypeFile == RTFSTYPE_FAT
2857 && i64Size >= _4G)
2858 {
2859 const char *pszUnit;
2860 uint64_t u64Print = formatDiskSize((uint64_t)i64Size, &pszUnit);
2861 setVMRuntimeErrorCallbackF(pVM, this, 0,
2862 "FatPartitionDetected",
2863 N_("The medium '%ls' has a logical size of %RU64%s "
2864 "but the file system the medium is located on seems "
2865 "to be FAT(32) which cannot handle files bigger than 4GB.\n"
2866 "We strongly recommend to put all your virtual disk images and "
2867 "the snapshot folder onto an NTFS partition"),
2868 strFile.raw(), u64Print, pszUnit);
2869 }
2870#else /* !RT_OS_WINDOWS */
2871 if ( enmFsTypeFile == RTFSTYPE_FAT
2872 || enmFsTypeFile == RTFSTYPE_EXT
2873 || enmFsTypeFile == RTFSTYPE_EXT2
2874 || enmFsTypeFile == RTFSTYPE_EXT3
2875 || enmFsTypeFile == RTFSTYPE_EXT4)
2876 {
2877 RTFILE file;
2878 rc = RTFileOpen(&file, utfFile.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
2879 if (RT_SUCCESS(rc))
2880 {
2881 RTFOFF maxSize;
2882 /* Careful: This function will work only on selected local file systems! */
2883 rc = RTFileGetMaxSizeEx(file, &maxSize);
2884 RTFileClose(file);
2885 if ( RT_SUCCESS(rc)
2886 && maxSize > 0
2887 && i64Size > (LONG64)maxSize)
2888 {
2889 const char *pszUnitSiz;
2890 const char *pszUnitMax;
2891 uint64_t u64PrintSiz = formatDiskSize((LONG64)i64Size, &pszUnitSiz);
2892 uint64_t u64PrintMax = formatDiskSize(maxSize, &pszUnitMax);
2893 setVMRuntimeErrorCallbackF(pVM, this, 0,
2894 "FatPartitionDetected", /* <= not exact but ... */
2895 N_("The medium '%ls' has a logical size of %RU64%s "
2896 "but the file system the medium is located on can "
2897 "only handle files up to %RU64%s in theory.\n"
2898 "We strongly recommend to put all your virtual disk "
2899 "images and the snapshot folder onto a proper "
2900 "file system (e.g. ext3) with a sufficient size"),
2901 strFile.raw(), u64PrintSiz, pszUnitSiz, u64PrintMax, pszUnitMax);
2902 }
2903 }
2904 }
2905#endif /* !RT_OS_WINDOWS */
2906
2907 /*
2908 * Snapshot folder:
2909 * Here we test only for a FAT partition as we had to create a dummy file otherwise
2910 */
2911 if ( enmFsTypeSnap == RTFSTYPE_FAT
2912 && i64Size >= _4G
2913 && !mfSnapshotFolderSizeWarningShown)
2914 {
2915 const char *pszUnit;
2916 uint64_t u64Print = formatDiskSize(i64Size, &pszUnit);
2917 setVMRuntimeErrorCallbackF(pVM, this, 0,
2918 "FatPartitionDetected",
2919#ifdef RT_OS_WINDOWS
2920 N_("The snapshot folder of this VM '%ls' seems to be located on "
2921 "a FAT(32) file system. The logical size of the medium '%ls' "
2922 "(%RU64%s) is bigger than the maximum file size this file "
2923 "system can handle (4GB).\n"
2924 "We strongly recommend to put all your virtual disk images and "
2925 "the snapshot folder onto an NTFS partition"),
2926#else
2927 N_("The snapshot folder of this VM '%ls' seems to be located on "
2928 "a FAT(32) file system. The logical size of the medium '%ls' "
2929 "(%RU64%s) is bigger than the maximum file size this file "
2930 "system can handle (4GB).\n"
2931 "We strongly recommend to put all your virtual disk images and "
2932 "the snapshot folder onto a proper file system (e.g. ext3)"),
2933#endif
2934 strSnap.raw(), strFile.raw(), u64Print, pszUnit);
2935 /* Show this particular warning only once */
2936 mfSnapshotFolderSizeWarningShown = true;
2937 }
2938
2939#ifdef RT_OS_LINUX
2940 /*
2941 * Ext4 bug: Check if the host I/O cache is disabled and the disk image is located
2942 * on an ext4 partition. Later we have to check the Linux kernel version!
2943 * This bug apparently applies to the XFS file system as well.
2944 * Linux 2.6.36 is known to be fixed (tested with 2.6.36-rc4).
2945 */
2946
2947 char szOsRelease[128];
2948 rc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szOsRelease, sizeof(szOsRelease));
2949 bool fKernelHasODirectBug = RT_FAILURE(rc)
2950 || (RTStrVersionCompare(szOsRelease, "2.6.36-rc4") < 0);
2951
2952 if ( (uCaps & MediumFormatCapabilities_Asynchronous)
2953 && !fUseHostIOCache
2954 && fKernelHasODirectBug)
2955 {
2956 if ( enmFsTypeFile == RTFSTYPE_EXT4
2957 || enmFsTypeFile == RTFSTYPE_XFS)
2958 {
2959 setVMRuntimeErrorCallbackF(pVM, this, 0,
2960 "Ext4PartitionDetected",
2961 N_("The host I/O cache for at least one controller is disabled "
2962 "and the medium '%ls' for this VM "
2963 "is located on an %s partition. There is a known Linux "
2964 "kernel bug which can lead to the corruption of the virtual "
2965 "disk image under these conditions.\n"
2966 "Either enable the host I/O cache permanently in the VM "
2967 "settings or put the disk image and the snapshot folder "
2968 "onto a different file system.\n"
2969 "The host I/O cache will now be enabled for this medium"),
2970 strFile.raw(), enmFsTypeFile == RTFSTYPE_EXT4 ? "ext4" : "xfs");
2971 fUseHostIOCache = true;
2972 }
2973 else if ( ( enmFsTypeSnap == RTFSTYPE_EXT4
2974 || enmFsTypeSnap == RTFSTYPE_XFS)
2975 && !mfSnapshotFolderExt4WarningShown)
2976 {
2977 setVMRuntimeErrorCallbackF(pVM, this, 0,
2978 "Ext4PartitionDetected",
2979 N_("The host I/O cache for at least one controller is disabled "
2980 "and the snapshot folder for this VM "
2981 "is located on an %s partition. There is a known Linux "
2982 "kernel bug which can lead to the corruption of the virtual "
2983 "disk image under these conditions.\n"
2984 "Either enable the host I/O cache permanently in the VM "
2985 "settings or put the disk image and the snapshot folder "
2986 "onto a different file system.\n"
2987 "The host I/O cache will now be enabled for this medium"),
2988 enmFsTypeSnap == RTFSTYPE_EXT4 ? "ext4" : "xfs");
2989 fUseHostIOCache = true;
2990 mfSnapshotFolderExt4WarningShown = true;
2991 }
2992 }
2993#endif
2994 }
2995 }
2996
2997 BOOL fPassthrough;
2998 hrc = pMediumAtt->COMGETTER(Passthrough)(&fPassthrough); H();
2999
3000 ComObjPtr<IBandwidthGroup> pBwGroup;
3001 Bstr strBwGroup;
3002 hrc = pMediumAtt->COMGETTER(BandwidthGroup)(pBwGroup.asOutParam()); H();
3003
3004 if (!pBwGroup.isNull())
3005 {
3006 hrc = pBwGroup->COMGETTER(Name)(strBwGroup.asOutParam()); H();
3007 }
3008
3009 rc = configMedium(pLunL0,
3010 !!fPassthrough,
3011 lType,
3012 fUseHostIOCache,
3013 fBuiltinIoCache,
3014 fSetupMerge,
3015 uMergeSource,
3016 uMergeTarget,
3017 strBwGroup.isEmpty() ? NULL : Utf8Str(strBwGroup).c_str(),
3018 pMedium,
3019 aMachineState,
3020 phrc);
3021 if (RT_FAILURE(rc))
3022 return rc;
3023
3024 if (fAttachDetach)
3025 {
3026 /* Attach the new driver. */
3027 rc = PDMR3DeviceAttach(pVM, pcszDevice, 0, uLUN,
3028 PDM_TACH_FLAGS_NOT_HOT_PLUG, NULL /*ppBase*/);
3029 AssertMsgReturn(RT_SUCCESS(rc), ("rc=%Rrc\n", rc), rc);
3030
3031 /* There is no need to handle removable medium mounting, as we
3032 * unconditionally replace everthing including the block driver level.
3033 * This means the new medium will be picked up automatically. */
3034 }
3035
3036 if (paLedDevType)
3037 paLedDevType[uLUN] = lType;
3038 }
3039 catch (ConfigError &x)
3040 {
3041 // InsertConfig threw something:
3042 return x.m_vrc;
3043 }
3044
3045#undef H
3046
3047 return VINF_SUCCESS;;
3048}
3049
3050int Console::configMedium(PCFGMNODE pLunL0,
3051 bool fPassthrough,
3052 DeviceType_T enmType,
3053 bool fUseHostIOCache,
3054 bool fBuiltinIoCache,
3055 bool fSetupMerge,
3056 unsigned uMergeSource,
3057 unsigned uMergeTarget,
3058 const char *pcszBwGroup,
3059 IMedium *pMedium,
3060 MachineState_T aMachineState,
3061 HRESULT *phrc)
3062{
3063 // InsertConfig* throws
3064 try
3065 {
3066 int rc = VINF_SUCCESS;
3067 HRESULT hrc;
3068 Bstr bstr;
3069
3070#define H() AssertMsgReturnStmt(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), if (phrc) *phrc = hrc, VERR_GENERAL_FAILURE)
3071
3072 PCFGMNODE pLunL1 = NULL;
3073 PCFGMNODE pCfg = NULL;
3074
3075 BOOL fHostDrive = FALSE;
3076 MediumType_T mediumType = MediumType_Normal;
3077 if (pMedium)
3078 {
3079 hrc = pMedium->COMGETTER(HostDrive)(&fHostDrive); H();
3080 hrc = pMedium->COMGETTER(Type)(&mediumType); H();
3081 }
3082
3083 if (fHostDrive)
3084 {
3085 Assert(pMedium);
3086 if (enmType == DeviceType_DVD)
3087 {
3088 InsertConfigString(pLunL0, "Driver", "HostDVD");
3089 InsertConfigNode(pLunL0, "Config", &pCfg);
3090
3091 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3092 InsertConfigString(pCfg, "Path", bstr);
3093
3094 InsertConfigInteger(pCfg, "Passthrough", fPassthrough);
3095 }
3096 else if (enmType == DeviceType_Floppy)
3097 {
3098 InsertConfigString(pLunL0, "Driver", "HostFloppy");
3099 InsertConfigNode(pLunL0, "Config", &pCfg);
3100
3101 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3102 InsertConfigString(pCfg, "Path", bstr);
3103 }
3104 }
3105 else
3106 {
3107 InsertConfigString(pLunL0, "Driver", "Block");
3108 InsertConfigNode(pLunL0, "Config", &pCfg);
3109 switch (enmType)
3110 {
3111 case DeviceType_DVD:
3112 InsertConfigString(pCfg, "Type", "DVD");
3113 InsertConfigInteger(pCfg, "Mountable", 1);
3114 break;
3115 case DeviceType_Floppy:
3116 InsertConfigString(pCfg, "Type", "Floppy 1.44");
3117 InsertConfigInteger(pCfg, "Mountable", 1);
3118 break;
3119 case DeviceType_HardDisk:
3120 default:
3121 InsertConfigString(pCfg, "Type", "HardDisk");
3122 InsertConfigInteger(pCfg, "Mountable", 0);
3123 }
3124
3125 if ( pMedium
3126 && ( enmType == DeviceType_DVD
3127 || enmType == DeviceType_Floppy
3128 ))
3129 {
3130 // if this medium represents an ISO image and this image is inaccessible,
3131 // the ignore it instead of causing a failure; this can happen when we
3132 // restore a VM state and the ISO has disappeared, e.g. because the Guest
3133 // Additions were mounted and the user upgraded VirtualBox. Previously
3134 // we failed on startup, but that's not good because the only way out then
3135 // would be to discard the VM state...
3136 MediumState_T mediumState;
3137 rc = pMedium->RefreshState(&mediumState);
3138 AssertMsgReturn(RT_SUCCESS(rc), ("rc=%Rrc\n", rc), rc);
3139
3140 if (mediumState == MediumState_Inaccessible)
3141 {
3142 Bstr loc;
3143 rc = pMedium->COMGETTER(Location)(loc.asOutParam());
3144 if (FAILED(rc)) return rc;
3145
3146 setVMRuntimeErrorCallbackF(mpVM,
3147 this,
3148 0,
3149 "DvdOrFloppyImageInaccessible",
3150 "The image file '%ls' is inaccessible and is being ignored. Please select a different image file for the virtual %s drive.",
3151 loc.raw(),
3152 (enmType == DeviceType_DVD) ? "DVD" : "floppy");
3153 pMedium = NULL;
3154 }
3155 }
3156
3157 if (pMedium)
3158 {
3159 /* Start with length of parent chain, as the list is reversed */
3160 unsigned uImage = 0;
3161 IMedium *pTmp = pMedium;
3162 while (pTmp)
3163 {
3164 uImage++;
3165 hrc = pTmp->COMGETTER(Parent)(&pTmp); H();
3166 }
3167 /* Index of last image */
3168 uImage--;
3169
3170#if 0 /* Enable for I/O debugging */
3171 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
3172 InsertConfigString(pLunL0, "Driver", "DiskIntegrity");
3173 InsertConfigNode(pLunL0, "Config", &pCfg);
3174 InsertConfigInteger(pCfg, "CheckConsistency", 0);
3175 InsertConfigInteger(pCfg, "CheckDoubleCompletions", 1);
3176#endif
3177
3178 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
3179 InsertConfigString(pLunL1, "Driver", "VD");
3180 InsertConfigNode(pLunL1, "Config", &pCfg);
3181
3182 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3183 InsertConfigString(pCfg, "Path", bstr);
3184
3185 hrc = pMedium->COMGETTER(Format)(bstr.asOutParam()); H();
3186 InsertConfigString(pCfg, "Format", bstr);
3187
3188 if (mediumType == MediumType_Readonly)
3189 {
3190 InsertConfigInteger(pCfg, "ReadOnly", 1);
3191 }
3192 else if (enmType == DeviceType_Floppy)
3193 {
3194 InsertConfigInteger(pCfg, "MaybeReadOnly", 1);
3195 }
3196
3197 /* Start without exclusive write access to the images. */
3198 /** @todo Live Migration: I don't quite like this, we risk screwing up when
3199 * we're resuming the VM if some 3rd dude have any of the VDIs open
3200 * with write sharing denied. However, if the two VMs are sharing a
3201 * image it really is necessary....
3202 *
3203 * So, on the "lock-media" command, the target teleporter should also
3204 * make DrvVD undo TempReadOnly. It gets interesting if we fail after
3205 * that. Grumble. */
3206 if ( enmType == DeviceType_HardDisk
3207 && ( aMachineState == MachineState_TeleportingIn
3208 || aMachineState == MachineState_FaultTolerantSyncing))
3209 {
3210 InsertConfigInteger(pCfg, "TempReadOnly", 1);
3211 }
3212
3213 /* Flag for opening the medium for sharing between VMs. This
3214 * is done at the moment only for the first (and only) medium
3215 * in the chain, as shared media can have no diffs. */
3216 if (mediumType == MediumType_Shareable)
3217 {
3218 InsertConfigInteger(pCfg, "Shareable", 1);
3219 }
3220
3221 if (!fUseHostIOCache)
3222 {
3223 InsertConfigInteger(pCfg, "UseNewIo", 1);
3224 /*
3225 * Activate the builtin I/O cache for harddisks only.
3226 * It caches writes only which doesn't make sense for DVD drives
3227 * and just increases the overhead.
3228 */
3229 if ( fBuiltinIoCache
3230 && (enmType == DeviceType_HardDisk))
3231 InsertConfigInteger(pCfg, "BlockCache", 1);
3232 }
3233
3234 if (fSetupMerge)
3235 {
3236 InsertConfigInteger(pCfg, "SetupMerge", 1);
3237 if (uImage == uMergeSource)
3238 {
3239 InsertConfigInteger(pCfg, "MergeSource", 1);
3240 }
3241 else if (uImage == uMergeTarget)
3242 {
3243 InsertConfigInteger(pCfg, "MergeTarget", 1);
3244 }
3245 }
3246
3247 switch (enmType)
3248 {
3249 case DeviceType_DVD:
3250 InsertConfigString(pCfg, "Type", "DVD");
3251 break;
3252 case DeviceType_Floppy:
3253 InsertConfigString(pCfg, "Type", "Floppy");
3254 break;
3255 case DeviceType_HardDisk:
3256 default:
3257 InsertConfigString(pCfg, "Type", "HardDisk");
3258 }
3259
3260 if (pcszBwGroup)
3261 InsertConfigString(pCfg, "BwGroup", pcszBwGroup);
3262
3263 /* Pass all custom parameters. */
3264 bool fHostIP = true;
3265 SafeArray<BSTR> names;
3266 SafeArray<BSTR> values;
3267 hrc = pMedium->GetProperties(NULL,
3268 ComSafeArrayAsOutParam(names),
3269 ComSafeArrayAsOutParam(values)); H();
3270
3271 if (names.size() != 0)
3272 {
3273 PCFGMNODE pVDC;
3274 InsertConfigNode(pCfg, "VDConfig", &pVDC);
3275 for (size_t ii = 0; ii < names.size(); ++ii)
3276 {
3277 if (values[ii] && *values[ii])
3278 {
3279 Utf8Str name = names[ii];
3280 Utf8Str value = values[ii];
3281 InsertConfigString(pVDC, name.c_str(), value);
3282 if ( name.compare("HostIPStack") == 0
3283 && value.compare("0") == 0)
3284 fHostIP = false;
3285 }
3286 }
3287 }
3288
3289 /* Create an inverted list of parents. */
3290 uImage--;
3291 IMedium *pParentMedium = pMedium;
3292 for (PCFGMNODE pParent = pCfg;; uImage--)
3293 {
3294 hrc = pParentMedium->COMGETTER(Parent)(&pMedium); H();
3295 if (!pMedium)
3296 break;
3297
3298 PCFGMNODE pCur;
3299 InsertConfigNode(pParent, "Parent", &pCur);
3300 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3301 InsertConfigString(pCur, "Path", bstr);
3302
3303 hrc = pMedium->COMGETTER(Format)(bstr.asOutParam()); H();
3304 InsertConfigString(pCur, "Format", bstr);
3305
3306 if (fSetupMerge)
3307 {
3308 if (uImage == uMergeSource)
3309 {
3310 InsertConfigInteger(pCur, "MergeSource", 1);
3311 }
3312 else if (uImage == uMergeTarget)
3313 {
3314 InsertConfigInteger(pCur, "MergeTarget", 1);
3315 }
3316 }
3317
3318 /* Pass all custom parameters. */
3319 SafeArray<BSTR> aNames;
3320 SafeArray<BSTR> aValues;
3321 hrc = pMedium->GetProperties(NULL,
3322 ComSafeArrayAsOutParam(aNames),
3323 ComSafeArrayAsOutParam(aValues)); H();
3324
3325 if (aNames.size() != 0)
3326 {
3327 PCFGMNODE pVDC;
3328 InsertConfigNode(pCur, "VDConfig", &pVDC);
3329 for (size_t ii = 0; ii < aNames.size(); ++ii)
3330 {
3331 if (aValues[ii] && *aValues[ii])
3332 {
3333 Utf8Str name = aNames[ii];
3334 Utf8Str value = aValues[ii];
3335 InsertConfigString(pVDC, name.c_str(), value);
3336 if ( name.compare("HostIPStack") == 0
3337 && value.compare("0") == 0)
3338 fHostIP = false;
3339 }
3340 }
3341 }
3342
3343 /* Custom code: put marker to not use host IP stack to driver
3344 * configuration node. Simplifies life of DrvVD a bit. */
3345 if (!fHostIP)
3346 {
3347 InsertConfigInteger(pCfg, "HostIPStack", 0);
3348 }
3349
3350 /* next */
3351 pParent = pCur;
3352 pParentMedium = pMedium;
3353 }
3354 }
3355 }
3356 }
3357 catch (ConfigError &x)
3358 {
3359 // InsertConfig threw something:
3360 return x.m_vrc;
3361 }
3362
3363#undef H
3364
3365 return VINF_SUCCESS;
3366}
3367
3368/**
3369 * Construct the Network configuration tree
3370 *
3371 * @returns VBox status code.
3372 *
3373 * @param pszDevice The PDM device name.
3374 * @param uInstance The PDM device instance.
3375 * @param uLun The PDM LUN number of the drive.
3376 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
3377 * @param pCfg Configuration node for the device
3378 * @param pLunL0 To store the pointer to the LUN#0.
3379 * @param pInst The instance CFGM node
3380 * @param fAttachDetach To determine if the network attachment should
3381 * be attached/detached after/before
3382 * configuration.
3383 * @param fIgnoreConnectFailure
3384 * True if connection failures should be ignored
3385 * (makes only sense for bridged/host-only networks).
3386 *
3387 * @note Locks this object for writing.
3388 */
3389int Console::configNetwork(const char *pszDevice,
3390 unsigned uInstance,
3391 unsigned uLun,
3392 INetworkAdapter *aNetworkAdapter,
3393 PCFGMNODE pCfg,
3394 PCFGMNODE pLunL0,
3395 PCFGMNODE pInst,
3396 bool fAttachDetach,
3397 bool fIgnoreConnectFailure)
3398{
3399 AutoCaller autoCaller(this);
3400 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
3401
3402 // InsertConfig* throws
3403 try
3404 {
3405 int rc = VINF_SUCCESS;
3406 HRESULT hrc;
3407 Bstr bstr;
3408
3409#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
3410
3411 /*
3412 * Locking the object before doing VMR3* calls is quite safe here, since
3413 * we're on EMT. Write lock is necessary because we indirectly modify the
3414 * meAttachmentType member.
3415 */
3416 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3417
3418 PVM pVM = mpVM;
3419
3420 ComPtr<IMachine> pMachine = machine();
3421
3422 ComPtr<IVirtualBox> virtualBox;
3423 hrc = pMachine->COMGETTER(Parent)(virtualBox.asOutParam());
3424 H();
3425
3426 ComPtr<IHost> host;
3427 hrc = virtualBox->COMGETTER(Host)(host.asOutParam());
3428 H();
3429
3430 BOOL fSniffer;
3431 hrc = aNetworkAdapter->COMGETTER(TraceEnabled)(&fSniffer);
3432 H();
3433
3434 if (fAttachDetach && fSniffer)
3435 {
3436 const char *pszNetDriver = "IntNet";
3437 if (meAttachmentType[uInstance] == NetworkAttachmentType_NAT)
3438 pszNetDriver = "NAT";
3439#if !defined(VBOX_WITH_NETFLT) && defined(RT_OS_LINUX)
3440 if (meAttachmentType[uInstance] == NetworkAttachmentType_Bridged)
3441 pszNetDriver = "HostInterface";
3442#endif
3443
3444 rc = PDMR3DriverDetach(pVM, pszDevice, uInstance, uLun, pszNetDriver, 0, 0 /*fFlags*/);
3445 if (rc == VINF_PDM_NO_DRIVER_ATTACHED_TO_LUN)
3446 rc = VINF_SUCCESS;
3447 AssertLogRelRCReturn(rc, rc);
3448
3449 pLunL0 = CFGMR3GetChildF(pInst, "LUN#%u", uLun);
3450 PCFGMNODE pLunAD = CFGMR3GetChildF(pLunL0, "AttachedDriver");
3451 if (pLunAD)
3452 {
3453 CFGMR3RemoveNode(pLunAD);
3454 }
3455 else
3456 {
3457 CFGMR3RemoveNode(pLunL0);
3458 InsertConfigNode(pInst, "LUN#0", &pLunL0);
3459 InsertConfigString(pLunL0, "Driver", "NetSniffer");
3460 InsertConfigNode(pLunL0, "Config", &pCfg);
3461 hrc = aNetworkAdapter->COMGETTER(TraceFile)(bstr.asOutParam()); H();
3462 if (!bstr.isEmpty()) /* check convention for indicating default file. */
3463 InsertConfigString(pCfg, "File", bstr);
3464 }
3465 }
3466 else if (fAttachDetach && !fSniffer)
3467 {
3468 rc = PDMR3DeviceDetach(pVM, pszDevice, uInstance, uLun, 0 /*fFlags*/);
3469 if (rc == VINF_PDM_NO_DRIVER_ATTACHED_TO_LUN)
3470 rc = VINF_SUCCESS;
3471 AssertLogRelRCReturn(rc, rc);
3472
3473 /* nuke anything which might have been left behind. */
3474 CFGMR3RemoveNode(CFGMR3GetChildF(pInst, "LUN#%u", uLun));
3475 }
3476 else if (!fAttachDetach && fSniffer)
3477 {
3478 /* insert the sniffer filter driver. */
3479 InsertConfigNode(pInst, "LUN#0", &pLunL0);
3480 InsertConfigString(pLunL0, "Driver", "NetSniffer");
3481 InsertConfigNode(pLunL0, "Config", &pCfg);
3482 hrc = aNetworkAdapter->COMGETTER(TraceFile)(bstr.asOutParam()); H();
3483 if (!bstr.isEmpty()) /* check convention for indicating default file. */
3484 InsertConfigString(pCfg, "File", bstr);
3485 }
3486
3487 Bstr networkName, trunkName, trunkType;
3488 NetworkAttachmentType_T eAttachmentType;
3489 hrc = aNetworkAdapter->COMGETTER(AttachmentType)(&eAttachmentType); H();
3490 switch (eAttachmentType)
3491 {
3492 case NetworkAttachmentType_Null:
3493 break;
3494
3495 case NetworkAttachmentType_NAT:
3496 {
3497 ComPtr<INATEngine> natDriver;
3498 hrc = aNetworkAdapter->COMGETTER(NatDriver)(natDriver.asOutParam()); H();
3499 if (fSniffer)
3500 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
3501 else
3502 InsertConfigNode(pInst, "LUN#0", &pLunL0);
3503 InsertConfigString(pLunL0, "Driver", "NAT");
3504 InsertConfigNode(pLunL0, "Config", &pCfg);
3505
3506 /* Configure TFTP prefix and boot filename. */
3507 hrc = virtualBox->COMGETTER(HomeFolder)(bstr.asOutParam()); H();
3508 if (!bstr.isEmpty())
3509 InsertConfigString(pCfg, "TFTPPrefix", Utf8StrFmt("%ls%c%s", bstr.raw(), RTPATH_DELIMITER, "TFTP"));
3510 hrc = pMachine->COMGETTER(Name)(bstr.asOutParam()); H();
3511 InsertConfigString(pCfg, "BootFile", Utf8StrFmt("%ls.pxe", bstr.raw()));
3512
3513 hrc = natDriver->COMGETTER(Network)(bstr.asOutParam()); H();
3514 if (!bstr.isEmpty())
3515 InsertConfigString(pCfg, "Network", bstr);
3516 else
3517 {
3518 ULONG uSlot;
3519 hrc = aNetworkAdapter->COMGETTER(Slot)(&uSlot); H();
3520 InsertConfigString(pCfg, "Network", Utf8StrFmt("10.0.%d.0/24", uSlot+2));
3521 }
3522 hrc = natDriver->COMGETTER(HostIP)(bstr.asOutParam()); H();
3523 if (!bstr.isEmpty())
3524 InsertConfigString(pCfg, "BindIP", bstr);
3525 ULONG mtu = 0;
3526 ULONG sockSnd = 0;
3527 ULONG sockRcv = 0;
3528 ULONG tcpSnd = 0;
3529 ULONG tcpRcv = 0;
3530 hrc = natDriver->GetNetworkSettings(&mtu, &sockSnd, &sockRcv, &tcpSnd, &tcpRcv); H();
3531 if (mtu)
3532 InsertConfigInteger(pCfg, "SlirpMTU", mtu);
3533 if (sockRcv)
3534 InsertConfigInteger(pCfg, "SockRcv", sockRcv);
3535 if (sockSnd)
3536 InsertConfigInteger(pCfg, "SockSnd", sockSnd);
3537 if (tcpRcv)
3538 InsertConfigInteger(pCfg, "TcpRcv", tcpRcv);
3539 if (tcpSnd)
3540 InsertConfigInteger(pCfg, "TcpSnd", tcpSnd);
3541 hrc = natDriver->COMGETTER(TftpPrefix)(bstr.asOutParam()); H();
3542 if (!bstr.isEmpty())
3543 {
3544 RemoveConfigValue(pCfg, "TFTPPrefix");
3545 InsertConfigString(pCfg, "TFTPPrefix", bstr);
3546 }
3547 hrc = natDriver->COMGETTER(TftpBootFile)(bstr.asOutParam()); H();
3548 if (!bstr.isEmpty())
3549 {
3550 RemoveConfigValue(pCfg, "BootFile");
3551 InsertConfigString(pCfg, "BootFile", bstr);
3552 }
3553 hrc = natDriver->COMGETTER(TftpNextServer)(bstr.asOutParam()); H();
3554 if (!bstr.isEmpty())
3555 InsertConfigString(pCfg, "NextServer", bstr);
3556 BOOL fDnsFlag;
3557 hrc = natDriver->COMGETTER(DnsPassDomain)(&fDnsFlag); H();
3558 InsertConfigInteger(pCfg, "PassDomain", fDnsFlag);
3559 hrc = natDriver->COMGETTER(DnsProxy)(&fDnsFlag); H();
3560 InsertConfigInteger(pCfg, "DNSProxy", fDnsFlag);
3561 hrc = natDriver->COMGETTER(DnsUseHostResolver)(&fDnsFlag); H();
3562 InsertConfigInteger(pCfg, "UseHostResolver", fDnsFlag);
3563
3564 ULONG aliasMode;
3565 hrc = natDriver->COMGETTER(AliasMode)(&aliasMode); H();
3566 InsertConfigInteger(pCfg, "AliasMode", aliasMode);
3567
3568 /* port-forwarding */
3569 SafeArray<BSTR> pfs;
3570 hrc = natDriver->COMGETTER(Redirects)(ComSafeArrayAsOutParam(pfs)); H();
3571 PCFGMNODE pPF = NULL; /* /Devices/Dev/.../Config/PF#0/ */
3572 for (unsigned int i = 0; i < pfs.size(); ++i)
3573 {
3574 uint16_t port = 0;
3575 BSTR r = pfs[i];
3576 Utf8Str utf = Utf8Str(r);
3577 Utf8Str strName;
3578 Utf8Str strProto;
3579 Utf8Str strHostPort;
3580 Utf8Str strHostIP;
3581 Utf8Str strGuestPort;
3582 Utf8Str strGuestIP;
3583 size_t pos, ppos;
3584 pos = ppos = 0;
3585#define ITERATE_TO_NEXT_TERM(res, str, pos, ppos) \
3586 do { \
3587 pos = str.find(",", ppos); \
3588 if (pos == Utf8Str::npos) \
3589 { \
3590 Log(( #res " extracting from %s is failed\n", str.c_str())); \
3591 continue; \
3592 } \
3593 res = str.substr(ppos, pos - ppos); \
3594 Log2((#res " %s pos:%d, ppos:%d\n", res.c_str(), pos, ppos)); \
3595 ppos = pos + 1; \
3596 } while (0)
3597 ITERATE_TO_NEXT_TERM(strName, utf, pos, ppos);
3598 ITERATE_TO_NEXT_TERM(strProto, utf, pos, ppos);
3599 ITERATE_TO_NEXT_TERM(strHostIP, utf, pos, ppos);
3600 ITERATE_TO_NEXT_TERM(strHostPort, utf, pos, ppos);
3601 ITERATE_TO_NEXT_TERM(strGuestIP, utf, pos, ppos);
3602 strGuestPort = utf.substr(ppos, utf.length() - ppos);
3603#undef ITERATE_TO_NEXT_TERM
3604
3605 uint32_t proto = strProto.toUInt32();
3606 bool fValid = true;
3607 switch (proto)
3608 {
3609 case NATProtocol_UDP:
3610 strProto = "UDP";
3611 break;
3612 case NATProtocol_TCP:
3613 strProto = "TCP";
3614 break;
3615 default:
3616 fValid = false;
3617 }
3618 /* continue with next rule if no valid proto was passed */
3619 if (!fValid)
3620 continue;
3621
3622 InsertConfigNode(pCfg, strName.c_str(), &pPF);
3623 InsertConfigString(pPF, "Protocol", strProto);
3624
3625 if (!strHostIP.isEmpty())
3626 InsertConfigString(pPF, "BindIP", strHostIP);
3627
3628 if (!strGuestIP.isEmpty())
3629 InsertConfigString(pPF, "GuestIP", strGuestIP);
3630
3631 port = RTStrToUInt16(strHostPort.c_str());
3632 if (port)
3633 InsertConfigInteger(pPF, "HostPort", port);
3634
3635 port = RTStrToUInt16(strGuestPort.c_str());
3636 if (port)
3637 InsertConfigInteger(pPF, "GuestPort", port);
3638 }
3639 break;
3640 }
3641
3642 case NetworkAttachmentType_Bridged:
3643 {
3644#if (defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT)
3645 hrc = attachToTapInterface(aNetworkAdapter);
3646 if (FAILED(hrc))
3647 {
3648 switch (hrc)
3649 {
3650 case VERR_ACCESS_DENIED:
3651 return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
3652 "Failed to open '/dev/net/tun' for read/write access. Please check the "
3653 "permissions of that node. Either run 'chmod 0666 /dev/net/tun' or "
3654 "change the group of that node and make yourself a member of that group. Make "
3655 "sure that these changes are permanent, especially if you are "
3656 "using udev"));
3657 default:
3658 AssertMsgFailed(("Could not attach to host interface! Bad!\n"));
3659 return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
3660 "Failed to initialize Host Interface Networking"));
3661 }
3662 }
3663
3664 Assert((int)maTapFD[uInstance] >= 0);
3665 if ((int)maTapFD[uInstance] >= 0)
3666 {
3667 if (fSniffer)
3668 {
3669 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
3670 }
3671 else
3672 {
3673 InsertConfigNode(pInst, "LUN#0", &pLunL0);
3674 }
3675 InsertConfigString(pLunL0, "Driver", "HostInterface");
3676 InsertConfigNode(pLunL0, "Config", &pCfg);
3677 InsertConfigInteger(pCfg, "FileHandle", maTapFD[uInstance]);
3678 }
3679
3680#elif defined(VBOX_WITH_NETFLT)
3681 /*
3682 * This is the new VBoxNetFlt+IntNet stuff.
3683 */
3684 if (fSniffer)
3685 {
3686 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
3687 }
3688 else
3689 {
3690 InsertConfigNode(pInst, "LUN#0", &pLunL0);
3691 }
3692
3693 Bstr HifName;
3694 hrc = aNetworkAdapter->COMGETTER(HostInterface)(HifName.asOutParam());
3695 if (FAILED(hrc))
3696 {
3697 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(HostInterface) failed, hrc (0x%x)", hrc));
3698 H();
3699 }
3700
3701 Utf8Str HifNameUtf8(HifName);
3702 const char *pszHifName = HifNameUtf8.c_str();
3703
3704# if defined(RT_OS_DARWIN)
3705 /* The name is on the form 'ifX: long name', chop it off at the colon. */
3706 char szTrunk[8];
3707 strncpy(szTrunk, pszHifName, sizeof(szTrunk));
3708 char *pszColon = (char *)memchr(szTrunk, ':', sizeof(szTrunk));
3709 if (!pszColon)
3710 {
3711 /*
3712 * Dynamic changing of attachment causes an attempt to configure
3713 * network with invalid host adapter (as it is must be changed before
3714 * the attachment), calling Detach here will cause a deadlock.
3715 * See #4750.
3716 * hrc = aNetworkAdapter->Detach(); H();
3717 */
3718 return VMSetError(pVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
3719 N_("Malformed host interface networking name '%ls'"),
3720 HifName.raw());
3721 }
3722 *pszColon = '\0';
3723 const char *pszTrunk = szTrunk;
3724
3725# elif defined(RT_OS_SOLARIS)
3726 /* The name is on the form format 'ifX[:1] - long name, chop it off at space. */
3727 char szTrunk[256];
3728 strlcpy(szTrunk, pszHifName, sizeof(szTrunk));
3729 char *pszSpace = (char *)memchr(szTrunk, ' ', sizeof(szTrunk));
3730
3731 /*
3732 * Currently don't bother about malformed names here for the sake of people using
3733 * VBoxManage and setting only the NIC name from there. If there is a space we
3734 * chop it off and proceed, otherwise just use whatever we've got.
3735 */
3736 if (pszSpace)
3737 *pszSpace = '\0';
3738
3739 /* Chop it off at the colon (zone naming eg: e1000g:1 we need only the e1000g) */
3740 char *pszColon = (char *)memchr(szTrunk, ':', sizeof(szTrunk));
3741 if (pszColon)
3742 *pszColon = '\0';
3743
3744 const char *pszTrunk = szTrunk;
3745
3746# elif defined(RT_OS_WINDOWS)
3747 ComPtr<IHostNetworkInterface> hostInterface;
3748 hrc = host->FindHostNetworkInterfaceByName(HifName.raw(),
3749 hostInterface.asOutParam());
3750 if (!SUCCEEDED(hrc))
3751 {
3752 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: FindByName failed, rc=%Rhrc (0x%x)", hrc, hrc));
3753 return VMSetError(pVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
3754 N_("Nonexistent host networking interface, name '%ls'"),
3755 HifName.raw());
3756 }
3757
3758 HostNetworkInterfaceType_T eIfType;
3759 hrc = hostInterface->COMGETTER(InterfaceType)(&eIfType);
3760 if (FAILED(hrc))
3761 {
3762 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(InterfaceType) failed, hrc (0x%x)", hrc));
3763 H();
3764 }
3765
3766 if (eIfType != HostNetworkInterfaceType_Bridged)
3767 {
3768 return VMSetError(pVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
3769 N_("Interface ('%ls') is not a Bridged Adapter interface"),
3770 HifName.raw());
3771 }
3772
3773 hrc = hostInterface->COMGETTER(Id)(bstr.asOutParam());
3774 if (FAILED(hrc))
3775 {
3776 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(Id) failed, hrc (0x%x)", hrc));
3777 H();
3778 }
3779 Guid hostIFGuid(bstr);
3780
3781 INetCfg *pNc;
3782 ComPtr<INetCfgComponent> pAdaptorComponent;
3783 LPWSTR pszApp;
3784
3785 hrc = VBoxNetCfgWinQueryINetCfg(FALSE /*fGetWriteLock*/,
3786 L"VirtualBox",
3787 &pNc,
3788 &pszApp);
3789 Assert(hrc == S_OK);
3790 if (hrc != S_OK)
3791 {
3792 LogRel(("NetworkAttachmentType_Bridged: Failed to get NetCfg, hrc=%Rhrc (0x%x)\n", hrc, hrc));
3793 H();
3794 }
3795
3796 /* get the adapter's INetCfgComponent*/
3797 hrc = VBoxNetCfgWinGetComponentByGuid(pNc, &GUID_DEVCLASS_NET, (GUID*)hostIFGuid.raw(), pAdaptorComponent.asOutParam());
3798 if (hrc != S_OK)
3799 {
3800 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
3801 LogRel(("NetworkAttachmentType_Bridged: VBoxNetCfgWinGetComponentByGuid failed, hrc (0x%x)", hrc));
3802 H();
3803 }
3804#define VBOX_WIN_BINDNAME_PREFIX "\\DEVICE\\"
3805 char szTrunkName[INTNET_MAX_TRUNK_NAME];
3806 char *pszTrunkName = szTrunkName;
3807 wchar_t * pswzBindName;
3808 hrc = pAdaptorComponent->GetBindName(&pswzBindName);
3809 Assert(hrc == S_OK);
3810 if (hrc == S_OK)
3811 {
3812 int cwBindName = (int)wcslen(pswzBindName) + 1;
3813 int cbFullBindNamePrefix = sizeof(VBOX_WIN_BINDNAME_PREFIX);
3814 if (sizeof(szTrunkName) > cbFullBindNamePrefix + cwBindName)
3815 {
3816 strcpy(szTrunkName, VBOX_WIN_BINDNAME_PREFIX);
3817 pszTrunkName += cbFullBindNamePrefix-1;
3818 if (!WideCharToMultiByte(CP_ACP, 0, pswzBindName, cwBindName, pszTrunkName,
3819 sizeof(szTrunkName) - cbFullBindNamePrefix + 1, NULL, NULL))
3820 {
3821 DWORD err = GetLastError();
3822 hrc = HRESULT_FROM_WIN32(err);
3823 AssertMsgFailed(("%hrc=%Rhrc %#x\n", hrc, hrc));
3824 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: WideCharToMultiByte failed, hr=%Rhrc (0x%x) err=%u\n", hrc, hrc, err));
3825 }
3826 }
3827 else
3828 {
3829 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: insufficient szTrunkName buffer space\n"));
3830 /** @todo set appropriate error code */
3831 hrc = E_FAIL;
3832 }
3833
3834 if (hrc != S_OK)
3835 {
3836 AssertFailed();
3837 CoTaskMemFree(pswzBindName);
3838 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
3839 H();
3840 }
3841
3842 /* we're not freeing the bind name since we'll use it later for detecting wireless*/
3843 }
3844 else
3845 {
3846 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
3847 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: VBoxNetCfgWinGetComponentByGuid failed, hrc (0x%x)", hrc));
3848 H();
3849 }
3850
3851 const char *pszTrunk = szTrunkName;
3852 /* we're not releasing the INetCfg stuff here since we use it later to figure out whether it is wireless */
3853
3854# elif defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
3855# if defined(RT_OS_FREEBSD)
3856 /*
3857 * If we bridge to a tap interface open it the `old' direct way.
3858 * This works and performs better than bridging a physical
3859 * interface via the current FreeBSD vboxnetflt implementation.
3860 */
3861 if (!strncmp(pszHifName, "tap", sizeof "tap" - 1)) {
3862 hrc = attachToTapInterface(aNetworkAdapter);
3863 if (FAILED(hrc))
3864 {
3865 switch (hrc)
3866 {
3867 case VERR_ACCESS_DENIED:
3868 return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
3869 "Failed to open '/dev/%s' for read/write access. Please check the "
3870 "permissions of that node, and that the net.link.tap.user_open "
3871 "sysctl is set. Either run 'chmod 0666 /dev/%s' or "
3872 "change the group of that node to vboxusers and make yourself "
3873 "a member of that group. Make sure that these changes are permanent."), pszHifName, pszHifName);
3874 default:
3875 AssertMsgFailed(("Could not attach to tap interface! Bad!\n"));
3876 return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
3877 "Failed to initialize Host Interface Networking"));
3878 }
3879 }
3880
3881 Assert((int)maTapFD[uInstance] >= 0);
3882 if ((int)maTapFD[uInstance] >= 0)
3883 {
3884 InsertConfigString(pLunL0, "Driver", "HostInterface");
3885 InsertConfigNode(pLunL0, "Config", &pCfg);
3886 InsertConfigInteger(pCfg, "FileHandle", maTapFD[uInstance]);
3887 }
3888 break;
3889 }
3890# endif
3891 /** @todo Check for malformed names. */
3892 const char *pszTrunk = pszHifName;
3893
3894 /* Issue a warning if the interface is down */
3895 {
3896 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
3897 if (iSock >= 0)
3898 {
3899 struct ifreq Req;
3900
3901 memset(&Req, 0, sizeof(Req));
3902 strncpy(Req.ifr_name, pszHifName, sizeof(Req.ifr_name) - 1);
3903 if (ioctl(iSock, SIOCGIFFLAGS, &Req) >= 0)
3904 if ((Req.ifr_flags & IFF_UP) == 0)
3905 {
3906 setVMRuntimeErrorCallbackF(pVM, this, 0, "BridgedInterfaceDown", "Bridged interface %s is down. Guest will not be able to use this interface", pszHifName);
3907 }
3908
3909 close(iSock);
3910 }
3911 }
3912
3913# else
3914# error "PORTME (VBOX_WITH_NETFLT)"
3915# endif
3916
3917 InsertConfigString(pLunL0, "Driver", "IntNet");
3918 InsertConfigNode(pLunL0, "Config", &pCfg);
3919 InsertConfigString(pCfg, "Trunk", pszTrunk);
3920 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetFlt);
3921 InsertConfigInteger(pCfg, "IgnoreConnectFailure", (uint64_t)fIgnoreConnectFailure);
3922 char szNetwork[INTNET_MAX_NETWORK_NAME];
3923 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszHifName);
3924 InsertConfigString(pCfg, "Network", szNetwork);
3925 networkName = Bstr(szNetwork);
3926 trunkName = Bstr(pszTrunk);
3927 trunkType = Bstr(TRUNKTYPE_NETFLT);
3928
3929# if defined(RT_OS_DARWIN)
3930 /** @todo Come up with a better deal here. Problem is that IHostNetworkInterface is completely useless here. */
3931 if ( strstr(pszHifName, "Wireless")
3932 || strstr(pszHifName, "AirPort" ))
3933 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
3934# elif defined(RT_OS_LINUX)
3935 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
3936 if (iSock >= 0)
3937 {
3938 struct iwreq WRq;
3939
3940 memset(&WRq, 0, sizeof(WRq));
3941 strncpy(WRq.ifr_name, pszHifName, IFNAMSIZ);
3942 bool fSharedMacOnWire = ioctl(iSock, SIOCGIWNAME, &WRq) >= 0;
3943 close(iSock);
3944 if (fSharedMacOnWire)
3945 {
3946 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
3947 Log(("Set SharedMacOnWire\n"));
3948 }
3949 else
3950 Log(("Failed to get wireless name\n"));
3951 }
3952 else
3953 Log(("Failed to open wireless socket\n"));
3954# elif defined(RT_OS_FREEBSD)
3955 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
3956 if (iSock >= 0)
3957 {
3958 struct ieee80211req WReq;
3959 uint8_t abData[32];
3960
3961 memset(&WReq, 0, sizeof(WReq));
3962 strncpy(WReq.i_name, pszHifName, sizeof(WReq.i_name));
3963 WReq.i_type = IEEE80211_IOC_SSID;
3964 WReq.i_val = -1;
3965 WReq.i_data = abData;
3966 WReq.i_len = sizeof(abData);
3967
3968 bool fSharedMacOnWire = ioctl(iSock, SIOCG80211, &WReq) >= 0;
3969 close(iSock);
3970 if (fSharedMacOnWire)
3971 {
3972 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
3973 Log(("Set SharedMacOnWire\n"));
3974 }
3975 else
3976 Log(("Failed to get wireless name\n"));
3977 }
3978 else
3979 Log(("Failed to open wireless socket\n"));
3980# elif defined(RT_OS_WINDOWS)
3981# define DEVNAME_PREFIX L"\\\\.\\"
3982 /* we are getting the medium type via IOCTL_NDIS_QUERY_GLOBAL_STATS Io Control
3983 * there is a pretty long way till there though since we need to obtain the symbolic link name
3984 * for the adapter device we are going to query given the device Guid */
3985
3986
3987 /* prepend the "\\\\.\\" to the bind name to obtain the link name */
3988
3989 wchar_t FileName[MAX_PATH];
3990 wcscpy(FileName, DEVNAME_PREFIX);
3991 wcscpy((wchar_t*)(((char*)FileName) + sizeof(DEVNAME_PREFIX) - sizeof(FileName[0])), pswzBindName);
3992
3993 /* open the device */
3994 HANDLE hDevice = CreateFile(FileName,
3995 GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
3996 NULL,
3997 OPEN_EXISTING,
3998 FILE_ATTRIBUTE_NORMAL,
3999 NULL);
4000
4001 if (hDevice != INVALID_HANDLE_VALUE)
4002 {
4003 bool fSharedMacOnWire = false;
4004
4005 /* now issue the OID_GEN_PHYSICAL_MEDIUM query */
4006 DWORD Oid = OID_GEN_PHYSICAL_MEDIUM;
4007 NDIS_PHYSICAL_MEDIUM PhMedium;
4008 DWORD cbResult;
4009 if (DeviceIoControl(hDevice,
4010 IOCTL_NDIS_QUERY_GLOBAL_STATS,
4011 &Oid,
4012 sizeof(Oid),
4013 &PhMedium,
4014 sizeof(PhMedium),
4015 &cbResult,
4016 NULL))
4017 {
4018 /* that was simple, now examine PhMedium */
4019 if ( PhMedium == NdisPhysicalMediumWirelessWan
4020 || PhMedium == NdisPhysicalMediumWirelessLan
4021 || PhMedium == NdisPhysicalMediumNative802_11
4022 || PhMedium == NdisPhysicalMediumBluetooth)
4023 fSharedMacOnWire = true;
4024 }
4025 else
4026 {
4027 int winEr = GetLastError();
4028 LogRel(("Console::configNetwork: DeviceIoControl failed, err (0x%x), ignoring\n", winEr));
4029 Assert(winEr == ERROR_INVALID_PARAMETER || winEr == ERROR_NOT_SUPPORTED || winEr == ERROR_BAD_COMMAND);
4030 }
4031 CloseHandle(hDevice);
4032
4033 if (fSharedMacOnWire)
4034 {
4035 Log(("this is a wireless adapter"));
4036 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4037 Log(("Set SharedMacOnWire\n"));
4038 }
4039 else
4040 Log(("this is NOT a wireless adapter"));
4041 }
4042 else
4043 {
4044 int winEr = GetLastError();
4045 AssertLogRelMsgFailed(("Console::configNetwork: CreateFile failed, err (0x%x), ignoring\n", winEr));
4046 }
4047
4048 CoTaskMemFree(pswzBindName);
4049
4050 pAdaptorComponent.setNull();
4051 /* release the pNc finally */
4052 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4053# else
4054 /** @todo PORTME: wireless detection */
4055# endif
4056
4057# if defined(RT_OS_SOLARIS)
4058# if 0 /* bird: this is a bit questionable and might cause more trouble than its worth. */
4059 /* Zone access restriction, don't allow snooping the global zone. */
4060 zoneid_t ZoneId = getzoneid();
4061 if (ZoneId != GLOBAL_ZONEID)
4062 {
4063 InsertConfigInteger(pCfg, "IgnoreAllPromisc", true);
4064 }
4065# endif
4066# endif
4067
4068#elif defined(RT_OS_WINDOWS) /* not defined NetFlt */
4069 /* NOTHING TO DO HERE */
4070#elif defined(RT_OS_LINUX)
4071/// @todo aleksey: is there anything to be done here?
4072#elif defined(RT_OS_FREEBSD)
4073/** @todo FreeBSD: Check out this later (HIF networking). */
4074#else
4075# error "Port me"
4076#endif
4077 break;
4078 }
4079
4080 case NetworkAttachmentType_Internal:
4081 {
4082 hrc = aNetworkAdapter->COMGETTER(InternalNetwork)(bstr.asOutParam()); H();
4083 if (!bstr.isEmpty())
4084 {
4085 if (fSniffer)
4086 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
4087 else
4088 InsertConfigNode(pInst, "LUN#0", &pLunL0);
4089 InsertConfigString(pLunL0, "Driver", "IntNet");
4090 InsertConfigNode(pLunL0, "Config", &pCfg);
4091 InsertConfigString(pCfg, "Network", bstr);
4092 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_WhateverNone);
4093 networkName = bstr;
4094 trunkType = Bstr(TRUNKTYPE_WHATEVER);
4095 }
4096 break;
4097 }
4098
4099 case NetworkAttachmentType_HostOnly:
4100 {
4101 if (fSniffer)
4102 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
4103 else
4104 InsertConfigNode(pInst, "LUN#0", &pLunL0);
4105
4106 InsertConfigString(pLunL0, "Driver", "IntNet");
4107 InsertConfigNode(pLunL0, "Config", &pCfg);
4108
4109 Bstr HifName;
4110 hrc = aNetworkAdapter->COMGETTER(HostInterface)(HifName.asOutParam());
4111 if (FAILED(hrc))
4112 {
4113 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(HostInterface) failed, hrc (0x%x)\n", hrc));
4114 H();
4115 }
4116
4117 Utf8Str HifNameUtf8(HifName);
4118 const char *pszHifName = HifNameUtf8.c_str();
4119 ComPtr<IHostNetworkInterface> hostInterface;
4120 rc = host->FindHostNetworkInterfaceByName(HifName.raw(),
4121 hostInterface.asOutParam());
4122 if (!SUCCEEDED(rc))
4123 {
4124 LogRel(("NetworkAttachmentType_HostOnly: FindByName failed, rc (0x%x)\n", rc));
4125 return VMSetError(pVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
4126 N_("Nonexistent host networking interface, name '%ls'"),
4127 HifName.raw());
4128 }
4129
4130 char szNetwork[INTNET_MAX_NETWORK_NAME];
4131 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszHifName);
4132
4133#if defined(RT_OS_WINDOWS)
4134# ifndef VBOX_WITH_NETFLT
4135 hrc = E_NOTIMPL;
4136 LogRel(("NetworkAttachmentType_HostOnly: Not Implemented\n"));
4137 H();
4138# else /* defined VBOX_WITH_NETFLT*/
4139 /** @todo r=bird: Put this in a function. */
4140
4141 HostNetworkInterfaceType_T eIfType;
4142 hrc = hostInterface->COMGETTER(InterfaceType)(&eIfType);
4143 if (FAILED(hrc))
4144 {
4145 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(InterfaceType) failed, hrc (0x%x)\n", hrc));
4146 H();
4147 }
4148
4149 if (eIfType != HostNetworkInterfaceType_HostOnly)
4150 return VMSetError(pVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
4151 N_("Interface ('%ls') is not a Host-Only Adapter interface"),
4152 HifName.raw());
4153
4154 hrc = hostInterface->COMGETTER(Id)(bstr.asOutParam());
4155 if (FAILED(hrc))
4156 {
4157 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(Id) failed, hrc (0x%x)\n", hrc));
4158 H();
4159 }
4160 Guid hostIFGuid(bstr);
4161
4162 INetCfg *pNc;
4163 ComPtr<INetCfgComponent> pAdaptorComponent;
4164 LPWSTR pszApp;
4165
4166 hrc = VBoxNetCfgWinQueryINetCfg(FALSE,
4167 L"VirtualBox",
4168 &pNc,
4169 &pszApp);
4170 Assert(hrc == S_OK);
4171 if (hrc != S_OK)
4172 {
4173 LogRel(("NetworkAttachmentType_HostOnly: Failed to get NetCfg, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4174 H();
4175 }
4176
4177 /* get the adapter's INetCfgComponent*/
4178 hrc = VBoxNetCfgWinGetComponentByGuid(pNc, &GUID_DEVCLASS_NET, (GUID*)hostIFGuid.raw(), pAdaptorComponent.asOutParam());
4179 if (hrc != S_OK)
4180 {
4181 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4182 LogRel(("NetworkAttachmentType_HostOnly: VBoxNetCfgWinGetComponentByGuid failed, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4183 H();
4184 }
4185#define VBOX_WIN_BINDNAME_PREFIX "\\DEVICE\\"
4186 char szTrunkName[INTNET_MAX_TRUNK_NAME];
4187 char *pszTrunkName = szTrunkName;
4188 wchar_t * pswzBindName;
4189 hrc = pAdaptorComponent->GetBindName(&pswzBindName);
4190 Assert(hrc == S_OK);
4191 if (hrc == S_OK)
4192 {
4193 int cwBindName = (int)wcslen(pswzBindName) + 1;
4194 int cbFullBindNamePrefix = sizeof(VBOX_WIN_BINDNAME_PREFIX);
4195 if (sizeof(szTrunkName) > cbFullBindNamePrefix + cwBindName)
4196 {
4197 strcpy(szTrunkName, VBOX_WIN_BINDNAME_PREFIX);
4198 pszTrunkName += cbFullBindNamePrefix-1;
4199 if (!WideCharToMultiByte(CP_ACP, 0, pswzBindName, cwBindName, pszTrunkName,
4200 sizeof(szTrunkName) - cbFullBindNamePrefix + 1, NULL, NULL))
4201 {
4202 DWORD err = GetLastError();
4203 hrc = HRESULT_FROM_WIN32(err);
4204 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: WideCharToMultiByte failed, hr=%Rhrc (0x%x) err=%u\n", hrc, hrc, err));
4205 }
4206 }
4207 else
4208 {
4209 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: insufficient szTrunkName buffer space\n"));
4210 /** @todo set appropriate error code */
4211 hrc = E_FAIL;
4212 }
4213
4214 if (hrc != S_OK)
4215 {
4216 AssertFailed();
4217 CoTaskMemFree(pswzBindName);
4218 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4219 H();
4220 }
4221 }
4222 else
4223 {
4224 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4225 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: VBoxNetCfgWinGetComponentByGuid failed, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4226 H();
4227 }
4228
4229
4230 CoTaskMemFree(pswzBindName);
4231
4232 pAdaptorComponent.setNull();
4233 /* release the pNc finally */
4234 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4235
4236 const char *pszTrunk = szTrunkName;
4237
4238 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetAdp);
4239 InsertConfigString(pCfg, "Trunk", pszTrunk);
4240 InsertConfigString(pCfg, "Network", szNetwork);
4241 InsertConfigInteger(pCfg, "IgnoreConnectFailure", (uint64_t)fIgnoreConnectFailure);
4242 networkName = Bstr(szNetwork);
4243 trunkName = Bstr(pszTrunk);
4244 trunkType = TRUNKTYPE_NETADP;
4245# endif /* defined VBOX_WITH_NETFLT*/
4246#elif defined(RT_OS_DARWIN)
4247 InsertConfigString(pCfg, "Trunk", pszHifName);
4248 InsertConfigString(pCfg, "Network", szNetwork);
4249 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetAdp);
4250 networkName = Bstr(szNetwork);
4251 trunkName = Bstr(pszHifName);
4252 trunkType = TRUNKTYPE_NETADP;
4253#else
4254 InsertConfigString(pCfg, "Trunk", pszHifName);
4255 InsertConfigString(pCfg, "Network", szNetwork);
4256 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetFlt);
4257 networkName = Bstr(szNetwork);
4258 trunkName = Bstr(pszHifName);
4259 trunkType = TRUNKTYPE_NETFLT;
4260#endif
4261#if !defined(RT_OS_WINDOWS) && defined(VBOX_WITH_NETFLT)
4262
4263 Bstr tmpAddr, tmpMask;
4264
4265 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPAddress",
4266 pszHifName).raw(),
4267 tmpAddr.asOutParam());
4268 if (SUCCEEDED(hrc) && !tmpAddr.isEmpty())
4269 {
4270 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPNetMask",
4271 pszHifName).raw(),
4272 tmpMask.asOutParam());
4273 if (SUCCEEDED(hrc) && !tmpMask.isEmpty())
4274 hrc = hostInterface->EnableStaticIpConfig(tmpAddr.raw(),
4275 tmpMask.raw());
4276 else
4277 hrc = hostInterface->EnableStaticIpConfig(tmpAddr.raw(),
4278 Bstr(VBOXNET_IPV4MASK_DEFAULT).raw());
4279 }
4280 else
4281 {
4282 /* Grab the IP number from the 'vboxnetX' instance number (see netif.h) */
4283 hrc = hostInterface->EnableStaticIpConfig(getDefaultIPv4Address(Bstr(pszHifName)).raw(),
4284 Bstr(VBOXNET_IPV4MASK_DEFAULT).raw());
4285 }
4286
4287 ComAssertComRC(hrc); /** @todo r=bird: Why this isn't fatal? (H()) */
4288
4289 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6Address",
4290 pszHifName).raw(),
4291 tmpAddr.asOutParam());
4292 if (SUCCEEDED(hrc))
4293 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6NetMask", pszHifName).raw(),
4294 tmpMask.asOutParam());
4295 if (SUCCEEDED(hrc) && !tmpAddr.isEmpty() && !tmpMask.isEmpty())
4296 {
4297 hrc = hostInterface->EnableStaticIpConfigV6(tmpAddr.raw(),
4298 Utf8Str(tmpMask).toUInt32());
4299 ComAssertComRC(hrc); /** @todo r=bird: Why this isn't fatal? (H()) */
4300 }
4301#endif
4302 break;
4303 }
4304
4305#if defined(VBOX_WITH_VDE)
4306 case NetworkAttachmentType_VDE:
4307 {
4308 hrc = aNetworkAdapter->COMGETTER(VDENetwork)(bstr.asOutParam()); H();
4309 InsertConfigNode(pInst, "LUN#0", &pLunL0);
4310 InsertConfigString(pLunL0, "Driver", "VDE");
4311 InsertConfigNode(pLunL0, "Config", &pCfg);
4312 if (!bstr.isEmpty())
4313 {
4314 InsertConfigString(pCfg, "Network", bstr);
4315 networkName = bstr;
4316 }
4317 break;
4318 }
4319#endif
4320
4321 default:
4322 AssertMsgFailed(("should not get here!\n"));
4323 break;
4324 }
4325
4326 /*
4327 * Attempt to attach the driver.
4328 */
4329 switch (eAttachmentType)
4330 {
4331 case NetworkAttachmentType_Null:
4332 break;
4333
4334 case NetworkAttachmentType_Bridged:
4335 case NetworkAttachmentType_Internal:
4336 case NetworkAttachmentType_HostOnly:
4337 case NetworkAttachmentType_NAT:
4338#if defined(VBOX_WITH_VDE)
4339 case NetworkAttachmentType_VDE:
4340#endif
4341 {
4342 if (SUCCEEDED(hrc) && SUCCEEDED(rc))
4343 {
4344 if (fAttachDetach)
4345 {
4346 rc = PDMR3DriverAttach(pVM, pszDevice, uInstance, uLun, 0 /*fFlags*/, NULL /* ppBase */);
4347 //AssertRC(rc);
4348 }
4349
4350 {
4351 /** @todo pritesh: get the dhcp server name from the
4352 * previous network configuration and then stop the server
4353 * else it may conflict with the dhcp server running with
4354 * the current attachment type
4355 */
4356 /* Stop the hostonly DHCP Server */
4357 }
4358
4359 if (!networkName.isEmpty())
4360 {
4361 /*
4362 * Until we implement service reference counters DHCP Server will be stopped
4363 * by DHCPServerRunner destructor.
4364 */
4365 ComPtr<IDHCPServer> dhcpServer;
4366 hrc = virtualBox->FindDHCPServerByNetworkName(networkName.raw(),
4367 dhcpServer.asOutParam());
4368 if (SUCCEEDED(hrc))
4369 {
4370 /* there is a DHCP server available for this network */
4371 BOOL fEnabled;
4372 hrc = dhcpServer->COMGETTER(Enabled)(&fEnabled);
4373 if (FAILED(hrc))
4374 {
4375 LogRel(("DHCP svr: COMGETTER(Enabled) failed, hrc (%Rhrc)", hrc));
4376 H();
4377 }
4378
4379 if (fEnabled)
4380 hrc = dhcpServer->Start(networkName.raw(),
4381 trunkName.raw(),
4382 trunkType.raw());
4383 }
4384 else
4385 hrc = S_OK;
4386 }
4387 }
4388
4389 break;
4390 }
4391
4392 default:
4393 AssertMsgFailed(("should not get here!\n"));
4394 break;
4395 }
4396
4397 meAttachmentType[uInstance] = eAttachmentType;
4398 }
4399 catch (ConfigError &x)
4400 {
4401 // InsertConfig threw something:
4402 return x.m_vrc;
4403 }
4404
4405#undef H
4406
4407 return VINF_SUCCESS;
4408}
4409
4410#ifdef VBOX_WITH_GUEST_PROPS
4411/**
4412 * Set an array of guest properties
4413 */
4414static void configSetProperties(VMMDev * const pVMMDev,
4415 void *names,
4416 void *values,
4417 void *timestamps,
4418 void *flags)
4419{
4420 VBOXHGCMSVCPARM parms[4];
4421
4422 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
4423 parms[0].u.pointer.addr = names;
4424 parms[0].u.pointer.size = 0; /* We don't actually care. */
4425 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
4426 parms[1].u.pointer.addr = values;
4427 parms[1].u.pointer.size = 0; /* We don't actually care. */
4428 parms[2].type = VBOX_HGCM_SVC_PARM_PTR;
4429 parms[2].u.pointer.addr = timestamps;
4430 parms[2].u.pointer.size = 0; /* We don't actually care. */
4431 parms[3].type = VBOX_HGCM_SVC_PARM_PTR;
4432 parms[3].u.pointer.addr = flags;
4433 parms[3].u.pointer.size = 0; /* We don't actually care. */
4434
4435 pVMMDev->hgcmHostCall("VBoxGuestPropSvc",
4436 guestProp::SET_PROPS_HOST,
4437 4,
4438 &parms[0]);
4439}
4440
4441/**
4442 * Set a single guest property
4443 */
4444static void configSetProperty(VMMDev * const pVMMDev,
4445 const char *pszName,
4446 const char *pszValue,
4447 const char *pszFlags)
4448{
4449 VBOXHGCMSVCPARM parms[4];
4450
4451 AssertPtrReturnVoid(pszName);
4452 AssertPtrReturnVoid(pszValue);
4453 AssertPtrReturnVoid(pszFlags);
4454 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
4455 parms[0].u.pointer.addr = (void *)pszName;
4456 parms[0].u.pointer.size = strlen(pszName) + 1;
4457 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
4458 parms[1].u.pointer.addr = (void *)pszValue;
4459 parms[1].u.pointer.size = strlen(pszValue) + 1;
4460 parms[2].type = VBOX_HGCM_SVC_PARM_PTR;
4461 parms[2].u.pointer.addr = (void *)pszFlags;
4462 parms[2].u.pointer.size = strlen(pszFlags) + 1;
4463 pVMMDev->hgcmHostCall("VBoxGuestPropSvc", guestProp::SET_PROP_HOST, 3,
4464 &parms[0]);
4465}
4466
4467/**
4468 * Set the global flags value by calling the service
4469 * @returns the status returned by the call to the service
4470 *
4471 * @param pTable the service instance handle
4472 * @param eFlags the flags to set
4473 */
4474int configSetGlobalPropertyFlags(VMMDev * const pVMMDev,
4475 guestProp::ePropFlags eFlags)
4476{
4477 VBOXHGCMSVCPARM paParm;
4478 paParm.setUInt32(eFlags);
4479 int rc = pVMMDev->hgcmHostCall("VBoxGuestPropSvc",
4480 guestProp::SET_GLOBAL_FLAGS_HOST, 1,
4481 &paParm);
4482 if (RT_FAILURE(rc))
4483 {
4484 char szFlags[guestProp::MAX_FLAGS_LEN];
4485 if (RT_FAILURE(writeFlags(eFlags, szFlags)))
4486 Log(("Failed to set the global flags.\n"));
4487 else
4488 Log(("Failed to set the global flags \"%s\".\n", szFlags));
4489 }
4490 return rc;
4491}
4492#endif /* VBOX_WITH_GUEST_PROPS */
4493
4494/**
4495 * Set up the Guest Property service, populate it with properties read from
4496 * the machine XML and set a couple of initial properties.
4497 */
4498/* static */ int Console::configGuestProperties(void *pvConsole)
4499{
4500#ifdef VBOX_WITH_GUEST_PROPS
4501 AssertReturn(pvConsole, VERR_GENERAL_FAILURE);
4502 ComObjPtr<Console> pConsole = static_cast<Console *>(pvConsole);
4503 AssertReturn(pConsole->m_pVMMDev, VERR_GENERAL_FAILURE);
4504
4505 /* Load the service */
4506 int rc = pConsole->m_pVMMDev->hgcmLoadService("VBoxGuestPropSvc", "VBoxGuestPropSvc");
4507
4508 if (RT_FAILURE(rc))
4509 {
4510 LogRel(("VBoxGuestPropSvc is not available. rc = %Rrc\n", rc));
4511 /* That is not a fatal failure. */
4512 rc = VINF_SUCCESS;
4513 }
4514 else
4515 {
4516 /*
4517 * Initialize built-in properties that can be changed and saved.
4518 *
4519 * These are typically transient properties that the guest cannot
4520 * change.
4521 */
4522
4523 /* Sysprep execution by VBoxService. */
4524 configSetProperty(pConsole->m_pVMMDev,
4525 "/VirtualBox/HostGuest/SysprepExec", "",
4526 "TRANSIENT, RDONLYGUEST");
4527 configSetProperty(pConsole->m_pVMMDev,
4528 "/VirtualBox/HostGuest/SysprepArgs", "",
4529 "TRANSIENT, RDONLYGUEST");
4530
4531 /*
4532 * Pull over the properties from the server.
4533 */
4534 SafeArray<BSTR> namesOut;
4535 SafeArray<BSTR> valuesOut;
4536 SafeArray<LONG64> timestampsOut;
4537 SafeArray<BSTR> flagsOut;
4538 HRESULT hrc;
4539 hrc = pConsole->mControl->PullGuestProperties(ComSafeArrayAsOutParam(namesOut),
4540 ComSafeArrayAsOutParam(valuesOut),
4541 ComSafeArrayAsOutParam(timestampsOut),
4542 ComSafeArrayAsOutParam(flagsOut));
4543 AssertMsgReturn(SUCCEEDED(hrc), ("hrc=%Rrc\n", hrc), VERR_GENERAL_FAILURE);
4544 size_t cProps = namesOut.size();
4545 size_t cAlloc = cProps + 1;
4546 if ( valuesOut.size() != cProps
4547 || timestampsOut.size() != cProps
4548 || flagsOut.size() != cProps
4549 )
4550 AssertFailedReturn(VERR_INVALID_PARAMETER);
4551
4552 char **papszNames, **papszValues, **papszFlags;
4553 char szEmpty[] = "";
4554 LONG64 *pai64Timestamps;
4555 papszNames = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
4556 papszValues = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
4557 pai64Timestamps = (LONG64 *)RTMemTmpAllocZ(sizeof(LONG64) * cAlloc);
4558 papszFlags = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
4559 if (papszNames && papszValues && pai64Timestamps && papszFlags)
4560 {
4561 for (unsigned i = 0; RT_SUCCESS(rc) && i < cProps; ++i)
4562 {
4563 AssertPtrReturn(namesOut[i], VERR_INVALID_PARAMETER);
4564 rc = RTUtf16ToUtf8(namesOut[i], &papszNames[i]);
4565 if (RT_FAILURE(rc))
4566 break;
4567 if (valuesOut[i])
4568 rc = RTUtf16ToUtf8(valuesOut[i], &papszValues[i]);
4569 else
4570 papszValues[i] = szEmpty;
4571 if (RT_FAILURE(rc))
4572 break;
4573 pai64Timestamps[i] = timestampsOut[i];
4574 if (flagsOut[i])
4575 rc = RTUtf16ToUtf8(flagsOut[i], &papszFlags[i]);
4576 else
4577 papszFlags[i] = szEmpty;
4578 }
4579 if (RT_SUCCESS(rc))
4580 configSetProperties(pConsole->m_pVMMDev,
4581 (void *)papszNames,
4582 (void *)papszValues,
4583 (void *)pai64Timestamps,
4584 (void *)papszFlags);
4585 for (unsigned i = 0; i < cProps; ++i)
4586 {
4587 RTStrFree(papszNames[i]);
4588 if (valuesOut[i])
4589 RTStrFree(papszValues[i]);
4590 if (flagsOut[i])
4591 RTStrFree(papszFlags[i]);
4592 }
4593 }
4594 else
4595 rc = VERR_NO_MEMORY;
4596 RTMemTmpFree(papszNames);
4597 RTMemTmpFree(papszValues);
4598 RTMemTmpFree(pai64Timestamps);
4599 RTMemTmpFree(papszFlags);
4600 AssertRCReturn(rc, rc);
4601
4602 /*
4603 * These properties have to be set before pulling over the properties
4604 * from the machine XML, to ensure that properties saved in the XML
4605 * will override them.
4606 */
4607 /* Set the VBox version string as a guest property */
4608 configSetProperty(pConsole->m_pVMMDev, "/VirtualBox/HostInfo/VBoxVer",
4609 VBOX_VERSION_STRING, "TRANSIENT, RDONLYGUEST");
4610 /* Set the VBox SVN revision as a guest property */
4611 configSetProperty(pConsole->m_pVMMDev, "/VirtualBox/HostInfo/VBoxRev",
4612 RTBldCfgRevisionStr(), "TRANSIENT, RDONLYGUEST");
4613
4614 /*
4615 * Register the host notification callback
4616 */
4617 HGCMSVCEXTHANDLE hDummy;
4618 HGCMHostRegisterServiceExtension(&hDummy, "VBoxGuestPropSvc",
4619 Console::doGuestPropNotification,
4620 pvConsole);
4621
4622#ifdef VBOX_WITH_GUEST_PROPS_RDONLY_GUEST
4623 rc = configSetGlobalPropertyFlags(pConsole->m_pVMMDev,
4624 guestProp::RDONLYGUEST);
4625 AssertRCReturn(rc, rc);
4626#endif
4627
4628 Log(("Set VBoxGuestPropSvc property store\n"));
4629 }
4630 return VINF_SUCCESS;
4631#else /* !VBOX_WITH_GUEST_PROPS */
4632 return VERR_NOT_SUPPORTED;
4633#endif /* !VBOX_WITH_GUEST_PROPS */
4634}
4635
4636/**
4637 * Set up the Guest Control service.
4638 */
4639/* static */ int Console::configGuestControl(void *pvConsole)
4640{
4641#ifdef VBOX_WITH_GUEST_CONTROL
4642 AssertReturn(pvConsole, VERR_GENERAL_FAILURE);
4643 ComObjPtr<Console> pConsole = static_cast<Console *>(pvConsole);
4644
4645 /* Load the service */
4646 int rc = pConsole->m_pVMMDev->hgcmLoadService("VBoxGuestControlSvc", "VBoxGuestControlSvc");
4647
4648 if (RT_FAILURE(rc))
4649 {
4650 LogRel(("VBoxGuestControlSvc is not available. rc = %Rrc\n", rc));
4651 /* That is not a fatal failure. */
4652 rc = VINF_SUCCESS;
4653 }
4654 else
4655 {
4656 HGCMSVCEXTHANDLE hDummy;
4657 rc = HGCMHostRegisterServiceExtension(&hDummy, "VBoxGuestControlSvc",
4658 &Guest::doGuestCtrlNotification,
4659 pConsole->getGuest());
4660 if (RT_FAILURE(rc))
4661 Log(("Cannot register VBoxGuestControlSvc extension!\n"));
4662 else
4663 Log(("VBoxGuestControlSvc loaded\n"));
4664 }
4665
4666 return rc;
4667#else /* !VBOX_WITH_GUEST_CONTROL */
4668 return VERR_NOT_SUPPORTED;
4669#endif /* !VBOX_WITH_GUEST_CONTROL */
4670}
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