VirtualBox

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

Last change on this file since 45426 was 45367, checked in by vboxsync, 12 years ago

Main: a couple of whitespace fixes

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette