VirtualBox

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

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

Main/Console: dump the VBoxInternal2 extradata settings since they influence the API behavior and are not visible elsewhere

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