VirtualBox

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

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

DBGF,DBGC,++: PVM -> PUVM. Some refactoring and cleanup as well.

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

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