VirtualBox

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

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

PDM,++: Change APIs used by Main from PVM to PUVM.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 209.5 KB
Line 
1/* $Id: ConsoleImpl2.cpp 44351 2013-01-24 12:04:39Z 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(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 PUVM pUVM = pConsole->mpUVM = VMR3GetUVM(pVM);
678 VMR3RetainUVM(pUVM);
679 int vrc;
680 try
681 {
682 vrc = pConsole->configConstructorInner(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 pVM The VM handle.
703 * @param pAlock The automatic lock instance. This is for when we have
704 * to leave it in order to avoid deadlocks (ext packs and
705 * more).
706 */
707int Console::configConstructorInner(PVM pVM, AutoWriteLock *pAlock)
708{
709 PUVM pUVM = VMR3GetUVM(pVM);
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 */
3077/*static*/
3078void Console::setVMRuntimeErrorCallbackF(PVM pVM, void *pvConsole, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, ...)
3079{
3080 va_list va;
3081 va_start(va, pszFormat);
3082 setVMRuntimeErrorCallback(pVM, pvConsole, fFlags, pszErrorId, pszFormat, va);
3083 va_end(va);
3084}
3085
3086/* XXX introduce RT format specifier */
3087static uint64_t formatDiskSize(uint64_t u64Size, const char **pszUnit)
3088{
3089 if (u64Size > INT64_C(5000)*_1G)
3090 {
3091 *pszUnit = "TB";
3092 return u64Size / _1T;
3093 }
3094 else if (u64Size > INT64_C(5000)*_1M)
3095 {
3096 *pszUnit = "GB";
3097 return u64Size / _1G;
3098 }
3099 else
3100 {
3101 *pszUnit = "MB";
3102 return u64Size / _1M;
3103 }
3104}
3105
3106int Console::configMediumAttachment(PCFGMNODE pCtlInst,
3107 const char *pcszDevice,
3108 unsigned uInstance,
3109 StorageBus_T enmBus,
3110 bool fUseHostIOCache,
3111 bool fBuiltinIOCache,
3112 bool fSetupMerge,
3113 unsigned uMergeSource,
3114 unsigned uMergeTarget,
3115 IMediumAttachment *pMediumAtt,
3116 MachineState_T aMachineState,
3117 HRESULT *phrc,
3118 bool fAttachDetach,
3119 bool fForceUnmount,
3120 bool fHotplug,
3121 PUVM pUVM,
3122 DeviceType_T *paLedDevType)
3123{
3124 // InsertConfig* throws
3125 try
3126 {
3127 int rc = VINF_SUCCESS;
3128 HRESULT hrc;
3129 Bstr bstr;
3130
3131// #define RC_CHECK() AssertMsgReturn(RT_SUCCESS(rc), ("rc=%Rrc\n", rc), rc)
3132#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
3133
3134 LONG lDev;
3135 hrc = pMediumAtt->COMGETTER(Device)(&lDev); H();
3136 LONG lPort;
3137 hrc = pMediumAtt->COMGETTER(Port)(&lPort); H();
3138 DeviceType_T lType;
3139 hrc = pMediumAtt->COMGETTER(Type)(&lType); H();
3140 BOOL fNonRotational;
3141 hrc = pMediumAtt->COMGETTER(NonRotational)(&fNonRotational); H();
3142 BOOL fDiscard;
3143 hrc = pMediumAtt->COMGETTER(Discard)(&fDiscard); H();
3144
3145 unsigned uLUN;
3146 PCFGMNODE pLunL0 = NULL;
3147 hrc = Console::convertBusPortDeviceToLun(enmBus, lPort, lDev, uLUN); H();
3148
3149 /* First check if the LUN already exists. */
3150 pLunL0 = CFGMR3GetChildF(pCtlInst, "LUN#%u", uLUN);
3151 if (pLunL0)
3152 {
3153 if (fAttachDetach)
3154 {
3155 if (lType != DeviceType_HardDisk)
3156 {
3157 /* Unmount existing media only for floppy and DVD drives. */
3158 PPDMIBASE pBase;
3159 rc = PDMR3QueryLun(pUVM, pcszDevice, uInstance, uLUN, &pBase);
3160 if (RT_FAILURE(rc))
3161 {
3162 if (rc == VERR_PDM_LUN_NOT_FOUND || rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
3163 rc = VINF_SUCCESS;
3164 AssertRC(rc);
3165 }
3166 else
3167 {
3168 PPDMIMOUNT pIMount = PDMIBASE_QUERY_INTERFACE(pBase, PDMIMOUNT);
3169 AssertReturn(pIMount, VERR_INVALID_POINTER);
3170
3171 /* Unmount the media (but do not eject the medium!) */
3172 rc = pIMount->pfnUnmount(pIMount, fForceUnmount, false /*=fEject*/);
3173 if (rc == VERR_PDM_MEDIA_NOT_MOUNTED)
3174 rc = VINF_SUCCESS;
3175 /* for example if the medium is locked */
3176 else if (RT_FAILURE(rc))
3177 return rc;
3178 }
3179 }
3180
3181 rc = PDMR3DeviceDetach(pUVM, pcszDevice, uInstance, uLUN, fHotplug ? 0 : PDM_TACH_FLAGS_NOT_HOT_PLUG);
3182 if (rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
3183 rc = VINF_SUCCESS;
3184 AssertRCReturn(rc, rc);
3185
3186 CFGMR3RemoveNode(pLunL0);
3187 }
3188 else
3189 AssertFailedReturn(VERR_INTERNAL_ERROR);
3190 }
3191
3192 InsertConfigNode(pCtlInst, Utf8StrFmt("LUN#%u", uLUN).c_str(), &pLunL0);
3193
3194 PCFGMNODE pCfg = CFGMR3GetChild(pCtlInst, "Config");
3195 if (pCfg)
3196 {
3197 if (!strcmp(pcszDevice, "piix3ide"))
3198 {
3199 PCFGMNODE pDrive = CFGMR3GetChild(pCfg, g_apszIDEDrives[uLUN]);
3200 if (!pDrive)
3201 InsertConfigNode(pCfg, g_apszIDEDrives[uLUN], &pDrive);
3202 /* Don't use the RemoveConfigValue wrapper above, as we don't
3203 * know if the leaf is present or not. */
3204 CFGMR3RemoveValue(pDrive, "NonRotationalMedium");
3205 InsertConfigInteger(pDrive, "NonRotationalMedium", !!fNonRotational);
3206 }
3207 else if (!strcmp(pcszDevice, "ahci"))
3208 {
3209 Utf8Str strPort = Utf8StrFmt("Port%u", uLUN);
3210 PCFGMNODE pDrive = CFGMR3GetChild(pCfg, strPort.c_str());
3211 if (!pDrive)
3212 InsertConfigNode(pCfg, strPort.c_str(), &pDrive);
3213 /* Don't use the RemoveConfigValue wrapper above, as we don't
3214 * know if the leaf is present or not. */
3215 CFGMR3RemoveValue(pDrive, "NonRotationalMedium");
3216 InsertConfigInteger(pDrive, "NonRotationalMedium", !!fNonRotational);
3217 }
3218 }
3219
3220 Utf8Str devicePath = Utf8StrFmt("%s/%u/LUN#%u", pcszDevice, uInstance, uLUN);
3221 mapMediumAttachments[devicePath] = pMediumAtt;
3222
3223 /* SCSI has a another driver between device and block. */
3224 if (enmBus == StorageBus_SCSI || enmBus == StorageBus_SAS)
3225 {
3226 InsertConfigString(pLunL0, "Driver", "SCSI");
3227 PCFGMNODE pL1Cfg = NULL;
3228 InsertConfigNode(pLunL0, "Config", &pL1Cfg);
3229 InsertConfigInteger(pL1Cfg, "NonRotationalMedium", !!fNonRotational);
3230
3231 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
3232 }
3233
3234 ComPtr<IMedium> pMedium;
3235 hrc = pMediumAtt->COMGETTER(Medium)(pMedium.asOutParam()); H();
3236
3237 /*
3238 * 1. Only check this for hard disk images.
3239 * 2. Only check during VM creation and not later, especially not during
3240 * taking an online snapshot!
3241 */
3242 if ( lType == DeviceType_HardDisk
3243 && ( aMachineState == MachineState_Starting
3244 || aMachineState == MachineState_Restoring))
3245 {
3246 /*
3247 * Some sanity checks.
3248 */
3249 ComPtr<IMediumFormat> pMediumFormat;
3250 hrc = pMedium->COMGETTER(MediumFormat)(pMediumFormat.asOutParam()); H();
3251 ULONG uCaps;
3252 hrc = pMediumFormat->COMGETTER(Capabilities)(&uCaps); H();
3253 if (uCaps & MediumFormatCapabilities_File)
3254 {
3255 Bstr strFile;
3256 hrc = pMedium->COMGETTER(Location)(strFile.asOutParam()); H();
3257 Utf8Str utfFile = Utf8Str(strFile);
3258 Bstr strSnap;
3259 ComPtr<IMachine> pMachine = machine();
3260 hrc = pMachine->COMGETTER(SnapshotFolder)(strSnap.asOutParam()); H();
3261 Utf8Str utfSnap = Utf8Str(strSnap);
3262 RTFSTYPE enmFsTypeFile = RTFSTYPE_UNKNOWN;
3263 RTFSTYPE enmFsTypeSnap = RTFSTYPE_UNKNOWN;
3264 int rc2 = RTFsQueryType(utfFile.c_str(), &enmFsTypeFile);
3265 AssertMsgRCReturn(rc2, ("Querying the file type of '%s' failed!\n", utfFile.c_str()), rc2);
3266 /* Ignore the error code. On error, the file system type is still 'unknown' so
3267 * none of the following paths are taken. This can happen for new VMs which
3268 * still don't have a snapshot folder. */
3269 (void)RTFsQueryType(utfSnap.c_str(), &enmFsTypeSnap);
3270 if (!mfSnapshotFolderDiskTypeShown)
3271 {
3272 LogRel(("File system of '%s' (snapshots) is %s\n",
3273 utfSnap.c_str(), RTFsTypeName(enmFsTypeSnap)));
3274 mfSnapshotFolderDiskTypeShown = true;
3275 }
3276 LogRel(("File system of '%s' is %s\n", utfFile.c_str(), RTFsTypeName(enmFsTypeFile)));
3277 LONG64 i64Size;
3278 hrc = pMedium->COMGETTER(LogicalSize)(&i64Size); H();
3279#ifdef RT_OS_WINDOWS
3280 if ( enmFsTypeFile == RTFSTYPE_FAT
3281 && i64Size >= _4G)
3282 {
3283 const char *pszUnit;
3284 uint64_t u64Print = formatDiskSize((uint64_t)i64Size, &pszUnit);
3285 setVMRuntimeErrorCallbackF(VMR3GetVM(pUVM), this, 0,
3286 "FatPartitionDetected",
3287 N_("The medium '%ls' has a logical size of %RU64%s "
3288 "but the file system the medium is located on seems "
3289 "to be FAT(32) which cannot handle files bigger than 4GB.\n"
3290 "We strongly recommend to put all your virtual disk images and "
3291 "the snapshot folder onto an NTFS partition"),
3292 strFile.raw(), u64Print, pszUnit);
3293 }
3294#else /* !RT_OS_WINDOWS */
3295 if ( enmFsTypeFile == RTFSTYPE_FAT
3296 || enmFsTypeFile == RTFSTYPE_EXT
3297 || enmFsTypeFile == RTFSTYPE_EXT2
3298 || enmFsTypeFile == RTFSTYPE_EXT3
3299 || enmFsTypeFile == RTFSTYPE_EXT4)
3300 {
3301 RTFILE file;
3302 rc = RTFileOpen(&file, utfFile.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
3303 if (RT_SUCCESS(rc))
3304 {
3305 RTFOFF maxSize;
3306 /* Careful: This function will work only on selected local file systems! */
3307 rc = RTFileGetMaxSizeEx(file, &maxSize);
3308 RTFileClose(file);
3309 if ( RT_SUCCESS(rc)
3310 && maxSize > 0
3311 && i64Size > (LONG64)maxSize)
3312 {
3313 const char *pszUnitSiz;
3314 const char *pszUnitMax;
3315 uint64_t u64PrintSiz = formatDiskSize((LONG64)i64Size, &pszUnitSiz);
3316 uint64_t u64PrintMax = formatDiskSize(maxSize, &pszUnitMax);
3317 setVMRuntimeErrorCallbackF(VMR3GetVM(pUVM), this, 0,
3318 "FatPartitionDetected", /* <= not exact but ... */
3319 N_("The medium '%ls' has a logical size of %RU64%s "
3320 "but the file system the medium is located on can "
3321 "only handle files up to %RU64%s in theory.\n"
3322 "We strongly recommend to put all your virtual disk "
3323 "images and the snapshot folder onto a proper "
3324 "file system (e.g. ext3) with a sufficient size"),
3325 strFile.raw(), u64PrintSiz, pszUnitSiz, u64PrintMax, pszUnitMax);
3326 }
3327 }
3328 }
3329#endif /* !RT_OS_WINDOWS */
3330
3331 /*
3332 * Snapshot folder:
3333 * Here we test only for a FAT partition as we had to create a dummy file otherwise
3334 */
3335 if ( enmFsTypeSnap == RTFSTYPE_FAT
3336 && i64Size >= _4G
3337 && !mfSnapshotFolderSizeWarningShown)
3338 {
3339 const char *pszUnit;
3340 uint64_t u64Print = formatDiskSize(i64Size, &pszUnit);
3341 setVMRuntimeErrorCallbackF(VMR3GetVM(pUVM), this, 0,
3342 "FatPartitionDetected",
3343#ifdef RT_OS_WINDOWS
3344 N_("The snapshot folder of this VM '%ls' seems to be located on "
3345 "a FAT(32) file system. The logical size of the medium '%ls' "
3346 "(%RU64%s) is bigger than the maximum file size this file "
3347 "system can handle (4GB).\n"
3348 "We strongly recommend to put all your virtual disk images and "
3349 "the snapshot folder onto an NTFS partition"),
3350#else
3351 N_("The snapshot folder of this VM '%ls' seems to be located on "
3352 "a FAT(32) file system. The logical size of the medium '%ls' "
3353 "(%RU64%s) is bigger than the maximum file size this file "
3354 "system can handle (4GB).\n"
3355 "We strongly recommend to put all your virtual disk images and "
3356 "the snapshot folder onto a proper file system (e.g. ext3)"),
3357#endif
3358 strSnap.raw(), strFile.raw(), u64Print, pszUnit);
3359 /* Show this particular warning only once */
3360 mfSnapshotFolderSizeWarningShown = true;
3361 }
3362
3363#ifdef RT_OS_LINUX
3364 /*
3365 * Ext4 bug: Check if the host I/O cache is disabled and the disk image is located
3366 * on an ext4 partition. Later we have to check the Linux kernel version!
3367 * This bug apparently applies to the XFS file system as well.
3368 * Linux 2.6.36 is known to be fixed (tested with 2.6.36-rc4).
3369 */
3370
3371 char szOsRelease[128];
3372 rc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szOsRelease, sizeof(szOsRelease));
3373 bool fKernelHasODirectBug = RT_FAILURE(rc)
3374 || (RTStrVersionCompare(szOsRelease, "2.6.36-rc4") < 0);
3375
3376 if ( (uCaps & MediumFormatCapabilities_Asynchronous)
3377 && !fUseHostIOCache
3378 && fKernelHasODirectBug)
3379 {
3380 if ( enmFsTypeFile == RTFSTYPE_EXT4
3381 || enmFsTypeFile == RTFSTYPE_XFS)
3382 {
3383 setVMRuntimeErrorCallbackF(VMR3GetVM(pUVM), this, 0,
3384 "Ext4PartitionDetected",
3385 N_("The host I/O cache for at least one controller is disabled "
3386 "and the medium '%ls' for this VM "
3387 "is located on an %s partition. There is a known Linux "
3388 "kernel bug which can lead to the corruption of the virtual "
3389 "disk image under these conditions.\n"
3390 "Either enable the host I/O cache permanently in the VM "
3391 "settings or put the disk image and the snapshot folder "
3392 "onto a different file system.\n"
3393 "The host I/O cache will now be enabled for this medium"),
3394 strFile.raw(), enmFsTypeFile == RTFSTYPE_EXT4 ? "ext4" : "xfs");
3395 fUseHostIOCache = true;
3396 }
3397 else if ( ( enmFsTypeSnap == RTFSTYPE_EXT4
3398 || enmFsTypeSnap == RTFSTYPE_XFS)
3399 && !mfSnapshotFolderExt4WarningShown)
3400 {
3401 setVMRuntimeErrorCallbackF(VMR3GetVM(pUVM), this, 0,
3402 "Ext4PartitionDetected",
3403 N_("The host I/O cache for at least one controller is disabled "
3404 "and the snapshot folder for this VM "
3405 "is located on an %s partition. There is a known Linux "
3406 "kernel bug which can lead to the corruption of the virtual "
3407 "disk image under these conditions.\n"
3408 "Either enable the host I/O cache permanently in the VM "
3409 "settings or put the disk image and the snapshot folder "
3410 "onto a different file system.\n"
3411 "The host I/O cache will now be enabled for this medium"),
3412 enmFsTypeSnap == RTFSTYPE_EXT4 ? "ext4" : "xfs");
3413 fUseHostIOCache = true;
3414 mfSnapshotFolderExt4WarningShown = true;
3415 }
3416 }
3417#endif
3418 }
3419 }
3420
3421 if ( pMedium
3422 && ( lType == DeviceType_DVD
3423 || lType == DeviceType_Floppy))
3424 {
3425 /*
3426 * Informative logging.
3427 */
3428 ComPtr<IMediumFormat> pMediumFormat;
3429 hrc = pMedium->COMGETTER(MediumFormat)(pMediumFormat.asOutParam()); H();
3430 ULONG uCaps;
3431 hrc = pMediumFormat->COMGETTER(Capabilities)(&uCaps); H();
3432 if (uCaps & MediumFormatCapabilities_File)
3433 {
3434 Bstr strFile;
3435 hrc = pMedium->COMGETTER(Location)(strFile.asOutParam()); H();
3436 Utf8Str utfFile = Utf8Str(strFile);
3437 RTFSTYPE enmFsTypeFile = RTFSTYPE_UNKNOWN;
3438 (void)RTFsQueryType(utfFile.c_str(), &enmFsTypeFile);
3439 LogRel(("File system of '%s' (%s) is %s\n",
3440 utfFile.c_str(), lType == DeviceType_DVD ? "DVD" : "Floppy",
3441 RTFsTypeName(enmFsTypeFile)));
3442 }
3443 }
3444
3445 BOOL fPassthrough;
3446 hrc = pMediumAtt->COMGETTER(Passthrough)(&fPassthrough); H();
3447
3448 ComObjPtr<IBandwidthGroup> pBwGroup;
3449 Bstr strBwGroup;
3450 hrc = pMediumAtt->COMGETTER(BandwidthGroup)(pBwGroup.asOutParam()); H();
3451
3452 if (!pBwGroup.isNull())
3453 {
3454 hrc = pBwGroup->COMGETTER(Name)(strBwGroup.asOutParam()); H();
3455 }
3456
3457 rc = configMedium(pLunL0,
3458 !!fPassthrough,
3459 lType,
3460 fUseHostIOCache,
3461 fBuiltinIOCache,
3462 fSetupMerge,
3463 uMergeSource,
3464 uMergeTarget,
3465 strBwGroup.isEmpty() ? NULL : Utf8Str(strBwGroup).c_str(),
3466 !!fDiscard,
3467 pMedium,
3468 aMachineState,
3469 phrc);
3470 if (RT_FAILURE(rc))
3471 return rc;
3472
3473 if (fAttachDetach)
3474 {
3475 /* Attach the new driver. */
3476 rc = PDMR3DeviceAttach(pUVM, pcszDevice, uInstance, uLUN,
3477 fHotplug ? 0 : PDM_TACH_FLAGS_NOT_HOT_PLUG, NULL /*ppBase*/);
3478 AssertRCReturn(rc, rc);
3479
3480 /* There is no need to handle removable medium mounting, as we
3481 * unconditionally replace everthing including the block driver level.
3482 * This means the new medium will be picked up automatically. */
3483 }
3484
3485 if (paLedDevType)
3486 paLedDevType[uLUN] = lType;
3487 }
3488 catch (ConfigError &x)
3489 {
3490 // InsertConfig threw something:
3491 return x.m_vrc;
3492 }
3493
3494#undef H
3495
3496 return VINF_SUCCESS;;
3497}
3498
3499int Console::configMedium(PCFGMNODE pLunL0,
3500 bool fPassthrough,
3501 DeviceType_T enmType,
3502 bool fUseHostIOCache,
3503 bool fBuiltinIOCache,
3504 bool fSetupMerge,
3505 unsigned uMergeSource,
3506 unsigned uMergeTarget,
3507 const char *pcszBwGroup,
3508 bool fDiscard,
3509 IMedium *pMedium,
3510 MachineState_T aMachineState,
3511 HRESULT *phrc)
3512{
3513 // InsertConfig* throws
3514 try
3515 {
3516 int rc = VINF_SUCCESS;
3517 HRESULT hrc;
3518 Bstr bstr;
3519 PCFGMNODE pLunL1 = NULL;
3520 PCFGMNODE pCfg = NULL;
3521
3522#define H() \
3523 AssertMsgReturnStmt(SUCCEEDED(hrc), ("hrc=%Rhrc\n", hrc), if (phrc) *phrc = hrc, Global::vboxStatusCodeFromCOM(hrc))
3524
3525
3526 BOOL fHostDrive = FALSE;
3527 MediumType_T mediumType = MediumType_Normal;
3528 if (pMedium)
3529 {
3530 hrc = pMedium->COMGETTER(HostDrive)(&fHostDrive); H();
3531 hrc = pMedium->COMGETTER(Type)(&mediumType); H();
3532 }
3533
3534 if (fHostDrive)
3535 {
3536 Assert(pMedium);
3537 if (enmType == DeviceType_DVD)
3538 {
3539 InsertConfigString(pLunL0, "Driver", "HostDVD");
3540 InsertConfigNode(pLunL0, "Config", &pCfg);
3541
3542 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3543 InsertConfigString(pCfg, "Path", bstr);
3544
3545 InsertConfigInteger(pCfg, "Passthrough", fPassthrough);
3546 }
3547 else if (enmType == DeviceType_Floppy)
3548 {
3549 InsertConfigString(pLunL0, "Driver", "HostFloppy");
3550 InsertConfigNode(pLunL0, "Config", &pCfg);
3551
3552 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3553 InsertConfigString(pCfg, "Path", bstr);
3554 }
3555 }
3556 else
3557 {
3558 InsertConfigString(pLunL0, "Driver", "Block");
3559 InsertConfigNode(pLunL0, "Config", &pCfg);
3560 switch (enmType)
3561 {
3562 case DeviceType_DVD:
3563 InsertConfigString(pCfg, "Type", "DVD");
3564 InsertConfigInteger(pCfg, "Mountable", 1);
3565 break;
3566 case DeviceType_Floppy:
3567 InsertConfigString(pCfg, "Type", "Floppy 1.44");
3568 InsertConfigInteger(pCfg, "Mountable", 1);
3569 break;
3570 case DeviceType_HardDisk:
3571 default:
3572 InsertConfigString(pCfg, "Type", "HardDisk");
3573 InsertConfigInteger(pCfg, "Mountable", 0);
3574 }
3575
3576 if ( pMedium
3577 && ( enmType == DeviceType_DVD
3578 || enmType == DeviceType_Floppy)
3579 )
3580 {
3581 // if this medium represents an ISO image and this image is inaccessible,
3582 // the ignore it instead of causing a failure; this can happen when we
3583 // restore a VM state and the ISO has disappeared, e.g. because the Guest
3584 // Additions were mounted and the user upgraded VirtualBox. Previously
3585 // we failed on startup, but that's not good because the only way out then
3586 // would be to discard the VM state...
3587 MediumState_T mediumState;
3588 hrc = pMedium->RefreshState(&mediumState); H();
3589 if (mediumState == MediumState_Inaccessible)
3590 {
3591 Bstr loc;
3592 hrc = pMedium->COMGETTER(Location)(loc.asOutParam()); H();
3593 setVMRuntimeErrorCallbackF(VMR3GetVM(mpUVM),
3594 this,
3595 0,
3596 "DvdOrFloppyImageInaccessible",
3597 "The image file '%ls' is inaccessible and is being ignored. Please select a different image file for the virtual %s drive.",
3598 loc.raw(),
3599 enmType == DeviceType_DVD ? "DVD" : "floppy");
3600 pMedium = NULL;
3601 }
3602 }
3603
3604 if (pMedium)
3605 {
3606 /* Start with length of parent chain, as the list is reversed */
3607 unsigned uImage = 0;
3608 IMedium *pTmp = pMedium;
3609 while (pTmp)
3610 {
3611 uImage++;
3612 hrc = pTmp->COMGETTER(Parent)(&pTmp); H();
3613 }
3614 /* Index of last image */
3615 uImage--;
3616
3617#if 0 /* Enable for I/O debugging */
3618 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
3619 InsertConfigString(pLunL0, "Driver", "DiskIntegrity");
3620 InsertConfigNode(pLunL0, "Config", &pCfg);
3621 InsertConfigInteger(pCfg, "CheckConsistency", 0);
3622 InsertConfigInteger(pCfg, "CheckDoubleCompletions", 1);
3623#endif
3624
3625 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL1);
3626 InsertConfigString(pLunL1, "Driver", "VD");
3627 InsertConfigNode(pLunL1, "Config", &pCfg);
3628
3629 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3630 InsertConfigString(pCfg, "Path", bstr);
3631
3632 hrc = pMedium->COMGETTER(Format)(bstr.asOutParam()); H();
3633 InsertConfigString(pCfg, "Format", bstr);
3634
3635 if (mediumType == MediumType_Readonly)
3636 InsertConfigInteger(pCfg, "ReadOnly", 1);
3637 else if (enmType == DeviceType_Floppy)
3638 InsertConfigInteger(pCfg, "MaybeReadOnly", 1);
3639
3640 /* Start without exclusive write access to the images. */
3641 /** @todo Live Migration: I don't quite like this, we risk screwing up when
3642 * we're resuming the VM if some 3rd dude have any of the VDIs open
3643 * with write sharing denied. However, if the two VMs are sharing a
3644 * image it really is necessary....
3645 *
3646 * So, on the "lock-media" command, the target teleporter should also
3647 * make DrvVD undo TempReadOnly. It gets interesting if we fail after
3648 * that. Grumble. */
3649 if ( enmType == DeviceType_HardDisk
3650 && ( aMachineState == MachineState_TeleportingIn
3651 || aMachineState == MachineState_FaultTolerantSyncing))
3652 InsertConfigInteger(pCfg, "TempReadOnly", 1);
3653
3654 /* Flag for opening the medium for sharing between VMs. This
3655 * is done at the moment only for the first (and only) medium
3656 * in the chain, as shared media can have no diffs. */
3657 if (mediumType == MediumType_Shareable)
3658 InsertConfigInteger(pCfg, "Shareable", 1);
3659
3660 if (!fUseHostIOCache)
3661 {
3662 InsertConfigInteger(pCfg, "UseNewIo", 1);
3663 /*
3664 * Activate the builtin I/O cache for harddisks only.
3665 * It caches writes only which doesn't make sense for DVD drives
3666 * and just increases the overhead.
3667 */
3668 if ( fBuiltinIOCache
3669 && (enmType == DeviceType_HardDisk))
3670 InsertConfigInteger(pCfg, "BlockCache", 1);
3671 }
3672
3673 if (fSetupMerge)
3674 {
3675 InsertConfigInteger(pCfg, "SetupMerge", 1);
3676 if (uImage == uMergeSource)
3677 InsertConfigInteger(pCfg, "MergeSource", 1);
3678 else if (uImage == uMergeTarget)
3679 InsertConfigInteger(pCfg, "MergeTarget", 1);
3680 }
3681
3682 switch (enmType)
3683 {
3684 case DeviceType_DVD:
3685 InsertConfigString(pCfg, "Type", "DVD");
3686 break;
3687 case DeviceType_Floppy:
3688 InsertConfigString(pCfg, "Type", "Floppy");
3689 break;
3690 case DeviceType_HardDisk:
3691 default:
3692 InsertConfigString(pCfg, "Type", "HardDisk");
3693 }
3694
3695 if (pcszBwGroup)
3696 InsertConfigString(pCfg, "BwGroup", pcszBwGroup);
3697
3698 if (fDiscard)
3699 InsertConfigInteger(pCfg, "Discard", 1);
3700
3701 /* Pass all custom parameters. */
3702 bool fHostIP = true;
3703 SafeArray<BSTR> names;
3704 SafeArray<BSTR> values;
3705 hrc = pMedium->GetProperties(Bstr().raw(),
3706 ComSafeArrayAsOutParam(names),
3707 ComSafeArrayAsOutParam(values)); H();
3708
3709 if (names.size() != 0)
3710 {
3711 PCFGMNODE pVDC;
3712 InsertConfigNode(pCfg, "VDConfig", &pVDC);
3713 for (size_t ii = 0; ii < names.size(); ++ii)
3714 {
3715 if (values[ii] && *values[ii])
3716 {
3717 Utf8Str name = names[ii];
3718 Utf8Str value = values[ii];
3719 InsertConfigString(pVDC, name.c_str(), value);
3720 if ( name.compare("HostIPStack") == 0
3721 && value.compare("0") == 0)
3722 fHostIP = false;
3723 }
3724 }
3725 }
3726
3727 /* Create an inverted list of parents. */
3728 uImage--;
3729 IMedium *pParentMedium = pMedium;
3730 for (PCFGMNODE pParent = pCfg;; uImage--)
3731 {
3732 hrc = pParentMedium->COMGETTER(Parent)(&pMedium); H();
3733 if (!pMedium)
3734 break;
3735
3736 PCFGMNODE pCur;
3737 InsertConfigNode(pParent, "Parent", &pCur);
3738 hrc = pMedium->COMGETTER(Location)(bstr.asOutParam()); H();
3739 InsertConfigString(pCur, "Path", bstr);
3740
3741 hrc = pMedium->COMGETTER(Format)(bstr.asOutParam()); H();
3742 InsertConfigString(pCur, "Format", bstr);
3743
3744 if (fSetupMerge)
3745 {
3746 if (uImage == uMergeSource)
3747 InsertConfigInteger(pCur, "MergeSource", 1);
3748 else if (uImage == uMergeTarget)
3749 InsertConfigInteger(pCur, "MergeTarget", 1);
3750 }
3751
3752 /* Pass all custom parameters. */
3753 SafeArray<BSTR> aNames;
3754 SafeArray<BSTR> aValues;
3755 hrc = pMedium->GetProperties(NULL,
3756 ComSafeArrayAsOutParam(aNames),
3757 ComSafeArrayAsOutParam(aValues)); H();
3758
3759 if (aNames.size() != 0)
3760 {
3761 PCFGMNODE pVDC;
3762 InsertConfigNode(pCur, "VDConfig", &pVDC);
3763 for (size_t ii = 0; ii < aNames.size(); ++ii)
3764 {
3765 if (aValues[ii] && *aValues[ii])
3766 {
3767 Utf8Str name = aNames[ii];
3768 Utf8Str value = aValues[ii];
3769 InsertConfigString(pVDC, name.c_str(), value);
3770 if ( name.compare("HostIPStack") == 0
3771 && value.compare("0") == 0)
3772 fHostIP = false;
3773 }
3774 }
3775 }
3776
3777 /* next */
3778 pParent = pCur;
3779 pParentMedium = pMedium;
3780 }
3781
3782 /* Custom code: put marker to not use host IP stack to driver
3783 * configuration node. Simplifies life of DrvVD a bit. */
3784 if (!fHostIP)
3785 InsertConfigInteger(pCfg, "HostIPStack", 0);
3786 }
3787 }
3788#undef H
3789 }
3790 catch (ConfigError &x)
3791 {
3792 // InsertConfig threw something:
3793 return x.m_vrc;
3794 }
3795
3796 return VINF_SUCCESS;
3797}
3798
3799/**
3800 * Construct the Network configuration tree
3801 *
3802 * @returns VBox status code.
3803 *
3804 * @param pszDevice The PDM device name.
3805 * @param uInstance The PDM device instance.
3806 * @param uLun The PDM LUN number of the drive.
3807 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
3808 * @param pCfg Configuration node for the device
3809 * @param pLunL0 To store the pointer to the LUN#0.
3810 * @param pInst The instance CFGM node
3811 * @param fAttachDetach To determine if the network attachment should
3812 * be attached/detached after/before
3813 * configuration.
3814 * @param fIgnoreConnectFailure
3815 * True if connection failures should be ignored
3816 * (makes only sense for bridged/host-only networks).
3817 *
3818 * @note Locks this object for writing.
3819 * @thread EMT
3820 */
3821int Console::configNetwork(const char *pszDevice,
3822 unsigned uInstance,
3823 unsigned uLun,
3824 INetworkAdapter *aNetworkAdapter,
3825 PCFGMNODE pCfg,
3826 PCFGMNODE pLunL0,
3827 PCFGMNODE pInst,
3828 bool fAttachDetach,
3829 bool fIgnoreConnectFailure)
3830{
3831 AutoCaller autoCaller(this);
3832 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
3833
3834 // InsertConfig* throws
3835 try
3836 {
3837 int rc = VINF_SUCCESS;
3838 HRESULT hrc;
3839 Bstr bstr;
3840
3841#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
3842
3843 /*
3844 * Locking the object before doing VMR3* calls is quite safe here, since
3845 * we're on EMT. Write lock is necessary because we indirectly modify the
3846 * meAttachmentType member.
3847 */
3848 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3849
3850 ComPtr<IMachine> pMachine = machine();
3851
3852 ComPtr<IVirtualBox> virtualBox;
3853 hrc = pMachine->COMGETTER(Parent)(virtualBox.asOutParam()); H();
3854
3855 ComPtr<IHost> host;
3856 hrc = virtualBox->COMGETTER(Host)(host.asOutParam()); H();
3857
3858 BOOL fSniffer;
3859 hrc = aNetworkAdapter->COMGETTER(TraceEnabled)(&fSniffer); H();
3860
3861 NetworkAdapterPromiscModePolicy_T enmPromiscModePolicy;
3862 hrc = aNetworkAdapter->COMGETTER(PromiscModePolicy)(&enmPromiscModePolicy); H();
3863 const char *pszPromiscuousGuestPolicy;
3864 switch (enmPromiscModePolicy)
3865 {
3866 case NetworkAdapterPromiscModePolicy_Deny: pszPromiscuousGuestPolicy = "deny"; break;
3867 case NetworkAdapterPromiscModePolicy_AllowNetwork: pszPromiscuousGuestPolicy = "allow-network"; break;
3868 case NetworkAdapterPromiscModePolicy_AllowAll: pszPromiscuousGuestPolicy = "allow-all"; break;
3869 default: AssertFailedReturn(VERR_INTERNAL_ERROR_4);
3870 }
3871
3872 if (fAttachDetach)
3873 {
3874 rc = PDMR3DeviceDetach(mpUVM, pszDevice, uInstance, uLun, 0 /*fFlags*/);
3875 if (rc == VINF_PDM_NO_DRIVER_ATTACHED_TO_LUN)
3876 rc = VINF_SUCCESS;
3877 AssertLogRelRCReturn(rc, rc);
3878
3879 /* nuke anything which might have been left behind. */
3880 CFGMR3RemoveNode(CFGMR3GetChildF(pInst, "LUN#%u", uLun));
3881 }
3882
3883#ifdef VBOX_WITH_NETSHAPER
3884 ComObjPtr<IBandwidthGroup> pBwGroup;
3885 Bstr strBwGroup;
3886 hrc = aNetworkAdapter->COMGETTER(BandwidthGroup)(pBwGroup.asOutParam()); H();
3887
3888 if (!pBwGroup.isNull())
3889 {
3890 hrc = pBwGroup->COMGETTER(Name)(strBwGroup.asOutParam()); H();
3891 }
3892#endif /* VBOX_WITH_NETSHAPER */
3893
3894 Utf8Str strNetDriver;
3895
3896
3897 InsertConfigNode(pInst, "LUN#0", &pLunL0);
3898
3899#ifdef VBOX_WITH_NETSHAPER
3900 if (!strBwGroup.isEmpty())
3901 {
3902 InsertConfigString(pLunL0, "Driver", "NetShaper");
3903 InsertConfigNode(pLunL0, "Config", &pCfg);
3904 InsertConfigString(pCfg, "BwGroup", strBwGroup);
3905 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
3906 }
3907#endif /* VBOX_WITH_NETSHAPER */
3908
3909 if (fSniffer)
3910 {
3911 InsertConfigString(pLunL0, "Driver", "NetSniffer");
3912 InsertConfigNode(pLunL0, "Config", &pCfg);
3913 hrc = aNetworkAdapter->COMGETTER(TraceFile)(bstr.asOutParam()); H();
3914 if (!bstr.isEmpty()) /* check convention for indicating default file. */
3915 InsertConfigString(pCfg, "File", bstr);
3916 InsertConfigNode(pLunL0, "AttachedDriver", &pLunL0);
3917 }
3918
3919
3920 Bstr networkName, trunkName, trunkType;
3921 NetworkAttachmentType_T eAttachmentType;
3922 hrc = aNetworkAdapter->COMGETTER(AttachmentType)(&eAttachmentType); H();
3923 switch (eAttachmentType)
3924 {
3925 case NetworkAttachmentType_Null:
3926 break;
3927
3928 case NetworkAttachmentType_NAT:
3929 {
3930 ComPtr<INATEngine> natEngine;
3931 hrc = aNetworkAdapter->COMGETTER(NATEngine)(natEngine.asOutParam()); H();
3932 InsertConfigString(pLunL0, "Driver", "NAT");
3933 InsertConfigNode(pLunL0, "Config", &pCfg);
3934
3935 /* Configure TFTP prefix and boot filename. */
3936 hrc = virtualBox->COMGETTER(HomeFolder)(bstr.asOutParam()); H();
3937 if (!bstr.isEmpty())
3938 InsertConfigString(pCfg, "TFTPPrefix", Utf8StrFmt("%ls%c%s", bstr.raw(), RTPATH_DELIMITER, "TFTP"));
3939 hrc = pMachine->COMGETTER(Name)(bstr.asOutParam()); H();
3940 InsertConfigString(pCfg, "BootFile", Utf8StrFmt("%ls.pxe", bstr.raw()));
3941
3942 hrc = natEngine->COMGETTER(Network)(bstr.asOutParam()); H();
3943 if (!bstr.isEmpty())
3944 InsertConfigString(pCfg, "Network", bstr);
3945 else
3946 {
3947 ULONG uSlot;
3948 hrc = aNetworkAdapter->COMGETTER(Slot)(&uSlot); H();
3949 InsertConfigString(pCfg, "Network", Utf8StrFmt("10.0.%d.0/24", uSlot+2));
3950 }
3951 hrc = natEngine->COMGETTER(HostIP)(bstr.asOutParam()); H();
3952 if (!bstr.isEmpty())
3953 InsertConfigString(pCfg, "BindIP", bstr);
3954 ULONG mtu = 0;
3955 ULONG sockSnd = 0;
3956 ULONG sockRcv = 0;
3957 ULONG tcpSnd = 0;
3958 ULONG tcpRcv = 0;
3959 hrc = natEngine->GetNetworkSettings(&mtu, &sockSnd, &sockRcv, &tcpSnd, &tcpRcv); H();
3960 if (mtu)
3961 InsertConfigInteger(pCfg, "SlirpMTU", mtu);
3962 if (sockRcv)
3963 InsertConfigInteger(pCfg, "SockRcv", sockRcv);
3964 if (sockSnd)
3965 InsertConfigInteger(pCfg, "SockSnd", sockSnd);
3966 if (tcpRcv)
3967 InsertConfigInteger(pCfg, "TcpRcv", tcpRcv);
3968 if (tcpSnd)
3969 InsertConfigInteger(pCfg, "TcpSnd", tcpSnd);
3970 hrc = natEngine->COMGETTER(TFTPPrefix)(bstr.asOutParam()); H();
3971 if (!bstr.isEmpty())
3972 {
3973 RemoveConfigValue(pCfg, "TFTPPrefix");
3974 InsertConfigString(pCfg, "TFTPPrefix", bstr);
3975 }
3976 hrc = natEngine->COMGETTER(TFTPBootFile)(bstr.asOutParam()); H();
3977 if (!bstr.isEmpty())
3978 {
3979 RemoveConfigValue(pCfg, "BootFile");
3980 InsertConfigString(pCfg, "BootFile", bstr);
3981 }
3982 hrc = natEngine->COMGETTER(TFTPNextServer)(bstr.asOutParam()); H();
3983 if (!bstr.isEmpty())
3984 InsertConfigString(pCfg, "NextServer", bstr);
3985 BOOL fDNSFlag;
3986 hrc = natEngine->COMGETTER(DNSPassDomain)(&fDNSFlag); H();
3987 InsertConfigInteger(pCfg, "PassDomain", fDNSFlag);
3988 hrc = natEngine->COMGETTER(DNSProxy)(&fDNSFlag); H();
3989 InsertConfigInteger(pCfg, "DNSProxy", fDNSFlag);
3990 hrc = natEngine->COMGETTER(DNSUseHostResolver)(&fDNSFlag); H();
3991 InsertConfigInteger(pCfg, "UseHostResolver", fDNSFlag);
3992
3993 ULONG aliasMode;
3994 hrc = natEngine->COMGETTER(AliasMode)(&aliasMode); H();
3995 InsertConfigInteger(pCfg, "AliasMode", aliasMode);
3996
3997 /* port-forwarding */
3998 SafeArray<BSTR> pfs;
3999 hrc = natEngine->COMGETTER(Redirects)(ComSafeArrayAsOutParam(pfs)); H();
4000 PCFGMNODE pPF = NULL; /* /Devices/Dev/.../Config/PF#0/ */
4001 for (unsigned int i = 0; i < pfs.size(); ++i)
4002 {
4003 uint16_t port = 0;
4004 BSTR r = pfs[i];
4005 Utf8Str utf = Utf8Str(r);
4006 Utf8Str strName;
4007 Utf8Str strProto;
4008 Utf8Str strHostPort;
4009 Utf8Str strHostIP;
4010 Utf8Str strGuestPort;
4011 Utf8Str strGuestIP;
4012 size_t pos, ppos;
4013 pos = ppos = 0;
4014#define ITERATE_TO_NEXT_TERM(res, str, pos, ppos) \
4015 do { \
4016 pos = str.find(",", ppos); \
4017 if (pos == Utf8Str::npos) \
4018 { \
4019 Log(( #res " extracting from %s is failed\n", str.c_str())); \
4020 continue; \
4021 } \
4022 res = str.substr(ppos, pos - ppos); \
4023 Log2((#res " %s pos:%d, ppos:%d\n", res.c_str(), pos, ppos)); \
4024 ppos = pos + 1; \
4025 } while (0)
4026 ITERATE_TO_NEXT_TERM(strName, utf, pos, ppos);
4027 ITERATE_TO_NEXT_TERM(strProto, utf, pos, ppos);
4028 ITERATE_TO_NEXT_TERM(strHostIP, utf, pos, ppos);
4029 ITERATE_TO_NEXT_TERM(strHostPort, utf, pos, ppos);
4030 ITERATE_TO_NEXT_TERM(strGuestIP, utf, pos, ppos);
4031 strGuestPort = utf.substr(ppos, utf.length() - ppos);
4032#undef ITERATE_TO_NEXT_TERM
4033
4034 uint32_t proto = strProto.toUInt32();
4035 bool fValid = true;
4036 switch (proto)
4037 {
4038 case NATProtocol_UDP:
4039 strProto = "UDP";
4040 break;
4041 case NATProtocol_TCP:
4042 strProto = "TCP";
4043 break;
4044 default:
4045 fValid = false;
4046 }
4047 /* continue with next rule if no valid proto was passed */
4048 if (!fValid)
4049 continue;
4050
4051 InsertConfigNode(pCfg, strName.c_str(), &pPF);
4052 InsertConfigString(pPF, "Protocol", strProto);
4053
4054 if (!strHostIP.isEmpty())
4055 InsertConfigString(pPF, "BindIP", strHostIP);
4056
4057 if (!strGuestIP.isEmpty())
4058 InsertConfigString(pPF, "GuestIP", strGuestIP);
4059
4060 port = RTStrToUInt16(strHostPort.c_str());
4061 if (port)
4062 InsertConfigInteger(pPF, "HostPort", port);
4063
4064 port = RTStrToUInt16(strGuestPort.c_str());
4065 if (port)
4066 InsertConfigInteger(pPF, "GuestPort", port);
4067 }
4068 break;
4069 }
4070
4071 case NetworkAttachmentType_Bridged:
4072 {
4073#if (defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT)
4074 hrc = attachToTapInterface(aNetworkAdapter);
4075 if (FAILED(hrc))
4076 {
4077 switch (hrc)
4078 {
4079 case VERR_ACCESS_DENIED:
4080 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4081 "Failed to open '/dev/net/tun' for read/write access. Please check the "
4082 "permissions of that node. Either run 'chmod 0666 /dev/net/tun' or "
4083 "change the group of that node and make yourself a member of that group. Make "
4084 "sure that these changes are permanent, especially if you are "
4085 "using udev"));
4086 default:
4087 AssertMsgFailed(("Could not attach to host interface! Bad!\n"));
4088 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4089 "Failed to initialize Host Interface Networking"));
4090 }
4091 }
4092
4093 Assert((int)maTapFD[uInstance] >= 0);
4094 if ((int)maTapFD[uInstance] >= 0)
4095 {
4096 InsertConfigString(pLunL0, "Driver", "HostInterface");
4097 InsertConfigNode(pLunL0, "Config", &pCfg);
4098 InsertConfigInteger(pCfg, "FileHandle", maTapFD[uInstance]);
4099 }
4100
4101#elif defined(VBOX_WITH_NETFLT)
4102 /*
4103 * This is the new VBoxNetFlt+IntNet stuff.
4104 */
4105 Bstr BridgedIfName;
4106 hrc = aNetworkAdapter->COMGETTER(BridgedInterface)(BridgedIfName.asOutParam());
4107 if (FAILED(hrc))
4108 {
4109 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(BridgedInterface) failed, hrc (0x%x)", hrc));
4110 H();
4111 }
4112
4113 Utf8Str BridgedIfNameUtf8(BridgedIfName);
4114 const char *pszBridgedIfName = BridgedIfNameUtf8.c_str();
4115
4116# if defined(RT_OS_DARWIN)
4117 /* The name is on the form 'ifX: long name', chop it off at the colon. */
4118 char szTrunk[8];
4119 RTStrCopy(szTrunk, sizeof(szTrunk), pszBridgedIfName);
4120 char *pszColon = (char *)memchr(szTrunk, ':', sizeof(szTrunk));
4121// Quick fix for @bugref{5633}
4122// if (!pszColon)
4123// {
4124// /*
4125// * Dynamic changing of attachment causes an attempt to configure
4126// * network with invalid host adapter (as it is must be changed before
4127// * the attachment), calling Detach here will cause a deadlock.
4128// * See @bugref{4750}.
4129// * hrc = aNetworkAdapter->Detach(); H();
4130// */
4131// return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4132// N_("Malformed host interface networking name '%ls'"),
4133// BridgedIfName.raw());
4134// }
4135 if (pszColon)
4136 *pszColon = '\0';
4137 const char *pszTrunk = szTrunk;
4138
4139# elif defined(RT_OS_SOLARIS)
4140 /* The name is on the form format 'ifX[:1] - long name, chop it off at space. */
4141 char szTrunk[256];
4142 strlcpy(szTrunk, pszBridgedIfName, sizeof(szTrunk));
4143 char *pszSpace = (char *)memchr(szTrunk, ' ', sizeof(szTrunk));
4144
4145 /*
4146 * Currently don't bother about malformed names here for the sake of people using
4147 * VBoxManage and setting only the NIC name from there. If there is a space we
4148 * chop it off and proceed, otherwise just use whatever we've got.
4149 */
4150 if (pszSpace)
4151 *pszSpace = '\0';
4152
4153 /* Chop it off at the colon (zone naming eg: e1000g:1 we need only the e1000g) */
4154 char *pszColon = (char *)memchr(szTrunk, ':', sizeof(szTrunk));
4155 if (pszColon)
4156 *pszColon = '\0';
4157
4158 const char *pszTrunk = szTrunk;
4159
4160# elif defined(RT_OS_WINDOWS)
4161 ComPtr<IHostNetworkInterface> hostInterface;
4162 hrc = host->FindHostNetworkInterfaceByName(BridgedIfName.raw(),
4163 hostInterface.asOutParam());
4164 if (!SUCCEEDED(hrc))
4165 {
4166 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: FindByName failed, rc=%Rhrc (0x%x)", hrc, hrc));
4167 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4168 N_("Nonexistent host networking interface, name '%ls'"),
4169 BridgedIfName.raw());
4170 }
4171
4172 HostNetworkInterfaceType_T eIfType;
4173 hrc = hostInterface->COMGETTER(InterfaceType)(&eIfType);
4174 if (FAILED(hrc))
4175 {
4176 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(InterfaceType) failed, hrc (0x%x)", hrc));
4177 H();
4178 }
4179
4180 if (eIfType != HostNetworkInterfaceType_Bridged)
4181 {
4182 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4183 N_("Interface ('%ls') is not a Bridged Adapter interface"),
4184 BridgedIfName.raw());
4185 }
4186
4187 hrc = hostInterface->COMGETTER(Id)(bstr.asOutParam());
4188 if (FAILED(hrc))
4189 {
4190 LogRel(("NetworkAttachmentType_Bridged: COMGETTER(Id) failed, hrc (0x%x)", hrc));
4191 H();
4192 }
4193 Guid hostIFGuid(bstr);
4194
4195 INetCfg *pNc;
4196 ComPtr<INetCfgComponent> pAdaptorComponent;
4197 LPWSTR pszApp;
4198
4199 hrc = VBoxNetCfgWinQueryINetCfg(&pNc, FALSE, L"VirtualBox", 10, &pszApp);
4200 Assert(hrc == S_OK);
4201 if (hrc != S_OK)
4202 {
4203 LogRel(("NetworkAttachmentType_Bridged: Failed to get NetCfg, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4204 H();
4205 }
4206
4207 /* get the adapter's INetCfgComponent*/
4208 hrc = VBoxNetCfgWinGetComponentByGuid(pNc, &GUID_DEVCLASS_NET, (GUID*)hostIFGuid.raw(), pAdaptorComponent.asOutParam());
4209 if (hrc != S_OK)
4210 {
4211 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4212 LogRel(("NetworkAttachmentType_Bridged: VBoxNetCfgWinGetComponentByGuid failed, hrc (0x%x)", hrc));
4213 H();
4214 }
4215#define VBOX_WIN_BINDNAME_PREFIX "\\DEVICE\\"
4216 char szTrunkName[INTNET_MAX_TRUNK_NAME];
4217 char *pszTrunkName = szTrunkName;
4218 wchar_t * pswzBindName;
4219 hrc = pAdaptorComponent->GetBindName(&pswzBindName);
4220 Assert(hrc == S_OK);
4221 if (hrc == S_OK)
4222 {
4223 int cwBindName = (int)wcslen(pswzBindName) + 1;
4224 int cbFullBindNamePrefix = sizeof(VBOX_WIN_BINDNAME_PREFIX);
4225 if (sizeof(szTrunkName) > cbFullBindNamePrefix + cwBindName)
4226 {
4227 strcpy(szTrunkName, VBOX_WIN_BINDNAME_PREFIX);
4228 pszTrunkName += cbFullBindNamePrefix-1;
4229 if (!WideCharToMultiByte(CP_ACP, 0, pswzBindName, cwBindName, pszTrunkName,
4230 sizeof(szTrunkName) - cbFullBindNamePrefix + 1, NULL, NULL))
4231 {
4232 DWORD err = GetLastError();
4233 hrc = HRESULT_FROM_WIN32(err);
4234 AssertMsgFailed(("%hrc=%Rhrc %#x\n", hrc, hrc));
4235 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: WideCharToMultiByte failed, hr=%Rhrc (0x%x) err=%u\n", hrc, hrc, err));
4236 }
4237 }
4238 else
4239 {
4240 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: insufficient szTrunkName buffer space\n"));
4241 /** @todo set appropriate error code */
4242 hrc = E_FAIL;
4243 }
4244
4245 if (hrc != S_OK)
4246 {
4247 AssertFailed();
4248 CoTaskMemFree(pswzBindName);
4249 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4250 H();
4251 }
4252
4253 /* we're not freeing the bind name since we'll use it later for detecting wireless*/
4254 }
4255 else
4256 {
4257 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4258 AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: VBoxNetCfgWinGetComponentByGuid failed, hrc (0x%x)", hrc));
4259 H();
4260 }
4261
4262 const char *pszTrunk = szTrunkName;
4263 /* we're not releasing the INetCfg stuff here since we use it later to figure out whether it is wireless */
4264
4265# elif defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
4266# if defined(RT_OS_FREEBSD)
4267 /*
4268 * If we bridge to a tap interface open it the `old' direct way.
4269 * This works and performs better than bridging a physical
4270 * interface via the current FreeBSD vboxnetflt implementation.
4271 */
4272 if (!strncmp(pszBridgedIfName, "tap", sizeof "tap" - 1)) {
4273 hrc = attachToTapInterface(aNetworkAdapter);
4274 if (FAILED(hrc))
4275 {
4276 switch (hrc)
4277 {
4278 case VERR_ACCESS_DENIED:
4279 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4280 "Failed to open '/dev/%s' for read/write access. Please check the "
4281 "permissions of that node, and that the net.link.tap.user_open "
4282 "sysctl is set. Either run 'chmod 0666 /dev/%s' or "
4283 "change the group of that node to vboxusers and make yourself "
4284 "a member of that group. Make sure that these changes are permanent."), pszBridgedIfName, pszBridgedIfName);
4285 default:
4286 AssertMsgFailed(("Could not attach to tap interface! Bad!\n"));
4287 return VMSetError(VMR3GetVM(mpUVM), VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
4288 "Failed to initialize Host Interface Networking"));
4289 }
4290 }
4291
4292 Assert((int)maTapFD[uInstance] >= 0);
4293 if ((int)maTapFD[uInstance] >= 0)
4294 {
4295 InsertConfigString(pLunL0, "Driver", "HostInterface");
4296 InsertConfigNode(pLunL0, "Config", &pCfg);
4297 InsertConfigInteger(pCfg, "FileHandle", maTapFD[uInstance]);
4298 }
4299 break;
4300 }
4301# endif
4302 /** @todo Check for malformed names. */
4303 const char *pszTrunk = pszBridgedIfName;
4304
4305 /* Issue a warning if the interface is down */
4306 {
4307 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
4308 if (iSock >= 0)
4309 {
4310 struct ifreq Req;
4311 RT_ZERO(Req);
4312 strncpy(Req.ifr_name, pszBridgedIfName, sizeof(Req.ifr_name) - 1);
4313 if (ioctl(iSock, SIOCGIFFLAGS, &Req) >= 0)
4314 if ((Req.ifr_flags & IFF_UP) == 0)
4315 setVMRuntimeErrorCallbackF(VMR3GetVM(mpUVM), this, 0, "BridgedInterfaceDown",
4316 "Bridged interface %s is down. Guest will not be able to use this interface",
4317 pszBridgedIfName);
4318
4319 close(iSock);
4320 }
4321 }
4322
4323# else
4324# error "PORTME (VBOX_WITH_NETFLT)"
4325# endif
4326
4327 InsertConfigString(pLunL0, "Driver", "IntNet");
4328 InsertConfigNode(pLunL0, "Config", &pCfg);
4329 InsertConfigString(pCfg, "Trunk", pszTrunk);
4330 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetFlt);
4331 InsertConfigInteger(pCfg, "IgnoreConnectFailure", (uint64_t)fIgnoreConnectFailure);
4332 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
4333 char szNetwork[INTNET_MAX_NETWORK_NAME];
4334
4335#if defined(RT_OS_SOLARIS) || defined(RT_OS_DARWIN)
4336 /*
4337 * 'pszTrunk' contains just the interface name required in ring-0, while 'pszBridgedIfName' contains
4338 * interface name + optional description. We must not pass any description to the VM as it can differ
4339 * for the same interface name, eg: "nge0 - ethernet" (GUI) vs "nge0" (VBoxManage).
4340 */
4341 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszTrunk);
4342#else
4343 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszBridgedIfName);
4344#endif
4345 InsertConfigString(pCfg, "Network", szNetwork);
4346 networkName = Bstr(szNetwork);
4347 trunkName = Bstr(pszTrunk);
4348 trunkType = Bstr(TRUNKTYPE_NETFLT);
4349
4350# if defined(RT_OS_DARWIN)
4351 /** @todo Come up with a better deal here. Problem is that IHostNetworkInterface is completely useless here. */
4352 if ( strstr(pszBridgedIfName, "Wireless")
4353 || strstr(pszBridgedIfName, "AirPort" ))
4354 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4355# elif defined(RT_OS_LINUX)
4356 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
4357 if (iSock >= 0)
4358 {
4359 struct iwreq WRq;
4360
4361 memset(&WRq, 0, sizeof(WRq));
4362 strncpy(WRq.ifr_name, pszBridgedIfName, IFNAMSIZ);
4363 bool fSharedMacOnWire = ioctl(iSock, SIOCGIWNAME, &WRq) >= 0;
4364 close(iSock);
4365 if (fSharedMacOnWire)
4366 {
4367 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4368 Log(("Set SharedMacOnWire\n"));
4369 }
4370 else
4371 Log(("Failed to get wireless name\n"));
4372 }
4373 else
4374 Log(("Failed to open wireless socket\n"));
4375# elif defined(RT_OS_FREEBSD)
4376 int iSock = socket(AF_INET, SOCK_DGRAM, 0);
4377 if (iSock >= 0)
4378 {
4379 struct ieee80211req WReq;
4380 uint8_t abData[32];
4381
4382 memset(&WReq, 0, sizeof(WReq));
4383 strncpy(WReq.i_name, pszBridgedIfName, sizeof(WReq.i_name));
4384 WReq.i_type = IEEE80211_IOC_SSID;
4385 WReq.i_val = -1;
4386 WReq.i_data = abData;
4387 WReq.i_len = sizeof(abData);
4388
4389 bool fSharedMacOnWire = ioctl(iSock, SIOCG80211, &WReq) >= 0;
4390 close(iSock);
4391 if (fSharedMacOnWire)
4392 {
4393 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4394 Log(("Set SharedMacOnWire\n"));
4395 }
4396 else
4397 Log(("Failed to get wireless name\n"));
4398 }
4399 else
4400 Log(("Failed to open wireless socket\n"));
4401# elif defined(RT_OS_WINDOWS)
4402# define DEVNAME_PREFIX L"\\\\.\\"
4403 /* we are getting the medium type via IOCTL_NDIS_QUERY_GLOBAL_STATS Io Control
4404 * there is a pretty long way till there though since we need to obtain the symbolic link name
4405 * for the adapter device we are going to query given the device Guid */
4406
4407
4408 /* prepend the "\\\\.\\" to the bind name to obtain the link name */
4409
4410 wchar_t FileName[MAX_PATH];
4411 wcscpy(FileName, DEVNAME_PREFIX);
4412 wcscpy((wchar_t*)(((char*)FileName) + sizeof(DEVNAME_PREFIX) - sizeof(FileName[0])), pswzBindName);
4413
4414 /* open the device */
4415 HANDLE hDevice = CreateFile(FileName,
4416 GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
4417 NULL,
4418 OPEN_EXISTING,
4419 FILE_ATTRIBUTE_NORMAL,
4420 NULL);
4421
4422 if (hDevice != INVALID_HANDLE_VALUE)
4423 {
4424 bool fSharedMacOnWire = false;
4425
4426 /* now issue the OID_GEN_PHYSICAL_MEDIUM query */
4427 DWORD Oid = OID_GEN_PHYSICAL_MEDIUM;
4428 NDIS_PHYSICAL_MEDIUM PhMedium;
4429 DWORD cbResult;
4430 if (DeviceIoControl(hDevice,
4431 IOCTL_NDIS_QUERY_GLOBAL_STATS,
4432 &Oid,
4433 sizeof(Oid),
4434 &PhMedium,
4435 sizeof(PhMedium),
4436 &cbResult,
4437 NULL))
4438 {
4439 /* that was simple, now examine PhMedium */
4440 if ( PhMedium == NdisPhysicalMediumWirelessWan
4441 || PhMedium == NdisPhysicalMediumWirelessLan
4442 || PhMedium == NdisPhysicalMediumNative802_11
4443 || PhMedium == NdisPhysicalMediumBluetooth)
4444 fSharedMacOnWire = true;
4445 }
4446 else
4447 {
4448 int winEr = GetLastError();
4449 LogRel(("Console::configNetwork: DeviceIoControl failed, err (0x%x), ignoring\n", winEr));
4450 Assert(winEr == ERROR_INVALID_PARAMETER || winEr == ERROR_NOT_SUPPORTED || winEr == ERROR_BAD_COMMAND);
4451 }
4452 CloseHandle(hDevice);
4453
4454 if (fSharedMacOnWire)
4455 {
4456 Log(("this is a wireless adapter"));
4457 InsertConfigInteger(pCfg, "SharedMacOnWire", true);
4458 Log(("Set SharedMacOnWire\n"));
4459 }
4460 else
4461 Log(("this is NOT a wireless adapter"));
4462 }
4463 else
4464 {
4465 int winEr = GetLastError();
4466 AssertLogRelMsgFailed(("Console::configNetwork: CreateFile failed, err (0x%x), ignoring\n", winEr));
4467 }
4468
4469 CoTaskMemFree(pswzBindName);
4470
4471 pAdaptorComponent.setNull();
4472 /* release the pNc finally */
4473 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4474# else
4475 /** @todo PORTME: wireless detection */
4476# endif
4477
4478# if defined(RT_OS_SOLARIS)
4479# if 0 /* bird: this is a bit questionable and might cause more trouble than its worth. */
4480 /* Zone access restriction, don't allow snooping the global zone. */
4481 zoneid_t ZoneId = getzoneid();
4482 if (ZoneId != GLOBAL_ZONEID)
4483 {
4484 InsertConfigInteger(pCfg, "IgnoreAllPromisc", true);
4485 }
4486# endif
4487# endif
4488
4489#elif defined(RT_OS_WINDOWS) /* not defined NetFlt */
4490 /* NOTHING TO DO HERE */
4491#elif defined(RT_OS_LINUX)
4492/// @todo aleksey: is there anything to be done here?
4493#elif defined(RT_OS_FREEBSD)
4494/** @todo FreeBSD: Check out this later (HIF networking). */
4495#else
4496# error "Port me"
4497#endif
4498 break;
4499 }
4500
4501 case NetworkAttachmentType_Internal:
4502 {
4503 hrc = aNetworkAdapter->COMGETTER(InternalNetwork)(bstr.asOutParam()); H();
4504 if (!bstr.isEmpty())
4505 {
4506 InsertConfigString(pLunL0, "Driver", "IntNet");
4507 InsertConfigNode(pLunL0, "Config", &pCfg);
4508 InsertConfigString(pCfg, "Network", bstr);
4509 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_WhateverNone);
4510 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
4511 networkName = bstr;
4512 trunkType = Bstr(TRUNKTYPE_WHATEVER);
4513 }
4514 break;
4515 }
4516
4517 case NetworkAttachmentType_HostOnly:
4518 {
4519 InsertConfigString(pLunL0, "Driver", "IntNet");
4520 InsertConfigNode(pLunL0, "Config", &pCfg);
4521
4522 Bstr HostOnlyName;
4523 hrc = aNetworkAdapter->COMGETTER(HostOnlyInterface)(HostOnlyName.asOutParam());
4524 if (FAILED(hrc))
4525 {
4526 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(HostOnlyInterface) failed, hrc (0x%x)\n", hrc));
4527 H();
4528 }
4529
4530 Utf8Str HostOnlyNameUtf8(HostOnlyName);
4531 const char *pszHostOnlyName = HostOnlyNameUtf8.c_str();
4532 ComPtr<IHostNetworkInterface> hostInterface;
4533 rc = host->FindHostNetworkInterfaceByName(HostOnlyName.raw(),
4534 hostInterface.asOutParam());
4535 if (!SUCCEEDED(rc))
4536 {
4537 LogRel(("NetworkAttachmentType_HostOnly: FindByName failed, rc (0x%x)\n", rc));
4538 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4539 N_("Nonexistent host networking interface, name '%ls'"),
4540 HostOnlyName.raw());
4541 }
4542
4543 char szNetwork[INTNET_MAX_NETWORK_NAME];
4544 RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszHostOnlyName);
4545
4546#if defined(RT_OS_WINDOWS)
4547# ifndef VBOX_WITH_NETFLT
4548 hrc = E_NOTIMPL;
4549 LogRel(("NetworkAttachmentType_HostOnly: Not Implemented\n"));
4550 H();
4551# else /* defined VBOX_WITH_NETFLT*/
4552 /** @todo r=bird: Put this in a function. */
4553
4554 HostNetworkInterfaceType_T eIfType;
4555 hrc = hostInterface->COMGETTER(InterfaceType)(&eIfType);
4556 if (FAILED(hrc))
4557 {
4558 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(InterfaceType) failed, hrc (0x%x)\n", hrc));
4559 H();
4560 }
4561
4562 if (eIfType != HostNetworkInterfaceType_HostOnly)
4563 return VMSetError(VMR3GetVM(mpUVM), VERR_INTERNAL_ERROR, RT_SRC_POS,
4564 N_("Interface ('%ls') is not a Host-Only Adapter interface"),
4565 HostOnlyName.raw());
4566
4567 hrc = hostInterface->COMGETTER(Id)(bstr.asOutParam());
4568 if (FAILED(hrc))
4569 {
4570 LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(Id) failed, hrc (0x%x)\n", hrc));
4571 H();
4572 }
4573 Guid hostIFGuid(bstr);
4574
4575 INetCfg *pNc;
4576 ComPtr<INetCfgComponent> pAdaptorComponent;
4577 LPWSTR pszApp;
4578 hrc = VBoxNetCfgWinQueryINetCfg(&pNc, FALSE, L"VirtualBox", 10, &pszApp);
4579 Assert(hrc == S_OK);
4580 if (hrc != S_OK)
4581 {
4582 LogRel(("NetworkAttachmentType_HostOnly: Failed to get NetCfg, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4583 H();
4584 }
4585
4586 /* get the adapter's INetCfgComponent*/
4587 hrc = VBoxNetCfgWinGetComponentByGuid(pNc, &GUID_DEVCLASS_NET, (GUID*)hostIFGuid.raw(), pAdaptorComponent.asOutParam());
4588 if (hrc != S_OK)
4589 {
4590 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4591 LogRel(("NetworkAttachmentType_HostOnly: VBoxNetCfgWinGetComponentByGuid failed, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4592 H();
4593 }
4594# define VBOX_WIN_BINDNAME_PREFIX "\\DEVICE\\"
4595 char szTrunkName[INTNET_MAX_TRUNK_NAME];
4596 char *pszTrunkName = szTrunkName;
4597 wchar_t * pswzBindName;
4598 hrc = pAdaptorComponent->GetBindName(&pswzBindName);
4599 Assert(hrc == S_OK);
4600 if (hrc == S_OK)
4601 {
4602 int cwBindName = (int)wcslen(pswzBindName) + 1;
4603 int cbFullBindNamePrefix = sizeof(VBOX_WIN_BINDNAME_PREFIX);
4604 if (sizeof(szTrunkName) > cbFullBindNamePrefix + cwBindName)
4605 {
4606 strcpy(szTrunkName, VBOX_WIN_BINDNAME_PREFIX);
4607 pszTrunkName += cbFullBindNamePrefix-1;
4608 if (!WideCharToMultiByte(CP_ACP, 0, pswzBindName, cwBindName, pszTrunkName,
4609 sizeof(szTrunkName) - cbFullBindNamePrefix + 1, NULL, NULL))
4610 {
4611 DWORD err = GetLastError();
4612 hrc = HRESULT_FROM_WIN32(err);
4613 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: WideCharToMultiByte failed, hr=%Rhrc (0x%x) err=%u\n", hrc, hrc, err));
4614 }
4615 }
4616 else
4617 {
4618 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: insufficient szTrunkName buffer space\n"));
4619 /** @todo set appropriate error code */
4620 hrc = E_FAIL;
4621 }
4622
4623 if (hrc != S_OK)
4624 {
4625 AssertFailed();
4626 CoTaskMemFree(pswzBindName);
4627 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4628 H();
4629 }
4630 }
4631 else
4632 {
4633 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4634 AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: VBoxNetCfgWinGetComponentByGuid failed, hrc=%Rhrc (0x%x)\n", hrc, hrc));
4635 H();
4636 }
4637
4638
4639 CoTaskMemFree(pswzBindName);
4640
4641 pAdaptorComponent.setNull();
4642 /* release the pNc finally */
4643 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
4644
4645 const char *pszTrunk = szTrunkName;
4646
4647 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetAdp);
4648 InsertConfigString(pCfg, "Trunk", pszTrunk);
4649 InsertConfigString(pCfg, "Network", szNetwork);
4650 InsertConfigInteger(pCfg, "IgnoreConnectFailure", (uint64_t)fIgnoreConnectFailure); /** @todo why is this windows only?? */
4651 networkName = Bstr(szNetwork);
4652 trunkName = Bstr(pszTrunk);
4653 trunkType = TRUNKTYPE_NETADP;
4654# endif /* defined VBOX_WITH_NETFLT*/
4655#elif defined(RT_OS_DARWIN)
4656 InsertConfigString(pCfg, "Trunk", pszHostOnlyName);
4657 InsertConfigString(pCfg, "Network", szNetwork);
4658 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetAdp);
4659 networkName = Bstr(szNetwork);
4660 trunkName = Bstr(pszHostOnlyName);
4661 trunkType = TRUNKTYPE_NETADP;
4662#else
4663 InsertConfigString(pCfg, "Trunk", pszHostOnlyName);
4664 InsertConfigString(pCfg, "Network", szNetwork);
4665 InsertConfigInteger(pCfg, "TrunkType", kIntNetTrunkType_NetFlt);
4666 networkName = Bstr(szNetwork);
4667 trunkName = Bstr(pszHostOnlyName);
4668 trunkType = TRUNKTYPE_NETFLT;
4669#endif
4670 InsertConfigString(pCfg, "IfPolicyPromisc", pszPromiscuousGuestPolicy);
4671
4672#if !defined(RT_OS_WINDOWS) && defined(VBOX_WITH_NETFLT)
4673
4674 Bstr tmpAddr, tmpMask;
4675
4676 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPAddress",
4677 pszHostOnlyName).raw(),
4678 tmpAddr.asOutParam());
4679 if (SUCCEEDED(hrc) && !tmpAddr.isEmpty())
4680 {
4681 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPNetMask",
4682 pszHostOnlyName).raw(),
4683 tmpMask.asOutParam());
4684 if (SUCCEEDED(hrc) && !tmpMask.isEmpty())
4685 hrc = hostInterface->EnableStaticIPConfig(tmpAddr.raw(),
4686 tmpMask.raw());
4687 else
4688 hrc = hostInterface->EnableStaticIPConfig(tmpAddr.raw(),
4689 Bstr(VBOXNET_IPV4MASK_DEFAULT).raw());
4690 }
4691 else
4692 {
4693 /* Grab the IP number from the 'vboxnetX' instance number (see netif.h) */
4694 hrc = hostInterface->EnableStaticIPConfig(getDefaultIPv4Address(Bstr(pszHostOnlyName)).raw(),
4695 Bstr(VBOXNET_IPV4MASK_DEFAULT).raw());
4696 }
4697
4698 ComAssertComRC(hrc); /** @todo r=bird: Why this isn't fatal? (H()) */
4699
4700 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6Address",
4701 pszHostOnlyName).raw(),
4702 tmpAddr.asOutParam());
4703 if (SUCCEEDED(hrc))
4704 hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6NetMask", pszHostOnlyName).raw(),
4705 tmpMask.asOutParam());
4706 if (SUCCEEDED(hrc) && !tmpAddr.isEmpty() && !tmpMask.isEmpty())
4707 {
4708 hrc = hostInterface->EnableStaticIPConfigV6(tmpAddr.raw(),
4709 Utf8Str(tmpMask).toUInt32());
4710 ComAssertComRC(hrc); /** @todo r=bird: Why this isn't fatal? (H()) */
4711 }
4712#endif
4713 break;
4714 }
4715
4716 case NetworkAttachmentType_Generic:
4717 {
4718 hrc = aNetworkAdapter->COMGETTER(GenericDriver)(bstr.asOutParam()); H();
4719 SafeArray<BSTR> names;
4720 SafeArray<BSTR> values;
4721 hrc = aNetworkAdapter->GetProperties(Bstr().raw(),
4722 ComSafeArrayAsOutParam(names),
4723 ComSafeArrayAsOutParam(values)); H();
4724
4725 InsertConfigString(pLunL0, "Driver", bstr);
4726 InsertConfigNode(pLunL0, "Config", &pCfg);
4727 for (size_t ii = 0; ii < names.size(); ++ii)
4728 {
4729 if (values[ii] && *values[ii])
4730 {
4731 Utf8Str name = names[ii];
4732 Utf8Str value = values[ii];
4733 InsertConfigString(pCfg, name.c_str(), value);
4734 }
4735 }
4736 break;
4737 }
4738
4739 default:
4740 AssertMsgFailed(("should not get here!\n"));
4741 break;
4742 }
4743
4744 /*
4745 * Attempt to attach the driver.
4746 */
4747 switch (eAttachmentType)
4748 {
4749 case NetworkAttachmentType_Null:
4750 break;
4751
4752 case NetworkAttachmentType_Bridged:
4753 case NetworkAttachmentType_Internal:
4754 case NetworkAttachmentType_HostOnly:
4755 case NetworkAttachmentType_NAT:
4756 case NetworkAttachmentType_Generic:
4757 {
4758 if (SUCCEEDED(hrc) && SUCCEEDED(rc))
4759 {
4760 if (fAttachDetach)
4761 {
4762 rc = PDMR3DriverAttach(mpUVM, pszDevice, uInstance, uLun, 0 /*fFlags*/, NULL /* ppBase */);
4763 //AssertRC(rc);
4764 }
4765
4766 {
4767 /** @todo pritesh: get the dhcp server name from the
4768 * previous network configuration and then stop the server
4769 * else it may conflict with the dhcp server running with
4770 * the current attachment type
4771 */
4772 /* Stop the hostonly DHCP Server */
4773 }
4774
4775 if (!networkName.isEmpty())
4776 {
4777 /*
4778 * Until we implement service reference counters DHCP Server will be stopped
4779 * by DHCPServerRunner destructor.
4780 */
4781 ComPtr<IDHCPServer> dhcpServer;
4782 hrc = virtualBox->FindDHCPServerByNetworkName(networkName.raw(),
4783 dhcpServer.asOutParam());
4784 if (SUCCEEDED(hrc))
4785 {
4786 /* there is a DHCP server available for this network */
4787 BOOL fEnabledDhcp;
4788 hrc = dhcpServer->COMGETTER(Enabled)(&fEnabledDhcp);
4789 if (FAILED(hrc))
4790 {
4791 LogRel(("DHCP svr: COMGETTER(Enabled) failed, hrc (%Rhrc)", hrc));
4792 H();
4793 }
4794
4795 if (fEnabledDhcp)
4796 hrc = dhcpServer->Start(networkName.raw(),
4797 trunkName.raw(),
4798 trunkType.raw());
4799 }
4800 else
4801 hrc = S_OK;
4802 }
4803 }
4804
4805 break;
4806 }
4807
4808 default:
4809 AssertMsgFailed(("should not get here!\n"));
4810 break;
4811 }
4812
4813 meAttachmentType[uInstance] = eAttachmentType;
4814 }
4815 catch (ConfigError &x)
4816 {
4817 // InsertConfig threw something:
4818 return x.m_vrc;
4819 }
4820
4821#undef H
4822
4823 return VINF_SUCCESS;
4824}
4825
4826#ifdef VBOX_WITH_GUEST_PROPS
4827/**
4828 * Set an array of guest properties
4829 */
4830static void configSetProperties(VMMDev * const pVMMDev,
4831 void *names,
4832 void *values,
4833 void *timestamps,
4834 void *flags)
4835{
4836 VBOXHGCMSVCPARM parms[4];
4837
4838 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
4839 parms[0].u.pointer.addr = names;
4840 parms[0].u.pointer.size = 0; /* We don't actually care. */
4841 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
4842 parms[1].u.pointer.addr = values;
4843 parms[1].u.pointer.size = 0; /* We don't actually care. */
4844 parms[2].type = VBOX_HGCM_SVC_PARM_PTR;
4845 parms[2].u.pointer.addr = timestamps;
4846 parms[2].u.pointer.size = 0; /* We don't actually care. */
4847 parms[3].type = VBOX_HGCM_SVC_PARM_PTR;
4848 parms[3].u.pointer.addr = flags;
4849 parms[3].u.pointer.size = 0; /* We don't actually care. */
4850
4851 pVMMDev->hgcmHostCall("VBoxGuestPropSvc",
4852 guestProp::SET_PROPS_HOST,
4853 4,
4854 &parms[0]);
4855}
4856
4857/**
4858 * Set a single guest property
4859 */
4860static void configSetProperty(VMMDev * const pVMMDev,
4861 const char *pszName,
4862 const char *pszValue,
4863 const char *pszFlags)
4864{
4865 VBOXHGCMSVCPARM parms[4];
4866
4867 AssertPtrReturnVoid(pszName);
4868 AssertPtrReturnVoid(pszValue);
4869 AssertPtrReturnVoid(pszFlags);
4870 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
4871 parms[0].u.pointer.addr = (void *)pszName;
4872 parms[0].u.pointer.size = strlen(pszName) + 1;
4873 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
4874 parms[1].u.pointer.addr = (void *)pszValue;
4875 parms[1].u.pointer.size = strlen(pszValue) + 1;
4876 parms[2].type = VBOX_HGCM_SVC_PARM_PTR;
4877 parms[2].u.pointer.addr = (void *)pszFlags;
4878 parms[2].u.pointer.size = strlen(pszFlags) + 1;
4879 pVMMDev->hgcmHostCall("VBoxGuestPropSvc", guestProp::SET_PROP_HOST, 3,
4880 &parms[0]);
4881}
4882
4883/**
4884 * Set the global flags value by calling the service
4885 * @returns the status returned by the call to the service
4886 *
4887 * @param pTable the service instance handle
4888 * @param eFlags the flags to set
4889 */
4890int configSetGlobalPropertyFlags(VMMDev * const pVMMDev,
4891 guestProp::ePropFlags eFlags)
4892{
4893 VBOXHGCMSVCPARM paParm;
4894 paParm.setUInt32(eFlags);
4895 int rc = pVMMDev->hgcmHostCall("VBoxGuestPropSvc",
4896 guestProp::SET_GLOBAL_FLAGS_HOST, 1,
4897 &paParm);
4898 if (RT_FAILURE(rc))
4899 {
4900 char szFlags[guestProp::MAX_FLAGS_LEN];
4901 if (RT_FAILURE(writeFlags(eFlags, szFlags)))
4902 Log(("Failed to set the global flags.\n"));
4903 else
4904 Log(("Failed to set the global flags \"%s\".\n", szFlags));
4905 }
4906 return rc;
4907}
4908#endif /* VBOX_WITH_GUEST_PROPS */
4909
4910/**
4911 * Set up the Guest Property service, populate it with properties read from
4912 * the machine XML and set a couple of initial properties.
4913 */
4914/* static */ int Console::configGuestProperties(void *pvConsole, PUVM pUVM)
4915{
4916#ifdef VBOX_WITH_GUEST_PROPS
4917 AssertReturn(pvConsole, VERR_GENERAL_FAILURE);
4918 ComObjPtr<Console> pConsole = static_cast<Console *>(pvConsole);
4919 AssertReturn(pConsole->m_pVMMDev, VERR_GENERAL_FAILURE);
4920
4921 /* Load the service */
4922 int rc = pConsole->m_pVMMDev->hgcmLoadService("VBoxGuestPropSvc", "VBoxGuestPropSvc");
4923
4924 if (RT_FAILURE(rc))
4925 {
4926 LogRel(("VBoxGuestPropSvc is not available. rc = %Rrc\n", rc));
4927 /* That is not a fatal failure. */
4928 rc = VINF_SUCCESS;
4929 }
4930 else
4931 {
4932 /*
4933 * Initialize built-in properties that can be changed and saved.
4934 *
4935 * These are typically transient properties that the guest cannot
4936 * change.
4937 */
4938
4939 {
4940 VBOXHGCMSVCPARM Params[2];
4941 int rc2 = pConsole->m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", guestProp::GET_DBGF_INFO_FN, 2, &Params[0]);
4942 if (RT_SUCCESS(rc2))
4943 {
4944 PFNDBGFHANDLEREXT pfnHandler = (PFNDBGFHANDLEREXT)(uintptr_t)Params[0].u.pointer.addr;
4945 void *pService = (void*)Params[1].u.pointer.addr;
4946 DBGFR3InfoRegisterExternal(VMR3GetVM(pUVM), "guestprops", "Display the guest properties", pfnHandler, pService);
4947 }
4948 }
4949
4950 /* Sysprep execution by VBoxService. */
4951 configSetProperty(pConsole->m_pVMMDev,
4952 "/VirtualBox/HostGuest/SysprepExec", "",
4953 "TRANSIENT, RDONLYGUEST");
4954 configSetProperty(pConsole->m_pVMMDev,
4955 "/VirtualBox/HostGuest/SysprepArgs", "",
4956 "TRANSIENT, RDONLYGUEST");
4957
4958 /*
4959 * Pull over the properties from the server.
4960 */
4961 SafeArray<BSTR> namesOut;
4962 SafeArray<BSTR> valuesOut;
4963 SafeArray<LONG64> timestampsOut;
4964 SafeArray<BSTR> flagsOut;
4965 HRESULT hrc;
4966 hrc = pConsole->mControl->PullGuestProperties(ComSafeArrayAsOutParam(namesOut),
4967 ComSafeArrayAsOutParam(valuesOut),
4968 ComSafeArrayAsOutParam(timestampsOut),
4969 ComSafeArrayAsOutParam(flagsOut));
4970 AssertMsgReturn(SUCCEEDED(hrc), ("hrc=%Rrc\n", hrc), VERR_GENERAL_FAILURE);
4971 size_t cProps = namesOut.size();
4972 size_t cAlloc = cProps + 1;
4973 if ( valuesOut.size() != cProps
4974 || timestampsOut.size() != cProps
4975 || flagsOut.size() != cProps
4976 )
4977 AssertFailedReturn(VERR_INVALID_PARAMETER);
4978
4979 char **papszNames, **papszValues, **papszFlags;
4980 char szEmpty[] = "";
4981 LONG64 *pai64Timestamps;
4982 papszNames = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
4983 papszValues = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
4984 pai64Timestamps = (LONG64 *)RTMemTmpAllocZ(sizeof(LONG64) * cAlloc);
4985 papszFlags = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
4986 if (papszNames && papszValues && pai64Timestamps && papszFlags)
4987 {
4988 for (unsigned i = 0; RT_SUCCESS(rc) && i < cProps; ++i)
4989 {
4990 AssertPtrReturn(namesOut[i], VERR_INVALID_PARAMETER);
4991 rc = RTUtf16ToUtf8(namesOut[i], &papszNames[i]);
4992 if (RT_FAILURE(rc))
4993 break;
4994 if (valuesOut[i])
4995 rc = RTUtf16ToUtf8(valuesOut[i], &papszValues[i]);
4996 else
4997 papszValues[i] = szEmpty;
4998 if (RT_FAILURE(rc))
4999 break;
5000 pai64Timestamps[i] = timestampsOut[i];
5001 if (flagsOut[i])
5002 rc = RTUtf16ToUtf8(flagsOut[i], &papszFlags[i]);
5003 else
5004 papszFlags[i] = szEmpty;
5005 }
5006 if (RT_SUCCESS(rc))
5007 configSetProperties(pConsole->m_pVMMDev,
5008 (void *)papszNames,
5009 (void *)papszValues,
5010 (void *)pai64Timestamps,
5011 (void *)papszFlags);
5012 for (unsigned i = 0; i < cProps; ++i)
5013 {
5014 RTStrFree(papszNames[i]);
5015 if (valuesOut[i])
5016 RTStrFree(papszValues[i]);
5017 if (flagsOut[i])
5018 RTStrFree(papszFlags[i]);
5019 }
5020 }
5021 else
5022 rc = VERR_NO_MEMORY;
5023 RTMemTmpFree(papszNames);
5024 RTMemTmpFree(papszValues);
5025 RTMemTmpFree(pai64Timestamps);
5026 RTMemTmpFree(papszFlags);
5027 AssertRCReturn(rc, rc);
5028
5029 /*
5030 * These properties have to be set before pulling over the properties
5031 * from the machine XML, to ensure that properties saved in the XML
5032 * will override them.
5033 */
5034 /* Set the raw VBox version string as a guest property. Used for host/guest
5035 * version comparison. */
5036 configSetProperty(pConsole->m_pVMMDev, "/VirtualBox/HostInfo/VBoxVer",
5037 VBOX_VERSION_STRING_RAW, "TRANSIENT, RDONLYGUEST");
5038 /* Set the full VBox version string as a guest property. Can contain vendor-specific
5039 * information/branding and/or pre-release tags. */
5040 configSetProperty(pConsole->m_pVMMDev, "/VirtualBox/HostInfo/VBoxVerExt",
5041 VBOX_VERSION_STRING, "TRANSIENT, RDONLYGUEST");
5042 /* Set the VBox SVN revision as a guest property */
5043 configSetProperty(pConsole->m_pVMMDev, "/VirtualBox/HostInfo/VBoxRev",
5044 RTBldCfgRevisionStr(), "TRANSIENT, RDONLYGUEST");
5045
5046 /*
5047 * Register the host notification callback
5048 */
5049 HGCMSVCEXTHANDLE hDummy;
5050 HGCMHostRegisterServiceExtension(&hDummy, "VBoxGuestPropSvc",
5051 Console::doGuestPropNotification,
5052 pvConsole);
5053
5054#ifdef VBOX_WITH_GUEST_PROPS_RDONLY_GUEST
5055 rc = configSetGlobalPropertyFlags(pConsole->m_pVMMDev,
5056 guestProp::RDONLYGUEST);
5057 AssertRCReturn(rc, rc);
5058#endif
5059
5060 Log(("Set VBoxGuestPropSvc property store\n"));
5061 }
5062 return VINF_SUCCESS;
5063#else /* !VBOX_WITH_GUEST_PROPS */
5064 return VERR_NOT_SUPPORTED;
5065#endif /* !VBOX_WITH_GUEST_PROPS */
5066}
5067
5068/**
5069 * Set up the Guest Control service.
5070 */
5071/* static */ int Console::configGuestControl(void *pvConsole)
5072{
5073#ifdef VBOX_WITH_GUEST_CONTROL
5074 AssertReturn(pvConsole, VERR_GENERAL_FAILURE);
5075 ComObjPtr<Console> pConsole = static_cast<Console *>(pvConsole);
5076
5077 /* Load the service */
5078 int rc = pConsole->m_pVMMDev->hgcmLoadService("VBoxGuestControlSvc", "VBoxGuestControlSvc");
5079
5080 if (RT_FAILURE(rc))
5081 {
5082 LogRel(("VBoxGuestControlSvc is not available. rc = %Rrc\n", rc));
5083 /* That is not a fatal failure. */
5084 rc = VINF_SUCCESS;
5085 }
5086 else
5087 {
5088 HGCMSVCEXTHANDLE hDummy;
5089 rc = HGCMHostRegisterServiceExtension(&hDummy, "VBoxGuestControlSvc",
5090 &Guest::notifyCtrlDispatcher,
5091 pConsole->getGuest());
5092 if (RT_FAILURE(rc))
5093 Log(("Cannot register VBoxGuestControlSvc extension!\n"));
5094 else
5095 Log(("VBoxGuestControlSvc loaded\n"));
5096 }
5097
5098 return rc;
5099#else /* !VBOX_WITH_GUEST_CONTROL */
5100 return VERR_NOT_SUPPORTED;
5101#endif /* !VBOX_WITH_GUEST_CONTROL */
5102}
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