VirtualBox

source: vbox/trunk/src/VBox/Main/ConsoleImpl2.cpp@ 35263

Last change on this file since 35263 was 35171, checked in by vboxsync, 13 years ago

Main/Console: log the file system of the snapshot folder as well

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

© 2023 Oracle
ContactPrivacy policyTerms of Use