PageRenderTime 92ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/src/VBox/Main/src-client/ConsoleImpl2.cpp

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