VirtualBox

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

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

Main/ConsoleImpl2: warning

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