VirtualBox

source: vbox/trunk/src/VBox/Main/src-client/ConsoleImpl.cpp@ 46972

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

Main/VPX: be more verbose on error

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 338.2 KB
Line 
1/* $Id: ConsoleImpl.cpp 46815 2013-06-26 19:32:21Z vboxsync $ */
2/** @file
3 * VBox Console COM Class implementation
4 */
5
6/*
7 * Copyright (C) 2005-2013 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/** @todo Move the TAP mess back into the driver! */
19#if defined(RT_OS_WINDOWS)
20#elif defined(RT_OS_LINUX)
21# include <errno.h>
22# include <sys/ioctl.h>
23# include <sys/poll.h>
24# include <sys/fcntl.h>
25# include <sys/types.h>
26# include <sys/wait.h>
27# include <net/if.h>
28# include <linux/if_tun.h>
29# include <stdio.h>
30# include <stdlib.h>
31# include <string.h>
32#elif defined(RT_OS_FREEBSD)
33# include <errno.h>
34# include <sys/ioctl.h>
35# include <sys/poll.h>
36# include <sys/fcntl.h>
37# include <sys/types.h>
38# include <sys/wait.h>
39# include <stdio.h>
40# include <stdlib.h>
41# include <string.h>
42#elif defined(RT_OS_SOLARIS)
43# include <iprt/coredumper.h>
44#endif
45
46#include "ConsoleImpl.h"
47
48#include "Global.h"
49#include "VirtualBoxErrorInfoImpl.h"
50#include "GuestImpl.h"
51#include "KeyboardImpl.h"
52#include "MouseImpl.h"
53#include "DisplayImpl.h"
54#include "MachineDebuggerImpl.h"
55#include "USBDeviceImpl.h"
56#include "RemoteUSBDeviceImpl.h"
57#include "SharedFolderImpl.h"
58#include "AudioSnifferInterface.h"
59#include "Nvram.h"
60#ifdef VBOX_WITH_USB_VIDEO
61# include "UsbWebcamInterface.h"
62#endif
63#ifdef VBOX_WITH_USB_CARDREADER
64# include "UsbCardReader.h"
65#endif
66#include "ProgressImpl.h"
67#include "ConsoleVRDPServer.h"
68#include "VMMDev.h"
69#ifdef VBOX_WITH_EXTPACK
70# include "ExtPackManagerImpl.h"
71#endif
72#include "BusAssignmentManager.h"
73
74#include "VBoxEvents.h"
75#include "AutoCaller.h"
76#include "Logging.h"
77
78#include <VBox/com/array.h>
79#include "VBox/com/ErrorInfo.h"
80#include <VBox/com/listeners.h>
81
82#include <iprt/asm.h>
83#include <iprt/buildconfig.h>
84#include <iprt/cpp/utils.h>
85#include <iprt/dir.h>
86#include <iprt/file.h>
87#include <iprt/ldr.h>
88#include <iprt/path.h>
89#include <iprt/process.h>
90#include <iprt/string.h>
91#include <iprt/system.h>
92
93#include <VBox/vmm/vmapi.h>
94#include <VBox/vmm/vmm.h>
95#include <VBox/vmm/pdmapi.h>
96#include <VBox/vmm/pdmasynccompletion.h>
97#include <VBox/vmm/pdmnetifs.h>
98#ifdef VBOX_WITH_USB
99# include <VBox/vmm/pdmusb.h>
100#endif
101#ifdef VBOX_WITH_NETSHAPER
102# include <VBox/vmm/pdmnetshaper.h>
103#endif /* VBOX_WITH_NETSHAPER */
104#include <VBox/vmm/mm.h>
105#include <VBox/vmm/ftm.h>
106#include <VBox/vmm/ssm.h>
107#include <VBox/err.h>
108#include <VBox/param.h>
109#include <VBox/vusb.h>
110
111#include <VBox/VMMDev.h>
112
113#include <VBox/HostServices/VBoxClipboardSvc.h>
114#include <VBox/HostServices/DragAndDropSvc.h>
115#ifdef VBOX_WITH_GUEST_PROPS
116# include <VBox/HostServices/GuestPropertySvc.h>
117# include <VBox/com/array.h>
118#endif
119
120#include <set>
121#include <algorithm>
122#include <memory> // for auto_ptr
123#include <vector>
124
125
126// VMTask and friends
127////////////////////////////////////////////////////////////////////////////////
128
129/**
130 * Task structure for asynchronous VM operations.
131 *
132 * Once created, the task structure adds itself as a Console caller. This means:
133 *
134 * 1. The user must check for #rc() before using the created structure
135 * (e.g. passing it as a thread function argument). If #rc() returns a
136 * failure, the Console object may not be used by the task (see
137 * Console::addCaller() for more details).
138 * 2. On successful initialization, the structure keeps the Console caller
139 * until destruction (to ensure Console remains in the Ready state and won't
140 * be accidentally uninitialized). Forgetting to delete the created task
141 * will lead to Console::uninit() stuck waiting for releasing all added
142 * callers.
143 *
144 * If \a aUsesVMPtr parameter is true, the task structure will also add itself
145 * as a Console::mpUVM caller with the same meaning as above. See
146 * Console::addVMCaller() for more info.
147 */
148struct VMTask
149{
150 VMTask(Console *aConsole,
151 Progress *aProgress,
152 const ComPtr<IProgress> &aServerProgress,
153 bool aUsesVMPtr)
154 : mConsole(aConsole),
155 mConsoleCaller(aConsole),
156 mProgress(aProgress),
157 mServerProgress(aServerProgress),
158 mpUVM(NULL),
159 mRC(E_FAIL),
160 mpSafeVMPtr(NULL)
161 {
162 AssertReturnVoid(aConsole);
163 mRC = mConsoleCaller.rc();
164 if (FAILED(mRC))
165 return;
166 if (aUsesVMPtr)
167 {
168 mpSafeVMPtr = new Console::SafeVMPtr(aConsole);
169 if (mpSafeVMPtr->isOk())
170 mpUVM = mpSafeVMPtr->rawUVM();
171 else
172 mRC = mpSafeVMPtr->rc();
173 }
174 }
175
176 ~VMTask()
177 {
178 releaseVMCaller();
179 }
180
181 HRESULT rc() const { return mRC; }
182 bool isOk() const { return SUCCEEDED(rc()); }
183
184 /** Releases the VM caller before destruction. Not normally necessary. */
185 void releaseVMCaller()
186 {
187 if (mpSafeVMPtr)
188 {
189 delete mpSafeVMPtr;
190 mpSafeVMPtr = NULL;
191 }
192 }
193
194 const ComObjPtr<Console> mConsole;
195 AutoCaller mConsoleCaller;
196 const ComObjPtr<Progress> mProgress;
197 Utf8Str mErrorMsg;
198 const ComPtr<IProgress> mServerProgress;
199 PUVM mpUVM;
200
201private:
202 HRESULT mRC;
203 Console::SafeVMPtr *mpSafeVMPtr;
204};
205
206struct VMTakeSnapshotTask : public VMTask
207{
208 VMTakeSnapshotTask(Console *aConsole,
209 Progress *aProgress,
210 IN_BSTR aName,
211 IN_BSTR aDescription)
212 : VMTask(aConsole, aProgress, NULL /* aServerProgress */,
213 false /* aUsesVMPtr */),
214 bstrName(aName),
215 bstrDescription(aDescription),
216 lastMachineState(MachineState_Null)
217 {}
218
219 Bstr bstrName,
220 bstrDescription;
221 Bstr bstrSavedStateFile; // received from BeginTakeSnapshot()
222 MachineState_T lastMachineState;
223 bool fTakingSnapshotOnline;
224 ULONG ulMemSize;
225};
226
227struct VMPowerUpTask : public VMTask
228{
229 VMPowerUpTask(Console *aConsole,
230 Progress *aProgress)
231 : VMTask(aConsole, aProgress, NULL /* aServerProgress */,
232 false /* aUsesVMPtr */),
233 mConfigConstructor(NULL),
234 mStartPaused(false),
235 mTeleporterEnabled(FALSE),
236 mEnmFaultToleranceState(FaultToleranceState_Inactive)
237 {}
238
239 PFNCFGMCONSTRUCTOR mConfigConstructor;
240 Utf8Str mSavedStateFile;
241 Console::SharedFolderDataMap mSharedFolders;
242 bool mStartPaused;
243 BOOL mTeleporterEnabled;
244 FaultToleranceState_T mEnmFaultToleranceState;
245
246 /* array of progress objects for hard disk reset operations */
247 typedef std::list<ComPtr<IProgress> > ProgressList;
248 ProgressList hardDiskProgresses;
249};
250
251struct VMPowerDownTask : public VMTask
252{
253 VMPowerDownTask(Console *aConsole,
254 const ComPtr<IProgress> &aServerProgress)
255 : VMTask(aConsole, NULL /* aProgress */, aServerProgress,
256 true /* aUsesVMPtr */)
257 {}
258};
259
260struct VMSaveTask : public VMTask
261{
262 VMSaveTask(Console *aConsole,
263 const ComPtr<IProgress> &aServerProgress,
264 const Utf8Str &aSavedStateFile,
265 MachineState_T aMachineStateBefore,
266 Reason_T aReason)
267 : VMTask(aConsole, NULL /* aProgress */, aServerProgress,
268 true /* aUsesVMPtr */),
269 mSavedStateFile(aSavedStateFile),
270 mMachineStateBefore(aMachineStateBefore),
271 mReason(aReason)
272 {}
273
274 Utf8Str mSavedStateFile;
275 /* The local machine state we had before. Required if something fails */
276 MachineState_T mMachineStateBefore;
277 /* The reason for saving state */
278 Reason_T mReason;
279};
280
281// Handler for global events
282////////////////////////////////////////////////////////////////////////////////
283inline static const char *networkAdapterTypeToName(NetworkAdapterType_T adapterType);
284
285class VmEventListener {
286public:
287 VmEventListener()
288 {}
289
290
291 HRESULT init(Console *aConsole)
292 {
293 mConsole = aConsole;
294 return S_OK;
295 }
296
297 void uninit()
298 {
299 }
300
301 virtual ~VmEventListener()
302 {
303 }
304
305 STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent * aEvent)
306 {
307 switch(aType)
308 {
309 case VBoxEventType_OnNATRedirect:
310 {
311 Bstr id;
312 ComPtr<IMachine> pMachine = mConsole->machine();
313 ComPtr<INATRedirectEvent> pNREv = aEvent;
314 HRESULT rc = E_FAIL;
315 Assert(pNREv);
316
317 Bstr interestedId;
318 rc = pMachine->COMGETTER(Id)(interestedId.asOutParam());
319 AssertComRC(rc);
320 rc = pNREv->COMGETTER(MachineId)(id.asOutParam());
321 AssertComRC(rc);
322 if (id != interestedId)
323 break;
324 /* now we can operate with redirects */
325 NATProtocol_T proto;
326 pNREv->COMGETTER(Proto)(&proto);
327 BOOL fRemove;
328 pNREv->COMGETTER(Remove)(&fRemove);
329 bool fUdp = (proto == NATProtocol_UDP);
330 Bstr hostIp, guestIp;
331 LONG hostPort, guestPort;
332 pNREv->COMGETTER(HostIP)(hostIp.asOutParam());
333 pNREv->COMGETTER(HostPort)(&hostPort);
334 pNREv->COMGETTER(GuestIP)(guestIp.asOutParam());
335 pNREv->COMGETTER(GuestPort)(&guestPort);
336 ULONG ulSlot;
337 rc = pNREv->COMGETTER(Slot)(&ulSlot);
338 AssertComRC(rc);
339 if (FAILED(rc))
340 break;
341 mConsole->onNATRedirectRuleChange(ulSlot, fRemove, proto, hostIp.raw(), hostPort, guestIp.raw(), guestPort);
342 }
343 break;
344
345 case VBoxEventType_OnHostPCIDevicePlug:
346 {
347 // handle if needed
348 break;
349 }
350
351 default:
352 AssertFailed();
353 }
354 return S_OK;
355 }
356private:
357 Console *mConsole;
358};
359
360typedef ListenerImpl<VmEventListener, Console*> VmEventListenerImpl;
361
362
363VBOX_LISTENER_DECLARE(VmEventListenerImpl)
364
365
366// constructor / destructor
367/////////////////////////////////////////////////////////////////////////////
368
369Console::Console()
370 : mSavedStateDataLoaded(false)
371 , mConsoleVRDPServer(NULL)
372 , mpUVM(NULL)
373 , mVMCallers(0)
374 , mVMZeroCallersSem(NIL_RTSEMEVENT)
375 , mVMDestroying(false)
376 , mVMPoweredOff(false)
377 , mVMIsAlreadyPoweringOff(false)
378 , mfSnapshotFolderSizeWarningShown(false)
379 , mfSnapshotFolderExt4WarningShown(false)
380 , mfSnapshotFolderDiskTypeShown(false)
381 , mpVmm2UserMethods(NULL)
382 , m_pVMMDev(NULL)
383 , mAudioSniffer(NULL)
384 , mNvram(NULL)
385#ifdef VBOX_WITH_USB_VIDEO
386 , mEmWebcam(NULL)
387#endif
388#ifdef VBOX_WITH_USB_CARDREADER
389 , mUsbCardReader(NULL)
390#endif
391 , mBusMgr(NULL)
392 , mVMStateChangeCallbackDisabled(false)
393 , mfUseHostClipboard(true)
394 , mMachineState(MachineState_PoweredOff)
395{
396}
397
398Console::~Console()
399{}
400
401HRESULT Console::FinalConstruct()
402{
403 LogFlowThisFunc(("\n"));
404
405 memset(mapStorageLeds, 0, sizeof(mapStorageLeds));
406 memset(mapNetworkLeds, 0, sizeof(mapNetworkLeds));
407 memset(&mapUSBLed, 0, sizeof(mapUSBLed));
408 memset(&mapSharedFolderLed, 0, sizeof(mapSharedFolderLed));
409
410 for (unsigned i = 0; i < RT_ELEMENTS(maStorageDevType); ++i)
411 maStorageDevType[i] = DeviceType_Null;
412
413 MYVMM2USERMETHODS *pVmm2UserMethods = (MYVMM2USERMETHODS *)RTMemAllocZ(sizeof(*mpVmm2UserMethods) + sizeof(Console *));
414 if (!pVmm2UserMethods)
415 return E_OUTOFMEMORY;
416 pVmm2UserMethods->u32Magic = VMM2USERMETHODS_MAGIC;
417 pVmm2UserMethods->u32Version = VMM2USERMETHODS_VERSION;
418 pVmm2UserMethods->pfnSaveState = Console::vmm2User_SaveState;
419 pVmm2UserMethods->pfnNotifyEmtInit = Console::vmm2User_NotifyEmtInit;
420 pVmm2UserMethods->pfnNotifyEmtTerm = Console::vmm2User_NotifyEmtTerm;
421 pVmm2UserMethods->pfnNotifyPdmtInit = Console::vmm2User_NotifyPdmtInit;
422 pVmm2UserMethods->pfnNotifyPdmtTerm = Console::vmm2User_NotifyPdmtTerm;
423 pVmm2UserMethods->u32EndMagic = VMM2USERMETHODS_MAGIC;
424 pVmm2UserMethods->pConsole = this;
425 mpVmm2UserMethods = pVmm2UserMethods;
426
427 return BaseFinalConstruct();
428}
429
430void Console::FinalRelease()
431{
432 LogFlowThisFunc(("\n"));
433
434 uninit();
435
436 BaseFinalRelease();
437}
438
439// public initializer/uninitializer for internal purposes only
440/////////////////////////////////////////////////////////////////////////////
441
442HRESULT Console::init(IMachine *aMachine, IInternalMachineControl *aControl, LockType_T aLockType)
443{
444 AssertReturn(aMachine && aControl, E_INVALIDARG);
445
446 /* Enclose the state transition NotReady->InInit->Ready */
447 AutoInitSpan autoInitSpan(this);
448 AssertReturn(autoInitSpan.isOk(), E_FAIL);
449
450 LogFlowThisFuncEnter();
451 LogFlowThisFunc(("aMachine=%p, aControl=%p\n", aMachine, aControl));
452
453 HRESULT rc = E_FAIL;
454
455 unconst(mMachine) = aMachine;
456 unconst(mControl) = aControl;
457
458 /* Cache essential properties and objects, and create child objects */
459
460 rc = mMachine->COMGETTER(State)(&mMachineState);
461 AssertComRCReturnRC(rc);
462
463#ifdef VBOX_WITH_EXTPACK
464 unconst(mptrExtPackManager).createObject();
465 rc = mptrExtPackManager->initExtPackManager(NULL, VBOXEXTPACKCTX_VM_PROCESS);
466 AssertComRCReturnRC(rc);
467#endif
468
469 // Event source may be needed by other children
470 unconst(mEventSource).createObject();
471 rc = mEventSource->init(static_cast<IConsole*>(this));
472 AssertComRCReturnRC(rc);
473
474 mcAudioRefs = 0;
475 mcVRDPClients = 0;
476 mu32SingleRDPClientId = 0;
477 mcGuestCredentialsProvided = false;
478
479 /* Now the VM specific parts */
480 if (aLockType == LockType_VM)
481 {
482 rc = mMachine->COMGETTER(VRDEServer)(unconst(mVRDEServer).asOutParam());
483 AssertComRCReturnRC(rc);
484
485 unconst(mGuest).createObject();
486 rc = mGuest->init(this);
487 AssertComRCReturnRC(rc);
488
489 unconst(mKeyboard).createObject();
490 rc = mKeyboard->init(this);
491 AssertComRCReturnRC(rc);
492
493 unconst(mMouse).createObject();
494 rc = mMouse->init(this);
495 AssertComRCReturnRC(rc);
496
497 unconst(mDisplay).createObject();
498 rc = mDisplay->init(this);
499 AssertComRCReturnRC(rc);
500
501 unconst(mVRDEServerInfo).createObject();
502 rc = mVRDEServerInfo->init(this);
503 AssertComRCReturnRC(rc);
504
505 /* Grab global and machine shared folder lists */
506
507 rc = fetchSharedFolders(true /* aGlobal */);
508 AssertComRCReturnRC(rc);
509 rc = fetchSharedFolders(false /* aGlobal */);
510 AssertComRCReturnRC(rc);
511
512 /* Create other child objects */
513
514 unconst(mConsoleVRDPServer) = new ConsoleVRDPServer(this);
515 AssertReturn(mConsoleVRDPServer, E_FAIL);
516
517 /* Figure out size of meAttachmentType vector */
518 ComPtr<IVirtualBox> pVirtualBox;
519 rc = aMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
520 AssertComRC(rc);
521 ComPtr<ISystemProperties> pSystemProperties;
522 if (pVirtualBox)
523 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
524 ChipsetType_T chipsetType = ChipsetType_PIIX3;
525 aMachine->COMGETTER(ChipsetType)(&chipsetType);
526 ULONG maxNetworkAdapters = 0;
527 if (pSystemProperties)
528 pSystemProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
529 meAttachmentType.resize(maxNetworkAdapters);
530 for (ULONG slot = 0; slot < maxNetworkAdapters; ++slot)
531 meAttachmentType[slot] = NetworkAttachmentType_Null;
532
533 // VirtualBox 4.0: We no longer initialize the VMMDev instance here,
534 // which starts the HGCM thread. Instead, this is now done in the
535 // power-up thread when a VM is actually being powered up to avoid
536 // having HGCM threads all over the place every time a session is
537 // opened, even if that session will not run a VM.
538 // unconst(m_pVMMDev) = new VMMDev(this);
539 // AssertReturn(mVMMDev, E_FAIL);
540
541 unconst(mAudioSniffer) = new AudioSniffer(this);
542 AssertReturn(mAudioSniffer, E_FAIL);
543
544 FirmwareType_T enmFirmwareType;
545 mMachine->COMGETTER(FirmwareType)(&enmFirmwareType);
546 if ( enmFirmwareType == FirmwareType_EFI
547 || enmFirmwareType == FirmwareType_EFI32
548 || enmFirmwareType == FirmwareType_EFI64
549 || enmFirmwareType == FirmwareType_EFIDUAL)
550 {
551 unconst(mNvram) = new Nvram(this);
552 AssertReturn(mNvram, E_FAIL);
553 }
554
555#ifdef VBOX_WITH_USB_VIDEO
556 unconst(mEmWebcam) = new EmWebcam(this);
557 AssertReturn(mEmWebcam, E_FAIL);
558#endif
559#ifdef VBOX_WITH_USB_CARDREADER
560 unconst(mUsbCardReader) = new UsbCardReader(this);
561 AssertReturn(mUsbCardReader, E_FAIL);
562#endif
563
564 /* VirtualBox events registration. */
565 {
566 ComPtr<IEventSource> pES;
567 rc = pVirtualBox->COMGETTER(EventSource)(pES.asOutParam());
568 AssertComRC(rc);
569 ComObjPtr<VmEventListenerImpl> aVmListener;
570 aVmListener.createObject();
571 aVmListener->init(new VmEventListener(), this);
572 mVmListener = aVmListener;
573 com::SafeArray<VBoxEventType_T> eventTypes;
574 eventTypes.push_back(VBoxEventType_OnNATRedirect);
575 eventTypes.push_back(VBoxEventType_OnHostPCIDevicePlug);
576 rc = pES->RegisterListener(aVmListener, ComSafeArrayAsInParam(eventTypes), true);
577 AssertComRC(rc);
578 }
579 }
580
581 /* Confirm a successful initialization when it's the case */
582 autoInitSpan.setSucceeded();
583
584#ifdef VBOX_WITH_EXTPACK
585 /* Let the extension packs have a go at things (hold no locks). */
586 if (SUCCEEDED(rc))
587 mptrExtPackManager->callAllConsoleReadyHooks(this);
588#endif
589
590 LogFlowThisFuncLeave();
591
592 return S_OK;
593}
594
595/**
596 * Uninitializes the Console object.
597 */
598void Console::uninit()
599{
600 LogFlowThisFuncEnter();
601
602 /* Enclose the state transition Ready->InUninit->NotReady */
603 AutoUninitSpan autoUninitSpan(this);
604 if (autoUninitSpan.uninitDone())
605 {
606 LogFlowThisFunc(("Already uninitialized.\n"));
607 LogFlowThisFuncLeave();
608 return;
609 }
610
611 LogFlowThisFunc(("initFailed()=%d\n", autoUninitSpan.initFailed()));
612 if (mVmListener)
613 {
614 ComPtr<IEventSource> pES;
615 ComPtr<IVirtualBox> pVirtualBox;
616 HRESULT rc = mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
617 AssertComRC(rc);
618 if (SUCCEEDED(rc) && !pVirtualBox.isNull())
619 {
620 rc = pVirtualBox->COMGETTER(EventSource)(pES.asOutParam());
621 AssertComRC(rc);
622 if (!pES.isNull())
623 {
624 rc = pES->UnregisterListener(mVmListener);
625 AssertComRC(rc);
626 }
627 }
628 mVmListener.setNull();
629 }
630
631 /* power down the VM if necessary */
632 if (mpUVM)
633 {
634 powerDown();
635 Assert(mpUVM == NULL);
636 }
637
638 if (mVMZeroCallersSem != NIL_RTSEMEVENT)
639 {
640 RTSemEventDestroy(mVMZeroCallersSem);
641 mVMZeroCallersSem = NIL_RTSEMEVENT;
642 }
643
644 if (mpVmm2UserMethods)
645 {
646 RTMemFree((void *)mpVmm2UserMethods);
647 mpVmm2UserMethods = NULL;
648 }
649
650 if (mNvram)
651 {
652 delete mNvram;
653 unconst(mNvram) = NULL;
654 }
655
656#ifdef VBOX_WITH_USB_VIDEO
657 if (mEmWebcam)
658 {
659 delete mEmWebcam;
660 unconst(mEmWebcam) = NULL;
661 }
662#endif
663
664#ifdef VBOX_WITH_USB_CARDREADER
665 if (mUsbCardReader)
666 {
667 delete mUsbCardReader;
668 unconst(mUsbCardReader) = NULL;
669 }
670#endif
671
672 if (mAudioSniffer)
673 {
674 delete mAudioSniffer;
675 unconst(mAudioSniffer) = NULL;
676 }
677
678 // if the VM had a VMMDev with an HGCM thread, then remove that here
679 if (m_pVMMDev)
680 {
681 delete m_pVMMDev;
682 unconst(m_pVMMDev) = NULL;
683 }
684
685 if (mBusMgr)
686 {
687 mBusMgr->Release();
688 mBusMgr = NULL;
689 }
690
691 m_mapGlobalSharedFolders.clear();
692 m_mapMachineSharedFolders.clear();
693 m_mapSharedFolders.clear(); // console instances
694
695 mRemoteUSBDevices.clear();
696 mUSBDevices.clear();
697
698 if (mVRDEServerInfo)
699 {
700 mVRDEServerInfo->uninit();
701 unconst(mVRDEServerInfo).setNull();
702 }
703
704 if (mDebugger)
705 {
706 mDebugger->uninit();
707 unconst(mDebugger).setNull();
708 }
709
710 if (mDisplay)
711 {
712 mDisplay->uninit();
713 unconst(mDisplay).setNull();
714 }
715
716 if (mMouse)
717 {
718 mMouse->uninit();
719 unconst(mMouse).setNull();
720 }
721
722 if (mKeyboard)
723 {
724 mKeyboard->uninit();
725 unconst(mKeyboard).setNull();
726 }
727
728 if (mGuest)
729 {
730 mGuest->uninit();
731 unconst(mGuest).setNull();
732 }
733
734 if (mConsoleVRDPServer)
735 {
736 delete mConsoleVRDPServer;
737 unconst(mConsoleVRDPServer) = NULL;
738 }
739
740 unconst(mVRDEServer).setNull();
741
742 unconst(mControl).setNull();
743 unconst(mMachine).setNull();
744
745 // we don't perform uninit() as it's possible that some pending event refers to this source
746 unconst(mEventSource).setNull();
747
748#ifdef CONSOLE_WITH_EVENT_CACHE
749 mCallbackData.clear();
750#endif
751
752 LogFlowThisFuncLeave();
753}
754
755#ifdef VBOX_WITH_GUEST_PROPS
756
757/**
758 * Handles guest properties on a VM reset.
759 *
760 * We must delete properties that are flagged TRANSRESET.
761 *
762 * @todo r=bird: Would be more efficient if we added a request to the HGCM
763 * service to do this instead of detouring thru VBoxSVC.
764 * (IMachine::SetGuestProperty ends up in VBoxSVC, which in turns calls
765 * back into the VM process and the HGCM service.)
766 */
767void Console::guestPropertiesHandleVMReset(void)
768{
769 com::SafeArray<BSTR> arrNames;
770 com::SafeArray<BSTR> arrValues;
771 com::SafeArray<LONG64> arrTimestamps;
772 com::SafeArray<BSTR> arrFlags;
773 HRESULT hrc = enumerateGuestProperties(Bstr("*").raw(),
774 ComSafeArrayAsOutParam(arrNames),
775 ComSafeArrayAsOutParam(arrValues),
776 ComSafeArrayAsOutParam(arrTimestamps),
777 ComSafeArrayAsOutParam(arrFlags));
778 if (SUCCEEDED(hrc))
779 {
780 for (size_t i = 0; i < arrFlags.size(); i++)
781 {
782 /* Delete all properties which have the flag "TRANSRESET". */
783 if (Utf8Str(arrFlags[i]).contains("TRANSRESET", Utf8Str::CaseInsensitive))
784 {
785 hrc = mMachine->DeleteGuestProperty(arrNames[i]);
786 if (FAILED(hrc))
787 LogRel(("RESET: Could not delete transient property \"%ls\", rc=%Rhrc\n",
788 arrNames[i], hrc));
789 }
790 }
791 }
792 else
793 LogRel(("RESET: Unable to enumerate guest properties, rc=%Rhrc\n", hrc));
794}
795
796bool Console::guestPropertiesVRDPEnabled(void)
797{
798 Bstr value;
799 HRESULT hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/EnableGuestPropertiesVRDP").raw(),
800 value.asOutParam());
801 if ( hrc == S_OK
802 && value == "1")
803 return true;
804 return false;
805}
806
807void Console::guestPropertiesVRDPUpdateLogon(uint32_t u32ClientId, const char *pszUser, const char *pszDomain)
808{
809 if (!guestPropertiesVRDPEnabled())
810 return;
811
812 LogFlowFunc(("\n"));
813
814 char szPropNm[256];
815 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
816
817 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Name", u32ClientId);
818 Bstr clientName;
819 mVRDEServerInfo->COMGETTER(ClientName)(clientName.asOutParam());
820
821 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
822 clientName.raw(),
823 bstrReadOnlyGuest.raw());
824
825 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/User", u32ClientId);
826 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
827 Bstr(pszUser).raw(),
828 bstrReadOnlyGuest.raw());
829
830 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Domain", u32ClientId);
831 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
832 Bstr(pszDomain).raw(),
833 bstrReadOnlyGuest.raw());
834
835 char szClientId[64];
836 RTStrPrintf(szClientId, sizeof(szClientId), "%u", u32ClientId);
837 mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VRDP/LastConnectedClient").raw(),
838 Bstr(szClientId).raw(),
839 bstrReadOnlyGuest.raw());
840
841 return;
842}
843
844void Console::guestPropertiesVRDPUpdateActiveClient(uint32_t u32ClientId)
845{
846 if (!guestPropertiesVRDPEnabled())
847 return;
848
849 LogFlowFunc(("%d\n", u32ClientId));
850
851 Bstr bstrFlags(L"RDONLYGUEST,TRANSIENT");
852
853 char szClientId[64];
854 RTStrPrintf(szClientId, sizeof(szClientId), "%u", u32ClientId);
855
856 mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VRDP/ActiveClient").raw(),
857 Bstr(szClientId).raw(),
858 bstrFlags.raw());
859
860 return;
861}
862
863void Console::guestPropertiesVRDPUpdateNameChange(uint32_t u32ClientId, const char *pszName)
864{
865 if (!guestPropertiesVRDPEnabled())
866 return;
867
868 LogFlowFunc(("\n"));
869
870 char szPropNm[256];
871 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
872
873 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Name", u32ClientId);
874 Bstr clientName(pszName);
875
876 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
877 clientName.raw(),
878 bstrReadOnlyGuest.raw());
879
880}
881
882void Console::guestPropertiesVRDPUpdateIPAddrChange(uint32_t u32ClientId, const char *pszIPAddr)
883{
884 if (!guestPropertiesVRDPEnabled())
885 return;
886
887 LogFlowFunc(("\n"));
888
889 char szPropNm[256];
890 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
891
892 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/IPAddr", u32ClientId);
893 Bstr clientIPAddr(pszIPAddr);
894
895 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
896 clientIPAddr.raw(),
897 bstrReadOnlyGuest.raw());
898
899}
900
901void Console::guestPropertiesVRDPUpdateLocationChange(uint32_t u32ClientId, const char *pszLocation)
902{
903 if (!guestPropertiesVRDPEnabled())
904 return;
905
906 LogFlowFunc(("\n"));
907
908 char szPropNm[256];
909 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
910
911 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Location", u32ClientId);
912 Bstr clientLocation(pszLocation);
913
914 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
915 clientLocation.raw(),
916 bstrReadOnlyGuest.raw());
917
918}
919
920void Console::guestPropertiesVRDPUpdateOtherInfoChange(uint32_t u32ClientId, const char *pszOtherInfo)
921{
922 if (!guestPropertiesVRDPEnabled())
923 return;
924
925 LogFlowFunc(("\n"));
926
927 char szPropNm[256];
928 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
929
930 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/OtherInfo", u32ClientId);
931 Bstr clientOtherInfo(pszOtherInfo);
932
933 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
934 clientOtherInfo.raw(),
935 bstrReadOnlyGuest.raw());
936
937}
938
939void Console::guestPropertiesVRDPUpdateClientAttach(uint32_t u32ClientId, bool fAttached)
940{
941 if (!guestPropertiesVRDPEnabled())
942 return;
943
944 LogFlowFunc(("\n"));
945
946 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
947
948 char szPropNm[256];
949 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Attach", u32ClientId);
950
951 Bstr bstrValue = fAttached? "1": "0";
952
953 mMachine->SetGuestProperty(Bstr(szPropNm).raw(),
954 bstrValue.raw(),
955 bstrReadOnlyGuest.raw());
956}
957
958void Console::guestPropertiesVRDPUpdateDisconnect(uint32_t u32ClientId)
959{
960 if (!guestPropertiesVRDPEnabled())
961 return;
962
963 LogFlowFunc(("\n"));
964
965 Bstr bstrReadOnlyGuest(L"RDONLYGUEST");
966
967 char szPropNm[256];
968 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Name", u32ClientId);
969 mMachine->SetGuestProperty(Bstr(szPropNm).raw(), NULL,
970 bstrReadOnlyGuest.raw());
971
972 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/User", u32ClientId);
973 mMachine->SetGuestProperty(Bstr(szPropNm).raw(), NULL,
974 bstrReadOnlyGuest.raw());
975
976 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Domain", u32ClientId);
977 mMachine->SetGuestProperty(Bstr(szPropNm).raw(), NULL,
978 bstrReadOnlyGuest.raw());
979
980 RTStrPrintf(szPropNm, sizeof(szPropNm), "/VirtualBox/HostInfo/VRDP/Client/%u/Attach", u32ClientId);
981 mMachine->SetGuestProperty(Bstr(szPropNm).raw(), NULL,
982 bstrReadOnlyGuest.raw());
983
984 char szClientId[64];
985 RTStrPrintf(szClientId, sizeof(szClientId), "%d", u32ClientId);
986 mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VRDP/LastDisconnectedClient").raw(),
987 Bstr(szClientId).raw(),
988 bstrReadOnlyGuest.raw());
989
990 return;
991}
992
993#endif /* VBOX_WITH_GUEST_PROPS */
994
995#ifdef VBOX_WITH_EXTPACK
996/**
997 * Used by VRDEServer and others to talke to the extension pack manager.
998 *
999 * @returns The extension pack manager.
1000 */
1001ExtPackManager *Console::getExtPackManager()
1002{
1003 return mptrExtPackManager;
1004}
1005#endif
1006
1007
1008int Console::VRDPClientLogon(uint32_t u32ClientId, const char *pszUser, const char *pszPassword, const char *pszDomain)
1009{
1010 LogFlowFuncEnter();
1011 LogFlowFunc(("%d, %s, %s, %s\n", u32ClientId, pszUser, pszPassword, pszDomain));
1012
1013 AutoCaller autoCaller(this);
1014 if (!autoCaller.isOk())
1015 {
1016 /* Console has been already uninitialized, deny request */
1017 LogRel(("AUTH: Access denied (Console uninitialized).\n"));
1018 LogFlowFuncLeave();
1019 return VERR_ACCESS_DENIED;
1020 }
1021
1022 Bstr id;
1023 HRESULT hrc = mMachine->COMGETTER(Id)(id.asOutParam());
1024 Guid uuid = Guid(id);
1025
1026 AssertComRCReturn(hrc, VERR_ACCESS_DENIED);
1027
1028 AuthType_T authType = AuthType_Null;
1029 hrc = mVRDEServer->COMGETTER(AuthType)(&authType);
1030 AssertComRCReturn(hrc, VERR_ACCESS_DENIED);
1031
1032 ULONG authTimeout = 0;
1033 hrc = mVRDEServer->COMGETTER(AuthTimeout)(&authTimeout);
1034 AssertComRCReturn(hrc, VERR_ACCESS_DENIED);
1035
1036 AuthResult result = AuthResultAccessDenied;
1037 AuthGuestJudgement guestJudgement = AuthGuestNotAsked;
1038
1039 LogFlowFunc(("Auth type %d\n", authType));
1040
1041 LogRel(("AUTH: User: [%s]. Domain: [%s]. Authentication type: [%s]\n",
1042 pszUser, pszDomain,
1043 authType == AuthType_Null?
1044 "Null":
1045 (authType == AuthType_External?
1046 "External":
1047 (authType == AuthType_Guest?
1048 "Guest":
1049 "INVALID"
1050 )
1051 )
1052 ));
1053
1054 switch (authType)
1055 {
1056 case AuthType_Null:
1057 {
1058 result = AuthResultAccessGranted;
1059 break;
1060 }
1061
1062 case AuthType_External:
1063 {
1064 /* Call the external library. */
1065 result = mConsoleVRDPServer->Authenticate(uuid, guestJudgement, pszUser, pszPassword, pszDomain, u32ClientId);
1066
1067 if (result != AuthResultDelegateToGuest)
1068 {
1069 break;
1070 }
1071
1072 LogRel(("AUTH: Delegated to guest.\n"));
1073
1074 LogFlowFunc(("External auth asked for guest judgement\n"));
1075 } /* pass through */
1076
1077 case AuthType_Guest:
1078 {
1079 guestJudgement = AuthGuestNotReacted;
1080
1081 // @todo r=dj locking required here for m_pVMMDev?
1082 PPDMIVMMDEVPORT pDevPort;
1083 if ( (m_pVMMDev)
1084 && ((pDevPort = m_pVMMDev->getVMMDevPort()))
1085 )
1086 {
1087 /* Issue the request to guest. Assume that the call does not require EMT. It should not. */
1088
1089 /* Ask the guest to judge these credentials. */
1090 uint32_t u32GuestFlags = VMMDEV_SETCREDENTIALS_JUDGE;
1091
1092 int rc = pDevPort->pfnSetCredentials(pDevPort, pszUser, pszPassword, pszDomain, u32GuestFlags);
1093
1094 if (RT_SUCCESS(rc))
1095 {
1096 /* Wait for guest. */
1097 rc = m_pVMMDev->WaitCredentialsJudgement(authTimeout, &u32GuestFlags);
1098
1099 if (RT_SUCCESS(rc))
1100 {
1101 switch (u32GuestFlags & (VMMDEV_CREDENTIALS_JUDGE_OK | VMMDEV_CREDENTIALS_JUDGE_DENY | VMMDEV_CREDENTIALS_JUDGE_NOJUDGEMENT))
1102 {
1103 case VMMDEV_CREDENTIALS_JUDGE_DENY: guestJudgement = AuthGuestAccessDenied; break;
1104 case VMMDEV_CREDENTIALS_JUDGE_NOJUDGEMENT: guestJudgement = AuthGuestNoJudgement; break;
1105 case VMMDEV_CREDENTIALS_JUDGE_OK: guestJudgement = AuthGuestAccessGranted; break;
1106 default:
1107 LogFlowFunc(("Invalid guest flags %08X!!!\n", u32GuestFlags)); break;
1108 }
1109 }
1110 else
1111 {
1112 LogFlowFunc(("Wait for credentials judgement rc = %Rrc!!!\n", rc));
1113 }
1114
1115 LogFlowFunc(("Guest judgement %d\n", guestJudgement));
1116 }
1117 else
1118 {
1119 LogFlowFunc(("Could not set credentials rc = %Rrc!!!\n", rc));
1120 }
1121 }
1122
1123 if (authType == AuthType_External)
1124 {
1125 LogRel(("AUTH: Guest judgement %d.\n", guestJudgement));
1126 LogFlowFunc(("External auth called again with guest judgement = %d\n", guestJudgement));
1127 result = mConsoleVRDPServer->Authenticate(uuid, guestJudgement, pszUser, pszPassword, pszDomain, u32ClientId);
1128 }
1129 else
1130 {
1131 switch (guestJudgement)
1132 {
1133 case AuthGuestAccessGranted:
1134 result = AuthResultAccessGranted;
1135 break;
1136 default:
1137 result = AuthResultAccessDenied;
1138 break;
1139 }
1140 }
1141 } break;
1142
1143 default:
1144 AssertFailed();
1145 }
1146
1147 LogFlowFunc(("Result = %d\n", result));
1148 LogFlowFuncLeave();
1149
1150 if (result != AuthResultAccessGranted)
1151 {
1152 /* Reject. */
1153 LogRel(("AUTH: Access denied.\n"));
1154 return VERR_ACCESS_DENIED;
1155 }
1156
1157 LogRel(("AUTH: Access granted.\n"));
1158
1159 /* Multiconnection check must be made after authentication, so bad clients would not interfere with a good one. */
1160 BOOL allowMultiConnection = FALSE;
1161 hrc = mVRDEServer->COMGETTER(AllowMultiConnection)(&allowMultiConnection);
1162 AssertComRCReturn(hrc, VERR_ACCESS_DENIED);
1163
1164 BOOL reuseSingleConnection = FALSE;
1165 hrc = mVRDEServer->COMGETTER(ReuseSingleConnection)(&reuseSingleConnection);
1166 AssertComRCReturn(hrc, VERR_ACCESS_DENIED);
1167
1168 LogFlowFunc(("allowMultiConnection %d, reuseSingleConnection = %d, mcVRDPClients = %d, mu32SingleRDPClientId = %d\n", allowMultiConnection, reuseSingleConnection, mcVRDPClients, mu32SingleRDPClientId));
1169
1170 if (allowMultiConnection == FALSE)
1171 {
1172 /* Note: the 'mcVRDPClients' variable is incremented in ClientConnect callback, which is called when the client
1173 * is successfully connected, that is after the ClientLogon callback. Therefore the mcVRDPClients
1174 * value is 0 for first client.
1175 */
1176 if (mcVRDPClients != 0)
1177 {
1178 Assert(mcVRDPClients == 1);
1179 /* There is a client already.
1180 * If required drop the existing client connection and let the connecting one in.
1181 */
1182 if (reuseSingleConnection)
1183 {
1184 LogRel(("AUTH: Multiple connections are not enabled. Disconnecting existing client.\n"));
1185 mConsoleVRDPServer->DisconnectClient(mu32SingleRDPClientId, false);
1186 }
1187 else
1188 {
1189 /* Reject. */
1190 LogRel(("AUTH: Multiple connections are not enabled. Access denied.\n"));
1191 return VERR_ACCESS_DENIED;
1192 }
1193 }
1194
1195 /* Save the connected client id. From now on it will be necessary to disconnect this one. */
1196 mu32SingleRDPClientId = u32ClientId;
1197 }
1198
1199#ifdef VBOX_WITH_GUEST_PROPS
1200 guestPropertiesVRDPUpdateLogon(u32ClientId, pszUser, pszDomain);
1201#endif /* VBOX_WITH_GUEST_PROPS */
1202
1203 /* Check if the successfully verified credentials are to be sent to the guest. */
1204 BOOL fProvideGuestCredentials = FALSE;
1205
1206 Bstr value;
1207 hrc = mMachine->GetExtraData(Bstr("VRDP/ProvideGuestCredentials").raw(),
1208 value.asOutParam());
1209 if (SUCCEEDED(hrc) && value == "1")
1210 {
1211 /* Provide credentials only if there are no logged in users. */
1212 Bstr noLoggedInUsersValue;
1213 LONG64 ul64Timestamp = 0;
1214 Bstr flags;
1215
1216 hrc = getGuestProperty(Bstr("/VirtualBox/GuestInfo/OS/NoLoggedInUsers").raw(),
1217 noLoggedInUsersValue.asOutParam(), &ul64Timestamp, flags.asOutParam());
1218
1219 if (SUCCEEDED(hrc) && noLoggedInUsersValue != Bstr("false"))
1220 {
1221 /* And only if there are no connected clients. */
1222 if (ASMAtomicCmpXchgBool(&mcGuestCredentialsProvided, true, false))
1223 {
1224 fProvideGuestCredentials = TRUE;
1225 }
1226 }
1227 }
1228
1229 // @todo r=dj locking required here for m_pVMMDev?
1230 if ( fProvideGuestCredentials
1231 && m_pVMMDev)
1232 {
1233 uint32_t u32GuestFlags = VMMDEV_SETCREDENTIALS_GUESTLOGON;
1234
1235 PPDMIVMMDEVPORT pDevPort = m_pVMMDev->getVMMDevPort();
1236 if (pDevPort)
1237 {
1238 int rc = pDevPort->pfnSetCredentials(m_pVMMDev->getVMMDevPort(),
1239 pszUser, pszPassword, pszDomain, u32GuestFlags);
1240 AssertRC(rc);
1241 }
1242 }
1243
1244 return VINF_SUCCESS;
1245}
1246
1247void Console::VRDPClientStatusChange(uint32_t u32ClientId, const char *pszStatus)
1248{
1249 LogFlowFuncEnter();
1250
1251 AutoCaller autoCaller(this);
1252 AssertComRCReturnVoid(autoCaller.rc());
1253
1254 LogFlowFunc(("%s\n", pszStatus));
1255
1256#ifdef VBOX_WITH_GUEST_PROPS
1257 /* Parse the status string. */
1258 if (RTStrICmp(pszStatus, "ATTACH") == 0)
1259 {
1260 guestPropertiesVRDPUpdateClientAttach(u32ClientId, true);
1261 }
1262 else if (RTStrICmp(pszStatus, "DETACH") == 0)
1263 {
1264 guestPropertiesVRDPUpdateClientAttach(u32ClientId, false);
1265 }
1266 else if (RTStrNICmp(pszStatus, "NAME=", strlen("NAME=")) == 0)
1267 {
1268 guestPropertiesVRDPUpdateNameChange(u32ClientId, pszStatus + strlen("NAME="));
1269 }
1270 else if (RTStrNICmp(pszStatus, "CIPA=", strlen("CIPA=")) == 0)
1271 {
1272 guestPropertiesVRDPUpdateIPAddrChange(u32ClientId, pszStatus + strlen("CIPA="));
1273 }
1274 else if (RTStrNICmp(pszStatus, "CLOCATION=", strlen("CLOCATION=")) == 0)
1275 {
1276 guestPropertiesVRDPUpdateLocationChange(u32ClientId, pszStatus + strlen("CLOCATION="));
1277 }
1278 else if (RTStrNICmp(pszStatus, "COINFO=", strlen("COINFO=")) == 0)
1279 {
1280 guestPropertiesVRDPUpdateOtherInfoChange(u32ClientId, pszStatus + strlen("COINFO="));
1281 }
1282#endif
1283
1284 LogFlowFuncLeave();
1285}
1286
1287void Console::VRDPClientConnect(uint32_t u32ClientId)
1288{
1289 LogFlowFuncEnter();
1290
1291 AutoCaller autoCaller(this);
1292 AssertComRCReturnVoid(autoCaller.rc());
1293
1294 uint32_t u32Clients = ASMAtomicIncU32(&mcVRDPClients);
1295 VMMDev *pDev;
1296 PPDMIVMMDEVPORT pPort;
1297 if ( (u32Clients == 1)
1298 && ((pDev = getVMMDev()))
1299 && ((pPort = pDev->getVMMDevPort()))
1300 )
1301 {
1302 pPort->pfnVRDPChange(pPort,
1303 true,
1304 VRDP_EXPERIENCE_LEVEL_FULL); // @todo configurable
1305 }
1306
1307 NOREF(u32ClientId);
1308 mDisplay->VideoAccelVRDP(true);
1309
1310#ifdef VBOX_WITH_GUEST_PROPS
1311 guestPropertiesVRDPUpdateActiveClient(u32ClientId);
1312#endif /* VBOX_WITH_GUEST_PROPS */
1313
1314 LogFlowFuncLeave();
1315 return;
1316}
1317
1318void Console::VRDPClientDisconnect(uint32_t u32ClientId,
1319 uint32_t fu32Intercepted)
1320{
1321 LogFlowFuncEnter();
1322
1323 AutoCaller autoCaller(this);
1324 AssertComRCReturnVoid(autoCaller.rc());
1325
1326 AssertReturnVoid(mConsoleVRDPServer);
1327
1328 uint32_t u32Clients = ASMAtomicDecU32(&mcVRDPClients);
1329 VMMDev *pDev;
1330 PPDMIVMMDEVPORT pPort;
1331
1332 if ( (u32Clients == 0)
1333 && ((pDev = getVMMDev()))
1334 && ((pPort = pDev->getVMMDevPort()))
1335 )
1336 {
1337 pPort->pfnVRDPChange(pPort,
1338 false,
1339 0);
1340 }
1341
1342 mDisplay->VideoAccelVRDP(false);
1343
1344 if (fu32Intercepted & VRDE_CLIENT_INTERCEPT_USB)
1345 {
1346 mConsoleVRDPServer->USBBackendDelete(u32ClientId);
1347 }
1348
1349 if (fu32Intercepted & VRDE_CLIENT_INTERCEPT_CLIPBOARD)
1350 {
1351 mConsoleVRDPServer->ClipboardDelete(u32ClientId);
1352 }
1353
1354 if (fu32Intercepted & VRDE_CLIENT_INTERCEPT_AUDIO)
1355 {
1356 mcAudioRefs--;
1357
1358 if (mcAudioRefs <= 0)
1359 {
1360 if (mAudioSniffer)
1361 {
1362 PPDMIAUDIOSNIFFERPORT port = mAudioSniffer->getAudioSnifferPort();
1363 if (port)
1364 {
1365 port->pfnSetup(port, false, false);
1366 }
1367 }
1368 }
1369 }
1370
1371 Bstr uuid;
1372 HRESULT hrc = mMachine->COMGETTER(Id)(uuid.asOutParam());
1373 AssertComRC(hrc);
1374
1375 AuthType_T authType = AuthType_Null;
1376 hrc = mVRDEServer->COMGETTER(AuthType)(&authType);
1377 AssertComRC(hrc);
1378
1379 if (authType == AuthType_External)
1380 mConsoleVRDPServer->AuthDisconnect(uuid, u32ClientId);
1381
1382#ifdef VBOX_WITH_GUEST_PROPS
1383 guestPropertiesVRDPUpdateDisconnect(u32ClientId);
1384 if (u32Clients == 0)
1385 guestPropertiesVRDPUpdateActiveClient(0);
1386#endif /* VBOX_WITH_GUEST_PROPS */
1387
1388 if (u32Clients == 0)
1389 mcGuestCredentialsProvided = false;
1390
1391 LogFlowFuncLeave();
1392 return;
1393}
1394
1395void Console::VRDPInterceptAudio(uint32_t u32ClientId)
1396{
1397 LogFlowFuncEnter();
1398
1399 AutoCaller autoCaller(this);
1400 AssertComRCReturnVoid(autoCaller.rc());
1401
1402 LogFlowFunc(("mAudioSniffer %p, u32ClientId %d.\n",
1403 mAudioSniffer, u32ClientId));
1404 NOREF(u32ClientId);
1405
1406 ++mcAudioRefs;
1407
1408 if (mcAudioRefs == 1)
1409 {
1410 if (mAudioSniffer)
1411 {
1412 PPDMIAUDIOSNIFFERPORT port = mAudioSniffer->getAudioSnifferPort();
1413 if (port)
1414 {
1415 port->pfnSetup(port, true, true);
1416 }
1417 }
1418 }
1419
1420 LogFlowFuncLeave();
1421 return;
1422}
1423
1424void Console::VRDPInterceptUSB(uint32_t u32ClientId, void **ppvIntercept)
1425{
1426 LogFlowFuncEnter();
1427
1428 AutoCaller autoCaller(this);
1429 AssertComRCReturnVoid(autoCaller.rc());
1430
1431 AssertReturnVoid(mConsoleVRDPServer);
1432
1433 mConsoleVRDPServer->USBBackendCreate(u32ClientId, ppvIntercept);
1434
1435 LogFlowFuncLeave();
1436 return;
1437}
1438
1439void Console::VRDPInterceptClipboard(uint32_t u32ClientId)
1440{
1441 LogFlowFuncEnter();
1442
1443 AutoCaller autoCaller(this);
1444 AssertComRCReturnVoid(autoCaller.rc());
1445
1446 AssertReturnVoid(mConsoleVRDPServer);
1447
1448 mConsoleVRDPServer->ClipboardCreate(u32ClientId);
1449
1450 LogFlowFuncLeave();
1451 return;
1452}
1453
1454
1455//static
1456const char *Console::sSSMConsoleUnit = "ConsoleData";
1457//static
1458uint32_t Console::sSSMConsoleVer = 0x00010001;
1459
1460inline static const char *networkAdapterTypeToName(NetworkAdapterType_T adapterType)
1461{
1462 switch (adapterType)
1463 {
1464 case NetworkAdapterType_Am79C970A:
1465 case NetworkAdapterType_Am79C973:
1466 return "pcnet";
1467#ifdef VBOX_WITH_E1000
1468 case NetworkAdapterType_I82540EM:
1469 case NetworkAdapterType_I82543GC:
1470 case NetworkAdapterType_I82545EM:
1471 return "e1000";
1472#endif
1473#ifdef VBOX_WITH_VIRTIO
1474 case NetworkAdapterType_Virtio:
1475 return "virtio-net";
1476#endif
1477 default:
1478 AssertFailed();
1479 return "unknown";
1480 }
1481 return NULL;
1482}
1483
1484/**
1485 * Loads various console data stored in the saved state file.
1486 * This method does validation of the state file and returns an error info
1487 * when appropriate.
1488 *
1489 * The method does nothing if the machine is not in the Saved file or if
1490 * console data from it has already been loaded.
1491 *
1492 * @note The caller must lock this object for writing.
1493 */
1494HRESULT Console::loadDataFromSavedState()
1495{
1496 if (mMachineState != MachineState_Saved || mSavedStateDataLoaded)
1497 return S_OK;
1498
1499 Bstr savedStateFile;
1500 HRESULT rc = mMachine->COMGETTER(StateFilePath)(savedStateFile.asOutParam());
1501 if (FAILED(rc))
1502 return rc;
1503
1504 PSSMHANDLE ssm;
1505 int vrc = SSMR3Open(Utf8Str(savedStateFile).c_str(), 0, &ssm);
1506 if (RT_SUCCESS(vrc))
1507 {
1508 uint32_t version = 0;
1509 vrc = SSMR3Seek(ssm, sSSMConsoleUnit, 0 /* iInstance */, &version);
1510 if (SSM_VERSION_MAJOR(version) == SSM_VERSION_MAJOR(sSSMConsoleVer))
1511 {
1512 if (RT_SUCCESS(vrc))
1513 vrc = loadStateFileExecInternal(ssm, version);
1514 else if (vrc == VERR_SSM_UNIT_NOT_FOUND)
1515 vrc = VINF_SUCCESS;
1516 }
1517 else
1518 vrc = VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
1519
1520 SSMR3Close(ssm);
1521 }
1522
1523 if (RT_FAILURE(vrc))
1524 rc = setError(VBOX_E_FILE_ERROR,
1525 tr("The saved state file '%ls' is invalid (%Rrc). Delete the saved state and try again"),
1526 savedStateFile.raw(), vrc);
1527
1528 mSavedStateDataLoaded = true;
1529
1530 return rc;
1531}
1532
1533/**
1534 * Callback handler to save various console data to the state file,
1535 * called when the user saves the VM state.
1536 *
1537 * @param pvUser pointer to Console
1538 *
1539 * @note Locks the Console object for reading.
1540 */
1541//static
1542DECLCALLBACK(void)
1543Console::saveStateFileExec(PSSMHANDLE pSSM, void *pvUser)
1544{
1545 LogFlowFunc(("\n"));
1546
1547 Console *that = static_cast<Console *>(pvUser);
1548 AssertReturnVoid(that);
1549
1550 AutoCaller autoCaller(that);
1551 AssertComRCReturnVoid(autoCaller.rc());
1552
1553 AutoReadLock alock(that COMMA_LOCKVAL_SRC_POS);
1554
1555 int vrc = SSMR3PutU32(pSSM, (uint32_t)that->m_mapSharedFolders.size());
1556 AssertRC(vrc);
1557
1558 for (SharedFolderMap::const_iterator it = that->m_mapSharedFolders.begin();
1559 it != that->m_mapSharedFolders.end();
1560 ++it)
1561 {
1562 SharedFolder *pSF = (*it).second;
1563 AutoCaller sfCaller(pSF);
1564 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
1565
1566 Utf8Str name = pSF->getName();
1567 vrc = SSMR3PutU32(pSSM, (uint32_t)name.length() + 1 /* term. 0 */);
1568 AssertRC(vrc);
1569 vrc = SSMR3PutStrZ(pSSM, name.c_str());
1570 AssertRC(vrc);
1571
1572 Utf8Str hostPath = pSF->getHostPath();
1573 vrc = SSMR3PutU32(pSSM, (uint32_t)hostPath.length() + 1 /* term. 0 */);
1574 AssertRC(vrc);
1575 vrc = SSMR3PutStrZ(pSSM, hostPath.c_str());
1576 AssertRC(vrc);
1577
1578 vrc = SSMR3PutBool(pSSM, !!pSF->isWritable());
1579 AssertRC(vrc);
1580
1581 vrc = SSMR3PutBool(pSSM, !!pSF->isAutoMounted());
1582 AssertRC(vrc);
1583 }
1584
1585 return;
1586}
1587
1588/**
1589 * Callback handler to load various console data from the state file.
1590 * Called when the VM is being restored from the saved state.
1591 *
1592 * @param pvUser pointer to Console
1593 * @param uVersion Console unit version.
1594 * Should match sSSMConsoleVer.
1595 * @param uPass The data pass.
1596 *
1597 * @note Should locks the Console object for writing, if necessary.
1598 */
1599//static
1600DECLCALLBACK(int)
1601Console::loadStateFileExec(PSSMHANDLE pSSM, void *pvUser, uint32_t uVersion, uint32_t uPass)
1602{
1603 LogFlowFunc(("\n"));
1604
1605 if (SSM_VERSION_MAJOR_CHANGED(uVersion, sSSMConsoleVer))
1606 return VERR_VERSION_MISMATCH;
1607 Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
1608
1609 Console *that = static_cast<Console *>(pvUser);
1610 AssertReturn(that, VERR_INVALID_PARAMETER);
1611
1612 /* Currently, nothing to do when we've been called from VMR3Load*. */
1613 return SSMR3SkipToEndOfUnit(pSSM);
1614}
1615
1616/**
1617 * Method to load various console data from the state file.
1618 * Called from #loadDataFromSavedState.
1619 *
1620 * @param pvUser pointer to Console
1621 * @param u32Version Console unit version.
1622 * Should match sSSMConsoleVer.
1623 *
1624 * @note Locks the Console object for writing.
1625 */
1626int
1627Console::loadStateFileExecInternal(PSSMHANDLE pSSM, uint32_t u32Version)
1628{
1629 AutoCaller autoCaller(this);
1630 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
1631
1632 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1633
1634 AssertReturn(m_mapSharedFolders.size() == 0, VERR_INTERNAL_ERROR);
1635
1636 uint32_t size = 0;
1637 int vrc = SSMR3GetU32(pSSM, &size);
1638 AssertRCReturn(vrc, vrc);
1639
1640 for (uint32_t i = 0; i < size; ++i)
1641 {
1642 Utf8Str strName;
1643 Utf8Str strHostPath;
1644 bool writable = true;
1645 bool autoMount = false;
1646
1647 uint32_t szBuf = 0;
1648 char *buf = NULL;
1649
1650 vrc = SSMR3GetU32(pSSM, &szBuf);
1651 AssertRCReturn(vrc, vrc);
1652 buf = new char[szBuf];
1653 vrc = SSMR3GetStrZ(pSSM, buf, szBuf);
1654 AssertRC(vrc);
1655 strName = buf;
1656 delete[] buf;
1657
1658 vrc = SSMR3GetU32(pSSM, &szBuf);
1659 AssertRCReturn(vrc, vrc);
1660 buf = new char[szBuf];
1661 vrc = SSMR3GetStrZ(pSSM, buf, szBuf);
1662 AssertRC(vrc);
1663 strHostPath = buf;
1664 delete[] buf;
1665
1666 if (u32Version > 0x00010000)
1667 SSMR3GetBool(pSSM, &writable);
1668
1669 if (u32Version > 0x00010000) // ???
1670 SSMR3GetBool(pSSM, &autoMount);
1671
1672 ComObjPtr<SharedFolder> pSharedFolder;
1673 pSharedFolder.createObject();
1674 HRESULT rc = pSharedFolder->init(this,
1675 strName,
1676 strHostPath,
1677 writable,
1678 autoMount,
1679 false /* fFailOnError */);
1680 AssertComRCReturn(rc, VERR_INTERNAL_ERROR);
1681
1682 m_mapSharedFolders.insert(std::make_pair(strName, pSharedFolder));
1683 }
1684
1685 return VINF_SUCCESS;
1686}
1687
1688#ifdef VBOX_WITH_GUEST_PROPS
1689
1690// static
1691DECLCALLBACK(int) Console::doGuestPropNotification(void *pvExtension,
1692 uint32_t u32Function,
1693 void *pvParms,
1694 uint32_t cbParms)
1695{
1696 using namespace guestProp;
1697
1698 Assert(u32Function == 0); NOREF(u32Function);
1699
1700 /*
1701 * No locking, as this is purely a notification which does not make any
1702 * changes to the object state.
1703 */
1704 PHOSTCALLBACKDATA pCBData = reinterpret_cast<PHOSTCALLBACKDATA>(pvParms);
1705 AssertReturn(sizeof(HOSTCALLBACKDATA) == cbParms, VERR_INVALID_PARAMETER);
1706 AssertReturn(HOSTCALLBACKMAGIC == pCBData->u32Magic, VERR_INVALID_PARAMETER);
1707 LogFlow(("Console::doGuestPropNotification: pCBData={.pcszName=%s, .pcszValue=%s, .pcszFlags=%s}\n",
1708 pCBData->pcszName, pCBData->pcszValue, pCBData->pcszFlags));
1709
1710 int rc;
1711 Bstr name(pCBData->pcszName);
1712 Bstr value(pCBData->pcszValue);
1713 Bstr flags(pCBData->pcszFlags);
1714 ComObjPtr<Console> pConsole = reinterpret_cast<Console *>(pvExtension);
1715 HRESULT hrc = pConsole->mControl->PushGuestProperty(name.raw(),
1716 value.raw(),
1717 pCBData->u64Timestamp,
1718 flags.raw());
1719 if (SUCCEEDED(hrc))
1720 rc = VINF_SUCCESS;
1721 else
1722 {
1723 LogFlow(("Console::doGuestPropNotification: hrc=%Rhrc pCBData={.pcszName=%s, .pcszValue=%s, .pcszFlags=%s}\n",
1724 hrc, pCBData->pcszName, pCBData->pcszValue, pCBData->pcszFlags));
1725 rc = Global::vboxStatusCodeFromCOM(hrc);
1726 }
1727 return rc;
1728}
1729
1730HRESULT Console::doEnumerateGuestProperties(CBSTR aPatterns,
1731 ComSafeArrayOut(BSTR, aNames),
1732 ComSafeArrayOut(BSTR, aValues),
1733 ComSafeArrayOut(LONG64, aTimestamps),
1734 ComSafeArrayOut(BSTR, aFlags))
1735{
1736 AssertReturn(m_pVMMDev, E_FAIL);
1737
1738 using namespace guestProp;
1739
1740 VBOXHGCMSVCPARM parm[3];
1741
1742 Utf8Str utf8Patterns(aPatterns);
1743 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
1744 parm[0].u.pointer.addr = (void*)utf8Patterns.c_str();
1745 parm[0].u.pointer.size = (uint32_t)utf8Patterns.length() + 1;
1746
1747 /*
1748 * Now things get slightly complicated. Due to a race with the guest adding
1749 * properties, there is no good way to know how much to enlarge a buffer for
1750 * the service to enumerate into. We choose a decent starting size and loop a
1751 * few times, each time retrying with the size suggested by the service plus
1752 * one Kb.
1753 */
1754 size_t cchBuf = 4096;
1755 Utf8Str Utf8Buf;
1756 int vrc = VERR_BUFFER_OVERFLOW;
1757 for (unsigned i = 0; i < 10 && (VERR_BUFFER_OVERFLOW == vrc); ++i)
1758 {
1759 try
1760 {
1761 Utf8Buf.reserve(cchBuf + 1024);
1762 }
1763 catch(...)
1764 {
1765 return E_OUTOFMEMORY;
1766 }
1767 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
1768 parm[1].u.pointer.addr = Utf8Buf.mutableRaw();
1769 parm[1].u.pointer.size = (uint32_t)cchBuf + 1024;
1770 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", ENUM_PROPS_HOST, 3,
1771 &parm[0]);
1772 Utf8Buf.jolt();
1773 if (parm[2].type != VBOX_HGCM_SVC_PARM_32BIT)
1774 return setError(E_FAIL, tr("Internal application error"));
1775 cchBuf = parm[2].u.uint32;
1776 }
1777 if (VERR_BUFFER_OVERFLOW == vrc)
1778 return setError(E_UNEXPECTED,
1779 tr("Temporary failure due to guest activity, please retry"));
1780
1781 /*
1782 * Finally we have to unpack the data returned by the service into the safe
1783 * arrays supplied by the caller. We start by counting the number of entries.
1784 */
1785 const char *pszBuf
1786 = reinterpret_cast<const char *>(parm[1].u.pointer.addr);
1787 unsigned cEntries = 0;
1788 /* The list is terminated by a zero-length string at the end of a set
1789 * of four strings. */
1790 for (size_t i = 0; strlen(pszBuf + i) != 0; )
1791 {
1792 /* We are counting sets of four strings. */
1793 for (unsigned j = 0; j < 4; ++j)
1794 i += strlen(pszBuf + i) + 1;
1795 ++cEntries;
1796 }
1797
1798 /*
1799 * And now we create the COM safe arrays and fill them in.
1800 */
1801 com::SafeArray<BSTR> names(cEntries);
1802 com::SafeArray<BSTR> values(cEntries);
1803 com::SafeArray<LONG64> timestamps(cEntries);
1804 com::SafeArray<BSTR> flags(cEntries);
1805 size_t iBuf = 0;
1806 /* Rely on the service to have formated the data correctly. */
1807 for (unsigned i = 0; i < cEntries; ++i)
1808 {
1809 size_t cchName = strlen(pszBuf + iBuf);
1810 Bstr(pszBuf + iBuf).detachTo(&names[i]);
1811 iBuf += cchName + 1;
1812 size_t cchValue = strlen(pszBuf + iBuf);
1813 Bstr(pszBuf + iBuf).detachTo(&values[i]);
1814 iBuf += cchValue + 1;
1815 size_t cchTimestamp = strlen(pszBuf + iBuf);
1816 timestamps[i] = RTStrToUInt64(pszBuf + iBuf);
1817 iBuf += cchTimestamp + 1;
1818 size_t cchFlags = strlen(pszBuf + iBuf);
1819 Bstr(pszBuf + iBuf).detachTo(&flags[i]);
1820 iBuf += cchFlags + 1;
1821 }
1822 names.detachTo(ComSafeArrayOutArg(aNames));
1823 values.detachTo(ComSafeArrayOutArg(aValues));
1824 timestamps.detachTo(ComSafeArrayOutArg(aTimestamps));
1825 flags.detachTo(ComSafeArrayOutArg(aFlags));
1826 return S_OK;
1827}
1828
1829#endif /* VBOX_WITH_GUEST_PROPS */
1830
1831
1832// IConsole properties
1833/////////////////////////////////////////////////////////////////////////////
1834
1835STDMETHODIMP Console::COMGETTER(Machine)(IMachine **aMachine)
1836{
1837 CheckComArgOutPointerValid(aMachine);
1838
1839 AutoCaller autoCaller(this);
1840 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1841
1842 /* mMachine is constant during life time, no need to lock */
1843 mMachine.queryInterfaceTo(aMachine);
1844
1845 /* callers expect to get a valid reference, better fail than crash them */
1846 if (mMachine.isNull())
1847 return E_FAIL;
1848
1849 return S_OK;
1850}
1851
1852STDMETHODIMP Console::COMGETTER(State)(MachineState_T *aMachineState)
1853{
1854 CheckComArgOutPointerValid(aMachineState);
1855
1856 AutoCaller autoCaller(this);
1857 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1858
1859 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1860
1861 /* we return our local state (since it's always the same as on the server) */
1862 *aMachineState = mMachineState;
1863
1864 return S_OK;
1865}
1866
1867STDMETHODIMP Console::COMGETTER(Guest)(IGuest **aGuest)
1868{
1869 CheckComArgOutPointerValid(aGuest);
1870
1871 AutoCaller autoCaller(this);
1872 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1873
1874 /* mGuest is constant during life time, no need to lock */
1875 mGuest.queryInterfaceTo(aGuest);
1876
1877 return S_OK;
1878}
1879
1880STDMETHODIMP Console::COMGETTER(Keyboard)(IKeyboard **aKeyboard)
1881{
1882 CheckComArgOutPointerValid(aKeyboard);
1883
1884 AutoCaller autoCaller(this);
1885 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1886
1887 /* mKeyboard is constant during life time, no need to lock */
1888 mKeyboard.queryInterfaceTo(aKeyboard);
1889
1890 return S_OK;
1891}
1892
1893STDMETHODIMP Console::COMGETTER(Mouse)(IMouse **aMouse)
1894{
1895 CheckComArgOutPointerValid(aMouse);
1896
1897 AutoCaller autoCaller(this);
1898 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1899
1900 /* mMouse is constant during life time, no need to lock */
1901 mMouse.queryInterfaceTo(aMouse);
1902
1903 return S_OK;
1904}
1905
1906STDMETHODIMP Console::COMGETTER(Display)(IDisplay **aDisplay)
1907{
1908 CheckComArgOutPointerValid(aDisplay);
1909
1910 AutoCaller autoCaller(this);
1911 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1912
1913 /* mDisplay is constant during life time, no need to lock */
1914 mDisplay.queryInterfaceTo(aDisplay);
1915
1916 return S_OK;
1917}
1918
1919STDMETHODIMP Console::COMGETTER(Debugger)(IMachineDebugger **aDebugger)
1920{
1921 CheckComArgOutPointerValid(aDebugger);
1922
1923 AutoCaller autoCaller(this);
1924 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1925
1926 /* we need a write lock because of the lazy mDebugger initialization*/
1927 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1928
1929 /* check if we have to create the debugger object */
1930 if (!mDebugger)
1931 {
1932 unconst(mDebugger).createObject();
1933 mDebugger->init(this);
1934 }
1935
1936 mDebugger.queryInterfaceTo(aDebugger);
1937
1938 return S_OK;
1939}
1940
1941STDMETHODIMP Console::COMGETTER(USBDevices)(ComSafeArrayOut(IUSBDevice *, aUSBDevices))
1942{
1943 CheckComArgOutSafeArrayPointerValid(aUSBDevices);
1944
1945 AutoCaller autoCaller(this);
1946 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1947
1948 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1949
1950 SafeIfaceArray<IUSBDevice> collection(mUSBDevices);
1951 collection.detachTo(ComSafeArrayOutArg(aUSBDevices));
1952
1953 return S_OK;
1954}
1955
1956STDMETHODIMP Console::COMGETTER(RemoteUSBDevices)(ComSafeArrayOut(IHostUSBDevice *, aRemoteUSBDevices))
1957{
1958 CheckComArgOutSafeArrayPointerValid(aRemoteUSBDevices);
1959
1960 AutoCaller autoCaller(this);
1961 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1962
1963 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1964
1965 SafeIfaceArray<IHostUSBDevice> collection(mRemoteUSBDevices);
1966 collection.detachTo(ComSafeArrayOutArg(aRemoteUSBDevices));
1967
1968 return S_OK;
1969}
1970
1971STDMETHODIMP Console::COMGETTER(VRDEServerInfo)(IVRDEServerInfo **aVRDEServerInfo)
1972{
1973 CheckComArgOutPointerValid(aVRDEServerInfo);
1974
1975 AutoCaller autoCaller(this);
1976 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1977
1978 /* mVRDEServerInfo is constant during life time, no need to lock */
1979 mVRDEServerInfo.queryInterfaceTo(aVRDEServerInfo);
1980
1981 return S_OK;
1982}
1983
1984STDMETHODIMP
1985Console::COMGETTER(SharedFolders)(ComSafeArrayOut(ISharedFolder *, aSharedFolders))
1986{
1987 CheckComArgOutSafeArrayPointerValid(aSharedFolders);
1988
1989 AutoCaller autoCaller(this);
1990 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1991
1992 /* loadDataFromSavedState() needs a write lock */
1993 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1994
1995 /* Read console data stored in the saved state file (if not yet done) */
1996 HRESULT rc = loadDataFromSavedState();
1997 if (FAILED(rc)) return rc;
1998
1999 SafeIfaceArray<ISharedFolder> sf(m_mapSharedFolders);
2000 sf.detachTo(ComSafeArrayOutArg(aSharedFolders));
2001
2002 return S_OK;
2003}
2004
2005
2006STDMETHODIMP Console::COMGETTER(EventSource)(IEventSource ** aEventSource)
2007{
2008 CheckComArgOutPointerValid(aEventSource);
2009
2010 AutoCaller autoCaller(this);
2011 HRESULT hrc = autoCaller.rc();
2012 if (SUCCEEDED(hrc))
2013 {
2014 // no need to lock - lifetime constant
2015 mEventSource.queryInterfaceTo(aEventSource);
2016 }
2017
2018 return hrc;
2019}
2020
2021STDMETHODIMP Console::COMGETTER(AttachedPCIDevices)(ComSafeArrayOut(IPCIDeviceAttachment *, aAttachments))
2022{
2023 CheckComArgOutSafeArrayPointerValid(aAttachments);
2024
2025 AutoCaller autoCaller(this);
2026 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2027
2028 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2029
2030 if (mBusMgr)
2031 mBusMgr->listAttachedPCIDevices(ComSafeArrayOutArg(aAttachments));
2032 else
2033 {
2034 com::SafeIfaceArray<IPCIDeviceAttachment> result((size_t)0);
2035 result.detachTo(ComSafeArrayOutArg(aAttachments));
2036 }
2037
2038 return S_OK;
2039}
2040
2041STDMETHODIMP Console::COMGETTER(UseHostClipboard)(BOOL *aUseHostClipboard)
2042{
2043 CheckComArgOutPointerValid(aUseHostClipboard);
2044
2045 AutoCaller autoCaller(this);
2046 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2047
2048 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2049
2050 *aUseHostClipboard = mfUseHostClipboard;
2051
2052 return S_OK;
2053}
2054
2055STDMETHODIMP Console::COMSETTER(UseHostClipboard)(BOOL aUseHostClipboard)
2056{
2057 AutoCaller autoCaller(this);
2058 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2059
2060 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2061
2062 mfUseHostClipboard = !!aUseHostClipboard;
2063
2064 return S_OK;
2065}
2066
2067// IConsole methods
2068/////////////////////////////////////////////////////////////////////////////
2069
2070
2071STDMETHODIMP Console::PowerUp(IProgress **aProgress)
2072{
2073 return powerUp(aProgress, false /* aPaused */);
2074}
2075
2076STDMETHODIMP Console::PowerUpPaused(IProgress **aProgress)
2077{
2078 return powerUp(aProgress, true /* aPaused */);
2079}
2080
2081STDMETHODIMP Console::PowerDown(IProgress **aProgress)
2082{
2083 LogFlowThisFuncEnter();
2084
2085 CheckComArgOutPointerValid(aProgress);
2086
2087 AutoCaller autoCaller(this);
2088 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2089
2090 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2091
2092 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
2093 switch (mMachineState)
2094 {
2095 case MachineState_Running:
2096 case MachineState_Paused:
2097 case MachineState_Stuck:
2098 break;
2099
2100 /* Try cancel the teleportation. */
2101 case MachineState_Teleporting:
2102 case MachineState_TeleportingPausedVM:
2103 if (!mptrCancelableProgress.isNull())
2104 {
2105 HRESULT hrc = mptrCancelableProgress->Cancel();
2106 if (SUCCEEDED(hrc))
2107 break;
2108 }
2109 return setError(VBOX_E_INVALID_VM_STATE, tr("Cannot power down at this point in a teleportation"));
2110
2111 /* Try cancel the live snapshot. */
2112 case MachineState_LiveSnapshotting:
2113 if (!mptrCancelableProgress.isNull())
2114 {
2115 HRESULT hrc = mptrCancelableProgress->Cancel();
2116 if (SUCCEEDED(hrc))
2117 break;
2118 }
2119 return setError(VBOX_E_INVALID_VM_STATE, tr("Cannot power down at this point in a live snapshot"));
2120
2121 /* Try cancel the FT sync. */
2122 case MachineState_FaultTolerantSyncing:
2123 if (!mptrCancelableProgress.isNull())
2124 {
2125 HRESULT hrc = mptrCancelableProgress->Cancel();
2126 if (SUCCEEDED(hrc))
2127 break;
2128 }
2129 return setError(VBOX_E_INVALID_VM_STATE, tr("Cannot power down at this point in a fault tolerant sync"));
2130
2131 /* extra nice error message for a common case */
2132 case MachineState_Saved:
2133 return setError(VBOX_E_INVALID_VM_STATE, tr("Cannot power down a saved virtual machine"));
2134 case MachineState_Stopping:
2135 return setError(VBOX_E_INVALID_VM_STATE, tr("The virtual machine is being powered down"));
2136 default:
2137 return setError(VBOX_E_INVALID_VM_STATE,
2138 tr("Invalid machine state: %s (must be Running, Paused or Stuck)"),
2139 Global::stringifyMachineState(mMachineState));
2140 }
2141
2142 LogFlowThisFunc(("Initiating SHUTDOWN request...\n"));
2143
2144 /* memorize the current machine state */
2145 MachineState_T lastMachineState = mMachineState;
2146
2147 HRESULT rc = S_OK;
2148 bool fBeganPowerDown = false;
2149
2150 do
2151 {
2152 ComPtr<IProgress> pProgress;
2153
2154 /*
2155 * request a progress object from the server
2156 * (this will set the machine state to Stopping on the server to block
2157 * others from accessing this machine)
2158 */
2159 rc = mControl->BeginPoweringDown(pProgress.asOutParam());
2160 if (FAILED(rc))
2161 break;
2162
2163 fBeganPowerDown = true;
2164
2165 /* sync the state with the server */
2166 setMachineStateLocally(MachineState_Stopping);
2167
2168 /* setup task object and thread to carry out the operation asynchronously */
2169 std::auto_ptr<VMPowerDownTask> task(new VMPowerDownTask(this, pProgress));
2170 AssertBreakStmt(task->isOk(), rc = E_FAIL);
2171
2172 int vrc = RTThreadCreate(NULL, Console::powerDownThread,
2173 (void *) task.get(), 0,
2174 RTTHREADTYPE_MAIN_WORKER, 0,
2175 "VMPwrDwn");
2176 if (RT_FAILURE(vrc))
2177 {
2178 rc = setError(E_FAIL, "Could not create VMPowerDown thread (%Rrc)", vrc);
2179 break;
2180 }
2181
2182 /* task is now owned by powerDownThread(), so release it */
2183 task.release();
2184
2185 /* pass the progress to the caller */
2186 pProgress.queryInterfaceTo(aProgress);
2187 }
2188 while (0);
2189
2190 if (FAILED(rc))
2191 {
2192 /* preserve existing error info */
2193 ErrorInfoKeeper eik;
2194
2195 if (fBeganPowerDown)
2196 {
2197 /*
2198 * cancel the requested power down procedure.
2199 * This will reset the machine state to the state it had right
2200 * before calling mControl->BeginPoweringDown().
2201 */
2202 mControl->EndPoweringDown(eik.getResultCode(), eik.getText().raw()); }
2203
2204 setMachineStateLocally(lastMachineState);
2205 }
2206
2207 LogFlowThisFunc(("rc=%Rhrc\n", rc));
2208 LogFlowThisFuncLeave();
2209
2210 return rc;
2211}
2212
2213STDMETHODIMP Console::Reset()
2214{
2215 LogFlowThisFuncEnter();
2216
2217 AutoCaller autoCaller(this);
2218 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2219
2220 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2221
2222 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
2223 if ( mMachineState != MachineState_Running
2224 && mMachineState != MachineState_Teleporting
2225 && mMachineState != MachineState_LiveSnapshotting
2226 /** @todo r=bird: This should be allowed on paused VMs as well. Later. */
2227 )
2228 return setInvalidMachineStateError();
2229
2230 /* protect mpUVM */
2231 SafeVMPtr ptrVM(this);
2232 if (!ptrVM.isOk())
2233 return ptrVM.rc();
2234
2235 /* release the lock before a VMR3* call (EMT will call us back)! */
2236 alock.release();
2237
2238 int vrc = VMR3Reset(ptrVM.rawUVM());
2239
2240 HRESULT rc = RT_SUCCESS(vrc) ? S_OK :
2241 setError(VBOX_E_VM_ERROR,
2242 tr("Could not reset the machine (%Rrc)"),
2243 vrc);
2244
2245 LogFlowThisFunc(("mMachineState=%d, rc=%Rhrc\n", mMachineState, rc));
2246 LogFlowThisFuncLeave();
2247 return rc;
2248}
2249
2250/*static*/ DECLCALLBACK(int) Console::unplugCpu(Console *pThis, PUVM pUVM, VMCPUID idCpu)
2251{
2252 LogFlowFunc(("pThis=%p pVM=%p idCpu=%u\n", pThis, pUVM, idCpu));
2253
2254 AssertReturn(pThis, VERR_INVALID_PARAMETER);
2255
2256 int vrc = PDMR3DeviceDetach(pUVM, "acpi", 0, idCpu, 0);
2257 Log(("UnplugCpu: rc=%Rrc\n", vrc));
2258
2259 return vrc;
2260}
2261
2262HRESULT Console::doCPURemove(ULONG aCpu, PUVM pUVM)
2263{
2264 HRESULT rc = S_OK;
2265
2266 LogFlowThisFuncEnter();
2267
2268 AutoCaller autoCaller(this);
2269 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2270
2271 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2272
2273 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
2274 AssertReturn(m_pVMMDev, E_FAIL);
2275 PPDMIVMMDEVPORT pVmmDevPort = m_pVMMDev->getVMMDevPort();
2276 AssertReturn(pVmmDevPort, E_FAIL);
2277
2278 if ( mMachineState != MachineState_Running
2279 && mMachineState != MachineState_Teleporting
2280 && mMachineState != MachineState_LiveSnapshotting
2281 )
2282 return setInvalidMachineStateError();
2283
2284 /* Check if the CPU is present */
2285 BOOL fCpuAttached;
2286 rc = mMachine->GetCPUStatus(aCpu, &fCpuAttached);
2287 if (FAILED(rc))
2288 return rc;
2289 if (!fCpuAttached)
2290 return setError(E_FAIL, tr("CPU %d is not attached"), aCpu);
2291
2292 /* Leave the lock before any EMT/VMMDev call. */
2293 alock.release();
2294 bool fLocked = true;
2295
2296 /* Check if the CPU is unlocked */
2297 PPDMIBASE pBase;
2298 int vrc = PDMR3QueryDeviceLun(pUVM, "acpi", 0, aCpu, &pBase);
2299 if (RT_SUCCESS(vrc))
2300 {
2301 Assert(pBase);
2302 PPDMIACPIPORT pApicPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIACPIPORT);
2303
2304 /* Notify the guest if possible. */
2305 uint32_t idCpuCore, idCpuPackage;
2306 vrc = VMR3GetCpuCoreAndPackageIdFromCpuId(pUVM, aCpu, &idCpuCore, &idCpuPackage); AssertRC(vrc);
2307 if (RT_SUCCESS(vrc))
2308 vrc = pVmmDevPort->pfnCpuHotUnplug(pVmmDevPort, idCpuCore, idCpuPackage);
2309 if (RT_SUCCESS(vrc))
2310 {
2311 unsigned cTries = 100;
2312 do
2313 {
2314 /* It will take some time until the event is processed in the guest. Wait... */
2315 vrc = pApicPort ? pApicPort->pfnGetCpuStatus(pApicPort, aCpu, &fLocked) : VERR_INVALID_POINTER;
2316 if (RT_SUCCESS(vrc) && !fLocked)
2317 break;
2318
2319 /* Sleep a bit */
2320 RTThreadSleep(100);
2321 } while (cTries-- > 0);
2322 }
2323 else if (vrc == VERR_CPU_HOTPLUG_NOT_MONITORED_BY_GUEST)
2324 {
2325 /* Query one time. It is possible that the user ejected the CPU. */
2326 vrc = pApicPort ? pApicPort->pfnGetCpuStatus(pApicPort, aCpu, &fLocked) : VERR_INVALID_POINTER;
2327 }
2328 }
2329
2330 /* If the CPU was unlocked we can detach it now. */
2331 if (RT_SUCCESS(vrc) && !fLocked)
2332 {
2333 /*
2334 * Call worker in EMT, that's faster and safer than doing everything
2335 * using VMR3ReqCall.
2336 */
2337 PVMREQ pReq;
2338 vrc = VMR3ReqCallU(pUVM, 0, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS,
2339 (PFNRT)Console::unplugCpu, 3,
2340 this, pUVM, (VMCPUID)aCpu);
2341 if (vrc == VERR_TIMEOUT || RT_SUCCESS(vrc))
2342 {
2343 vrc = VMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
2344 AssertRC(vrc);
2345 if (RT_SUCCESS(vrc))
2346 vrc = pReq->iStatus;
2347 }
2348 VMR3ReqFree(pReq);
2349
2350 if (RT_SUCCESS(vrc))
2351 {
2352 /* Detach it from the VM */
2353 vrc = VMR3HotUnplugCpu(pUVM, aCpu);
2354 AssertRC(vrc);
2355 }
2356 else
2357 rc = setError(VBOX_E_VM_ERROR,
2358 tr("Hot-Remove failed (rc=%Rrc)"), vrc);
2359 }
2360 else
2361 rc = setError(VBOX_E_VM_ERROR,
2362 tr("Hot-Remove was aborted because the CPU may still be used by the guest"), VERR_RESOURCE_BUSY);
2363
2364 LogFlowThisFunc(("mMachineState=%d, rc=%Rhrc\n", mMachineState, rc));
2365 LogFlowThisFuncLeave();
2366 return rc;
2367}
2368
2369/*static*/ DECLCALLBACK(int) Console::plugCpu(Console *pThis, PUVM pUVM, VMCPUID idCpu)
2370{
2371 LogFlowFunc(("pThis=%p uCpu=%u\n", pThis, idCpu));
2372
2373 AssertReturn(pThis, VERR_INVALID_PARAMETER);
2374
2375 int rc = VMR3HotPlugCpu(pUVM, idCpu);
2376 AssertRC(rc);
2377
2378 PCFGMNODE pInst = CFGMR3GetChild(CFGMR3GetRootU(pUVM), "Devices/acpi/0/");
2379 AssertRelease(pInst);
2380 /* nuke anything which might have been left behind. */
2381 CFGMR3RemoveNode(CFGMR3GetChildF(pInst, "LUN#%u", idCpu));
2382
2383#define RC_CHECK() do { if (RT_FAILURE(rc)) { AssertReleaseRC(rc); break; } } while (0)
2384
2385 PCFGMNODE pLunL0;
2386 PCFGMNODE pCfg;
2387 rc = CFGMR3InsertNodeF(pInst, &pLunL0, "LUN#%u", idCpu); RC_CHECK();
2388 rc = CFGMR3InsertString(pLunL0, "Driver", "ACPICpu"); RC_CHECK();
2389 rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg); RC_CHECK();
2390
2391 /*
2392 * Attach the driver.
2393 */
2394 PPDMIBASE pBase;
2395 rc = PDMR3DeviceAttach(pUVM, "acpi", 0, idCpu, 0, &pBase); RC_CHECK();
2396
2397 Log(("PlugCpu: rc=%Rrc\n", rc));
2398
2399 CFGMR3Dump(pInst);
2400
2401#undef RC_CHECK
2402
2403 return VINF_SUCCESS;
2404}
2405
2406HRESULT Console::doCPUAdd(ULONG aCpu, PUVM pUVM)
2407{
2408 HRESULT rc = S_OK;
2409
2410 LogFlowThisFuncEnter();
2411
2412 AutoCaller autoCaller(this);
2413 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2414
2415 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2416
2417 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
2418 if ( mMachineState != MachineState_Running
2419 && mMachineState != MachineState_Teleporting
2420 && mMachineState != MachineState_LiveSnapshotting
2421 /** @todo r=bird: This should be allowed on paused VMs as well. Later. */
2422 )
2423 return setInvalidMachineStateError();
2424
2425 AssertReturn(m_pVMMDev, E_FAIL);
2426 PPDMIVMMDEVPORT pDevPort = m_pVMMDev->getVMMDevPort();
2427 AssertReturn(pDevPort, E_FAIL);
2428
2429 /* Check if the CPU is present */
2430 BOOL fCpuAttached;
2431 rc = mMachine->GetCPUStatus(aCpu, &fCpuAttached);
2432 if (FAILED(rc)) return rc;
2433
2434 if (fCpuAttached)
2435 return setError(E_FAIL,
2436 tr("CPU %d is already attached"), aCpu);
2437
2438 /*
2439 * Call worker in EMT, that's faster and safer than doing everything
2440 * using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
2441 * here to make requests from under the lock in order to serialize them.
2442 */
2443 PVMREQ pReq;
2444 int vrc = VMR3ReqCallU(pUVM, 0, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS,
2445 (PFNRT)Console::plugCpu, 3,
2446 this, pUVM, aCpu);
2447
2448 /* release the lock before a VMR3* call (EMT will call us back)! */
2449 alock.release();
2450
2451 if (vrc == VERR_TIMEOUT || RT_SUCCESS(vrc))
2452 {
2453 vrc = VMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
2454 AssertRC(vrc);
2455 if (RT_SUCCESS(vrc))
2456 vrc = pReq->iStatus;
2457 }
2458 VMR3ReqFree(pReq);
2459
2460 rc = RT_SUCCESS(vrc) ? S_OK :
2461 setError(VBOX_E_VM_ERROR,
2462 tr("Could not add CPU to the machine (%Rrc)"),
2463 vrc);
2464
2465 if (RT_SUCCESS(vrc))
2466 {
2467 /* Notify the guest if possible. */
2468 uint32_t idCpuCore, idCpuPackage;
2469 vrc = VMR3GetCpuCoreAndPackageIdFromCpuId(pUVM, aCpu, &idCpuCore, &idCpuPackage); AssertRC(vrc);
2470 if (RT_SUCCESS(vrc))
2471 vrc = pDevPort->pfnCpuHotPlug(pDevPort, idCpuCore, idCpuPackage);
2472 /** @todo warning if the guest doesn't support it */
2473 }
2474
2475 LogFlowThisFunc(("mMachineState=%d, rc=%Rhrc\n", mMachineState, rc));
2476 LogFlowThisFuncLeave();
2477 return rc;
2478}
2479
2480STDMETHODIMP Console::Pause()
2481{
2482 LogFlowThisFuncEnter();
2483
2484 HRESULT rc = pause(Reason_Unspecified);
2485
2486 LogFlowThisFunc(("rc=%Rhrc\n", rc));
2487 LogFlowThisFuncLeave();
2488 return rc;
2489}
2490
2491STDMETHODIMP Console::Resume()
2492{
2493 LogFlowThisFuncEnter();
2494
2495 HRESULT rc = resume(Reason_Unspecified);
2496
2497 LogFlowThisFunc(("rc=%Rhrc\n", rc));
2498 LogFlowThisFuncLeave();
2499 return rc;
2500}
2501
2502STDMETHODIMP Console::PowerButton()
2503{
2504 LogFlowThisFuncEnter();
2505
2506 AutoCaller autoCaller(this);
2507 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2508
2509 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2510
2511 if ( mMachineState != MachineState_Running
2512 && mMachineState != MachineState_Teleporting
2513 && mMachineState != MachineState_LiveSnapshotting
2514 )
2515 return setInvalidMachineStateError();
2516
2517 /* get the VM handle. */
2518 SafeVMPtr ptrVM(this);
2519 if (!ptrVM.isOk())
2520 return ptrVM.rc();
2521
2522 // no need to release lock, as there are no cross-thread callbacks
2523
2524 /* get the acpi device interface and press the button. */
2525 PPDMIBASE pBase;
2526 int vrc = PDMR3QueryDeviceLun(ptrVM.rawUVM(), "acpi", 0, 0, &pBase);
2527 if (RT_SUCCESS(vrc))
2528 {
2529 Assert(pBase);
2530 PPDMIACPIPORT pPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIACPIPORT);
2531 if (pPort)
2532 vrc = pPort->pfnPowerButtonPress(pPort);
2533 else
2534 vrc = VERR_PDM_MISSING_INTERFACE;
2535 }
2536
2537 HRESULT rc = RT_SUCCESS(vrc) ? S_OK :
2538 setError(VBOX_E_PDM_ERROR,
2539 tr("Controlled power off failed (%Rrc)"),
2540 vrc);
2541
2542 LogFlowThisFunc(("rc=%Rhrc\n", rc));
2543 LogFlowThisFuncLeave();
2544 return rc;
2545}
2546
2547STDMETHODIMP Console::GetPowerButtonHandled(BOOL *aHandled)
2548{
2549 LogFlowThisFuncEnter();
2550
2551 CheckComArgOutPointerValid(aHandled);
2552
2553 *aHandled = FALSE;
2554
2555 AutoCaller autoCaller(this);
2556
2557 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2558
2559 if ( mMachineState != MachineState_Running
2560 && mMachineState != MachineState_Teleporting
2561 && mMachineState != MachineState_LiveSnapshotting
2562 )
2563 return setInvalidMachineStateError();
2564
2565 /* get the VM handle. */
2566 SafeVMPtr ptrVM(this);
2567 if (!ptrVM.isOk())
2568 return ptrVM.rc();
2569
2570 // no need to release lock, as there are no cross-thread callbacks
2571
2572 /* get the acpi device interface and check if the button press was handled. */
2573 PPDMIBASE pBase;
2574 int vrc = PDMR3QueryDeviceLun(ptrVM.rawUVM(), "acpi", 0, 0, &pBase);
2575 if (RT_SUCCESS(vrc))
2576 {
2577 Assert(pBase);
2578 PPDMIACPIPORT pPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIACPIPORT);
2579 if (pPort)
2580 {
2581 bool fHandled = false;
2582 vrc = pPort->pfnGetPowerButtonHandled(pPort, &fHandled);
2583 if (RT_SUCCESS(vrc))
2584 *aHandled = fHandled;
2585 }
2586 else
2587 vrc = VERR_PDM_MISSING_INTERFACE;
2588 }
2589
2590 HRESULT rc = RT_SUCCESS(vrc) ? S_OK :
2591 setError(VBOX_E_PDM_ERROR,
2592 tr("Checking if the ACPI Power Button event was handled by the guest OS failed (%Rrc)"),
2593 vrc);
2594
2595 LogFlowThisFunc(("rc=%Rhrc\n", rc));
2596 LogFlowThisFuncLeave();
2597 return rc;
2598}
2599
2600STDMETHODIMP Console::GetGuestEnteredACPIMode(BOOL *aEntered)
2601{
2602 LogFlowThisFuncEnter();
2603
2604 CheckComArgOutPointerValid(aEntered);
2605
2606 *aEntered = FALSE;
2607
2608 AutoCaller autoCaller(this);
2609
2610 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2611
2612 if ( mMachineState != MachineState_Running
2613 && mMachineState != MachineState_Teleporting
2614 && mMachineState != MachineState_LiveSnapshotting
2615 )
2616 return setError(VBOX_E_INVALID_VM_STATE,
2617 tr("Invalid machine state %s when checking if the guest entered the ACPI mode)"),
2618 Global::stringifyMachineState(mMachineState));
2619
2620 /* get the VM handle. */
2621 SafeVMPtr ptrVM(this);
2622 if (!ptrVM.isOk())
2623 return ptrVM.rc();
2624
2625 // no need to release lock, as there are no cross-thread callbacks
2626
2627 /* get the acpi device interface and query the information. */
2628 PPDMIBASE pBase;
2629 int vrc = PDMR3QueryDeviceLun(ptrVM.rawUVM(), "acpi", 0, 0, &pBase);
2630 if (RT_SUCCESS(vrc))
2631 {
2632 Assert(pBase);
2633 PPDMIACPIPORT pPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIACPIPORT);
2634 if (pPort)
2635 {
2636 bool fEntered = false;
2637 vrc = pPort->pfnGetGuestEnteredACPIMode(pPort, &fEntered);
2638 if (RT_SUCCESS(vrc))
2639 *aEntered = fEntered;
2640 }
2641 else
2642 vrc = VERR_PDM_MISSING_INTERFACE;
2643 }
2644
2645 LogFlowThisFuncLeave();
2646 return S_OK;
2647}
2648
2649STDMETHODIMP Console::SleepButton()
2650{
2651 LogFlowThisFuncEnter();
2652
2653 AutoCaller autoCaller(this);
2654 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2655
2656 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2657
2658 if ( mMachineState != MachineState_Running
2659 && mMachineState != MachineState_Teleporting
2660 && mMachineState != MachineState_LiveSnapshotting)
2661 return setInvalidMachineStateError();
2662
2663 /* get the VM handle. */
2664 SafeVMPtr ptrVM(this);
2665 if (!ptrVM.isOk())
2666 return ptrVM.rc();
2667
2668 // no need to release lock, as there are no cross-thread callbacks
2669
2670 /* get the acpi device interface and press the sleep button. */
2671 PPDMIBASE pBase;
2672 int vrc = PDMR3QueryDeviceLun(ptrVM.rawUVM(), "acpi", 0, 0, &pBase);
2673 if (RT_SUCCESS(vrc))
2674 {
2675 Assert(pBase);
2676 PPDMIACPIPORT pPort = PDMIBASE_QUERY_INTERFACE(pBase, PDMIACPIPORT);
2677 if (pPort)
2678 vrc = pPort->pfnSleepButtonPress(pPort);
2679 else
2680 vrc = VERR_PDM_MISSING_INTERFACE;
2681 }
2682
2683 HRESULT rc = RT_SUCCESS(vrc) ? S_OK :
2684 setError(VBOX_E_PDM_ERROR,
2685 tr("Sending sleep button event failed (%Rrc)"),
2686 vrc);
2687
2688 LogFlowThisFunc(("rc=%Rhrc\n", rc));
2689 LogFlowThisFuncLeave();
2690 return rc;
2691}
2692
2693STDMETHODIMP Console::SaveState(IProgress **aProgress)
2694{
2695 LogFlowThisFuncEnter();
2696
2697 HRESULT rc = saveState(Reason_Unspecified, aProgress);
2698
2699 LogFlowThisFunc(("rc=%Rhrc\n", rc));
2700 LogFlowThisFuncLeave();
2701 return rc;
2702}
2703
2704STDMETHODIMP Console::AdoptSavedState(IN_BSTR aSavedStateFile)
2705{
2706 CheckComArgStrNotEmptyOrNull(aSavedStateFile);
2707
2708 AutoCaller autoCaller(this);
2709 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2710
2711 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2712
2713 if ( mMachineState != MachineState_PoweredOff
2714 && mMachineState != MachineState_Teleported
2715 && mMachineState != MachineState_Aborted
2716 )
2717 return setError(VBOX_E_INVALID_VM_STATE,
2718 tr("Cannot adopt the saved machine state as the machine is not in Powered Off, Teleported or Aborted state (machine state: %s)"),
2719 Global::stringifyMachineState(mMachineState));
2720
2721 return mControl->AdoptSavedState(aSavedStateFile);
2722}
2723
2724STDMETHODIMP Console::DiscardSavedState(BOOL aRemoveFile)
2725{
2726 AutoCaller autoCaller(this);
2727 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2728
2729 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2730
2731 if (mMachineState != MachineState_Saved)
2732 return setError(VBOX_E_INVALID_VM_STATE,
2733 tr("Cannot delete the machine state as the machine is not in the saved state (machine state: %s)"),
2734 Global::stringifyMachineState(mMachineState));
2735
2736 HRESULT rc = mControl->SetRemoveSavedStateFile(aRemoveFile);
2737 if (FAILED(rc)) return rc;
2738
2739 /*
2740 * Saved -> PoweredOff transition will be detected in the SessionMachine
2741 * and properly handled.
2742 */
2743 rc = setMachineState(MachineState_PoweredOff);
2744
2745 return rc;
2746}
2747
2748/** read the value of a LED. */
2749inline uint32_t readAndClearLed(PPDMLED pLed)
2750{
2751 if (!pLed)
2752 return 0;
2753 uint32_t u32 = pLed->Actual.u32 | pLed->Asserted.u32;
2754 pLed->Asserted.u32 = 0;
2755 return u32;
2756}
2757
2758STDMETHODIMP Console::GetDeviceActivity(DeviceType_T aDeviceType,
2759 DeviceActivity_T *aDeviceActivity)
2760{
2761 CheckComArgNotNull(aDeviceActivity);
2762
2763 AutoCaller autoCaller(this);
2764 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2765
2766 /*
2767 * Note: we don't lock the console object here because
2768 * readAndClearLed() should be thread safe.
2769 */
2770
2771 /* Get LED array to read */
2772 PDMLEDCORE SumLed = {0};
2773 switch (aDeviceType)
2774 {
2775 case DeviceType_Floppy:
2776 case DeviceType_DVD:
2777 case DeviceType_HardDisk:
2778 {
2779 for (unsigned i = 0; i < RT_ELEMENTS(mapStorageLeds); ++i)
2780 if (maStorageDevType[i] == aDeviceType)
2781 SumLed.u32 |= readAndClearLed(mapStorageLeds[i]);
2782 break;
2783 }
2784
2785 case DeviceType_Network:
2786 {
2787 for (unsigned i = 0; i < RT_ELEMENTS(mapNetworkLeds); ++i)
2788 SumLed.u32 |= readAndClearLed(mapNetworkLeds[i]);
2789 break;
2790 }
2791
2792 case DeviceType_USB:
2793 {
2794 for (unsigned i = 0; i < RT_ELEMENTS(mapUSBLed); ++i)
2795 SumLed.u32 |= readAndClearLed(mapUSBLed[i]);
2796 break;
2797 }
2798
2799 case DeviceType_SharedFolder:
2800 {
2801 SumLed.u32 |= readAndClearLed(mapSharedFolderLed);
2802 break;
2803 }
2804
2805 default:
2806 return setError(E_INVALIDARG,
2807 tr("Invalid device type: %d"),
2808 aDeviceType);
2809 }
2810
2811 /* Compose the result */
2812 switch (SumLed.u32 & (PDMLED_READING | PDMLED_WRITING))
2813 {
2814 case 0:
2815 *aDeviceActivity = DeviceActivity_Idle;
2816 break;
2817 case PDMLED_READING:
2818 *aDeviceActivity = DeviceActivity_Reading;
2819 break;
2820 case PDMLED_WRITING:
2821 case PDMLED_READING | PDMLED_WRITING:
2822 *aDeviceActivity = DeviceActivity_Writing;
2823 break;
2824 }
2825
2826 return S_OK;
2827}
2828
2829STDMETHODIMP Console::AttachUSBDevice(IN_BSTR aId)
2830{
2831#ifdef VBOX_WITH_USB
2832 AutoCaller autoCaller(this);
2833 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2834
2835 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2836
2837 if ( mMachineState != MachineState_Running
2838 && mMachineState != MachineState_Paused)
2839 return setError(VBOX_E_INVALID_VM_STATE,
2840 tr("Cannot attach a USB device to the machine which is not running or paused (machine state: %s)"),
2841 Global::stringifyMachineState(mMachineState));
2842
2843 /* Get the VM handle. */
2844 SafeVMPtr ptrVM(this);
2845 if (!ptrVM.isOk())
2846 return ptrVM.rc();
2847
2848 /* Don't proceed unless we've found the usb controller. */
2849 PPDMIBASE pBase = NULL;
2850 int vrc = PDMR3QueryLun(ptrVM.rawUVM(), "usb-ohci", 0, 0, &pBase);
2851 if (RT_FAILURE(vrc))
2852 return setError(VBOX_E_PDM_ERROR,
2853 tr("The virtual machine does not have a USB controller"));
2854
2855 /* release the lock because the USB Proxy service may call us back
2856 * (via onUSBDeviceAttach()) */
2857 alock.release();
2858
2859 /* Request the device capture */
2860 return mControl->CaptureUSBDevice(aId);
2861
2862#else /* !VBOX_WITH_USB */
2863 return setError(VBOX_E_PDM_ERROR,
2864 tr("The virtual machine does not have a USB controller"));
2865#endif /* !VBOX_WITH_USB */
2866}
2867
2868STDMETHODIMP Console::DetachUSBDevice(IN_BSTR aId, IUSBDevice **aDevice)
2869{
2870#ifdef VBOX_WITH_USB
2871 CheckComArgOutPointerValid(aDevice);
2872
2873 AutoCaller autoCaller(this);
2874 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2875
2876 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2877
2878 /* Find it. */
2879 ComObjPtr<OUSBDevice> pUSBDevice;
2880 USBDeviceList::iterator it = mUSBDevices.begin();
2881 Guid uuid(aId);
2882 while (it != mUSBDevices.end())
2883 {
2884 if ((*it)->id() == uuid)
2885 {
2886 pUSBDevice = *it;
2887 break;
2888 }
2889 ++it;
2890 }
2891
2892 if (!pUSBDevice)
2893 return setError(E_INVALIDARG,
2894 tr("USB device with UUID {%RTuuid} is not attached to this machine"),
2895 Guid(aId).raw());
2896
2897 /* Remove the device from the collection, it is re-added below for failures */
2898 mUSBDevices.erase(it);
2899
2900 /*
2901 * Inform the USB device and USB proxy about what's cooking.
2902 */
2903 alock.release();
2904 HRESULT rc = mControl->DetachUSBDevice(aId, false /* aDone */);
2905 if (FAILED(rc))
2906 {
2907 /* Re-add the device to the collection */
2908 alock.acquire();
2909 mUSBDevices.push_back(pUSBDevice);
2910 return rc;
2911 }
2912
2913 /* Request the PDM to detach the USB device. */
2914 rc = detachUSBDevice(pUSBDevice);
2915 if (SUCCEEDED(rc))
2916 {
2917 /* Request the device release. Even if it fails, the device will
2918 * remain as held by proxy, which is OK for us (the VM process). */
2919 rc = mControl->DetachUSBDevice(aId, true /* aDone */);
2920 }
2921 else
2922 {
2923 /* Re-add the device to the collection */
2924 alock.acquire();
2925 mUSBDevices.push_back(pUSBDevice);
2926 }
2927
2928 return rc;
2929
2930
2931#else /* !VBOX_WITH_USB */
2932 return setError(VBOX_E_PDM_ERROR,
2933 tr("The virtual machine does not have a USB controller"));
2934#endif /* !VBOX_WITH_USB */
2935}
2936
2937STDMETHODIMP Console::FindUSBDeviceByAddress(IN_BSTR aAddress, IUSBDevice **aDevice)
2938{
2939#ifdef VBOX_WITH_USB
2940 CheckComArgStrNotEmptyOrNull(aAddress);
2941 CheckComArgOutPointerValid(aDevice);
2942
2943 *aDevice = NULL;
2944
2945 SafeIfaceArray<IUSBDevice> devsvec;
2946 HRESULT rc = COMGETTER(USBDevices)(ComSafeArrayAsOutParam(devsvec));
2947 if (FAILED(rc)) return rc;
2948
2949 for (size_t i = 0; i < devsvec.size(); ++i)
2950 {
2951 Bstr address;
2952 rc = devsvec[i]->COMGETTER(Address)(address.asOutParam());
2953 if (FAILED(rc)) return rc;
2954 if (address == aAddress)
2955 {
2956 ComObjPtr<OUSBDevice> pUSBDevice;
2957 pUSBDevice.createObject();
2958 pUSBDevice->init(devsvec[i]);
2959 return pUSBDevice.queryInterfaceTo(aDevice);
2960 }
2961 }
2962
2963 return setErrorNoLog(VBOX_E_OBJECT_NOT_FOUND,
2964 tr("Could not find a USB device with address '%ls'"),
2965 aAddress);
2966
2967#else /* !VBOX_WITH_USB */
2968 return E_NOTIMPL;
2969#endif /* !VBOX_WITH_USB */
2970}
2971
2972STDMETHODIMP Console::FindUSBDeviceById(IN_BSTR aId, IUSBDevice **aDevice)
2973{
2974#ifdef VBOX_WITH_USB
2975 CheckComArgExpr(aId, Guid(aId).isValid());
2976 CheckComArgOutPointerValid(aDevice);
2977
2978 *aDevice = NULL;
2979
2980 SafeIfaceArray<IUSBDevice> devsvec;
2981 HRESULT rc = COMGETTER(USBDevices)(ComSafeArrayAsOutParam(devsvec));
2982 if (FAILED(rc)) return rc;
2983
2984 for (size_t i = 0; i < devsvec.size(); ++i)
2985 {
2986 Bstr id;
2987 rc = devsvec[i]->COMGETTER(Id)(id.asOutParam());
2988 if (FAILED(rc)) return rc;
2989 if (id == aId)
2990 {
2991 ComObjPtr<OUSBDevice> pUSBDevice;
2992 pUSBDevice.createObject();
2993 pUSBDevice->init(devsvec[i]);
2994 return pUSBDevice.queryInterfaceTo(aDevice);
2995 }
2996 }
2997
2998 return setErrorNoLog(VBOX_E_OBJECT_NOT_FOUND,
2999 tr("Could not find a USB device with uuid {%RTuuid}"),
3000 Guid(aId).raw());
3001
3002#else /* !VBOX_WITH_USB */
3003 return E_NOTIMPL;
3004#endif /* !VBOX_WITH_USB */
3005}
3006
3007STDMETHODIMP
3008Console::CreateSharedFolder(IN_BSTR aName, IN_BSTR aHostPath, BOOL aWritable, BOOL aAutoMount)
3009{
3010 CheckComArgStrNotEmptyOrNull(aName);
3011 CheckComArgStrNotEmptyOrNull(aHostPath);
3012
3013 LogFlowThisFunc(("Entering for '%ls' -> '%ls'\n", aName, aHostPath));
3014
3015 AutoCaller autoCaller(this);
3016 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3017
3018 Utf8Str strName(aName);
3019 Utf8Str strHostPath(aHostPath);
3020
3021 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3022
3023 /// @todo see @todo in AttachUSBDevice() about the Paused state
3024 if (mMachineState == MachineState_Saved)
3025 return setError(VBOX_E_INVALID_VM_STATE,
3026 tr("Cannot create a transient shared folder on the machine in the saved state"));
3027 if ( mMachineState != MachineState_PoweredOff
3028 && mMachineState != MachineState_Teleported
3029 && mMachineState != MachineState_Aborted
3030 && mMachineState != MachineState_Running
3031 && mMachineState != MachineState_Paused
3032 )
3033 return setError(VBOX_E_INVALID_VM_STATE,
3034 tr("Cannot create a transient shared folder on the machine while it is changing the state (machine state: %s)"),
3035 Global::stringifyMachineState(mMachineState));
3036
3037 ComObjPtr<SharedFolder> pSharedFolder;
3038 HRESULT rc = findSharedFolder(strName, pSharedFolder, false /* aSetError */);
3039 if (SUCCEEDED(rc))
3040 return setError(VBOX_E_FILE_ERROR,
3041 tr("Shared folder named '%s' already exists"),
3042 strName.c_str());
3043
3044 pSharedFolder.createObject();
3045 rc = pSharedFolder->init(this,
3046 strName,
3047 strHostPath,
3048 !!aWritable,
3049 !!aAutoMount,
3050 true /* fFailOnError */);
3051 if (FAILED(rc)) return rc;
3052
3053 /* If the VM is online and supports shared folders, share this folder
3054 * under the specified name. (Ignore any failure to obtain the VM handle.) */
3055 SafeVMPtrQuiet ptrVM(this);
3056 if ( ptrVM.isOk()
3057 && m_pVMMDev
3058 && m_pVMMDev->isShFlActive()
3059 )
3060 {
3061 /* first, remove the machine or the global folder if there is any */
3062 SharedFolderDataMap::const_iterator it;
3063 if (findOtherSharedFolder(aName, it))
3064 {
3065 rc = removeSharedFolder(aName);
3066 if (FAILED(rc))
3067 return rc;
3068 }
3069
3070 /* second, create the given folder */
3071 rc = createSharedFolder(aName, SharedFolderData(aHostPath, !!aWritable, !!aAutoMount));
3072 if (FAILED(rc))
3073 return rc;
3074 }
3075
3076 m_mapSharedFolders.insert(std::make_pair(aName, pSharedFolder));
3077
3078 /* Notify console callbacks after the folder is added to the list. */
3079 alock.release();
3080 fireSharedFolderChangedEvent(mEventSource, Scope_Session);
3081
3082 LogFlowThisFunc(("Leaving for '%ls' -> '%ls'\n", aName, aHostPath));
3083
3084 return rc;
3085}
3086
3087STDMETHODIMP Console::RemoveSharedFolder(IN_BSTR aName)
3088{
3089 CheckComArgStrNotEmptyOrNull(aName);
3090
3091 AutoCaller autoCaller(this);
3092 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3093
3094 LogFlowThisFunc(("Entering for '%ls'\n", aName));
3095
3096 Utf8Str strName(aName);
3097
3098 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3099
3100 /// @todo see @todo in AttachUSBDevice() about the Paused state
3101 if (mMachineState == MachineState_Saved)
3102 return setError(VBOX_E_INVALID_VM_STATE,
3103 tr("Cannot remove a transient shared folder from the machine in the saved state"));
3104 if ( mMachineState != MachineState_PoweredOff
3105 && mMachineState != MachineState_Teleported
3106 && mMachineState != MachineState_Aborted
3107 && mMachineState != MachineState_Running
3108 && mMachineState != MachineState_Paused
3109 )
3110 return setError(VBOX_E_INVALID_VM_STATE,
3111 tr("Cannot remove a transient shared folder from the machine while it is changing the state (machine state: %s)"),
3112 Global::stringifyMachineState(mMachineState));
3113
3114 ComObjPtr<SharedFolder> pSharedFolder;
3115 HRESULT rc = findSharedFolder(aName, pSharedFolder, true /* aSetError */);
3116 if (FAILED(rc)) return rc;
3117
3118 /* protect the VM handle (if not NULL) */
3119 SafeVMPtrQuiet ptrVM(this);
3120 if ( ptrVM.isOk()
3121 && m_pVMMDev
3122 && m_pVMMDev->isShFlActive()
3123 )
3124 {
3125 /* if the VM is online and supports shared folders, UNshare this
3126 * folder. */
3127
3128 /* first, remove the given folder */
3129 rc = removeSharedFolder(strName);
3130 if (FAILED(rc)) return rc;
3131
3132 /* first, remove the machine or the global folder if there is any */
3133 SharedFolderDataMap::const_iterator it;
3134 if (findOtherSharedFolder(strName, it))
3135 {
3136 rc = createSharedFolder(strName, it->second);
3137 /* don't check rc here because we need to remove the console
3138 * folder from the collection even on failure */
3139 }
3140 }
3141
3142 m_mapSharedFolders.erase(strName);
3143
3144 /* Notify console callbacks after the folder is removed from the list. */
3145 alock.release();
3146 fireSharedFolderChangedEvent(mEventSource, Scope_Session);
3147
3148 LogFlowThisFunc(("Leaving for '%ls'\n", aName));
3149
3150 return rc;
3151}
3152
3153STDMETHODIMP Console::TakeSnapshot(IN_BSTR aName,
3154 IN_BSTR aDescription,
3155 IProgress **aProgress)
3156{
3157 LogFlowThisFuncEnter();
3158
3159 CheckComArgStrNotEmptyOrNull(aName);
3160 CheckComArgOutPointerValid(aProgress);
3161
3162 AutoCaller autoCaller(this);
3163 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3164
3165 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3166 LogFlowThisFunc(("aName='%ls' mMachineState=%d\n", aName, mMachineState));
3167
3168 if (Global::IsTransient(mMachineState))
3169 return setError(VBOX_E_INVALID_VM_STATE,
3170 tr("Cannot take a snapshot of the machine while it is changing the state (machine state: %s)"),
3171 Global::stringifyMachineState(mMachineState));
3172
3173 HRESULT rc = S_OK;
3174
3175 /* prepare the progress object:
3176 a) count the no. of hard disk attachments to get a matching no. of progress sub-operations */
3177 ULONG cOperations = 2; // always at least setting up + finishing up
3178 ULONG ulTotalOperationsWeight = 2; // one each for setting up + finishing up
3179 SafeIfaceArray<IMediumAttachment> aMediumAttachments;
3180 rc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(aMediumAttachments));
3181 if (FAILED(rc))
3182 return setError(rc, tr("Cannot get medium attachments of the machine"));
3183
3184 ULONG ulMemSize;
3185 rc = mMachine->COMGETTER(MemorySize)(&ulMemSize);
3186 if (FAILED(rc))
3187 return rc;
3188
3189 for (size_t i = 0;
3190 i < aMediumAttachments.size();
3191 ++i)
3192 {
3193 DeviceType_T type;
3194 rc = aMediumAttachments[i]->COMGETTER(Type)(&type);
3195 if (FAILED(rc))
3196 return rc;
3197
3198 if (type == DeviceType_HardDisk)
3199 {
3200 ++cOperations;
3201
3202 // assume that creating a diff image takes as long as saving a 1MB state
3203 // (note, the same value must be used in SessionMachine::BeginTakingSnapshot() on the server!)
3204 ulTotalOperationsWeight += 1;
3205 }
3206 }
3207
3208 // b) one extra sub-operations for online snapshots OR offline snapshots that have a saved state (needs to be copied)
3209 bool const fTakingSnapshotOnline = Global::IsOnline(mMachineState);
3210
3211 LogFlowFunc(("fTakingSnapshotOnline = %d, mMachineState = %d\n", fTakingSnapshotOnline, mMachineState));
3212
3213 if (fTakingSnapshotOnline)
3214 {
3215 ++cOperations;
3216 ulTotalOperationsWeight += ulMemSize;
3217 }
3218
3219 // finally, create the progress object
3220 ComObjPtr<Progress> pProgress;
3221 pProgress.createObject();
3222 rc = pProgress->init(static_cast<IConsole *>(this),
3223 Bstr(tr("Taking a snapshot of the virtual machine")).raw(),
3224 (mMachineState >= MachineState_FirstOnline)
3225 && (mMachineState <= MachineState_LastOnline) /* aCancelable */,
3226 cOperations,
3227 ulTotalOperationsWeight,
3228 Bstr(tr("Setting up snapshot operation")).raw(), // first sub-op description
3229 1); // ulFirstOperationWeight
3230
3231 if (FAILED(rc))
3232 return rc;
3233
3234 VMTakeSnapshotTask *pTask;
3235 if (!(pTask = new VMTakeSnapshotTask(this, pProgress, aName, aDescription)))
3236 return E_OUTOFMEMORY;
3237
3238 Assert(pTask->mProgress);
3239
3240 try
3241 {
3242 mptrCancelableProgress = pProgress;
3243
3244 /*
3245 * If we fail here it means a PowerDown() call happened on another
3246 * thread while we were doing Pause() (which releases the Console lock).
3247 * We assign PowerDown() a higher precedence than TakeSnapshot(),
3248 * therefore just return the error to the caller.
3249 */
3250 rc = pTask->rc();
3251 if (FAILED(rc)) throw rc;
3252
3253 pTask->ulMemSize = ulMemSize;
3254
3255 /* memorize the current machine state */
3256 pTask->lastMachineState = mMachineState;
3257 pTask->fTakingSnapshotOnline = fTakingSnapshotOnline;
3258
3259 int vrc = RTThreadCreate(NULL,
3260 Console::fntTakeSnapshotWorker,
3261 (void *)pTask,
3262 0,
3263 RTTHREADTYPE_MAIN_WORKER,
3264 0,
3265 "TakeSnap");
3266 if (FAILED(vrc))
3267 throw setError(E_FAIL,
3268 tr("Could not create VMTakeSnap thread (%Rrc)"),
3269 vrc);
3270
3271 pTask->mProgress.queryInterfaceTo(aProgress);
3272 }
3273 catch (HRESULT erc)
3274 {
3275 delete pTask;
3276 rc = erc;
3277 mptrCancelableProgress.setNull();
3278 }
3279
3280 LogFlowThisFunc(("rc=%Rhrc\n", rc));
3281 LogFlowThisFuncLeave();
3282 return rc;
3283}
3284
3285STDMETHODIMP Console::DeleteSnapshot(IN_BSTR aId, IProgress **aProgress)
3286{
3287 CheckComArgExpr(aId, Guid(aId).isValid());
3288 CheckComArgOutPointerValid(aProgress);
3289
3290 AutoCaller autoCaller(this);
3291 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3292
3293 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3294
3295 if (Global::IsTransient(mMachineState))
3296 return setError(VBOX_E_INVALID_VM_STATE,
3297 tr("Cannot delete a snapshot of the machine while it is changing the state (machine state: %s)"),
3298 Global::stringifyMachineState(mMachineState));
3299
3300 MachineState_T machineState = MachineState_Null;
3301 HRESULT rc = mControl->DeleteSnapshot(this, aId, aId, FALSE /* fDeleteAllChildren */, &machineState, aProgress);
3302 if (FAILED(rc)) return rc;
3303
3304 setMachineStateLocally(machineState);
3305 return S_OK;
3306}
3307
3308STDMETHODIMP Console::DeleteSnapshotAndAllChildren(IN_BSTR aId, IProgress **aProgress)
3309{
3310 CheckComArgExpr(aId, Guid(aId).isValid());
3311 CheckComArgOutPointerValid(aProgress);
3312
3313 AutoCaller autoCaller(this);
3314 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3315
3316 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3317
3318 if (Global::IsTransient(mMachineState))
3319 return setError(VBOX_E_INVALID_VM_STATE,
3320 tr("Cannot delete a snapshot of the machine while it is changing the state (machine state: %s)"),
3321 Global::stringifyMachineState(mMachineState));
3322
3323 MachineState_T machineState = MachineState_Null;
3324 HRESULT rc = mControl->DeleteSnapshot(this, aId, aId, TRUE /* fDeleteAllChildren */, &machineState, aProgress);
3325 if (FAILED(rc)) return rc;
3326
3327 setMachineStateLocally(machineState);
3328 return S_OK;
3329}
3330
3331STDMETHODIMP Console::DeleteSnapshotRange(IN_BSTR aStartId, IN_BSTR aEndId, IProgress **aProgress)
3332{
3333 CheckComArgExpr(aStartId, Guid(aStartId).isValid());
3334 CheckComArgExpr(aEndId, Guid(aEndId).isValid());
3335 CheckComArgOutPointerValid(aProgress);
3336
3337 AutoCaller autoCaller(this);
3338 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3339
3340 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3341
3342 if (Global::IsTransient(mMachineState))
3343 return setError(VBOX_E_INVALID_VM_STATE,
3344 tr("Cannot delete a snapshot of the machine while it is changing the state (machine state: %s)"),
3345 Global::stringifyMachineState(mMachineState));
3346
3347 MachineState_T machineState = MachineState_Null;
3348 HRESULT rc = mControl->DeleteSnapshot(this, aStartId, aEndId, FALSE /* fDeleteAllChildren */, &machineState, aProgress);
3349 if (FAILED(rc)) return rc;
3350
3351 setMachineStateLocally(machineState);
3352 return S_OK;
3353}
3354
3355STDMETHODIMP Console::RestoreSnapshot(ISnapshot *aSnapshot, IProgress **aProgress)
3356{
3357 AutoCaller autoCaller(this);
3358 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3359
3360 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3361
3362 if (Global::IsOnlineOrTransient(mMachineState))
3363 return setError(VBOX_E_INVALID_VM_STATE,
3364 tr("Cannot delete the current state of the running machine (machine state: %s)"),
3365 Global::stringifyMachineState(mMachineState));
3366
3367 MachineState_T machineState = MachineState_Null;
3368 HRESULT rc = mControl->RestoreSnapshot(this, aSnapshot, &machineState, aProgress);
3369 if (FAILED(rc)) return rc;
3370
3371 setMachineStateLocally(machineState);
3372 return S_OK;
3373}
3374
3375// Non-interface public methods
3376/////////////////////////////////////////////////////////////////////////////
3377
3378/*static*/
3379HRESULT Console::setErrorStatic(HRESULT aResultCode, const char *pcsz, ...)
3380{
3381 va_list args;
3382 va_start(args, pcsz);
3383 HRESULT rc = setErrorInternal(aResultCode,
3384 getStaticClassIID(),
3385 getStaticComponentName(),
3386 Utf8Str(pcsz, args),
3387 false /* aWarning */,
3388 true /* aLogIt */);
3389 va_end(args);
3390 return rc;
3391}
3392
3393HRESULT Console::setInvalidMachineStateError()
3394{
3395 return setError(VBOX_E_INVALID_VM_STATE,
3396 tr("Invalid machine state: %s"),
3397 Global::stringifyMachineState(mMachineState));
3398}
3399
3400
3401/* static */
3402const char *Console::convertControllerTypeToDev(StorageControllerType_T enmCtrlType)
3403{
3404 switch (enmCtrlType)
3405 {
3406 case StorageControllerType_LsiLogic:
3407 return "lsilogicscsi";
3408 case StorageControllerType_BusLogic:
3409 return "buslogic";
3410 case StorageControllerType_LsiLogicSas:
3411 return "lsilogicsas";
3412 case StorageControllerType_IntelAhci:
3413 return "ahci";
3414 case StorageControllerType_PIIX3:
3415 case StorageControllerType_PIIX4:
3416 case StorageControllerType_ICH6:
3417 return "piix3ide";
3418 case StorageControllerType_I82078:
3419 return "i82078";
3420 default:
3421 return NULL;
3422 }
3423}
3424
3425HRESULT Console::convertBusPortDeviceToLun(StorageBus_T enmBus, LONG port, LONG device, unsigned &uLun)
3426{
3427 switch (enmBus)
3428 {
3429 case StorageBus_IDE:
3430 case StorageBus_Floppy:
3431 {
3432 AssertMsgReturn(port < 2 && port >= 0, ("%d\n", port), E_INVALIDARG);
3433 AssertMsgReturn(device < 2 && device >= 0, ("%d\n", device), E_INVALIDARG);
3434 uLun = 2 * port + device;
3435 return S_OK;
3436 }
3437 case StorageBus_SATA:
3438 case StorageBus_SCSI:
3439 case StorageBus_SAS:
3440 {
3441 uLun = port;
3442 return S_OK;
3443 }
3444 default:
3445 uLun = 0;
3446 AssertMsgFailedReturn(("%d\n", enmBus), E_INVALIDARG);
3447 }
3448}
3449
3450// private methods
3451/////////////////////////////////////////////////////////////////////////////
3452
3453/**
3454 * Process a medium change.
3455 *
3456 * @param aMediumAttachment The medium attachment with the new medium state.
3457 * @param fForce Force medium chance, if it is locked or not.
3458 * @param pUVM Safe VM handle.
3459 *
3460 * @note Locks this object for writing.
3461 */
3462HRESULT Console::doMediumChange(IMediumAttachment *aMediumAttachment, bool fForce, PUVM pUVM)
3463{
3464 AutoCaller autoCaller(this);
3465 AssertComRCReturnRC(autoCaller.rc());
3466
3467 /* We will need to release the write lock before calling EMT */
3468 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3469
3470 HRESULT rc = S_OK;
3471 const char *pszDevice = NULL;
3472
3473 SafeIfaceArray<IStorageController> ctrls;
3474 rc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
3475 AssertComRC(rc);
3476 IMedium *pMedium;
3477 rc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
3478 AssertComRC(rc);
3479 Bstr mediumLocation;
3480 if (pMedium)
3481 {
3482 rc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
3483 AssertComRC(rc);
3484 }
3485
3486 Bstr attCtrlName;
3487 rc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
3488 AssertComRC(rc);
3489 ComPtr<IStorageController> pStorageController;
3490 for (size_t i = 0; i < ctrls.size(); ++i)
3491 {
3492 Bstr ctrlName;
3493 rc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
3494 AssertComRC(rc);
3495 if (attCtrlName == ctrlName)
3496 {
3497 pStorageController = ctrls[i];
3498 break;
3499 }
3500 }
3501 if (pStorageController.isNull())
3502 return setError(E_FAIL,
3503 tr("Could not find storage controller '%ls'"), attCtrlName.raw());
3504
3505 StorageControllerType_T enmCtrlType;
3506 rc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
3507 AssertComRC(rc);
3508 pszDevice = convertControllerTypeToDev(enmCtrlType);
3509
3510 StorageBus_T enmBus;
3511 rc = pStorageController->COMGETTER(Bus)(&enmBus);
3512 AssertComRC(rc);
3513 ULONG uInstance;
3514 rc = pStorageController->COMGETTER(Instance)(&uInstance);
3515 AssertComRC(rc);
3516 BOOL fUseHostIOCache;
3517 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
3518 AssertComRC(rc);
3519
3520 /*
3521 * Call worker in EMT, that's faster and safer than doing everything
3522 * using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
3523 * here to make requests from under the lock in order to serialize them.
3524 */
3525 PVMREQ pReq;
3526 int vrc = VMR3ReqCallU(pUVM,
3527 VMCPUID_ANY,
3528 &pReq,
3529 0 /* no wait! */,
3530 VMREQFLAGS_VBOX_STATUS,
3531 (PFNRT)Console::changeRemovableMedium,
3532 8,
3533 this,
3534 pUVM,
3535 pszDevice,
3536 uInstance,
3537 enmBus,
3538 fUseHostIOCache,
3539 aMediumAttachment,
3540 fForce);
3541
3542 /* release the lock before waiting for a result (EMT will call us back!) */
3543 alock.release();
3544
3545 if (vrc == VERR_TIMEOUT || RT_SUCCESS(vrc))
3546 {
3547 vrc = VMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
3548 AssertRC(vrc);
3549 if (RT_SUCCESS(vrc))
3550 vrc = pReq->iStatus;
3551 }
3552 VMR3ReqFree(pReq);
3553
3554 if (RT_SUCCESS(vrc))
3555 {
3556 LogFlowThisFunc(("Returns S_OK\n"));
3557 return S_OK;
3558 }
3559
3560 if (pMedium)
3561 return setError(E_FAIL,
3562 tr("Could not mount the media/drive '%ls' (%Rrc)"),
3563 mediumLocation.raw(), vrc);
3564
3565 return setError(E_FAIL,
3566 tr("Could not unmount the currently mounted media/drive (%Rrc)"),
3567 vrc);
3568}
3569
3570/**
3571 * Performs the medium change in EMT.
3572 *
3573 * @returns VBox status code.
3574 *
3575 * @param pThis Pointer to the Console object.
3576 * @param pUVM The VM handle.
3577 * @param pcszDevice The PDM device name.
3578 * @param uInstance The PDM device instance.
3579 * @param uLun The PDM LUN number of the drive.
3580 * @param fHostDrive True if this is a host drive attachment.
3581 * @param pszPath The path to the media / drive which is now being mounted / captured.
3582 * If NULL no media or drive is attached and the LUN will be configured with
3583 * the default block driver with no media. This will also be the state if
3584 * mounting / capturing the specified media / drive fails.
3585 * @param pszFormat Medium format string, usually "RAW".
3586 * @param fPassthrough Enables using passthrough mode of the host DVD drive if applicable.
3587 *
3588 * @thread EMT
3589 */
3590DECLCALLBACK(int) Console::changeRemovableMedium(Console *pConsole,
3591 PUVM pUVM,
3592 const char *pcszDevice,
3593 unsigned uInstance,
3594 StorageBus_T enmBus,
3595 bool fUseHostIOCache,
3596 IMediumAttachment *aMediumAtt,
3597 bool fForce)
3598{
3599 LogFlowFunc(("pConsole=%p uInstance=%u pszDevice=%p:{%s} enmBus=%u, aMediumAtt=%p, fForce=%d\n",
3600 pConsole, uInstance, pcszDevice, pcszDevice, enmBus, aMediumAtt, fForce));
3601
3602 AssertReturn(pConsole, VERR_INVALID_PARAMETER);
3603
3604 AutoCaller autoCaller(pConsole);
3605 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
3606
3607 /*
3608 * Suspend the VM first.
3609 *
3610 * The VM must not be running since it might have pending I/O to
3611 * the drive which is being changed.
3612 */
3613 bool fResume;
3614 VMSTATE enmVMState = VMR3GetStateU(pUVM);
3615 switch (enmVMState)
3616 {
3617 case VMSTATE_RESETTING:
3618 case VMSTATE_RUNNING:
3619 {
3620 LogFlowFunc(("Suspending the VM...\n"));
3621 /* disable the callback to prevent Console-level state change */
3622 pConsole->mVMStateChangeCallbackDisabled = true;
3623 int rc = VMR3Suspend(pUVM, VMSUSPENDREASON_RECONFIG);
3624 pConsole->mVMStateChangeCallbackDisabled = false;
3625 AssertRCReturn(rc, rc);
3626 fResume = true;
3627 break;
3628 }
3629
3630 case VMSTATE_SUSPENDED:
3631 case VMSTATE_CREATED:
3632 case VMSTATE_OFF:
3633 fResume = false;
3634 break;
3635
3636 case VMSTATE_RUNNING_LS:
3637 case VMSTATE_RUNNING_FT:
3638 return setErrorInternal(VBOX_E_INVALID_VM_STATE,
3639 COM_IIDOF(IConsole),
3640 getStaticComponentName(),
3641 (enmVMState == VMSTATE_RUNNING_LS) ? Utf8Str(tr("Cannot change drive during live migration")) : Utf8Str(tr("Cannot change drive during fault tolerant syncing")),
3642 false /*aWarning*/,
3643 true /*aLogIt*/);
3644
3645 default:
3646 AssertMsgFailedReturn(("enmVMState=%d\n", enmVMState), VERR_ACCESS_DENIED);
3647 }
3648
3649 /* Determine the base path for the device instance. */
3650 PCFGMNODE pCtlInst;
3651 pCtlInst = CFGMR3GetChildF(CFGMR3GetRootU(pUVM), "Devices/%s/%u/", pcszDevice, uInstance);
3652 AssertReturn(pCtlInst, VERR_INTERNAL_ERROR);
3653
3654 int rc = VINF_SUCCESS;
3655 int rcRet = VINF_SUCCESS;
3656
3657 rcRet = pConsole->configMediumAttachment(pCtlInst,
3658 pcszDevice,
3659 uInstance,
3660 enmBus,
3661 fUseHostIOCache,
3662 false /* fSetupMerge */,
3663 false /* fBuiltinIOCache */,
3664 0 /* uMergeSource */,
3665 0 /* uMergeTarget */,
3666 aMediumAtt,
3667 pConsole->mMachineState,
3668 NULL /* phrc */,
3669 true /* fAttachDetach */,
3670 fForce /* fForceUnmount */,
3671 false /* fHotplug */,
3672 pUVM,
3673 NULL /* paLedDevType */);
3674 /** @todo this dumps everything attached to this device instance, which
3675 * is more than necessary. Dumping the changed LUN would be enough. */
3676 CFGMR3Dump(pCtlInst);
3677
3678 /*
3679 * Resume the VM if necessary.
3680 */
3681 if (fResume)
3682 {
3683 LogFlowFunc(("Resuming the VM...\n"));
3684 /* disable the callback to prevent Console-level state change */
3685 pConsole->mVMStateChangeCallbackDisabled = true;
3686 rc = VMR3Resume(pUVM, VMRESUMEREASON_RECONFIG);
3687 pConsole->mVMStateChangeCallbackDisabled = false;
3688 AssertRC(rc);
3689 if (RT_FAILURE(rc))
3690 {
3691 /* too bad, we failed. try to sync the console state with the VMM state */
3692 vmstateChangeCallback(pUVM, VMSTATE_SUSPENDED, enmVMState, pConsole);
3693 }
3694 /// @todo (r=dmik) if we failed with drive mount, then the VMR3Resume
3695 // error (if any) will be hidden from the caller. For proper reporting
3696 // of such multiple errors to the caller we need to enhance the
3697 // IVirtualBoxError interface. For now, give the first error the higher
3698 // priority.
3699 if (RT_SUCCESS(rcRet))
3700 rcRet = rc;
3701 }
3702
3703 LogFlowFunc(("Returning %Rrc\n", rcRet));
3704 return rcRet;
3705}
3706
3707
3708/**
3709 * Attach a new storage device to the VM.
3710 *
3711 * @param aMediumAttachment The medium attachment which is added.
3712 * @param pUVM Safe VM handle.
3713 * @param fSilent Flag whether to notify the guest about the attached device.
3714 *
3715 * @note Locks this object for writing.
3716 */
3717HRESULT Console::doStorageDeviceAttach(IMediumAttachment *aMediumAttachment, PUVM pUVM, bool fSilent)
3718{
3719 AutoCaller autoCaller(this);
3720 AssertComRCReturnRC(autoCaller.rc());
3721
3722 /* We will need to release the write lock before calling EMT */
3723 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3724
3725 HRESULT rc = S_OK;
3726 const char *pszDevice = NULL;
3727
3728 SafeIfaceArray<IStorageController> ctrls;
3729 rc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
3730 AssertComRC(rc);
3731 IMedium *pMedium;
3732 rc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
3733 AssertComRC(rc);
3734 Bstr mediumLocation;
3735 if (pMedium)
3736 {
3737 rc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
3738 AssertComRC(rc);
3739 }
3740
3741 Bstr attCtrlName;
3742 rc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
3743 AssertComRC(rc);
3744 ComPtr<IStorageController> pStorageController;
3745 for (size_t i = 0; i < ctrls.size(); ++i)
3746 {
3747 Bstr ctrlName;
3748 rc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
3749 AssertComRC(rc);
3750 if (attCtrlName == ctrlName)
3751 {
3752 pStorageController = ctrls[i];
3753 break;
3754 }
3755 }
3756 if (pStorageController.isNull())
3757 return setError(E_FAIL,
3758 tr("Could not find storage controller '%ls'"), attCtrlName.raw());
3759
3760 StorageControllerType_T enmCtrlType;
3761 rc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
3762 AssertComRC(rc);
3763 pszDevice = convertControllerTypeToDev(enmCtrlType);
3764
3765 StorageBus_T enmBus;
3766 rc = pStorageController->COMGETTER(Bus)(&enmBus);
3767 AssertComRC(rc);
3768 ULONG uInstance;
3769 rc = pStorageController->COMGETTER(Instance)(&uInstance);
3770 AssertComRC(rc);
3771 BOOL fUseHostIOCache;
3772 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
3773 AssertComRC(rc);
3774
3775 /*
3776 * Call worker in EMT, that's faster and safer than doing everything
3777 * using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
3778 * here to make requests from under the lock in order to serialize them.
3779 */
3780 PVMREQ pReq;
3781 int vrc = VMR3ReqCallU(pUVM,
3782 VMCPUID_ANY,
3783 &pReq,
3784 0 /* no wait! */,
3785 VMREQFLAGS_VBOX_STATUS,
3786 (PFNRT)Console::attachStorageDevice,
3787 8,
3788 this,
3789 pUVM,
3790 pszDevice,
3791 uInstance,
3792 enmBus,
3793 fUseHostIOCache,
3794 aMediumAttachment,
3795 fSilent);
3796
3797 /* release the lock before waiting for a result (EMT will call us back!) */
3798 alock.release();
3799
3800 if (vrc == VERR_TIMEOUT || RT_SUCCESS(vrc))
3801 {
3802 vrc = VMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
3803 AssertRC(vrc);
3804 if (RT_SUCCESS(vrc))
3805 vrc = pReq->iStatus;
3806 }
3807 VMR3ReqFree(pReq);
3808
3809 if (RT_SUCCESS(vrc))
3810 {
3811 LogFlowThisFunc(("Returns S_OK\n"));
3812 return S_OK;
3813 }
3814
3815 if (!pMedium)
3816 return setError(E_FAIL,
3817 tr("Could not mount the media/drive '%ls' (%Rrc)"),
3818 mediumLocation.raw(), vrc);
3819
3820 return setError(E_FAIL,
3821 tr("Could not unmount the currently mounted media/drive (%Rrc)"),
3822 vrc);
3823}
3824
3825
3826/**
3827 * Performs the storage attach operation in EMT.
3828 *
3829 * @returns VBox status code.
3830 *
3831 * @param pThis Pointer to the Console object.
3832 * @param pUVM The VM handle.
3833 * @param pcszDevice The PDM device name.
3834 * @param uInstance The PDM device instance.
3835 * @param fSilent Flag whether to inform the guest about the attached device.
3836 *
3837 * @thread EMT
3838 */
3839DECLCALLBACK(int) Console::attachStorageDevice(Console *pConsole,
3840 PUVM pUVM,
3841 const char *pcszDevice,
3842 unsigned uInstance,
3843 StorageBus_T enmBus,
3844 bool fUseHostIOCache,
3845 IMediumAttachment *aMediumAtt,
3846 bool fSilent)
3847{
3848 LogFlowFunc(("pConsole=%p uInstance=%u pszDevice=%p:{%s} enmBus=%u, aMediumAtt=%p\n",
3849 pConsole, uInstance, pcszDevice, pcszDevice, enmBus, aMediumAtt));
3850
3851 AssertReturn(pConsole, VERR_INVALID_PARAMETER);
3852
3853 AutoCaller autoCaller(pConsole);
3854 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
3855
3856 /*
3857 * Suspend the VM first.
3858 *
3859 * The VM must not be running since it might have pending I/O to
3860 * the drive which is being changed.
3861 */
3862 bool fResume;
3863 VMSTATE enmVMState = VMR3GetStateU(pUVM);
3864 switch (enmVMState)
3865 {
3866 case VMSTATE_RESETTING:
3867 case VMSTATE_RUNNING:
3868 {
3869 LogFlowFunc(("Suspending the VM...\n"));
3870 /* disable the callback to prevent Console-level state change */
3871 pConsole->mVMStateChangeCallbackDisabled = true;
3872 int rc = VMR3Suspend(pUVM, VMSUSPENDREASON_RECONFIG);
3873 pConsole->mVMStateChangeCallbackDisabled = false;
3874 AssertRCReturn(rc, rc);
3875 fResume = true;
3876 break;
3877 }
3878
3879 case VMSTATE_SUSPENDED:
3880 case VMSTATE_CREATED:
3881 case VMSTATE_OFF:
3882 fResume = false;
3883 break;
3884
3885 case VMSTATE_RUNNING_LS:
3886 case VMSTATE_RUNNING_FT:
3887 return setErrorInternal(VBOX_E_INVALID_VM_STATE,
3888 COM_IIDOF(IConsole),
3889 getStaticComponentName(),
3890 (enmVMState == VMSTATE_RUNNING_LS) ? Utf8Str(tr("Cannot change drive during live migration")) : Utf8Str(tr("Cannot change drive during fault tolerant syncing")),
3891 false /*aWarning*/,
3892 true /*aLogIt*/);
3893
3894 default:
3895 AssertMsgFailedReturn(("enmVMState=%d\n", enmVMState), VERR_ACCESS_DENIED);
3896 }
3897
3898 /* Determine the base path for the device instance. */
3899 PCFGMNODE pCtlInst;
3900 pCtlInst = CFGMR3GetChildF(CFGMR3GetRootU(pUVM), "Devices/%s/%u/", pcszDevice, uInstance);
3901 AssertReturn(pCtlInst, VERR_INTERNAL_ERROR);
3902
3903 int rc = VINF_SUCCESS;
3904 int rcRet = VINF_SUCCESS;
3905
3906 rcRet = pConsole->configMediumAttachment(pCtlInst,
3907 pcszDevice,
3908 uInstance,
3909 enmBus,
3910 fUseHostIOCache,
3911 false /* fSetupMerge */,
3912 false /* fBuiltinIOCache */,
3913 0 /* uMergeSource */,
3914 0 /* uMergeTarget */,
3915 aMediumAtt,
3916 pConsole->mMachineState,
3917 NULL /* phrc */,
3918 true /* fAttachDetach */,
3919 false /* fForceUnmount */,
3920 !fSilent /* fHotplug */,
3921 pUVM,
3922 NULL /* paLedDevType */);
3923 /** @todo this dumps everything attached to this device instance, which
3924 * is more than necessary. Dumping the changed LUN would be enough. */
3925 CFGMR3Dump(pCtlInst);
3926
3927 /*
3928 * Resume the VM if necessary.
3929 */
3930 if (fResume)
3931 {
3932 LogFlowFunc(("Resuming the VM...\n"));
3933 /* disable the callback to prevent Console-level state change */
3934 pConsole->mVMStateChangeCallbackDisabled = true;
3935 rc = VMR3Resume(pUVM, VMRESUMEREASON_RECONFIG);
3936 pConsole->mVMStateChangeCallbackDisabled = false;
3937 AssertRC(rc);
3938 if (RT_FAILURE(rc))
3939 {
3940 /* too bad, we failed. try to sync the console state with the VMM state */
3941 vmstateChangeCallback(pUVM, VMSTATE_SUSPENDED, enmVMState, pConsole);
3942 }
3943 /** @todo if we failed with drive mount, then the VMR3Resume
3944 * error (if any) will be hidden from the caller. For proper reporting
3945 * of such multiple errors to the caller we need to enhance the
3946 * IVirtualBoxError interface. For now, give the first error the higher
3947 * priority.
3948 */
3949 if (RT_SUCCESS(rcRet))
3950 rcRet = rc;
3951 }
3952
3953 LogFlowFunc(("Returning %Rrc\n", rcRet));
3954 return rcRet;
3955}
3956
3957/**
3958 * Attach a new storage device to the VM.
3959 *
3960 * @param aMediumAttachment The medium attachment which is added.
3961 * @param pUVM Safe VM handle.
3962 * @param fSilent Flag whether to notify the guest about the detached device.
3963 *
3964 * @note Locks this object for writing.
3965 */
3966HRESULT Console::doStorageDeviceDetach(IMediumAttachment *aMediumAttachment, PUVM pUVM, bool fSilent)
3967{
3968 AutoCaller autoCaller(this);
3969 AssertComRCReturnRC(autoCaller.rc());
3970
3971 /* We will need to release the write lock before calling EMT */
3972 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3973
3974 HRESULT rc = S_OK;
3975 const char *pszDevice = NULL;
3976
3977 SafeIfaceArray<IStorageController> ctrls;
3978 rc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
3979 AssertComRC(rc);
3980 IMedium *pMedium;
3981 rc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
3982 AssertComRC(rc);
3983 Bstr mediumLocation;
3984 if (pMedium)
3985 {
3986 rc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
3987 AssertComRC(rc);
3988 }
3989
3990 Bstr attCtrlName;
3991 rc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
3992 AssertComRC(rc);
3993 ComPtr<IStorageController> pStorageController;
3994 for (size_t i = 0; i < ctrls.size(); ++i)
3995 {
3996 Bstr ctrlName;
3997 rc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
3998 AssertComRC(rc);
3999 if (attCtrlName == ctrlName)
4000 {
4001 pStorageController = ctrls[i];
4002 break;
4003 }
4004 }
4005 if (pStorageController.isNull())
4006 return setError(E_FAIL,
4007 tr("Could not find storage controller '%ls'"), attCtrlName.raw());
4008
4009 StorageControllerType_T enmCtrlType;
4010 rc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
4011 AssertComRC(rc);
4012 pszDevice = convertControllerTypeToDev(enmCtrlType);
4013
4014 StorageBus_T enmBus;
4015 rc = pStorageController->COMGETTER(Bus)(&enmBus);
4016 AssertComRC(rc);
4017 ULONG uInstance;
4018 rc = pStorageController->COMGETTER(Instance)(&uInstance);
4019 AssertComRC(rc);
4020
4021 /*
4022 * Call worker in EMT, that's faster and safer than doing everything
4023 * using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
4024 * here to make requests from under the lock in order to serialize them.
4025 */
4026 PVMREQ pReq;
4027 int vrc = VMR3ReqCallU(pUVM,
4028 VMCPUID_ANY,
4029 &pReq,
4030 0 /* no wait! */,
4031 VMREQFLAGS_VBOX_STATUS,
4032 (PFNRT)Console::detachStorageDevice,
4033 7,
4034 this,
4035 pUVM,
4036 pszDevice,
4037 uInstance,
4038 enmBus,
4039 aMediumAttachment,
4040 fSilent);
4041
4042 /* release the lock before waiting for a result (EMT will call us back!) */
4043 alock.release();
4044
4045 if (vrc == VERR_TIMEOUT || RT_SUCCESS(vrc))
4046 {
4047 vrc = VMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
4048 AssertRC(vrc);
4049 if (RT_SUCCESS(vrc))
4050 vrc = pReq->iStatus;
4051 }
4052 VMR3ReqFree(pReq);
4053
4054 if (RT_SUCCESS(vrc))
4055 {
4056 LogFlowThisFunc(("Returns S_OK\n"));
4057 return S_OK;
4058 }
4059
4060 if (!pMedium)
4061 return setError(E_FAIL,
4062 tr("Could not mount the media/drive '%ls' (%Rrc)"),
4063 mediumLocation.raw(), vrc);
4064
4065 return setError(E_FAIL,
4066 tr("Could not unmount the currently mounted media/drive (%Rrc)"),
4067 vrc);
4068}
4069
4070/**
4071 * Performs the storage detach operation in EMT.
4072 *
4073 * @returns VBox status code.
4074 *
4075 * @param pThis Pointer to the Console object.
4076 * @param pUVM The VM handle.
4077 * @param pcszDevice The PDM device name.
4078 * @param uInstance The PDM device instance.
4079 * @param fSilent Flag whether to notify the guest about the detached device.
4080 *
4081 * @thread EMT
4082 */
4083DECLCALLBACK(int) Console::detachStorageDevice(Console *pConsole,
4084 PUVM pUVM,
4085 const char *pcszDevice,
4086 unsigned uInstance,
4087 StorageBus_T enmBus,
4088 IMediumAttachment *pMediumAtt,
4089 bool fSilent)
4090{
4091 LogFlowFunc(("pConsole=%p uInstance=%u pszDevice=%p:{%s} enmBus=%u, pMediumAtt=%p\n",
4092 pConsole, uInstance, pcszDevice, pcszDevice, enmBus, pMediumAtt));
4093
4094 AssertReturn(pConsole, VERR_INVALID_PARAMETER);
4095
4096 AutoCaller autoCaller(pConsole);
4097 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
4098
4099 /*
4100 * Suspend the VM first.
4101 *
4102 * The VM must not be running since it might have pending I/O to
4103 * the drive which is being changed.
4104 */
4105 bool fResume;
4106 VMSTATE enmVMState = VMR3GetStateU(pUVM);
4107 switch (enmVMState)
4108 {
4109 case VMSTATE_RESETTING:
4110 case VMSTATE_RUNNING:
4111 {
4112 LogFlowFunc(("Suspending the VM...\n"));
4113 /* disable the callback to prevent Console-level state change */
4114 pConsole->mVMStateChangeCallbackDisabled = true;
4115 int rc = VMR3Suspend(pUVM, VMSUSPENDREASON_RECONFIG);
4116 pConsole->mVMStateChangeCallbackDisabled = false;
4117 AssertRCReturn(rc, rc);
4118 fResume = true;
4119 break;
4120 }
4121
4122 case VMSTATE_SUSPENDED:
4123 case VMSTATE_CREATED:
4124 case VMSTATE_OFF:
4125 fResume = false;
4126 break;
4127
4128 case VMSTATE_RUNNING_LS:
4129 case VMSTATE_RUNNING_FT:
4130 return setErrorInternal(VBOX_E_INVALID_VM_STATE,
4131 COM_IIDOF(IConsole),
4132 getStaticComponentName(),
4133 (enmVMState == VMSTATE_RUNNING_LS) ? Utf8Str(tr("Cannot change drive during live migration")) : Utf8Str(tr("Cannot change drive during fault tolerant syncing")),
4134 false /*aWarning*/,
4135 true /*aLogIt*/);
4136
4137 default:
4138 AssertMsgFailedReturn(("enmVMState=%d\n", enmVMState), VERR_ACCESS_DENIED);
4139 }
4140
4141 /* Determine the base path for the device instance. */
4142 PCFGMNODE pCtlInst;
4143 pCtlInst = CFGMR3GetChildF(CFGMR3GetRootU(pUVM), "Devices/%s/%u/", pcszDevice, uInstance);
4144 AssertReturn(pCtlInst, VERR_INTERNAL_ERROR);
4145
4146#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
4147
4148 HRESULT hrc;
4149 int rc = VINF_SUCCESS;
4150 int rcRet = VINF_SUCCESS;
4151 unsigned uLUN;
4152 LONG lDev;
4153 LONG lPort;
4154 DeviceType_T lType;
4155 PCFGMNODE pLunL0 = NULL;
4156 PCFGMNODE pCfg = NULL;
4157
4158 hrc = pMediumAtt->COMGETTER(Device)(&lDev); H();
4159 hrc = pMediumAtt->COMGETTER(Port)(&lPort); H();
4160 hrc = pMediumAtt->COMGETTER(Type)(&lType); H();
4161 hrc = Console::convertBusPortDeviceToLun(enmBus, lPort, lDev, uLUN); H();
4162
4163#undef H
4164
4165 /* First check if the LUN really exists. */
4166 pLunL0 = CFGMR3GetChildF(pCtlInst, "LUN#%u", uLUN);
4167 if (pLunL0)
4168 {
4169 uint32_t fFlags = 0;
4170
4171 if (fSilent)
4172 fFlags |= PDM_TACH_FLAGS_NOT_HOT_PLUG;
4173
4174 rc = PDMR3DeviceDetach(pUVM, pcszDevice, uInstance, uLUN, fFlags);
4175 if (rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
4176 rc = VINF_SUCCESS;
4177 AssertRCReturn(rc, rc);
4178 CFGMR3RemoveNode(pLunL0);
4179
4180 Utf8Str devicePath = Utf8StrFmt("%s/%u/LUN#%u", pcszDevice, uInstance, uLUN);
4181 pConsole->mapMediumAttachments.erase(devicePath);
4182
4183 }
4184 else
4185 AssertFailedReturn(VERR_INTERNAL_ERROR);
4186
4187 CFGMR3Dump(pCtlInst);
4188
4189 /*
4190 * Resume the VM if necessary.
4191 */
4192 if (fResume)
4193 {
4194 LogFlowFunc(("Resuming the VM...\n"));
4195 /* disable the callback to prevent Console-level state change */
4196 pConsole->mVMStateChangeCallbackDisabled = true;
4197 rc = VMR3Resume(pUVM, VMRESUMEREASON_RECONFIG);
4198 pConsole->mVMStateChangeCallbackDisabled = false;
4199 AssertRC(rc);
4200 if (RT_FAILURE(rc))
4201 {
4202 /* too bad, we failed. try to sync the console state with the VMM state */
4203 vmstateChangeCallback(pUVM, VMSTATE_SUSPENDED, enmVMState, pConsole);
4204 }
4205 /** @todo: if we failed with drive mount, then the VMR3Resume
4206 * error (if any) will be hidden from the caller. For proper reporting
4207 * of such multiple errors to the caller we need to enhance the
4208 * IVirtualBoxError interface. For now, give the first error the higher
4209 * priority.
4210 */
4211 if (RT_SUCCESS(rcRet))
4212 rcRet = rc;
4213 }
4214
4215 LogFlowFunc(("Returning %Rrc\n", rcRet));
4216 return rcRet;
4217}
4218
4219/**
4220 * Called by IInternalSessionControl::OnNetworkAdapterChange().
4221 *
4222 * @note Locks this object for writing.
4223 */
4224HRESULT Console::onNetworkAdapterChange(INetworkAdapter *aNetworkAdapter, BOOL changeAdapter)
4225{
4226 LogFlowThisFunc(("\n"));
4227
4228 AutoCaller autoCaller(this);
4229 AssertComRCReturnRC(autoCaller.rc());
4230
4231 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4232
4233 HRESULT rc = S_OK;
4234
4235 /* don't trigger network changes if the VM isn't running */
4236 SafeVMPtrQuiet ptrVM(this);
4237 if (ptrVM.isOk())
4238 {
4239 /* Get the properties we need from the adapter */
4240 BOOL fCableConnected, fTraceEnabled;
4241 rc = aNetworkAdapter->COMGETTER(CableConnected)(&fCableConnected);
4242 AssertComRC(rc);
4243 if (SUCCEEDED(rc))
4244 {
4245 rc = aNetworkAdapter->COMGETTER(TraceEnabled)(&fTraceEnabled);
4246 AssertComRC(rc);
4247 }
4248 if (SUCCEEDED(rc))
4249 {
4250 ULONG ulInstance;
4251 rc = aNetworkAdapter->COMGETTER(Slot)(&ulInstance);
4252 AssertComRC(rc);
4253 if (SUCCEEDED(rc))
4254 {
4255 /*
4256 * Find the adapter instance, get the config interface and update
4257 * the link state.
4258 */
4259 NetworkAdapterType_T adapterType;
4260 rc = aNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
4261 AssertComRC(rc);
4262 const char *pszAdapterName = networkAdapterTypeToName(adapterType);
4263
4264 // prevent cross-thread deadlocks, don't need the lock any more
4265 alock.release();
4266
4267 PPDMIBASE pBase;
4268 int vrc = PDMR3QueryDeviceLun(ptrVM.rawUVM(), pszAdapterName, ulInstance, 0, &pBase);
4269 if (RT_SUCCESS(vrc))
4270 {
4271 Assert(pBase);
4272 PPDMINETWORKCONFIG pINetCfg;
4273 pINetCfg = PDMIBASE_QUERY_INTERFACE(pBase, PDMINETWORKCONFIG);
4274 if (pINetCfg)
4275 {
4276 Log(("Console::onNetworkAdapterChange: setting link state to %d\n",
4277 fCableConnected));
4278 vrc = pINetCfg->pfnSetLinkState(pINetCfg,
4279 fCableConnected ? PDMNETWORKLINKSTATE_UP
4280 : PDMNETWORKLINKSTATE_DOWN);
4281 ComAssertRC(vrc);
4282 }
4283 if (RT_SUCCESS(vrc) && changeAdapter)
4284 {
4285 VMSTATE enmVMState = VMR3GetStateU(ptrVM.rawUVM());
4286 if ( enmVMState == VMSTATE_RUNNING /** @todo LiveMigration: Forbid or deal correctly with the _LS variants */
4287 || enmVMState == VMSTATE_SUSPENDED)
4288 {
4289 if (fTraceEnabled && fCableConnected && pINetCfg)
4290 {
4291 vrc = pINetCfg->pfnSetLinkState(pINetCfg, PDMNETWORKLINKSTATE_DOWN);
4292 ComAssertRC(vrc);
4293 }
4294
4295 rc = doNetworkAdapterChange(ptrVM.rawUVM(), pszAdapterName, ulInstance, 0, aNetworkAdapter);
4296
4297 if (fTraceEnabled && fCableConnected && pINetCfg)
4298 {
4299 vrc = pINetCfg->pfnSetLinkState(pINetCfg, PDMNETWORKLINKSTATE_UP);
4300 ComAssertRC(vrc);
4301 }
4302 }
4303 }
4304 }
4305 else if (vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
4306 return setError(E_FAIL,
4307 tr("The network adapter #%u is not enabled"), ulInstance);
4308 else
4309 ComAssertRC(vrc);
4310
4311 if (RT_FAILURE(vrc))
4312 rc = E_FAIL;
4313
4314 alock.acquire();
4315 }
4316 }
4317 ptrVM.release();
4318 }
4319
4320 // definitely don't need the lock any more
4321 alock.release();
4322
4323 /* notify console callbacks on success */
4324 if (SUCCEEDED(rc))
4325 fireNetworkAdapterChangedEvent(mEventSource, aNetworkAdapter);
4326
4327 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4328 return rc;
4329}
4330
4331/**
4332 * Called by IInternalSessionControl::OnNATEngineChange().
4333 *
4334 * @note Locks this object for writing.
4335 */
4336HRESULT Console::onNATRedirectRuleChange(ULONG ulInstance, BOOL aNatRuleRemove,
4337 NATProtocol_T aProto, IN_BSTR aHostIP, LONG aHostPort, IN_BSTR aGuestIP, LONG aGuestPort)
4338{
4339 LogFlowThisFunc(("\n"));
4340
4341 AutoCaller autoCaller(this);
4342 AssertComRCReturnRC(autoCaller.rc());
4343
4344 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4345
4346 HRESULT rc = S_OK;
4347
4348 /* don't trigger NAT engine changes if the VM isn't running */
4349 SafeVMPtrQuiet ptrVM(this);
4350 if (ptrVM.isOk())
4351 {
4352 do
4353 {
4354 ComPtr<INetworkAdapter> pNetworkAdapter;
4355 rc = machine()->GetNetworkAdapter(ulInstance, pNetworkAdapter.asOutParam());
4356 if ( FAILED(rc)
4357 || pNetworkAdapter.isNull())
4358 break;
4359
4360 /*
4361 * Find the adapter instance, get the config interface and update
4362 * the link state.
4363 */
4364 NetworkAdapterType_T adapterType;
4365 rc = pNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
4366 if (FAILED(rc))
4367 {
4368 AssertComRC(rc);
4369 rc = E_FAIL;
4370 break;
4371 }
4372
4373 const char *pszAdapterName = networkAdapterTypeToName(adapterType);
4374 PPDMIBASE pBase;
4375 int vrc = PDMR3QueryLun(ptrVM.rawUVM(), pszAdapterName, ulInstance, 0, &pBase);
4376 if (RT_FAILURE(vrc))
4377 {
4378 ComAssertRC(vrc);
4379 rc = E_FAIL;
4380 break;
4381 }
4382
4383 NetworkAttachmentType_T attachmentType;
4384 rc = pNetworkAdapter->COMGETTER(AttachmentType)(&attachmentType);
4385 if ( FAILED(rc)
4386 || attachmentType != NetworkAttachmentType_NAT)
4387 {
4388 rc = E_FAIL;
4389 break;
4390 }
4391
4392 /* look down for PDMINETWORKNATCONFIG interface */
4393 PPDMINETWORKNATCONFIG pNetNatCfg = NULL;
4394 while (pBase)
4395 {
4396 pNetNatCfg = (PPDMINETWORKNATCONFIG)pBase->pfnQueryInterface(pBase, PDMINETWORKNATCONFIG_IID);
4397 if (pNetNatCfg)
4398 break;
4399 /** @todo r=bird: This stinks! */
4400 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pBase);
4401 pBase = pDrvIns->pDownBase;
4402 }
4403 if (!pNetNatCfg)
4404 break;
4405
4406 bool fUdp = aProto == NATProtocol_UDP;
4407 vrc = pNetNatCfg->pfnRedirectRuleCommand(pNetNatCfg, !!aNatRuleRemove, fUdp,
4408 Utf8Str(aHostIP).c_str(), aHostPort, Utf8Str(aGuestIP).c_str(),
4409 aGuestPort);
4410 if (RT_FAILURE(vrc))
4411 rc = E_FAIL;
4412 } while (0); /* break loop */
4413 ptrVM.release();
4414 }
4415
4416 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4417 return rc;
4418}
4419
4420
4421/**
4422 * Process a network adaptor change.
4423 *
4424 * @returns COM status code.
4425 *
4426 * @parma pUVM The VM handle (caller hold this safely).
4427 * @param pszDevice The PDM device name.
4428 * @param uInstance The PDM device instance.
4429 * @param uLun The PDM LUN number of the drive.
4430 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
4431 */
4432HRESULT Console::doNetworkAdapterChange(PUVM pUVM,
4433 const char *pszDevice,
4434 unsigned uInstance,
4435 unsigned uLun,
4436 INetworkAdapter *aNetworkAdapter)
4437{
4438 LogFlowThisFunc(("pszDevice=%p:{%s} uInstance=%u uLun=%u aNetworkAdapter=%p\n",
4439 pszDevice, pszDevice, uInstance, uLun, aNetworkAdapter));
4440
4441 AutoCaller autoCaller(this);
4442 AssertComRCReturnRC(autoCaller.rc());
4443
4444 /*
4445 * Call worker in EMT, that's faster and safer than doing everything
4446 * using VM3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
4447 * here to make requests from under the lock in order to serialize them.
4448 */
4449 PVMREQ pReq;
4450 int vrc = VMR3ReqCallU(pUVM, 0 /*idDstCpu*/, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS,
4451 (PFNRT)Console::changeNetworkAttachment, 6,
4452 this, pUVM, pszDevice, uInstance, uLun, aNetworkAdapter);
4453
4454 if (vrc == VERR_TIMEOUT || RT_SUCCESS(vrc))
4455 {
4456 vrc = VMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
4457 AssertRC(vrc);
4458 if (RT_SUCCESS(vrc))
4459 vrc = pReq->iStatus;
4460 }
4461 VMR3ReqFree(pReq);
4462
4463 if (RT_SUCCESS(vrc))
4464 {
4465 LogFlowThisFunc(("Returns S_OK\n"));
4466 return S_OK;
4467 }
4468
4469 return setError(E_FAIL,
4470 tr("Could not change the network adaptor attachement type (%Rrc)"),
4471 vrc);
4472}
4473
4474
4475/**
4476 * Performs the Network Adaptor change in EMT.
4477 *
4478 * @returns VBox status code.
4479 *
4480 * @param pThis Pointer to the Console object.
4481 * @param pUVM The VM handle.
4482 * @param pszDevice The PDM device name.
4483 * @param uInstance The PDM device instance.
4484 * @param uLun The PDM LUN number of the drive.
4485 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
4486 *
4487 * @thread EMT
4488 * @note Locks the Console object for writing.
4489 */
4490DECLCALLBACK(int) Console::changeNetworkAttachment(Console *pThis,
4491 PUVM pUVM,
4492 const char *pszDevice,
4493 unsigned uInstance,
4494 unsigned uLun,
4495 INetworkAdapter *aNetworkAdapter)
4496{
4497 LogFlowFunc(("pThis=%p pszDevice=%p:{%s} uInstance=%u uLun=%u aNetworkAdapter=%p\n",
4498 pThis, pszDevice, pszDevice, uInstance, uLun, aNetworkAdapter));
4499
4500 AssertReturn(pThis, VERR_INVALID_PARAMETER);
4501
4502 AutoCaller autoCaller(pThis);
4503 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
4504
4505 ComPtr<IVirtualBox> pVirtualBox;
4506 pThis->mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
4507 ComPtr<ISystemProperties> pSystemProperties;
4508 if (pVirtualBox)
4509 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
4510 ChipsetType_T chipsetType = ChipsetType_PIIX3;
4511 pThis->mMachine->COMGETTER(ChipsetType)(&chipsetType);
4512 ULONG maxNetworkAdapters = 0;
4513 if (pSystemProperties)
4514 pSystemProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
4515 AssertMsg( ( !strcmp(pszDevice, "pcnet")
4516 || !strcmp(pszDevice, "e1000")
4517 || !strcmp(pszDevice, "virtio-net"))
4518 && uLun == 0
4519 && uInstance < maxNetworkAdapters,
4520 ("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
4521 Log(("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
4522
4523 /*
4524 * Suspend the VM first.
4525 *
4526 * The VM must not be running since it might have pending I/O to
4527 * the drive which is being changed.
4528 */
4529 bool fResume;
4530 VMSTATE enmVMState = VMR3GetStateU(pUVM);
4531 switch (enmVMState)
4532 {
4533 case VMSTATE_RESETTING:
4534 case VMSTATE_RUNNING:
4535 {
4536 LogFlowFunc(("Suspending the VM...\n"));
4537 /* disable the callback to prevent Console-level state change */
4538 pThis->mVMStateChangeCallbackDisabled = true;
4539 int rc = VMR3Suspend(pUVM, VMSUSPENDREASON_RECONFIG);
4540 pThis->mVMStateChangeCallbackDisabled = false;
4541 AssertRCReturn(rc, rc);
4542 fResume = true;
4543 break;
4544 }
4545
4546 case VMSTATE_SUSPENDED:
4547 case VMSTATE_CREATED:
4548 case VMSTATE_OFF:
4549 fResume = false;
4550 break;
4551
4552 default:
4553 AssertLogRelMsgFailedReturn(("enmVMState=%d\n", enmVMState), VERR_ACCESS_DENIED);
4554 }
4555
4556 int rc = VINF_SUCCESS;
4557 int rcRet = VINF_SUCCESS;
4558
4559 PCFGMNODE pCfg = NULL; /* /Devices/Dev/.../Config/ */
4560 PCFGMNODE pLunL0 = NULL; /* /Devices/Dev/0/LUN#0/ */
4561 PCFGMNODE pInst = CFGMR3GetChildF(CFGMR3GetRootU(pUVM), "Devices/%s/%d/", pszDevice, uInstance);
4562 AssertRelease(pInst);
4563
4564 rcRet = pThis->configNetwork(pszDevice, uInstance, uLun, aNetworkAdapter, pCfg, pLunL0, pInst,
4565 true /*fAttachDetach*/, false /*fIgnoreConnectFailure*/);
4566
4567 /*
4568 * Resume the VM if necessary.
4569 */
4570 if (fResume)
4571 {
4572 LogFlowFunc(("Resuming the VM...\n"));
4573 /* disable the callback to prevent Console-level state change */
4574 pThis->mVMStateChangeCallbackDisabled = true;
4575 rc = VMR3Resume(pUVM, VMRESUMEREASON_RECONFIG);
4576 pThis->mVMStateChangeCallbackDisabled = false;
4577 AssertRC(rc);
4578 if (RT_FAILURE(rc))
4579 {
4580 /* too bad, we failed. try to sync the console state with the VMM state */
4581 vmstateChangeCallback(pUVM, VMSTATE_SUSPENDED, enmVMState, pThis);
4582 }
4583 /// @todo (r=dmik) if we failed with drive mount, then the VMR3Resume
4584 // error (if any) will be hidden from the caller. For proper reporting
4585 // of such multiple errors to the caller we need to enhance the
4586 // IVirtualBoxError interface. For now, give the first error the higher
4587 // priority.
4588 if (RT_SUCCESS(rcRet))
4589 rcRet = rc;
4590 }
4591
4592 LogFlowFunc(("Returning %Rrc\n", rcRet));
4593 return rcRet;
4594}
4595
4596
4597/**
4598 * Called by IInternalSessionControl::OnSerialPortChange().
4599 */
4600HRESULT Console::onSerialPortChange(ISerialPort *aSerialPort)
4601{
4602 LogFlowThisFunc(("\n"));
4603
4604 AutoCaller autoCaller(this);
4605 AssertComRCReturnRC(autoCaller.rc());
4606
4607 fireSerialPortChangedEvent(mEventSource, aSerialPort);
4608
4609 LogFlowThisFunc(("Leaving rc=%#x\n", S_OK));
4610 return S_OK;
4611}
4612
4613/**
4614 * Called by IInternalSessionControl::OnParallelPortChange().
4615 */
4616HRESULT Console::onParallelPortChange(IParallelPort *aParallelPort)
4617{
4618 LogFlowThisFunc(("\n"));
4619
4620 AutoCaller autoCaller(this);
4621 AssertComRCReturnRC(autoCaller.rc());
4622
4623 fireParallelPortChangedEvent(mEventSource, aParallelPort);
4624
4625 LogFlowThisFunc(("Leaving rc=%#x\n", S_OK));
4626 return S_OK;
4627}
4628
4629/**
4630 * Called by IInternalSessionControl::OnStorageControllerChange().
4631 */
4632HRESULT Console::onStorageControllerChange()
4633{
4634 LogFlowThisFunc(("\n"));
4635
4636 AutoCaller autoCaller(this);
4637 AssertComRCReturnRC(autoCaller.rc());
4638
4639 fireStorageControllerChangedEvent(mEventSource);
4640
4641 LogFlowThisFunc(("Leaving rc=%#x\n", S_OK));
4642 return S_OK;
4643}
4644
4645/**
4646 * Called by IInternalSessionControl::OnMediumChange().
4647 */
4648HRESULT Console::onMediumChange(IMediumAttachment *aMediumAttachment, BOOL aForce)
4649{
4650 LogFlowThisFunc(("\n"));
4651
4652 AutoCaller autoCaller(this);
4653 AssertComRCReturnRC(autoCaller.rc());
4654
4655 HRESULT rc = S_OK;
4656
4657 /* don't trigger medium changes if the VM isn't running */
4658 SafeVMPtrQuiet ptrVM(this);
4659 if (ptrVM.isOk())
4660 {
4661 rc = doMediumChange(aMediumAttachment, !!aForce, ptrVM.rawUVM());
4662 ptrVM.release();
4663 }
4664
4665 /* notify console callbacks on success */
4666 if (SUCCEEDED(rc))
4667 fireMediumChangedEvent(mEventSource, aMediumAttachment);
4668
4669 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4670 return rc;
4671}
4672
4673/**
4674 * Called by IInternalSessionControl::OnCPUChange().
4675 *
4676 * @note Locks this object for writing.
4677 */
4678HRESULT Console::onCPUChange(ULONG aCPU, BOOL aRemove)
4679{
4680 LogFlowThisFunc(("\n"));
4681
4682 AutoCaller autoCaller(this);
4683 AssertComRCReturnRC(autoCaller.rc());
4684
4685 HRESULT rc = S_OK;
4686
4687 /* don't trigger CPU changes if the VM isn't running */
4688 SafeVMPtrQuiet ptrVM(this);
4689 if (ptrVM.isOk())
4690 {
4691 if (aRemove)
4692 rc = doCPURemove(aCPU, ptrVM.rawUVM());
4693 else
4694 rc = doCPUAdd(aCPU, ptrVM.rawUVM());
4695 ptrVM.release();
4696 }
4697
4698 /* notify console callbacks on success */
4699 if (SUCCEEDED(rc))
4700 fireCPUChangedEvent(mEventSource, aCPU, aRemove);
4701
4702 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4703 return rc;
4704}
4705
4706/**
4707 * Called by IInternalSessionControl::OnCpuExecutionCapChange().
4708 *
4709 * @note Locks this object for writing.
4710 */
4711HRESULT Console::onCPUExecutionCapChange(ULONG aExecutionCap)
4712{
4713 LogFlowThisFunc(("\n"));
4714
4715 AutoCaller autoCaller(this);
4716 AssertComRCReturnRC(autoCaller.rc());
4717
4718 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4719
4720 HRESULT rc = S_OK;
4721
4722 /* don't trigger the CPU priority change if the VM isn't running */
4723 SafeVMPtrQuiet ptrVM(this);
4724 if (ptrVM.isOk())
4725 {
4726 if ( mMachineState == MachineState_Running
4727 || mMachineState == MachineState_Teleporting
4728 || mMachineState == MachineState_LiveSnapshotting
4729 )
4730 {
4731 /* No need to call in the EMT thread. */
4732 rc = VMR3SetCpuExecutionCap(ptrVM.rawUVM(), aExecutionCap);
4733 }
4734 else
4735 rc = setInvalidMachineStateError();
4736 ptrVM.release();
4737 }
4738
4739 /* notify console callbacks on success */
4740 if (SUCCEEDED(rc))
4741 {
4742 alock.release();
4743 fireCPUExecutionCapChangedEvent(mEventSource, aExecutionCap);
4744 }
4745
4746 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4747 return rc;
4748}
4749
4750/**
4751 * Called by IInternalSessionControl::OnClipboardModeChange().
4752 *
4753 * @note Locks this object for writing.
4754 */
4755HRESULT Console::onClipboardModeChange(ClipboardMode_T aClipboardMode)
4756{
4757 LogFlowThisFunc(("\n"));
4758
4759 AutoCaller autoCaller(this);
4760 AssertComRCReturnRC(autoCaller.rc());
4761
4762 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4763
4764 HRESULT rc = S_OK;
4765
4766 /* don't trigger the clipboard mode change if the VM isn't running */
4767 SafeVMPtrQuiet ptrVM(this);
4768 if (ptrVM.isOk())
4769 {
4770 if ( mMachineState == MachineState_Running
4771 || mMachineState == MachineState_Teleporting
4772 || mMachineState == MachineState_LiveSnapshotting)
4773 changeClipboardMode(aClipboardMode);
4774 else
4775 rc = setInvalidMachineStateError();
4776 ptrVM.release();
4777 }
4778
4779 /* notify console callbacks on success */
4780 if (SUCCEEDED(rc))
4781 {
4782 alock.release();
4783 fireClipboardModeChangedEvent(mEventSource, aClipboardMode);
4784 }
4785
4786 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4787 return rc;
4788}
4789
4790/**
4791 * Called by IInternalSessionControl::OnDragAndDropModeChange().
4792 *
4793 * @note Locks this object for writing.
4794 */
4795HRESULT Console::onDragAndDropModeChange(DragAndDropMode_T aDragAndDropMode)
4796{
4797 LogFlowThisFunc(("\n"));
4798
4799 AutoCaller autoCaller(this);
4800 AssertComRCReturnRC(autoCaller.rc());
4801
4802 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4803
4804 HRESULT rc = S_OK;
4805
4806 /* don't trigger the drag'n'drop mode change if the VM isn't running */
4807 SafeVMPtrQuiet ptrVM(this);
4808 if (ptrVM.isOk())
4809 {
4810 if ( mMachineState == MachineState_Running
4811 || mMachineState == MachineState_Teleporting
4812 || mMachineState == MachineState_LiveSnapshotting)
4813 changeDragAndDropMode(aDragAndDropMode);
4814 else
4815 rc = setInvalidMachineStateError();
4816 ptrVM.release();
4817 }
4818
4819 /* notify console callbacks on success */
4820 if (SUCCEEDED(rc))
4821 {
4822 alock.release();
4823 fireDragAndDropModeChangedEvent(mEventSource, aDragAndDropMode);
4824 }
4825
4826 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4827 return rc;
4828}
4829
4830/**
4831 * Called by IInternalSessionControl::OnVRDEServerChange().
4832 *
4833 * @note Locks this object for writing.
4834 */
4835HRESULT Console::onVRDEServerChange(BOOL aRestart)
4836{
4837 AutoCaller autoCaller(this);
4838 AssertComRCReturnRC(autoCaller.rc());
4839
4840 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4841
4842 HRESULT rc = S_OK;
4843
4844 /* don't trigger VRDE server changes if the VM isn't running */
4845 SafeVMPtrQuiet ptrVM(this);
4846 if (ptrVM.isOk())
4847 {
4848 if ( mVRDEServer
4849 && ( mMachineState == MachineState_Running
4850 || mMachineState == MachineState_Teleporting
4851 || mMachineState == MachineState_LiveSnapshotting
4852 || mMachineState == MachineState_Paused
4853 )
4854 )
4855 {
4856 BOOL vrdpEnabled = FALSE;
4857
4858 rc = mVRDEServer->COMGETTER(Enabled)(&vrdpEnabled);
4859 ComAssertComRCRetRC(rc);
4860
4861 if (aRestart)
4862 {
4863 /* VRDP server may call this Console object back from other threads (VRDP INPUT or OUTPUT). */
4864 alock.release();
4865
4866 if (vrdpEnabled)
4867 {
4868 // If there was no VRDP server started the 'stop' will do nothing.
4869 // However if a server was started and this notification was called,
4870 // we have to restart the server.
4871 mConsoleVRDPServer->Stop();
4872
4873 if (RT_FAILURE(mConsoleVRDPServer->Launch()))
4874 rc = E_FAIL;
4875 else
4876 mConsoleVRDPServer->EnableConnections();
4877 }
4878 else
4879 mConsoleVRDPServer->Stop();
4880
4881 alock.acquire();
4882 }
4883 }
4884 else
4885 rc = setInvalidMachineStateError();
4886 ptrVM.release();
4887 }
4888
4889 /* notify console callbacks on success */
4890 if (SUCCEEDED(rc))
4891 {
4892 alock.release();
4893 fireVRDEServerChangedEvent(mEventSource);
4894 }
4895
4896 return rc;
4897}
4898
4899void Console::onVRDEServerInfoChange()
4900{
4901 AutoCaller autoCaller(this);
4902 AssertComRCReturnVoid(autoCaller.rc());
4903
4904 fireVRDEServerInfoChangedEvent(mEventSource);
4905}
4906
4907HRESULT Console::onVideoCaptureChange()
4908{
4909 AutoCaller autoCaller(this);
4910 AssertComRCReturnRC(autoCaller.rc());
4911
4912 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4913
4914 HRESULT rc = S_OK;
4915
4916 /* don't trigger video capture changes if the VM isn't running */
4917 SafeVMPtrQuiet ptrVM(this);
4918 if (ptrVM.isOk())
4919 {
4920 BOOL fEnabled;
4921 rc = mMachine->COMGETTER(VideoCaptureEnabled)(&fEnabled);
4922 SafeArray<BOOL> screens;
4923 if (SUCCEEDED(rc))
4924 rc = mMachine->COMGETTER(VideoCaptureScreens)(ComSafeArrayAsOutParam(screens));
4925 if (mDisplay)
4926 {
4927 int vrc = VINF_SUCCESS;
4928 if (SUCCEEDED(rc))
4929 vrc = mDisplay->VideoCaptureEnableScreens(ComSafeArrayAsInParam(screens));
4930 if (RT_SUCCESS(vrc))
4931 {
4932 if (fEnabled)
4933 {
4934 vrc = mDisplay->VideoCaptureStart();
4935 if (RT_FAILURE(vrc))
4936 rc = setError(E_FAIL, tr("Unable to start video capturing (%Rrc)"), vrc);
4937 }
4938 else
4939 mDisplay->VideoCaptureStop();
4940 }
4941 else
4942 rc = setError(E_FAIL, tr("Unable to set screens for capturing (%Rrc)"), vrc);
4943 }
4944 ptrVM.release();
4945 }
4946
4947 /* notify console callbacks on success */
4948 if (SUCCEEDED(rc))
4949 {
4950 alock.release();
4951 fireVideoCaptureChangedEvent(mEventSource);
4952 }
4953
4954 return rc;
4955}
4956
4957/**
4958 * Called by IInternalSessionControl::OnUSBControllerChange().
4959 */
4960HRESULT Console::onUSBControllerChange()
4961{
4962 LogFlowThisFunc(("\n"));
4963
4964 AutoCaller autoCaller(this);
4965 AssertComRCReturnRC(autoCaller.rc());
4966
4967 fireUSBControllerChangedEvent(mEventSource);
4968
4969 return S_OK;
4970}
4971
4972/**
4973 * Called by IInternalSessionControl::OnSharedFolderChange().
4974 *
4975 * @note Locks this object for writing.
4976 */
4977HRESULT Console::onSharedFolderChange(BOOL aGlobal)
4978{
4979 LogFlowThisFunc(("aGlobal=%RTbool\n", aGlobal));
4980
4981 AutoCaller autoCaller(this);
4982 AssertComRCReturnRC(autoCaller.rc());
4983
4984 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4985
4986 HRESULT rc = fetchSharedFolders(aGlobal);
4987
4988 /* notify console callbacks on success */
4989 if (SUCCEEDED(rc))
4990 {
4991 alock.release();
4992 fireSharedFolderChangedEvent(mEventSource, aGlobal ? (Scope_T)Scope_Global : (Scope_T)Scope_Machine);
4993 }
4994
4995 return rc;
4996}
4997
4998/**
4999 * Called by IInternalSessionControl::OnUSBDeviceAttach() or locally by
5000 * processRemoteUSBDevices() after IInternalMachineControl::RunUSBDeviceFilters()
5001 * returns TRUE for a given remote USB device.
5002 *
5003 * @return S_OK if the device was attached to the VM.
5004 * @return failure if not attached.
5005 *
5006 * @param aDevice
5007 * The device in question.
5008 * @param aMaskedIfs
5009 * The interfaces to hide from the guest.
5010 *
5011 * @note Locks this object for writing.
5012 */
5013HRESULT Console::onUSBDeviceAttach(IUSBDevice *aDevice, IVirtualBoxErrorInfo *aError, ULONG aMaskedIfs)
5014{
5015#ifdef VBOX_WITH_USB
5016 LogFlowThisFunc(("aDevice=%p aError=%p\n", aDevice, aError));
5017
5018 AutoCaller autoCaller(this);
5019 ComAssertComRCRetRC(autoCaller.rc());
5020
5021 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5022
5023 /* Get the VM pointer (we don't need error info, since it's a callback). */
5024 SafeVMPtrQuiet ptrVM(this);
5025 if (!ptrVM.isOk())
5026 {
5027 /* The VM may be no more operational when this message arrives
5028 * (e.g. it may be Saving or Stopping or just PoweredOff) --
5029 * autoVMCaller.rc() will return a failure in this case. */
5030 LogFlowThisFunc(("Attach request ignored (mMachineState=%d).\n",
5031 mMachineState));
5032 return ptrVM.rc();
5033 }
5034
5035 if (aError != NULL)
5036 {
5037 /* notify callbacks about the error */
5038 alock.release();
5039 onUSBDeviceStateChange(aDevice, true /* aAttached */, aError);
5040 return S_OK;
5041 }
5042
5043 /* Don't proceed unless there's at least one USB hub. */
5044 if (!PDMR3UsbHasHub(ptrVM.rawUVM()))
5045 {
5046 LogFlowThisFunc(("Attach request ignored (no USB controller).\n"));
5047 return E_FAIL;
5048 }
5049
5050 alock.release();
5051 HRESULT rc = attachUSBDevice(aDevice, aMaskedIfs);
5052 if (FAILED(rc))
5053 {
5054 /* take the current error info */
5055 com::ErrorInfoKeeper eik;
5056 /* the error must be a VirtualBoxErrorInfo instance */
5057 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
5058 Assert(!pError.isNull());
5059 if (!pError.isNull())
5060 {
5061 /* notify callbacks about the error */
5062 onUSBDeviceStateChange(aDevice, true /* aAttached */, pError);
5063 }
5064 }
5065
5066 return rc;
5067
5068#else /* !VBOX_WITH_USB */
5069 return E_FAIL;
5070#endif /* !VBOX_WITH_USB */
5071}
5072
5073/**
5074 * Called by IInternalSessionControl::OnUSBDeviceDetach() and locally by
5075 * processRemoteUSBDevices().
5076 *
5077 * @note Locks this object for writing.
5078 */
5079HRESULT Console::onUSBDeviceDetach(IN_BSTR aId,
5080 IVirtualBoxErrorInfo *aError)
5081{
5082#ifdef VBOX_WITH_USB
5083 Guid Uuid(aId);
5084 LogFlowThisFunc(("aId={%RTuuid} aError=%p\n", Uuid.raw(), aError));
5085
5086 AutoCaller autoCaller(this);
5087 AssertComRCReturnRC(autoCaller.rc());
5088
5089 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5090
5091 /* Find the device. */
5092 ComObjPtr<OUSBDevice> pUSBDevice;
5093 USBDeviceList::iterator it = mUSBDevices.begin();
5094 while (it != mUSBDevices.end())
5095 {
5096 LogFlowThisFunc(("it={%RTuuid}\n", (*it)->id().raw()));
5097 if ((*it)->id() == Uuid)
5098 {
5099 pUSBDevice = *it;
5100 break;
5101 }
5102 ++it;
5103 }
5104
5105
5106 if (pUSBDevice.isNull())
5107 {
5108 LogFlowThisFunc(("USB device not found.\n"));
5109
5110 /* The VM may be no more operational when this message arrives
5111 * (e.g. it may be Saving or Stopping or just PoweredOff). Use
5112 * AutoVMCaller to detect it -- AutoVMCaller::rc() will return a
5113 * failure in this case. */
5114
5115 AutoVMCallerQuiet autoVMCaller(this);
5116 if (FAILED(autoVMCaller.rc()))
5117 {
5118 LogFlowThisFunc(("Detach request ignored (mMachineState=%d).\n",
5119 mMachineState));
5120 return autoVMCaller.rc();
5121 }
5122
5123 /* the device must be in the list otherwise */
5124 AssertFailedReturn(E_FAIL);
5125 }
5126
5127 if (aError != NULL)
5128 {
5129 /* notify callback about an error */
5130 alock.release();
5131 onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, aError);
5132 return S_OK;
5133 }
5134
5135 /* Remove the device from the collection, it is re-added below for failures */
5136 mUSBDevices.erase(it);
5137
5138 alock.release();
5139 HRESULT rc = detachUSBDevice(pUSBDevice);
5140 if (FAILED(rc))
5141 {
5142 /* Re-add the device to the collection */
5143 alock.acquire();
5144 mUSBDevices.push_back(pUSBDevice);
5145 alock.release();
5146 /* take the current error info */
5147 com::ErrorInfoKeeper eik;
5148 /* the error must be a VirtualBoxErrorInfo instance */
5149 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
5150 Assert(!pError.isNull());
5151 if (!pError.isNull())
5152 {
5153 /* notify callbacks about the error */
5154 onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, pError);
5155 }
5156 }
5157
5158 return rc;
5159
5160#else /* !VBOX_WITH_USB */
5161 return E_FAIL;
5162#endif /* !VBOX_WITH_USB */
5163}
5164
5165/**
5166 * Called by IInternalSessionControl::OnBandwidthGroupChange().
5167 *
5168 * @note Locks this object for writing.
5169 */
5170HRESULT Console::onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
5171{
5172 LogFlowThisFunc(("\n"));
5173
5174 AutoCaller autoCaller(this);
5175 AssertComRCReturnRC(autoCaller.rc());
5176
5177 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5178
5179 HRESULT rc = S_OK;
5180
5181 /* don't trigger bandwidth group changes if the VM isn't running */
5182 SafeVMPtrQuiet ptrVM(this);
5183 if (ptrVM.isOk())
5184 {
5185 if ( mMachineState == MachineState_Running
5186 || mMachineState == MachineState_Teleporting
5187 || mMachineState == MachineState_LiveSnapshotting
5188 )
5189 {
5190 /* No need to call in the EMT thread. */
5191 LONG64 cMax;
5192 Bstr strName;
5193 BandwidthGroupType_T enmType;
5194 rc = aBandwidthGroup->COMGETTER(Name)(strName.asOutParam());
5195 if (SUCCEEDED(rc))
5196 rc = aBandwidthGroup->COMGETTER(MaxBytesPerSec)(&cMax);
5197 if (SUCCEEDED(rc))
5198 rc = aBandwidthGroup->COMGETTER(Type)(&enmType);
5199
5200 if (SUCCEEDED(rc))
5201 {
5202 int vrc = VINF_SUCCESS;
5203 if (enmType == BandwidthGroupType_Disk)
5204 vrc = PDMR3AsyncCompletionBwMgrSetMaxForFile(ptrVM.rawUVM(), Utf8Str(strName).c_str(), cMax);
5205#ifdef VBOX_WITH_NETSHAPER
5206 else if (enmType == BandwidthGroupType_Network)
5207 vrc = PDMR3NsBwGroupSetLimit(ptrVM.rawUVM(), Utf8Str(strName).c_str(), cMax);
5208 else
5209 rc = E_NOTIMPL;
5210#endif /* VBOX_WITH_NETSHAPER */
5211 AssertRC(vrc);
5212 }
5213 }
5214 else
5215 rc = setInvalidMachineStateError();
5216 ptrVM.release();
5217 }
5218
5219 /* notify console callbacks on success */
5220 if (SUCCEEDED(rc))
5221 {
5222 alock.release();
5223 fireBandwidthGroupChangedEvent(mEventSource, aBandwidthGroup);
5224 }
5225
5226 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
5227 return rc;
5228}
5229
5230/**
5231 * Called by IInternalSessionControl::OnStorageDeviceChange().
5232 *
5233 * @note Locks this object for writing.
5234 */
5235HRESULT Console::onStorageDeviceChange(IMediumAttachment *aMediumAttachment, BOOL aRemove, BOOL aSilent)
5236{
5237 LogFlowThisFunc(("\n"));
5238
5239 AutoCaller autoCaller(this);
5240 AssertComRCReturnRC(autoCaller.rc());
5241
5242 HRESULT rc = S_OK;
5243
5244 /* don't trigger medium changes if the VM isn't running */
5245 SafeVMPtrQuiet ptrVM(this);
5246 if (ptrVM.isOk())
5247 {
5248 if (aRemove)
5249 rc = doStorageDeviceDetach(aMediumAttachment, ptrVM.rawUVM(), RT_BOOL(aSilent));
5250 else
5251 rc = doStorageDeviceAttach(aMediumAttachment, ptrVM.rawUVM(), RT_BOOL(aSilent));
5252 ptrVM.release();
5253 }
5254
5255 /* notify console callbacks on success */
5256 if (SUCCEEDED(rc))
5257 fireStorageDeviceChangedEvent(mEventSource, aMediumAttachment, aRemove, aSilent);
5258
5259 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
5260 return rc;
5261}
5262
5263/**
5264 * @note Temporarily locks this object for writing.
5265 */
5266HRESULT Console::getGuestProperty(IN_BSTR aName, BSTR *aValue,
5267 LONG64 *aTimestamp, BSTR *aFlags)
5268{
5269#ifndef VBOX_WITH_GUEST_PROPS
5270 ReturnComNotImplemented();
5271#else /* VBOX_WITH_GUEST_PROPS */
5272 if (!VALID_PTR(aName))
5273 return E_INVALIDARG;
5274 if (!VALID_PTR(aValue))
5275 return E_POINTER;
5276 if ((aTimestamp != NULL) && !VALID_PTR(aTimestamp))
5277 return E_POINTER;
5278 if ((aFlags != NULL) && !VALID_PTR(aFlags))
5279 return E_POINTER;
5280
5281 AutoCaller autoCaller(this);
5282 AssertComRCReturnRC(autoCaller.rc());
5283
5284 /* protect mpUVM (if not NULL) */
5285 SafeVMPtrQuiet ptrVM(this);
5286 if (FAILED(ptrVM.rc()))
5287 return ptrVM.rc();
5288
5289 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
5290 * ptrVM, so there is no need to hold a lock of this */
5291
5292 HRESULT rc = E_UNEXPECTED;
5293 using namespace guestProp;
5294
5295 try
5296 {
5297 VBOXHGCMSVCPARM parm[4];
5298 Utf8Str Utf8Name = aName;
5299 char szBuffer[MAX_VALUE_LEN + MAX_FLAGS_LEN];
5300
5301 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
5302 parm[0].u.pointer.addr = (void*)Utf8Name.c_str();
5303 /* The + 1 is the null terminator */
5304 parm[0].u.pointer.size = (uint32_t)Utf8Name.length() + 1;
5305 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
5306 parm[1].u.pointer.addr = szBuffer;
5307 parm[1].u.pointer.size = sizeof(szBuffer);
5308 int vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GET_PROP_HOST,
5309 4, &parm[0]);
5310 /* The returned string should never be able to be greater than our buffer */
5311 AssertLogRel(vrc != VERR_BUFFER_OVERFLOW);
5312 AssertLogRel(RT_FAILURE(vrc) || VBOX_HGCM_SVC_PARM_64BIT == parm[2].type);
5313 if (RT_SUCCESS(vrc) || (VERR_NOT_FOUND == vrc))
5314 {
5315 rc = S_OK;
5316 if (vrc != VERR_NOT_FOUND)
5317 {
5318 Utf8Str strBuffer(szBuffer);
5319 strBuffer.cloneTo(aValue);
5320
5321 if (aTimestamp)
5322 *aTimestamp = parm[2].u.uint64;
5323
5324 if (aFlags)
5325 {
5326 size_t iFlags = strBuffer.length() + 1;
5327 Utf8Str(szBuffer + iFlags).cloneTo(aFlags);
5328 }
5329 }
5330 else
5331 aValue = NULL;
5332 }
5333 else
5334 rc = setError(E_UNEXPECTED,
5335 tr("The service call failed with the error %Rrc"),
5336 vrc);
5337 }
5338 catch(std::bad_alloc & /*e*/)
5339 {
5340 rc = E_OUTOFMEMORY;
5341 }
5342 return rc;
5343#endif /* VBOX_WITH_GUEST_PROPS */
5344}
5345
5346/**
5347 * @note Temporarily locks this object for writing.
5348 */
5349HRESULT Console::setGuestProperty(IN_BSTR aName, IN_BSTR aValue, IN_BSTR aFlags)
5350{
5351#ifndef VBOX_WITH_GUEST_PROPS
5352 ReturnComNotImplemented();
5353#else /* VBOX_WITH_GUEST_PROPS */
5354 if (!RT_VALID_PTR(aName))
5355 return setError(E_INVALIDARG, tr("Name cannot be NULL or an invalid pointer"));
5356 if (aValue != NULL && !RT_VALID_PTR(aValue))
5357 return setError(E_INVALIDARG, tr("Invalid value pointer"));
5358 if (aFlags != NULL && !RT_VALID_PTR(aFlags))
5359 return setError(E_INVALIDARG, tr("Invalid flags pointer"));
5360
5361 AutoCaller autoCaller(this);
5362 AssertComRCReturnRC(autoCaller.rc());
5363
5364 /* protect mpUVM (if not NULL) */
5365 SafeVMPtrQuiet ptrVM(this);
5366 if (FAILED(ptrVM.rc()))
5367 return ptrVM.rc();
5368
5369 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
5370 * ptrVM, so there is no need to hold a lock of this */
5371
5372 using namespace guestProp;
5373
5374 VBOXHGCMSVCPARM parm[3];
5375
5376 Utf8Str Utf8Name = aName;
5377 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
5378 parm[0].u.pointer.addr = (void*)Utf8Name.c_str();
5379 /* The + 1 is the null terminator */
5380 parm[0].u.pointer.size = (uint32_t)Utf8Name.length() + 1;
5381
5382 Utf8Str Utf8Value;
5383 if (aValue != NULL)
5384 {
5385 Utf8Value = aValue;
5386 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
5387 parm[1].u.pointer.addr = (void *)Utf8Value.c_str();
5388 /* The + 1 is the null terminator */
5389 parm[1].u.pointer.size = (uint32_t)Utf8Value.length() + 1;
5390 }
5391
5392 Utf8Str Utf8Flags;
5393 if (aFlags != NULL)
5394 {
5395 Utf8Flags = aFlags;
5396 parm[2].type = VBOX_HGCM_SVC_PARM_PTR;
5397 parm[2].u.pointer.addr = (void*)Utf8Flags.c_str();
5398 /* The + 1 is the null terminator */
5399 parm[2].u.pointer.size = (uint32_t)Utf8Flags.length() + 1;
5400 }
5401
5402 int vrc;
5403 if (aValue != NULL && aFlags != NULL)
5404 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", SET_PROP_HOST,
5405 3, &parm[0]);
5406 else if (aValue != NULL)
5407 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", SET_PROP_VALUE_HOST,
5408 2, &parm[0]);
5409 else
5410 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", DEL_PROP_HOST,
5411 1, &parm[0]);
5412 HRESULT hrc;
5413 if (RT_SUCCESS(vrc))
5414 hrc = S_OK;
5415 else
5416 hrc = setError(E_UNEXPECTED, tr("The service call failed with the error %Rrc"), vrc);
5417 return hrc;
5418#endif /* VBOX_WITH_GUEST_PROPS */
5419}
5420
5421
5422/**
5423 * @note Temporarily locks this object for writing.
5424 */
5425HRESULT Console::enumerateGuestProperties(IN_BSTR aPatterns,
5426 ComSafeArrayOut(BSTR, aNames),
5427 ComSafeArrayOut(BSTR, aValues),
5428 ComSafeArrayOut(LONG64, aTimestamps),
5429 ComSafeArrayOut(BSTR, aFlags))
5430{
5431#ifndef VBOX_WITH_GUEST_PROPS
5432 ReturnComNotImplemented();
5433#else /* VBOX_WITH_GUEST_PROPS */
5434 if (!VALID_PTR(aPatterns) && (aPatterns != NULL))
5435 return E_POINTER;
5436 if (ComSafeArrayOutIsNull(aNames))
5437 return E_POINTER;
5438 if (ComSafeArrayOutIsNull(aValues))
5439 return E_POINTER;
5440 if (ComSafeArrayOutIsNull(aTimestamps))
5441 return E_POINTER;
5442 if (ComSafeArrayOutIsNull(aFlags))
5443 return E_POINTER;
5444
5445 AutoCaller autoCaller(this);
5446 AssertComRCReturnRC(autoCaller.rc());
5447
5448 /* protect mpUVM (if not NULL) */
5449 AutoVMCallerWeak autoVMCaller(this);
5450 if (FAILED(autoVMCaller.rc()))
5451 return autoVMCaller.rc();
5452
5453 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
5454 * autoVMCaller, so there is no need to hold a lock of this */
5455
5456 return doEnumerateGuestProperties(aPatterns, ComSafeArrayOutArg(aNames),
5457 ComSafeArrayOutArg(aValues),
5458 ComSafeArrayOutArg(aTimestamps),
5459 ComSafeArrayOutArg(aFlags));
5460#endif /* VBOX_WITH_GUEST_PROPS */
5461}
5462
5463
5464/*
5465 * Internal: helper function for connecting progress reporting
5466 */
5467static int onlineMergeMediumProgress(void *pvUser, unsigned uPercentage)
5468{
5469 HRESULT rc = S_OK;
5470 IProgress *pProgress = static_cast<IProgress *>(pvUser);
5471 if (pProgress)
5472 rc = pProgress->SetCurrentOperationProgress(uPercentage);
5473 return SUCCEEDED(rc) ? VINF_SUCCESS : VERR_GENERAL_FAILURE;
5474}
5475
5476/**
5477 * @note Temporarily locks this object for writing. bird: And/or reading?
5478 */
5479HRESULT Console::onlineMergeMedium(IMediumAttachment *aMediumAttachment,
5480 ULONG aSourceIdx, ULONG aTargetIdx,
5481 IMedium *aSource, IMedium *aTarget,
5482 BOOL aMergeForward,
5483 IMedium *aParentForTarget,
5484 ComSafeArrayIn(IMedium *, aChildrenToReparent),
5485 IProgress *aProgress)
5486{
5487 AutoCaller autoCaller(this);
5488 AssertComRCReturnRC(autoCaller.rc());
5489
5490 HRESULT rc = S_OK;
5491 int vrc = VINF_SUCCESS;
5492
5493 /* Get the VM - must be done before the read-locking. */
5494 SafeVMPtr ptrVM(this);
5495 if (!ptrVM.isOk())
5496 return ptrVM.rc();
5497
5498 /* We will need to release the lock before doing the actual merge */
5499 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5500
5501 /* paranoia - we don't want merges to happen while teleporting etc. */
5502 switch (mMachineState)
5503 {
5504 case MachineState_DeletingSnapshotOnline:
5505 case MachineState_DeletingSnapshotPaused:
5506 break;
5507
5508 default:
5509 return setInvalidMachineStateError();
5510 }
5511
5512 /** @todo AssertComRC -> AssertComRCReturn! Could potentially end up
5513 * using uninitialized variables here. */
5514 BOOL fBuiltinIOCache;
5515 rc = mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
5516 AssertComRC(rc);
5517 SafeIfaceArray<IStorageController> ctrls;
5518 rc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
5519 AssertComRC(rc);
5520 LONG lDev;
5521 rc = aMediumAttachment->COMGETTER(Device)(&lDev);
5522 AssertComRC(rc);
5523 LONG lPort;
5524 rc = aMediumAttachment->COMGETTER(Port)(&lPort);
5525 AssertComRC(rc);
5526 IMedium *pMedium;
5527 rc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
5528 AssertComRC(rc);
5529 Bstr mediumLocation;
5530 if (pMedium)
5531 {
5532 rc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
5533 AssertComRC(rc);
5534 }
5535
5536 Bstr attCtrlName;
5537 rc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
5538 AssertComRC(rc);
5539 ComPtr<IStorageController> pStorageController;
5540 for (size_t i = 0; i < ctrls.size(); ++i)
5541 {
5542 Bstr ctrlName;
5543 rc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
5544 AssertComRC(rc);
5545 if (attCtrlName == ctrlName)
5546 {
5547 pStorageController = ctrls[i];
5548 break;
5549 }
5550 }
5551 if (pStorageController.isNull())
5552 return setError(E_FAIL,
5553 tr("Could not find storage controller '%ls'"),
5554 attCtrlName.raw());
5555
5556 StorageControllerType_T enmCtrlType;
5557 rc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
5558 AssertComRC(rc);
5559 const char *pcszDevice = convertControllerTypeToDev(enmCtrlType);
5560
5561 StorageBus_T enmBus;
5562 rc = pStorageController->COMGETTER(Bus)(&enmBus);
5563 AssertComRC(rc);
5564 ULONG uInstance;
5565 rc = pStorageController->COMGETTER(Instance)(&uInstance);
5566 AssertComRC(rc);
5567 BOOL fUseHostIOCache;
5568 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
5569 AssertComRC(rc);
5570
5571 unsigned uLUN;
5572 rc = Console::convertBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);
5573 AssertComRCReturnRC(rc);
5574
5575 alock.release();
5576
5577 /* Pause the VM, as it might have pending IO on this drive */
5578 VMSTATE enmVMState = VMR3GetStateU(ptrVM.rawUVM());
5579 if (mMachineState == MachineState_DeletingSnapshotOnline)
5580 {
5581 LogFlowFunc(("Suspending the VM...\n"));
5582 /* disable the callback to prevent Console-level state change */
5583 mVMStateChangeCallbackDisabled = true;
5584 int vrc2 = VMR3Suspend(ptrVM.rawUVM(), VMSUSPENDREASON_RECONFIG);
5585 mVMStateChangeCallbackDisabled = false;
5586 AssertRCReturn(vrc2, E_FAIL);
5587 }
5588
5589 vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(),
5590 VMCPUID_ANY,
5591 (PFNRT)reconfigureMediumAttachment,
5592 13,
5593 this,
5594 ptrVM.rawUVM(),
5595 pcszDevice,
5596 uInstance,
5597 enmBus,
5598 fUseHostIOCache,
5599 fBuiltinIOCache,
5600 true /* fSetupMerge */,
5601 aSourceIdx,
5602 aTargetIdx,
5603 aMediumAttachment,
5604 mMachineState,
5605 &rc);
5606 /* error handling is after resuming the VM */
5607
5608 if (mMachineState == MachineState_DeletingSnapshotOnline)
5609 {
5610 LogFlowFunc(("Resuming the VM...\n"));
5611 /* disable the callback to prevent Console-level state change */
5612 mVMStateChangeCallbackDisabled = true;
5613 int vrc2 = VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_RECONFIG);
5614 mVMStateChangeCallbackDisabled = false;
5615 if (RT_FAILURE(vrc2))
5616 {
5617 /* too bad, we failed. try to sync the console state with the VMM state */
5618 AssertLogRelRC(vrc2);
5619 vmstateChangeCallback(ptrVM.rawUVM(), VMSTATE_SUSPENDED, enmVMState, this);
5620 }
5621 }
5622
5623 if (RT_FAILURE(vrc))
5624 return setError(E_FAIL, tr("%Rrc"), vrc);
5625 if (FAILED(rc))
5626 return rc;
5627
5628 PPDMIBASE pIBase = NULL;
5629 PPDMIMEDIA pIMedium = NULL;
5630 vrc = PDMR3QueryDriverOnLun(ptrVM.rawUVM(), pcszDevice, uInstance, uLUN, "VD", &pIBase);
5631 if (RT_SUCCESS(vrc))
5632 {
5633 if (pIBase)
5634 {
5635 pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
5636 if (!pIMedium)
5637 return setError(E_FAIL, tr("could not query medium interface of controller"));
5638 }
5639 else
5640 return setError(E_FAIL, tr("could not query base interface of controller"));
5641 }
5642
5643 /* Finally trigger the merge. */
5644 vrc = pIMedium->pfnMerge(pIMedium, onlineMergeMediumProgress, aProgress);
5645 if (RT_FAILURE(vrc))
5646 return setError(E_FAIL, tr("Failed to perform an online medium merge (%Rrc)"), vrc);
5647
5648 /* Pause the VM, as it might have pending IO on this drive */
5649 enmVMState = VMR3GetStateU(ptrVM.rawUVM());
5650 if (mMachineState == MachineState_DeletingSnapshotOnline)
5651 {
5652 LogFlowFunc(("Suspending the VM...\n"));
5653 /* disable the callback to prevent Console-level state change */
5654 mVMStateChangeCallbackDisabled = true;
5655 int vrc2 = VMR3Suspend(ptrVM.rawUVM(), VMSUSPENDREASON_RECONFIG);
5656 mVMStateChangeCallbackDisabled = false;
5657 AssertRCReturn(vrc2, E_FAIL);
5658 }
5659
5660 /* Update medium chain and state now, so that the VM can continue. */
5661 rc = mControl->FinishOnlineMergeMedium(aMediumAttachment, aSource, aTarget,
5662 aMergeForward, aParentForTarget,
5663 ComSafeArrayInArg(aChildrenToReparent));
5664
5665 vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(),
5666 VMCPUID_ANY,
5667 (PFNRT)reconfigureMediumAttachment,
5668 13,
5669 this,
5670 ptrVM.rawUVM(),
5671 pcszDevice,
5672 uInstance,
5673 enmBus,
5674 fUseHostIOCache,
5675 fBuiltinIOCache,
5676 false /* fSetupMerge */,
5677 0 /* uMergeSource */,
5678 0 /* uMergeTarget */,
5679 aMediumAttachment,
5680 mMachineState,
5681 &rc);
5682 /* error handling is after resuming the VM */
5683
5684 if (mMachineState == MachineState_DeletingSnapshotOnline)
5685 {
5686 LogFlowFunc(("Resuming the VM...\n"));
5687 /* disable the callback to prevent Console-level state change */
5688 mVMStateChangeCallbackDisabled = true;
5689 int vrc2 = VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_RECONFIG);
5690 mVMStateChangeCallbackDisabled = false;
5691 AssertRC(vrc2);
5692 if (RT_FAILURE(vrc2))
5693 {
5694 /* too bad, we failed. try to sync the console state with the VMM state */
5695 vmstateChangeCallback(ptrVM.rawUVM(), VMSTATE_SUSPENDED, enmVMState, this);
5696 }
5697 }
5698
5699 if (RT_FAILURE(vrc))
5700 return setError(E_FAIL, tr("%Rrc"), vrc);
5701 if (FAILED(rc))
5702 return rc;
5703
5704 return rc;
5705}
5706
5707
5708/**
5709 * Merely passes the call to Guest::enableVMMStatistics().
5710 */
5711void Console::enableVMMStatistics(BOOL aEnable)
5712{
5713 if (mGuest)
5714 mGuest->enableVMMStatistics(aEnable);
5715}
5716
5717/**
5718 * Worker for Console::Pause and internal entry point for pausing a VM for
5719 * a specific reason.
5720 */
5721HRESULT Console::pause(Reason_T aReason)
5722{
5723 LogFlowThisFuncEnter();
5724
5725 AutoCaller autoCaller(this);
5726 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5727
5728 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5729
5730 switch (mMachineState)
5731 {
5732 case MachineState_Running:
5733 case MachineState_Teleporting:
5734 case MachineState_LiveSnapshotting:
5735 break;
5736
5737 case MachineState_Paused:
5738 case MachineState_TeleportingPausedVM:
5739 case MachineState_Saving:
5740 return setError(VBOX_E_INVALID_VM_STATE, tr("Already paused"));
5741
5742 default:
5743 return setInvalidMachineStateError();
5744 }
5745
5746 /* get the VM handle. */
5747 SafeVMPtr ptrVM(this);
5748 if (!ptrVM.isOk())
5749 return ptrVM.rc();
5750
5751 /* release the lock before a VMR3* call (EMT will call us back)! */
5752 alock.release();
5753
5754 LogFlowThisFunc(("Sending PAUSE request...\n"));
5755 if (aReason != Reason_Unspecified)
5756 LogRel(("Pausing VM execution, reason \"%s\"\n", Global::stringifyReason(aReason)));
5757
5758 /** @todo r=klaus make use of aReason */
5759 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
5760 if (aReason == Reason_HostSuspend)
5761 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
5762 else if (aReason == Reason_HostBatteryLow)
5763 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
5764 int vrc = VMR3Suspend(ptrVM.rawUVM(), enmReason);
5765
5766 HRESULT hrc = S_OK;
5767 if (RT_FAILURE(vrc))
5768 hrc = setError(VBOX_E_VM_ERROR, tr("Could not suspend the machine execution (%Rrc)"), vrc);
5769
5770 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
5771 LogFlowThisFuncLeave();
5772 return hrc;
5773}
5774
5775/**
5776 * Worker for Console::Resume and internal entry point for resuming a VM for
5777 * a specific reason.
5778 */
5779HRESULT Console::resume(Reason_T aReason)
5780{
5781 LogFlowThisFuncEnter();
5782
5783 AutoCaller autoCaller(this);
5784 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5785
5786 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5787
5788 if (mMachineState != MachineState_Paused)
5789 return setError(VBOX_E_INVALID_VM_STATE,
5790 tr("Cannot resume the machine as it is not paused (machine state: %s)"),
5791 Global::stringifyMachineState(mMachineState));
5792
5793 /* get the VM handle. */
5794 SafeVMPtr ptrVM(this);
5795 if (!ptrVM.isOk())
5796 return ptrVM.rc();
5797
5798 /* release the lock before a VMR3* call (EMT will call us back)! */
5799 alock.release();
5800
5801 LogFlowThisFunc(("Sending RESUME request...\n"));
5802 if (aReason != Reason_Unspecified)
5803 LogRel(("Resuming VM execution, reason \"%s\"\n", Global::stringifyReason(aReason)));
5804
5805 int vrc;
5806 if (VMR3GetStateU(ptrVM.rawUVM()) == VMSTATE_CREATED)
5807 {
5808#ifdef VBOX_WITH_EXTPACK
5809 vrc = mptrExtPackManager->callAllVmPowerOnHooks(this, VMR3GetVM(ptrVM.rawUVM()));
5810#else
5811 vrc = VINF_SUCCESS;
5812#endif
5813 if (RT_SUCCESS(vrc))
5814 vrc = VMR3PowerOn(ptrVM.rawUVM()); /* (PowerUpPaused) */
5815 }
5816 else
5817 {
5818 VMRESUMEREASON enmReason = VMRESUMEREASON_USER;
5819 if (aReason == Reason_HostResume)
5820 enmReason = VMRESUMEREASON_HOST_RESUME;
5821 vrc = VMR3Resume(ptrVM.rawUVM(), enmReason);
5822 }
5823
5824 HRESULT rc = RT_SUCCESS(vrc) ? S_OK :
5825 setError(VBOX_E_VM_ERROR,
5826 tr("Could not resume the machine execution (%Rrc)"),
5827 vrc);
5828
5829 LogFlowThisFunc(("rc=%Rhrc\n", rc));
5830 LogFlowThisFuncLeave();
5831 return rc;
5832}
5833
5834/**
5835 * Worker for Console::SaveState and internal entry point for saving state of
5836 * a VM for a specific reason.
5837 */
5838HRESULT Console::saveState(Reason_T aReason, IProgress **aProgress)
5839{
5840 LogFlowThisFuncEnter();
5841
5842 CheckComArgOutPointerValid(aProgress);
5843
5844 AutoCaller autoCaller(this);
5845 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5846
5847 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5848
5849 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
5850 if ( mMachineState != MachineState_Running
5851 && mMachineState != MachineState_Paused)
5852 {
5853 return setError(VBOX_E_INVALID_VM_STATE,
5854 tr("Cannot save the execution state as the machine is not running or paused (machine state: %s)"),
5855 Global::stringifyMachineState(mMachineState));
5856 }
5857
5858 if (aReason != Reason_Unspecified)
5859 LogRel(("Saving state of VM, reason \"%s\"\n", Global::stringifyReason(aReason)));
5860
5861 /* memorize the current machine state */
5862 MachineState_T lastMachineState = mMachineState;
5863
5864 if (mMachineState == MachineState_Running)
5865 {
5866 /* get the VM handle. */
5867 SafeVMPtr ptrVM(this);
5868 if (!ptrVM.isOk())
5869 return ptrVM.rc();
5870
5871 /* release the lock before a VMR3* call (EMT will call us back)! */
5872 alock.release();
5873 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
5874 if (aReason == Reason_HostSuspend)
5875 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
5876 else if (aReason == Reason_HostBatteryLow)
5877 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
5878 int vrc = VMR3Suspend(ptrVM.rawUVM(), enmReason);
5879 alock.acquire();
5880
5881 HRESULT hrc = S_OK;
5882 if (RT_FAILURE(vrc))
5883 hrc = setError(VBOX_E_VM_ERROR, tr("Could not suspend the machine execution (%Rrc)"), vrc);
5884 if (FAILED(hrc))
5885 return hrc;
5886 }
5887
5888 HRESULT rc = S_OK;
5889 bool fBeganSavingState = false;
5890 bool fTaskCreationFailed = false;
5891
5892 do
5893 {
5894 ComPtr<IProgress> pProgress;
5895 Bstr stateFilePath;
5896
5897 /*
5898 * request a saved state file path from the server
5899 * (this will set the machine state to Saving on the server to block
5900 * others from accessing this machine)
5901 */
5902 rc = mControl->BeginSavingState(pProgress.asOutParam(),
5903 stateFilePath.asOutParam());
5904 if (FAILED(rc))
5905 break;
5906
5907 fBeganSavingState = true;
5908
5909 /* sync the state with the server */
5910 setMachineStateLocally(MachineState_Saving);
5911
5912 /* ensure the directory for the saved state file exists */
5913 {
5914 Utf8Str dir = stateFilePath;
5915 dir.stripFilename();
5916 if (!RTDirExists(dir.c_str()))
5917 {
5918 int vrc = RTDirCreateFullPath(dir.c_str(), 0700);
5919 if (RT_FAILURE(vrc))
5920 {
5921 rc = setError(VBOX_E_FILE_ERROR,
5922 tr("Could not create a directory '%s' to save the state to (%Rrc)"),
5923 dir.c_str(), vrc);
5924 break;
5925 }
5926 }
5927 }
5928
5929 /* Create a task object early to ensure mpUVM protection is successful. */
5930 std::auto_ptr<VMSaveTask> task(new VMSaveTask(this, pProgress,
5931 stateFilePath,
5932 lastMachineState,
5933 aReason));
5934 rc = task->rc();
5935 /*
5936 * If we fail here it means a PowerDown() call happened on another
5937 * thread while we were doing Pause() (which releases the Console lock).
5938 * We assign PowerDown() a higher precedence than SaveState(),
5939 * therefore just return the error to the caller.
5940 */
5941 if (FAILED(rc))
5942 {
5943 fTaskCreationFailed = true;
5944 break;
5945 }
5946
5947 /* create a thread to wait until the VM state is saved */
5948 int vrc = RTThreadCreate(NULL, Console::saveStateThread, (void *)task.get(),
5949 0, RTTHREADTYPE_MAIN_WORKER, 0, "VMSave");
5950 if (RT_FAILURE(vrc))
5951 {
5952 rc = setError(E_FAIL, "Could not create VMSave thread (%Rrc)", vrc);
5953 break;
5954 }
5955
5956 /* task is now owned by saveStateThread(), so release it */
5957 task.release();
5958
5959 /* return the progress to the caller */
5960 pProgress.queryInterfaceTo(aProgress);
5961 } while (0);
5962
5963 if (FAILED(rc) && !fTaskCreationFailed)
5964 {
5965 /* preserve existing error info */
5966 ErrorInfoKeeper eik;
5967
5968 if (fBeganSavingState)
5969 {
5970 /*
5971 * cancel the requested save state procedure.
5972 * This will reset the machine state to the state it had right
5973 * before calling mControl->BeginSavingState().
5974 */
5975 mControl->EndSavingState(eik.getResultCode(), eik.getText().raw());
5976 }
5977
5978 if (lastMachineState == MachineState_Running)
5979 {
5980 /* restore the paused state if appropriate */
5981 setMachineStateLocally(MachineState_Paused);
5982 /* restore the running state if appropriate */
5983 SafeVMPtr ptrVM(this);
5984 if (ptrVM.isOk())
5985 {
5986 alock.release();
5987 VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_STATE_RESTORED);
5988 alock.acquire();
5989 }
5990 }
5991 else
5992 setMachineStateLocally(lastMachineState);
5993 }
5994
5995 LogFlowThisFunc(("rc=%Rhrc\n", rc));
5996 LogFlowThisFuncLeave();
5997 return rc;
5998}
5999
6000/**
6001 * Gets called by Session::UpdateMachineState()
6002 * (IInternalSessionControl::updateMachineState()).
6003 *
6004 * Must be called only in certain cases (see the implementation).
6005 *
6006 * @note Locks this object for writing.
6007 */
6008HRESULT Console::updateMachineState(MachineState_T aMachineState)
6009{
6010 AutoCaller autoCaller(this);
6011 AssertComRCReturnRC(autoCaller.rc());
6012
6013 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6014
6015 AssertReturn( mMachineState == MachineState_Saving
6016 || mMachineState == MachineState_LiveSnapshotting
6017 || mMachineState == MachineState_RestoringSnapshot
6018 || mMachineState == MachineState_DeletingSnapshot
6019 || mMachineState == MachineState_DeletingSnapshotOnline
6020 || mMachineState == MachineState_DeletingSnapshotPaused
6021 , E_FAIL);
6022
6023 return setMachineStateLocally(aMachineState);
6024}
6025
6026#ifdef CONSOLE_WITH_EVENT_CACHE
6027/**
6028 * @note Locks this object for writing.
6029 */
6030#endif
6031void Console::onMousePointerShapeChange(bool fVisible, bool fAlpha,
6032 uint32_t xHot, uint32_t yHot,
6033 uint32_t width, uint32_t height,
6034 ComSafeArrayIn(BYTE,pShape))
6035{
6036#if 0
6037 LogFlowThisFuncEnter();
6038 LogFlowThisFunc(("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, height=%d, shape=%p\n",
6039 fVisible, fAlpha, xHot, yHot, width, height, pShape));
6040#endif
6041
6042 AutoCaller autoCaller(this);
6043 AssertComRCReturnVoid(autoCaller.rc());
6044
6045#ifdef CONSOLE_WITH_EVENT_CACHE
6046 {
6047 /* We need a write lock because we alter the cached callback data */
6048 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6049
6050 /* Save the callback arguments */
6051 mCallbackData.mpsc.visible = fVisible;
6052 mCallbackData.mpsc.alpha = fAlpha;
6053 mCallbackData.mpsc.xHot = xHot;
6054 mCallbackData.mpsc.yHot = yHot;
6055 mCallbackData.mpsc.width = width;
6056 mCallbackData.mpsc.height = height;
6057
6058 /* start with not valid */
6059 bool wasValid = mCallbackData.mpsc.valid;
6060 mCallbackData.mpsc.valid = false;
6061
6062 com::SafeArray<BYTE> aShape(ComSafeArrayInArg(pShape));
6063 if (aShape.size() != 0)
6064 mCallbackData.mpsc.shape.initFrom(aShape);
6065 else
6066 mCallbackData.mpsc.shape.resize(0);
6067 mCallbackData.mpsc.valid = true;
6068 }
6069#endif
6070
6071 fireMousePointerShapeChangedEvent(mEventSource, fVisible, fAlpha, xHot, yHot, width, height, ComSafeArrayInArg(pShape));
6072
6073#if 0
6074 LogFlowThisFuncLeave();
6075#endif
6076}
6077
6078#ifdef CONSOLE_WITH_EVENT_CACHE
6079/**
6080 * @note Locks this object for writing.
6081 */
6082#endif
6083void Console::onMouseCapabilityChange(BOOL supportsAbsolute, BOOL supportsRelative, BOOL needsHostCursor)
6084{
6085 LogFlowThisFunc(("supportsAbsolute=%d supportsRelative=%d needsHostCursor=%d\n",
6086 supportsAbsolute, supportsRelative, needsHostCursor));
6087
6088 AutoCaller autoCaller(this);
6089 AssertComRCReturnVoid(autoCaller.rc());
6090
6091#ifdef CONSOLE_WITH_EVENT_CACHE
6092 {
6093 /* We need a write lock because we alter the cached callback data */
6094 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6095
6096 /* save the callback arguments */
6097 mCallbackData.mcc.supportsAbsolute = supportsAbsolute;
6098 mCallbackData.mcc.supportsRelative = supportsRelative;
6099 mCallbackData.mcc.needsHostCursor = needsHostCursor;
6100 mCallbackData.mcc.valid = true;
6101 }
6102#endif
6103
6104 fireMouseCapabilityChangedEvent(mEventSource, supportsAbsolute, supportsRelative, needsHostCursor);
6105}
6106
6107void Console::onStateChange(MachineState_T machineState)
6108{
6109 AutoCaller autoCaller(this);
6110 AssertComRCReturnVoid(autoCaller.rc());
6111 fireStateChangedEvent(mEventSource, machineState);
6112}
6113
6114void Console::onAdditionsStateChange()
6115{
6116 AutoCaller autoCaller(this);
6117 AssertComRCReturnVoid(autoCaller.rc());
6118
6119 fireAdditionsStateChangedEvent(mEventSource);
6120}
6121
6122/**
6123 * @remarks This notification only is for reporting an incompatible
6124 * Guest Additions interface, *not* the Guest Additions version!
6125 *
6126 * The user will be notified inside the guest if new Guest
6127 * Additions are available (via VBoxTray/VBoxClient).
6128 */
6129void Console::onAdditionsOutdated()
6130{
6131 AutoCaller autoCaller(this);
6132 AssertComRCReturnVoid(autoCaller.rc());
6133
6134 /** @todo implement this */
6135}
6136
6137#ifdef CONSOLE_WITH_EVENT_CACHE
6138/**
6139 * @note Locks this object for writing.
6140 */
6141#endif
6142void Console::onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
6143{
6144 AutoCaller autoCaller(this);
6145 AssertComRCReturnVoid(autoCaller.rc());
6146
6147#ifdef CONSOLE_WITH_EVENT_CACHE
6148 {
6149 /* We need a write lock because we alter the cached callback data */
6150 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6151
6152 /* save the callback arguments */
6153 mCallbackData.klc.numLock = fNumLock;
6154 mCallbackData.klc.capsLock = fCapsLock;
6155 mCallbackData.klc.scrollLock = fScrollLock;
6156 mCallbackData.klc.valid = true;
6157 }
6158#endif
6159
6160 fireKeyboardLedsChangedEvent(mEventSource, fNumLock, fCapsLock, fScrollLock);
6161}
6162
6163void Console::onUSBDeviceStateChange(IUSBDevice *aDevice, bool aAttached,
6164 IVirtualBoxErrorInfo *aError)
6165{
6166 AutoCaller autoCaller(this);
6167 AssertComRCReturnVoid(autoCaller.rc());
6168
6169 fireUSBDeviceStateChangedEvent(mEventSource, aDevice, aAttached, aError);
6170}
6171
6172void Console::onRuntimeError(BOOL aFatal, IN_BSTR aErrorID, IN_BSTR aMessage)
6173{
6174 AutoCaller autoCaller(this);
6175 AssertComRCReturnVoid(autoCaller.rc());
6176
6177 fireRuntimeErrorEvent(mEventSource, aFatal, aErrorID, aMessage);
6178}
6179
6180HRESULT Console::onShowWindow(BOOL aCheck, BOOL *aCanShow, LONG64 *aWinId)
6181{
6182 AssertReturn(aCanShow, E_POINTER);
6183 AssertReturn(aWinId, E_POINTER);
6184
6185 *aCanShow = FALSE;
6186 *aWinId = 0;
6187
6188 AutoCaller autoCaller(this);
6189 AssertComRCReturnRC(autoCaller.rc());
6190
6191 VBoxEventDesc evDesc;
6192 if (aCheck)
6193 {
6194 evDesc.init(mEventSource, VBoxEventType_OnCanShowWindow);
6195 BOOL fDelivered = evDesc.fire(5000); /* Wait up to 5 secs for delivery */
6196 //Assert(fDelivered);
6197 if (fDelivered)
6198 {
6199 ComPtr<IEvent> pEvent;
6200 evDesc.getEvent(pEvent.asOutParam());
6201 // bit clumsy
6202 ComPtr<ICanShowWindowEvent> pCanShowEvent = pEvent;
6203 if (pCanShowEvent)
6204 {
6205 BOOL fVetoed = FALSE;
6206 pCanShowEvent->IsVetoed(&fVetoed);
6207 *aCanShow = !fVetoed;
6208 }
6209 else
6210 {
6211 AssertFailed();
6212 *aCanShow = TRUE;
6213 }
6214 }
6215 else
6216 *aCanShow = TRUE;
6217 }
6218 else
6219 {
6220 evDesc.init(mEventSource, VBoxEventType_OnShowWindow, INT64_C(0));
6221 BOOL fDelivered = evDesc.fire(5000); /* Wait up to 5 secs for delivery */
6222 //Assert(fDelivered);
6223 if (fDelivered)
6224 {
6225 ComPtr<IEvent> pEvent;
6226 evDesc.getEvent(pEvent.asOutParam());
6227 ComPtr<IShowWindowEvent> pShowEvent = pEvent;
6228 if (pShowEvent)
6229 {
6230 LONG64 iEvWinId = 0;
6231 pShowEvent->COMGETTER(WinId)(&iEvWinId);
6232 if (iEvWinId != 0 && *aWinId == 0)
6233 *aWinId = iEvWinId;
6234 }
6235 else
6236 AssertFailed();
6237 }
6238 }
6239
6240 return S_OK;
6241}
6242
6243// private methods
6244////////////////////////////////////////////////////////////////////////////////
6245
6246/**
6247 * Increases the usage counter of the mpUVM pointer.
6248 *
6249 * Guarantees that VMR3Destroy() will not be called on it at least until
6250 * releaseVMCaller() is called.
6251 *
6252 * If this method returns a failure, the caller is not allowed to use mpUVM and
6253 * may return the failed result code to the upper level. This method sets the
6254 * extended error info on failure if \a aQuiet is false.
6255 *
6256 * Setting \a aQuiet to true is useful for methods that don't want to return
6257 * the failed result code to the caller when this method fails (e.g. need to
6258 * silently check for the mpUVM availability).
6259 *
6260 * When mpUVM is NULL but \a aAllowNullVM is true, a corresponding error will be
6261 * returned instead of asserting. Having it false is intended as a sanity check
6262 * for methods that have checked mMachineState and expect mpUVM *NOT* to be
6263 * NULL.
6264 *
6265 * @param aQuiet true to suppress setting error info
6266 * @param aAllowNullVM true to accept mpUVM being NULL and return a failure
6267 * (otherwise this method will assert if mpUVM is NULL)
6268 *
6269 * @note Locks this object for writing.
6270 */
6271HRESULT Console::addVMCaller(bool aQuiet /* = false */,
6272 bool aAllowNullVM /* = false */)
6273{
6274 AutoCaller autoCaller(this);
6275 /** @todo Fix race during console/VM reference destruction, refer @bugref{6318}
6276 * comment 25. */
6277 if (FAILED(autoCaller.rc()))
6278 return autoCaller.rc();
6279
6280 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6281
6282 if (mVMDestroying)
6283 {
6284 /* powerDown() is waiting for all callers to finish */
6285 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED,
6286 tr("The virtual machine is being powered down"));
6287 }
6288
6289 if (mpUVM == NULL)
6290 {
6291 Assert(aAllowNullVM == true);
6292
6293 /* The machine is not powered up */
6294 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED,
6295 tr("The virtual machine is not powered up"));
6296 }
6297
6298 ++mVMCallers;
6299
6300 return S_OK;
6301}
6302
6303/**
6304 * Decreases the usage counter of the mpUVM pointer.
6305 *
6306 * Must always complete the addVMCaller() call after the mpUVM pointer is no
6307 * more necessary.
6308 *
6309 * @note Locks this object for writing.
6310 */
6311void Console::releaseVMCaller()
6312{
6313 AutoCaller autoCaller(this);
6314 AssertComRCReturnVoid(autoCaller.rc());
6315
6316 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6317
6318 AssertReturnVoid(mpUVM != NULL);
6319
6320 Assert(mVMCallers > 0);
6321 --mVMCallers;
6322
6323 if (mVMCallers == 0 && mVMDestroying)
6324 {
6325 /* inform powerDown() there are no more callers */
6326 RTSemEventSignal(mVMZeroCallersSem);
6327 }
6328}
6329
6330
6331HRESULT Console::safeVMPtrRetainer(PUVM *a_ppUVM, bool a_Quiet)
6332{
6333 *a_ppUVM = NULL;
6334
6335 AutoCaller autoCaller(this);
6336 AssertComRCReturnRC(autoCaller.rc());
6337 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6338
6339 /*
6340 * Repeat the checks done by addVMCaller.
6341 */
6342 if (mVMDestroying) /* powerDown() is waiting for all callers to finish */
6343 return a_Quiet
6344 ? E_ACCESSDENIED
6345 : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
6346 PUVM pUVM = mpUVM;
6347 if (!pUVM)
6348 return a_Quiet
6349 ? E_ACCESSDENIED
6350 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
6351
6352 /*
6353 * Retain a reference to the user mode VM handle and get the global handle.
6354 */
6355 uint32_t cRefs = VMR3RetainUVM(pUVM);
6356 if (cRefs == UINT32_MAX)
6357 return a_Quiet
6358 ? E_ACCESSDENIED
6359 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
6360
6361 /* done */
6362 *a_ppUVM = pUVM;
6363 return S_OK;
6364}
6365
6366void Console::safeVMPtrReleaser(PUVM *a_ppUVM)
6367{
6368 if (*a_ppUVM)
6369 VMR3ReleaseUVM(*a_ppUVM);
6370 *a_ppUVM = NULL;
6371}
6372
6373
6374/**
6375 * Initialize the release logging facility. In case something
6376 * goes wrong, there will be no release logging. Maybe in the future
6377 * we can add some logic to use different file names in this case.
6378 * Note that the logic must be in sync with Machine::DeleteSettings().
6379 */
6380HRESULT Console::consoleInitReleaseLog(const ComPtr<IMachine> aMachine)
6381{
6382 HRESULT hrc = S_OK;
6383
6384 Bstr logFolder;
6385 hrc = aMachine->COMGETTER(LogFolder)(logFolder.asOutParam());
6386 if (FAILED(hrc))
6387 return hrc;
6388
6389 Utf8Str logDir = logFolder;
6390
6391 /* make sure the Logs folder exists */
6392 Assert(logDir.length());
6393 if (!RTDirExists(logDir.c_str()))
6394 RTDirCreateFullPath(logDir.c_str(), 0700);
6395
6396 Utf8Str logFile = Utf8StrFmt("%s%cVBox.log",
6397 logDir.c_str(), RTPATH_DELIMITER);
6398 Utf8Str pngFile = Utf8StrFmt("%s%cVBox.png",
6399 logDir.c_str(), RTPATH_DELIMITER);
6400
6401 /*
6402 * Age the old log files
6403 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
6404 * Overwrite target files in case they exist.
6405 */
6406 ComPtr<IVirtualBox> pVirtualBox;
6407 aMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
6408 ComPtr<ISystemProperties> pSystemProperties;
6409 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
6410 ULONG cHistoryFiles = 3;
6411 pSystemProperties->COMGETTER(LogHistoryCount)(&cHistoryFiles);
6412 if (cHistoryFiles)
6413 {
6414 for (int i = cHistoryFiles-1; i >= 0; i--)
6415 {
6416 Utf8Str *files[] = { &logFile, &pngFile };
6417 Utf8Str oldName, newName;
6418
6419 for (unsigned int j = 0; j < RT_ELEMENTS(files); ++j)
6420 {
6421 if (i > 0)
6422 oldName = Utf8StrFmt("%s.%d", files[j]->c_str(), i);
6423 else
6424 oldName = *files[j];
6425 newName = Utf8StrFmt("%s.%d", files[j]->c_str(), i + 1);
6426 /* If the old file doesn't exist, delete the new file (if it
6427 * exists) to provide correct rotation even if the sequence is
6428 * broken */
6429 if ( RTFileRename(oldName.c_str(), newName.c_str(), RTFILEMOVE_FLAGS_REPLACE)
6430 == VERR_FILE_NOT_FOUND)
6431 RTFileDelete(newName.c_str());
6432 }
6433 }
6434 }
6435
6436 char szError[RTPATH_MAX + 128];
6437 int vrc = com::VBoxLogRelCreate("VM", logFile.c_str(),
6438 RTLOGFLAGS_PREFIX_TIME_PROG | RTLOGFLAGS_RESTRICT_GROUPS,
6439 "all all.restrict -default.restrict",
6440 "VBOX_RELEASE_LOG", RTLOGDEST_FILE,
6441 32768 /* cMaxEntriesPerGroup */,
6442 0 /* cHistory */, 0 /* uHistoryFileTime */,
6443 0 /* uHistoryFileSize */, szError, sizeof(szError));
6444 if (RT_FAILURE(vrc))
6445 hrc = setError(E_FAIL, tr("Failed to open release log (%s, %Rrc)"),
6446 szError, vrc);
6447
6448 /* If we've made any directory changes, flush the directory to increase
6449 the likelihood that the log file will be usable after a system panic.
6450
6451 Tip: Try 'export VBOX_RELEASE_LOG_FLAGS=flush' if the last bits of the log
6452 is missing. Just don't have too high hopes for this to help. */
6453 if (SUCCEEDED(hrc) || cHistoryFiles)
6454 RTDirFlush(logDir.c_str());
6455
6456 return hrc;
6457}
6458
6459/**
6460 * Common worker for PowerUp and PowerUpPaused.
6461 *
6462 * @returns COM status code.
6463 *
6464 * @param aProgress Where to return the progress object.
6465 * @param aPaused true if PowerUpPaused called.
6466 */
6467HRESULT Console::powerUp(IProgress **aProgress, bool aPaused)
6468{
6469
6470 LogFlowThisFuncEnter();
6471
6472 CheckComArgOutPointerValid(aProgress);
6473
6474 AutoCaller autoCaller(this);
6475 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6476
6477 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6478
6479 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
6480 HRESULT rc = S_OK;
6481 ComObjPtr<Progress> pPowerupProgress;
6482 bool fBeganPoweringUp = false;
6483
6484 LONG cOperations = 1;
6485 LONG ulTotalOperationsWeight = 1;
6486
6487 try
6488 {
6489
6490 if (Global::IsOnlineOrTransient(mMachineState))
6491 throw setError(VBOX_E_INVALID_VM_STATE,
6492 tr("The virtual machine is already running or busy (machine state: %s)"),
6493 Global::stringifyMachineState(mMachineState));
6494
6495 /* Set up release logging as early as possible after the check if
6496 * there is already a running VM which we shouldn't disturb. */
6497 rc = consoleInitReleaseLog(mMachine);
6498 if (FAILED(rc))
6499 throw rc;
6500
6501 /* test and clear the TeleporterEnabled property */
6502 BOOL fTeleporterEnabled;
6503 rc = mMachine->COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
6504 if (FAILED(rc))
6505 throw rc;
6506
6507#if 0 /** @todo we should save it afterwards, but that isn't necessarily a good idea. Find a better place for this (VBoxSVC). */
6508 if (fTeleporterEnabled)
6509 {
6510 rc = mMachine->COMSETTER(TeleporterEnabled)(FALSE);
6511 if (FAILED(rc))
6512 throw rc;
6513 }
6514#endif
6515
6516 /* test the FaultToleranceState property */
6517 FaultToleranceState_T enmFaultToleranceState;
6518 rc = mMachine->COMGETTER(FaultToleranceState)(&enmFaultToleranceState);
6519 if (FAILED(rc))
6520 throw rc;
6521 BOOL fFaultToleranceSyncEnabled = (enmFaultToleranceState == FaultToleranceState_Standby);
6522
6523 /* Create a progress object to track progress of this operation. Must
6524 * be done as early as possible (together with BeginPowerUp()) as this
6525 * is vital for communicating as much as possible early powerup
6526 * failure information to the API caller */
6527 pPowerupProgress.createObject();
6528 Bstr progressDesc;
6529 if (mMachineState == MachineState_Saved)
6530 progressDesc = tr("Restoring virtual machine");
6531 else if (fTeleporterEnabled)
6532 progressDesc = tr("Teleporting virtual machine");
6533 else if (fFaultToleranceSyncEnabled)
6534 progressDesc = tr("Fault Tolerance syncing of remote virtual machine");
6535 else
6536 progressDesc = tr("Starting virtual machine");
6537
6538 /* Check all types of shared folders and compose a single list */
6539 SharedFolderDataMap sharedFolders;
6540 {
6541 /* first, insert global folders */
6542 for (SharedFolderDataMap::const_iterator it = m_mapGlobalSharedFolders.begin();
6543 it != m_mapGlobalSharedFolders.end();
6544 ++it)
6545 {
6546 const SharedFolderData &d = it->second;
6547 sharedFolders[it->first] = d;
6548 }
6549
6550 /* second, insert machine folders */
6551 for (SharedFolderDataMap::const_iterator it = m_mapMachineSharedFolders.begin();
6552 it != m_mapMachineSharedFolders.end();
6553 ++it)
6554 {
6555 const SharedFolderData &d = it->second;
6556 sharedFolders[it->first] = d;
6557 }
6558
6559 /* third, insert console folders */
6560 for (SharedFolderMap::const_iterator it = m_mapSharedFolders.begin();
6561 it != m_mapSharedFolders.end();
6562 ++it)
6563 {
6564 SharedFolder *pSF = it->second;
6565 AutoCaller sfCaller(pSF);
6566 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
6567 sharedFolders[it->first] = SharedFolderData(pSF->getHostPath(),
6568 pSF->isWritable(),
6569 pSF->isAutoMounted());
6570 }
6571 }
6572
6573 Bstr savedStateFile;
6574
6575 /*
6576 * Saved VMs will have to prove that their saved states seem kosher.
6577 */
6578 if (mMachineState == MachineState_Saved)
6579 {
6580 rc = mMachine->COMGETTER(StateFilePath)(savedStateFile.asOutParam());
6581 if (FAILED(rc))
6582 throw rc;
6583 ComAssertRet(!savedStateFile.isEmpty(), E_FAIL);
6584 int vrc = SSMR3ValidateFile(Utf8Str(savedStateFile).c_str(), false /* fChecksumIt */);
6585 if (RT_FAILURE(vrc))
6586 throw setError(VBOX_E_FILE_ERROR,
6587 tr("VM cannot start because the saved state file '%ls' is invalid (%Rrc). Delete the saved state prior to starting the VM"),
6588 savedStateFile.raw(), vrc);
6589 }
6590
6591 /* Setup task object and thread to carry out the operaton
6592 * Asycnhronously */
6593 std::auto_ptr<VMPowerUpTask> task(new VMPowerUpTask(this, pPowerupProgress));
6594 ComAssertComRCRetRC(task->rc());
6595
6596 task->mConfigConstructor = configConstructor;
6597 task->mSharedFolders = sharedFolders;
6598 task->mStartPaused = aPaused;
6599 if (mMachineState == MachineState_Saved)
6600 task->mSavedStateFile = savedStateFile;
6601 task->mTeleporterEnabled = fTeleporterEnabled;
6602 task->mEnmFaultToleranceState = enmFaultToleranceState;
6603
6604 /* Reset differencing hard disks for which autoReset is true,
6605 * but only if the machine has no snapshots OR the current snapshot
6606 * is an OFFLINE snapshot; otherwise we would reset the current
6607 * differencing image of an ONLINE snapshot which contains the disk
6608 * state of the machine while it was previously running, but without
6609 * the corresponding machine state, which is equivalent to powering
6610 * off a running machine and not good idea
6611 */
6612 ComPtr<ISnapshot> pCurrentSnapshot;
6613 rc = mMachine->COMGETTER(CurrentSnapshot)(pCurrentSnapshot.asOutParam());
6614 if (FAILED(rc))
6615 throw rc;
6616
6617 BOOL fCurrentSnapshotIsOnline = false;
6618 if (pCurrentSnapshot)
6619 {
6620 rc = pCurrentSnapshot->COMGETTER(Online)(&fCurrentSnapshotIsOnline);
6621 if (FAILED(rc))
6622 throw rc;
6623 }
6624
6625 if (!fCurrentSnapshotIsOnline)
6626 {
6627 LogFlowThisFunc(("Looking for immutable images to reset\n"));
6628
6629 com::SafeIfaceArray<IMediumAttachment> atts;
6630 rc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
6631 if (FAILED(rc))
6632 throw rc;
6633
6634 for (size_t i = 0;
6635 i < atts.size();
6636 ++i)
6637 {
6638 DeviceType_T devType;
6639 rc = atts[i]->COMGETTER(Type)(&devType);
6640 /** @todo later applies to floppies as well */
6641 if (devType == DeviceType_HardDisk)
6642 {
6643 ComPtr<IMedium> pMedium;
6644 rc = atts[i]->COMGETTER(Medium)(pMedium.asOutParam());
6645 if (FAILED(rc))
6646 throw rc;
6647
6648 /* needs autoreset? */
6649 BOOL autoReset = FALSE;
6650 rc = pMedium->COMGETTER(AutoReset)(&autoReset);
6651 if (FAILED(rc))
6652 throw rc;
6653
6654 if (autoReset)
6655 {
6656 ComPtr<IProgress> pResetProgress;
6657 rc = pMedium->Reset(pResetProgress.asOutParam());
6658 if (FAILED(rc))
6659 throw rc;
6660
6661 /* save for later use on the powerup thread */
6662 task->hardDiskProgresses.push_back(pResetProgress);
6663 }
6664 }
6665 }
6666 }
6667 else
6668 LogFlowThisFunc(("Machine has a current snapshot which is online, skipping immutable images reset\n"));
6669
6670 /* setup task object and thread to carry out the operation
6671 * asynchronously */
6672
6673#ifdef VBOX_WITH_EXTPACK
6674 mptrExtPackManager->dumpAllToReleaseLog();
6675#endif
6676
6677#ifdef RT_OS_SOLARIS
6678 /* setup host core dumper for the VM */
6679 Bstr value;
6680 HRESULT hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpEnabled").raw(), value.asOutParam());
6681 if (SUCCEEDED(hrc) && value == "1")
6682 {
6683 Bstr coreDumpDir, coreDumpReplaceSys, coreDumpLive;
6684 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpDir").raw(), coreDumpDir.asOutParam());
6685 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpReplaceSystemDump").raw(), coreDumpReplaceSys.asOutParam());
6686 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpLive").raw(), coreDumpLive.asOutParam());
6687
6688 uint32_t fCoreFlags = 0;
6689 if ( coreDumpReplaceSys.isEmpty() == false
6690 && Utf8Str(coreDumpReplaceSys).toUInt32() == 1)
6691 fCoreFlags |= RTCOREDUMPER_FLAGS_REPLACE_SYSTEM_DUMP;
6692
6693 if ( coreDumpLive.isEmpty() == false
6694 && Utf8Str(coreDumpLive).toUInt32() == 1)
6695 fCoreFlags |= RTCOREDUMPER_FLAGS_LIVE_CORE;
6696
6697 Utf8Str strDumpDir(coreDumpDir);
6698 const char *pszDumpDir = strDumpDir.c_str();
6699 if ( pszDumpDir
6700 && *pszDumpDir == '\0')
6701 pszDumpDir = NULL;
6702
6703 int vrc;
6704 if ( pszDumpDir
6705 && !RTDirExists(pszDumpDir))
6706 {
6707 /*
6708 * Try create the directory.
6709 */
6710 vrc = RTDirCreateFullPath(pszDumpDir, 0700);
6711 if (RT_FAILURE(vrc))
6712 throw setError(E_FAIL, "Failed to setup CoreDumper. Couldn't create dump directory '%s' (%Rrc)\n", pszDumpDir, vrc);
6713 }
6714
6715 vrc = RTCoreDumperSetup(pszDumpDir, fCoreFlags);
6716 if (RT_FAILURE(vrc))
6717 throw setError(E_FAIL, "Failed to setup CoreDumper (%Rrc)", vrc);
6718 else
6719 LogRel(("CoreDumper setup successful. pszDumpDir=%s fFlags=%#x\n", pszDumpDir ? pszDumpDir : ".", fCoreFlags));
6720 }
6721#endif
6722
6723
6724 // If there is immutable drive the process that.
6725 VMPowerUpTask::ProgressList progresses(task->hardDiskProgresses);
6726 if (aProgress && progresses.size() > 0){
6727
6728 for (VMPowerUpTask::ProgressList::const_iterator it = progresses.begin(); it != progresses.end(); ++it)
6729 {
6730 ++cOperations;
6731 ulTotalOperationsWeight += 1;
6732 }
6733 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
6734 progressDesc.raw(),
6735 TRUE, // Cancelable
6736 cOperations,
6737 ulTotalOperationsWeight,
6738 Bstr(tr("Starting Hard Disk operations")).raw(),
6739 1,
6740 NULL);
6741 AssertComRCReturnRC(rc);
6742 }
6743 else if ( mMachineState == MachineState_Saved
6744 || (!fTeleporterEnabled && !fFaultToleranceSyncEnabled))
6745 {
6746 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
6747 progressDesc.raw(),
6748 FALSE /* aCancelable */);
6749 }
6750 else if (fTeleporterEnabled)
6751 {
6752 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
6753 progressDesc.raw(),
6754 TRUE /* aCancelable */,
6755 3 /* cOperations */,
6756 10 /* ulTotalOperationsWeight */,
6757 Bstr(tr("Teleporting virtual machine")).raw(),
6758 1 /* ulFirstOperationWeight */,
6759 NULL);
6760 }
6761 else if (fFaultToleranceSyncEnabled)
6762 {
6763 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
6764 progressDesc.raw(),
6765 TRUE /* aCancelable */,
6766 3 /* cOperations */,
6767 10 /* ulTotalOperationsWeight */,
6768 Bstr(tr("Fault Tolerance syncing of remote virtual machine")).raw(),
6769 1 /* ulFirstOperationWeight */,
6770 NULL);
6771 }
6772
6773 if (FAILED(rc))
6774 throw rc;
6775
6776 /* Tell VBoxSVC and Machine about the progress object so they can
6777 combine/proxy it to any openRemoteSession caller. */
6778 LogFlowThisFunc(("Calling BeginPowerUp...\n"));
6779 rc = mControl->BeginPowerUp(pPowerupProgress);
6780 if (FAILED(rc))
6781 {
6782 LogFlowThisFunc(("BeginPowerUp failed\n"));
6783 throw rc;
6784 }
6785 fBeganPoweringUp = true;
6786
6787 LogFlowThisFunc(("Checking if canceled...\n"));
6788 BOOL fCanceled;
6789 rc = pPowerupProgress->COMGETTER(Canceled)(&fCanceled);
6790 if (FAILED(rc))
6791 throw rc;
6792
6793 if (fCanceled)
6794 {
6795 LogFlowThisFunc(("Canceled in BeginPowerUp\n"));
6796 throw setError(E_FAIL, tr("Powerup was canceled"));
6797 }
6798 LogFlowThisFunc(("Not canceled yet.\n"));
6799
6800 /** @todo this code prevents starting a VM with unavailable bridged
6801 * networking interface. The only benefit is a slightly better error
6802 * message, which should be moved to the driver code. This is the
6803 * only reason why I left the code in for now. The driver allows
6804 * unavailable bridged networking interfaces in certain circumstances,
6805 * and this is sabotaged by this check. The VM will initially have no
6806 * network connectivity, but the user can fix this at runtime. */
6807#if 0
6808 /* the network cards will undergo a quick consistency check */
6809 for (ULONG slot = 0;
6810 slot < maxNetworkAdapters;
6811 ++slot)
6812 {
6813 ComPtr<INetworkAdapter> pNetworkAdapter;
6814 mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
6815 BOOL enabled = FALSE;
6816 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
6817 if (!enabled)
6818 continue;
6819
6820 NetworkAttachmentType_T netattach;
6821 pNetworkAdapter->COMGETTER(AttachmentType)(&netattach);
6822 switch (netattach)
6823 {
6824 case NetworkAttachmentType_Bridged:
6825 {
6826 /* a valid host interface must have been set */
6827 Bstr hostif;
6828 pNetworkAdapter->COMGETTER(HostInterface)(hostif.asOutParam());
6829 if (hostif.isEmpty())
6830 {
6831 throw setError(VBOX_E_HOST_ERROR,
6832 tr("VM cannot start because host interface networking requires a host interface name to be set"));
6833 }
6834 ComPtr<IVirtualBox> pVirtualBox;
6835 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
6836 ComPtr<IHost> pHost;
6837 pVirtualBox->COMGETTER(Host)(pHost.asOutParam());
6838 ComPtr<IHostNetworkInterface> pHostInterface;
6839 if (!SUCCEEDED(pHost->FindHostNetworkInterfaceByName(hostif.raw(),
6840 pHostInterface.asOutParam())))
6841 {
6842 throw setError(VBOX_E_HOST_ERROR,
6843 tr("VM cannot start because the host interface '%ls' does not exist"),
6844 hostif.raw());
6845 }
6846 break;
6847 }
6848 default:
6849 break;
6850 }
6851 }
6852#endif // 0
6853
6854 /* Read console data stored in the saved state file (if not yet done) */
6855 rc = loadDataFromSavedState();
6856 if (FAILED(rc))
6857 throw rc;
6858
6859 /* setup task object and thread to carry out the operation
6860 * asynchronously */
6861 if (aProgress){
6862 rc = pPowerupProgress.queryInterfaceTo(aProgress);
6863 AssertComRCReturnRC(rc);
6864 }
6865
6866 int vrc = RTThreadCreate(NULL, Console::powerUpThread,
6867 (void *)task.get(), 0,
6868 RTTHREADTYPE_MAIN_WORKER, 0, "VMPwrUp");
6869 if (RT_FAILURE(vrc))
6870 throw setError(E_FAIL, "Could not create VMPowerUp thread (%Rrc)", vrc);
6871
6872 /* task is now owned by powerUpThread(), so release it */
6873 task.release();
6874
6875 /* finally, set the state: no right to fail in this method afterwards
6876 * since we've already started the thread and it is now responsible for
6877 * any error reporting and appropriate state change! */
6878 if (mMachineState == MachineState_Saved)
6879 setMachineState(MachineState_Restoring);
6880 else if (fTeleporterEnabled)
6881 setMachineState(MachineState_TeleportingIn);
6882 else if (enmFaultToleranceState == FaultToleranceState_Standby)
6883 setMachineState(MachineState_FaultTolerantSyncing);
6884 else
6885 setMachineState(MachineState_Starting);
6886 }
6887 catch (HRESULT aRC) { rc = aRC; }
6888
6889 if (FAILED(rc) && fBeganPoweringUp)
6890 {
6891
6892 /* The progress object will fetch the current error info */
6893 if (!pPowerupProgress.isNull())
6894 pPowerupProgress->notifyComplete(rc);
6895
6896 /* Save the error info across the IPC below. Can't be done before the
6897 * progress notification above, as saving the error info deletes it
6898 * from the current context, and thus the progress object wouldn't be
6899 * updated correctly. */
6900 ErrorInfoKeeper eik;
6901
6902 /* signal end of operation */
6903 mControl->EndPowerUp(rc);
6904 }
6905
6906 LogFlowThisFunc(("mMachineState=%d, rc=%Rhrc\n", mMachineState, rc));
6907 LogFlowThisFuncLeave();
6908 return rc;
6909}
6910
6911/**
6912 * Internal power off worker routine.
6913 *
6914 * This method may be called only at certain places with the following meaning
6915 * as shown below:
6916 *
6917 * - if the machine state is either Running or Paused, a normal
6918 * Console-initiated powerdown takes place (e.g. PowerDown());
6919 * - if the machine state is Saving, saveStateThread() has successfully done its
6920 * job;
6921 * - if the machine state is Starting or Restoring, powerUpThread() has failed
6922 * to start/load the VM;
6923 * - if the machine state is Stopping, the VM has powered itself off (i.e. not
6924 * as a result of the powerDown() call).
6925 *
6926 * Calling it in situations other than the above will cause unexpected behavior.
6927 *
6928 * Note that this method should be the only one that destroys mpUVM and sets it
6929 * to NULL.
6930 *
6931 * @param aProgress Progress object to run (may be NULL).
6932 *
6933 * @note Locks this object for writing.
6934 *
6935 * @note Never call this method from a thread that called addVMCaller() or
6936 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
6937 * release(). Otherwise it will deadlock.
6938 */
6939HRESULT Console::powerDown(IProgress *aProgress /*= NULL*/)
6940{
6941 LogFlowThisFuncEnter();
6942
6943 AutoCaller autoCaller(this);
6944 AssertComRCReturnRC(autoCaller.rc());
6945
6946 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6947
6948 /* Total # of steps for the progress object. Must correspond to the
6949 * number of "advance percent count" comments in this method! */
6950 enum { StepCount = 7 };
6951 /* current step */
6952 ULONG step = 0;
6953
6954 HRESULT rc = S_OK;
6955 int vrc = VINF_SUCCESS;
6956
6957 /* sanity */
6958 Assert(mVMDestroying == false);
6959
6960 PUVM pUVM = mpUVM; Assert(pUVM != NULL);
6961 uint32_t cRefs = VMR3RetainUVM(pUVM); Assert(cRefs != UINT32_MAX);
6962
6963 AssertMsg( mMachineState == MachineState_Running
6964 || mMachineState == MachineState_Paused
6965 || mMachineState == MachineState_Stuck
6966 || mMachineState == MachineState_Starting
6967 || mMachineState == MachineState_Stopping
6968 || mMachineState == MachineState_Saving
6969 || mMachineState == MachineState_Restoring
6970 || mMachineState == MachineState_TeleportingPausedVM
6971 || mMachineState == MachineState_FaultTolerantSyncing
6972 || mMachineState == MachineState_TeleportingIn
6973 , ("Invalid machine state: %s\n", Global::stringifyMachineState(mMachineState)));
6974
6975 LogRel(("Console::powerDown(): A request to power off the VM has been issued (mMachineState=%s, InUninit=%d)\n",
6976 Global::stringifyMachineState(mMachineState), autoCaller.state() == InUninit));
6977
6978 /* Check if we need to power off the VM. In case of mVMPoweredOff=true, the
6979 * VM has already powered itself off in vmstateChangeCallback() and is just
6980 * notifying Console about that. In case of Starting or Restoring,
6981 * powerUpThread() is calling us on failure, so the VM is already off at
6982 * that point. */
6983 if ( !mVMPoweredOff
6984 && ( mMachineState == MachineState_Starting
6985 || mMachineState == MachineState_Restoring
6986 || mMachineState == MachineState_FaultTolerantSyncing
6987 || mMachineState == MachineState_TeleportingIn)
6988 )
6989 mVMPoweredOff = true;
6990
6991 /*
6992 * Go to Stopping state if not already there.
6993 *
6994 * Note that we don't go from Saving/Restoring to Stopping because
6995 * vmstateChangeCallback() needs it to set the state to Saved on
6996 * VMSTATE_TERMINATED. In terms of protecting from inappropriate operations
6997 * while leaving the lock below, Saving or Restoring should be fine too.
6998 * Ditto for TeleportingPausedVM -> Teleported.
6999 */
7000 if ( mMachineState != MachineState_Saving
7001 && mMachineState != MachineState_Restoring
7002 && mMachineState != MachineState_Stopping
7003 && mMachineState != MachineState_TeleportingIn
7004 && mMachineState != MachineState_TeleportingPausedVM
7005 && mMachineState != MachineState_FaultTolerantSyncing
7006 )
7007 setMachineState(MachineState_Stopping);
7008
7009 /* ----------------------------------------------------------------------
7010 * DONE with necessary state changes, perform the power down actions (it's
7011 * safe to release the object lock now if needed)
7012 * ---------------------------------------------------------------------- */
7013
7014 /* Stop the VRDP server to prevent new clients connection while VM is being
7015 * powered off. */
7016 if (mConsoleVRDPServer)
7017 {
7018 LogFlowThisFunc(("Stopping VRDP server...\n"));
7019
7020 /* Leave the lock since EMT will call us back as addVMCaller()
7021 * in updateDisplayData(). */
7022 alock.release();
7023
7024 mConsoleVRDPServer->Stop();
7025
7026 alock.acquire();
7027 }
7028
7029 /* advance percent count */
7030 if (aProgress)
7031 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount );
7032
7033
7034 /* ----------------------------------------------------------------------
7035 * Now, wait for all mpUVM callers to finish their work if there are still
7036 * some on other threads. NO methods that need mpUVM (or initiate other calls
7037 * that need it) may be called after this point
7038 * ---------------------------------------------------------------------- */
7039
7040 /* go to the destroying state to prevent from adding new callers */
7041 mVMDestroying = true;
7042
7043 if (mVMCallers > 0)
7044 {
7045 /* lazy creation */
7046 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
7047 RTSemEventCreate(&mVMZeroCallersSem);
7048
7049 LogFlowThisFunc(("Waiting for mpUVM callers (%d) to drop to zero...\n", mVMCallers));
7050
7051 alock.release();
7052
7053 RTSemEventWait(mVMZeroCallersSem, RT_INDEFINITE_WAIT);
7054
7055 alock.acquire();
7056 }
7057
7058 /* advance percent count */
7059 if (aProgress)
7060 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount );
7061
7062 vrc = VINF_SUCCESS;
7063
7064 /*
7065 * Power off the VM if not already done that.
7066 * Leave the lock since EMT will call vmstateChangeCallback.
7067 *
7068 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
7069 * VM-(guest-)initiated power off happened in parallel a ms before this
7070 * call. So far, we let this error pop up on the user's side.
7071 */
7072 if (!mVMPoweredOff)
7073 {
7074 LogFlowThisFunc(("Powering off the VM...\n"));
7075 alock.release();
7076 vrc = VMR3PowerOff(pUVM);
7077#ifdef VBOX_WITH_EXTPACK
7078 mptrExtPackManager->callAllVmPowerOffHooks(this, VMR3GetVM(pUVM));
7079#endif
7080 alock.acquire();
7081 }
7082
7083 /* advance percent count */
7084 if (aProgress)
7085 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount );
7086
7087#ifdef VBOX_WITH_HGCM
7088 /* Shutdown HGCM services before destroying the VM. */
7089 if (m_pVMMDev)
7090 {
7091 LogFlowThisFunc(("Shutdown HGCM...\n"));
7092
7093 /* Leave the lock since EMT will call us back as addVMCaller() */
7094 alock.release();
7095
7096 m_pVMMDev->hgcmShutdown();
7097
7098 alock.acquire();
7099 }
7100
7101 /* advance percent count */
7102 if (aProgress)
7103 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount);
7104
7105#endif /* VBOX_WITH_HGCM */
7106
7107 LogFlowThisFunc(("Ready for VM destruction.\n"));
7108
7109 /* If we are called from Console::uninit(), then try to destroy the VM even
7110 * on failure (this will most likely fail too, but what to do?..) */
7111 if (RT_SUCCESS(vrc) || autoCaller.state() == InUninit)
7112 {
7113 /* If the machine has an USB controller, release all USB devices
7114 * (symmetric to the code in captureUSBDevices()) */
7115 bool fHasUSBController = false;
7116 {
7117 PPDMIBASE pBase;
7118 vrc = PDMR3QueryLun(pUVM, "usb-ohci", 0, 0, &pBase);
7119 if (RT_SUCCESS(vrc))
7120 {
7121 fHasUSBController = true;
7122 alock.release();
7123 detachAllUSBDevices(false /* aDone */);
7124 alock.acquire();
7125 }
7126 }
7127
7128 /* Now we've got to destroy the VM as well. (mpUVM is not valid beyond
7129 * this point). We release the lock before calling VMR3Destroy() because
7130 * it will result into calling destructors of drivers associated with
7131 * Console children which may in turn try to lock Console (e.g. by
7132 * instantiating SafeVMPtr to access mpUVM). It's safe here because
7133 * mVMDestroying is set which should prevent any activity. */
7134
7135 /* Set mpUVM to NULL early just in case if some old code is not using
7136 * addVMCaller()/releaseVMCaller(). (We have our own ref on pUVM.) */
7137 VMR3ReleaseUVM(mpUVM);
7138 mpUVM = NULL;
7139
7140 LogFlowThisFunc(("Destroying the VM...\n"));
7141
7142 alock.release();
7143
7144 vrc = VMR3Destroy(pUVM);
7145
7146 /* take the lock again */
7147 alock.acquire();
7148
7149 /* advance percent count */
7150 if (aProgress)
7151 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount);
7152
7153 if (RT_SUCCESS(vrc))
7154 {
7155 LogFlowThisFunc(("Machine has been destroyed (mMachineState=%d)\n",
7156 mMachineState));
7157 /* Note: the Console-level machine state change happens on the
7158 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
7159 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
7160 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
7161 * occurred yet. This is okay, because mMachineState is already
7162 * Stopping in this case, so any other attempt to call PowerDown()
7163 * will be rejected. */
7164 }
7165 else
7166 {
7167 /* bad bad bad, but what to do? (Give Console our UVM ref.) */
7168 mpUVM = pUVM;
7169 pUVM = NULL;
7170 rc = setError(VBOX_E_VM_ERROR,
7171 tr("Could not destroy the machine. (Error: %Rrc)"),
7172 vrc);
7173 }
7174
7175 /* Complete the detaching of the USB devices. */
7176 if (fHasUSBController)
7177 {
7178 alock.release();
7179 detachAllUSBDevices(true /* aDone */);
7180 alock.acquire();
7181 }
7182
7183 /* advance percent count */
7184 if (aProgress)
7185 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount);
7186 }
7187 else
7188 {
7189 rc = setError(VBOX_E_VM_ERROR,
7190 tr("Could not power off the machine. (Error: %Rrc)"),
7191 vrc);
7192 }
7193
7194 /*
7195 * Finished with the destruction.
7196 *
7197 * Note that if something impossible happened and we've failed to destroy
7198 * the VM, mVMDestroying will remain true and mMachineState will be
7199 * something like Stopping, so most Console methods will return an error
7200 * to the caller.
7201 */
7202 if (pUVM != NULL)
7203 VMR3ReleaseUVM(pUVM);
7204 else
7205 mVMDestroying = false;
7206
7207#ifdef CONSOLE_WITH_EVENT_CACHE
7208 if (SUCCEEDED(rc))
7209 mCallbackData.clear();
7210#endif
7211
7212 LogFlowThisFuncLeave();
7213 return rc;
7214}
7215
7216/**
7217 * @note Locks this object for writing.
7218 */
7219HRESULT Console::setMachineState(MachineState_T aMachineState,
7220 bool aUpdateServer /* = true */)
7221{
7222 AutoCaller autoCaller(this);
7223 AssertComRCReturnRC(autoCaller.rc());
7224
7225 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7226
7227 HRESULT rc = S_OK;
7228
7229 if (mMachineState != aMachineState)
7230 {
7231 LogThisFunc(("machineState=%s -> %s aUpdateServer=%RTbool\n",
7232 Global::stringifyMachineState(mMachineState), Global::stringifyMachineState(aMachineState), aUpdateServer));
7233 mMachineState = aMachineState;
7234
7235 /// @todo (dmik)
7236 // possibly, we need to redo onStateChange() using the dedicated
7237 // Event thread, like it is done in VirtualBox. This will make it
7238 // much safer (no deadlocks possible if someone tries to use the
7239 // console from the callback), however, listeners will lose the
7240 // ability to synchronously react to state changes (is it really
7241 // necessary??)
7242 LogFlowThisFunc(("Doing onStateChange()...\n"));
7243 onStateChange(aMachineState);
7244 LogFlowThisFunc(("Done onStateChange()\n"));
7245
7246 if (aUpdateServer)
7247 {
7248 /* Server notification MUST be done from under the lock; otherwise
7249 * the machine state here and on the server might go out of sync
7250 * which can lead to various unexpected results (like the machine
7251 * state being >= MachineState_Running on the server, while the
7252 * session state is already SessionState_Unlocked at the same time
7253 * there).
7254 *
7255 * Cross-lock conditions should be carefully watched out: calling
7256 * UpdateState we will require Machine and SessionMachine locks
7257 * (remember that here we're holding the Console lock here, and also
7258 * all locks that have been acquire by the thread before calling
7259 * this method).
7260 */
7261 LogFlowThisFunc(("Doing mControl->UpdateState()...\n"));
7262 rc = mControl->UpdateState(aMachineState);
7263 LogFlowThisFunc(("mControl->UpdateState()=%Rhrc\n", rc));
7264 }
7265 }
7266
7267 return rc;
7268}
7269
7270/**
7271 * Searches for a shared folder with the given logical name
7272 * in the collection of shared folders.
7273 *
7274 * @param aName logical name of the shared folder
7275 * @param aSharedFolder where to return the found object
7276 * @param aSetError whether to set the error info if the folder is
7277 * not found
7278 * @return
7279 * S_OK when found or E_INVALIDARG when not found
7280 *
7281 * @note The caller must lock this object for writing.
7282 */
7283HRESULT Console::findSharedFolder(const Utf8Str &strName,
7284 ComObjPtr<SharedFolder> &aSharedFolder,
7285 bool aSetError /* = false */)
7286{
7287 /* sanity check */
7288 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7289
7290 SharedFolderMap::const_iterator it = m_mapSharedFolders.find(strName);
7291 if (it != m_mapSharedFolders.end())
7292 {
7293 aSharedFolder = it->second;
7294 return S_OK;
7295 }
7296
7297 if (aSetError)
7298 setError(VBOX_E_FILE_ERROR,
7299 tr("Could not find a shared folder named '%s'."),
7300 strName.c_str());
7301
7302 return VBOX_E_FILE_ERROR;
7303}
7304
7305/**
7306 * Fetches the list of global or machine shared folders from the server.
7307 *
7308 * @param aGlobal true to fetch global folders.
7309 *
7310 * @note The caller must lock this object for writing.
7311 */
7312HRESULT Console::fetchSharedFolders(BOOL aGlobal)
7313{
7314 /* sanity check */
7315 AssertReturn(AutoCaller(this).state() == InInit ||
7316 isWriteLockOnCurrentThread(), E_FAIL);
7317
7318 LogFlowThisFunc(("Entering\n"));
7319
7320 /* Check if we're online and keep it that way. */
7321 SafeVMPtrQuiet ptrVM(this);
7322 AutoVMCallerQuietWeak autoVMCaller(this);
7323 bool const online = ptrVM.isOk()
7324 && m_pVMMDev
7325 && m_pVMMDev->isShFlActive();
7326
7327 HRESULT rc = S_OK;
7328
7329 try
7330 {
7331 if (aGlobal)
7332 {
7333 /// @todo grab & process global folders when they are done
7334 }
7335 else
7336 {
7337 SharedFolderDataMap oldFolders;
7338 if (online)
7339 oldFolders = m_mapMachineSharedFolders;
7340
7341 m_mapMachineSharedFolders.clear();
7342
7343 SafeIfaceArray<ISharedFolder> folders;
7344 rc = mMachine->COMGETTER(SharedFolders)(ComSafeArrayAsOutParam(folders));
7345 if (FAILED(rc)) throw rc;
7346
7347 for (size_t i = 0; i < folders.size(); ++i)
7348 {
7349 ComPtr<ISharedFolder> pSharedFolder = folders[i];
7350
7351 Bstr bstrName;
7352 Bstr bstrHostPath;
7353 BOOL writable;
7354 BOOL autoMount;
7355
7356 rc = pSharedFolder->COMGETTER(Name)(bstrName.asOutParam());
7357 if (FAILED(rc)) throw rc;
7358 Utf8Str strName(bstrName);
7359
7360 rc = pSharedFolder->COMGETTER(HostPath)(bstrHostPath.asOutParam());
7361 if (FAILED(rc)) throw rc;
7362 Utf8Str strHostPath(bstrHostPath);
7363
7364 rc = pSharedFolder->COMGETTER(Writable)(&writable);
7365 if (FAILED(rc)) throw rc;
7366
7367 rc = pSharedFolder->COMGETTER(AutoMount)(&autoMount);
7368 if (FAILED(rc)) throw rc;
7369
7370 m_mapMachineSharedFolders.insert(std::make_pair(strName,
7371 SharedFolderData(strHostPath, !!writable, !!autoMount)));
7372
7373 /* send changes to HGCM if the VM is running */
7374 if (online)
7375 {
7376 SharedFolderDataMap::iterator it = oldFolders.find(strName);
7377 if ( it == oldFolders.end()
7378 || it->second.m_strHostPath != strHostPath)
7379 {
7380 /* a new machine folder is added or
7381 * the existing machine folder is changed */
7382 if (m_mapSharedFolders.find(strName) != m_mapSharedFolders.end())
7383 ; /* the console folder exists, nothing to do */
7384 else
7385 {
7386 /* remove the old machine folder (when changed)
7387 * or the global folder if any (when new) */
7388 if ( it != oldFolders.end()
7389 || m_mapGlobalSharedFolders.find(strName) != m_mapGlobalSharedFolders.end()
7390 )
7391 {
7392 rc = removeSharedFolder(strName);
7393 if (FAILED(rc)) throw rc;
7394 }
7395
7396 /* create the new machine folder */
7397 rc = createSharedFolder(strName,
7398 SharedFolderData(strHostPath, !!writable, !!autoMount));
7399 if (FAILED(rc)) throw rc;
7400 }
7401 }
7402 /* forget the processed (or identical) folder */
7403 if (it != oldFolders.end())
7404 oldFolders.erase(it);
7405 }
7406 }
7407
7408 /* process outdated (removed) folders */
7409 if (online)
7410 {
7411 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
7412 it != oldFolders.end(); ++it)
7413 {
7414 if (m_mapSharedFolders.find(it->first) != m_mapSharedFolders.end())
7415 ; /* the console folder exists, nothing to do */
7416 else
7417 {
7418 /* remove the outdated machine folder */
7419 rc = removeSharedFolder(it->first);
7420 if (FAILED(rc)) throw rc;
7421
7422 /* create the global folder if there is any */
7423 SharedFolderDataMap::const_iterator git =
7424 m_mapGlobalSharedFolders.find(it->first);
7425 if (git != m_mapGlobalSharedFolders.end())
7426 {
7427 rc = createSharedFolder(git->first, git->second);
7428 if (FAILED(rc)) throw rc;
7429 }
7430 }
7431 }
7432 }
7433 }
7434 }
7435 catch (HRESULT rc2)
7436 {
7437 if (online)
7438 setVMRuntimeErrorCallbackF(0, "BrokenSharedFolder",
7439 N_("Broken shared folder!"));
7440 }
7441
7442 LogFlowThisFunc(("Leaving\n"));
7443
7444 return rc;
7445}
7446
7447/**
7448 * Searches for a shared folder with the given name in the list of machine
7449 * shared folders and then in the list of the global shared folders.
7450 *
7451 * @param aName Name of the folder to search for.
7452 * @param aIt Where to store the pointer to the found folder.
7453 * @return @c true if the folder was found and @c false otherwise.
7454 *
7455 * @note The caller must lock this object for reading.
7456 */
7457bool Console::findOtherSharedFolder(const Utf8Str &strName,
7458 SharedFolderDataMap::const_iterator &aIt)
7459{
7460 /* sanity check */
7461 AssertReturn(isWriteLockOnCurrentThread(), false);
7462
7463 /* first, search machine folders */
7464 aIt = m_mapMachineSharedFolders.find(strName);
7465 if (aIt != m_mapMachineSharedFolders.end())
7466 return true;
7467
7468 /* second, search machine folders */
7469 aIt = m_mapGlobalSharedFolders.find(strName);
7470 if (aIt != m_mapGlobalSharedFolders.end())
7471 return true;
7472
7473 return false;
7474}
7475
7476/**
7477 * Calls the HGCM service to add a shared folder definition.
7478 *
7479 * @param aName Shared folder name.
7480 * @param aHostPath Shared folder path.
7481 *
7482 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
7483 * @note Doesn't lock anything.
7484 */
7485HRESULT Console::createSharedFolder(const Utf8Str &strName, const SharedFolderData &aData)
7486{
7487 ComAssertRet(strName.isNotEmpty(), E_FAIL);
7488 ComAssertRet(aData.m_strHostPath.isNotEmpty(), E_FAIL);
7489
7490 /* sanity checks */
7491 AssertReturn(mpUVM, E_FAIL);
7492 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
7493
7494 VBOXHGCMSVCPARM parms[SHFL_CPARMS_ADD_MAPPING];
7495 SHFLSTRING *pFolderName, *pMapName;
7496 size_t cbString;
7497
7498 Bstr value;
7499 HRESULT hrc = mMachine->GetExtraData(BstrFmt("VBoxInternal2/SharedFoldersEnableSymlinksCreate/%s",
7500 strName.c_str()).raw(),
7501 value.asOutParam());
7502 bool fSymlinksCreate = hrc == S_OK && value == "1";
7503
7504 Log(("Adding shared folder '%s' -> '%s'\n", strName.c_str(), aData.m_strHostPath.c_str()));
7505
7506 // check whether the path is valid and exists
7507 char hostPathFull[RTPATH_MAX];
7508 int vrc = RTPathAbsEx(NULL,
7509 aData.m_strHostPath.c_str(),
7510 hostPathFull,
7511 sizeof(hostPathFull));
7512
7513 bool fMissing = false;
7514 if (RT_FAILURE(vrc))
7515 return setError(E_INVALIDARG,
7516 tr("Invalid shared folder path: '%s' (%Rrc)"),
7517 aData.m_strHostPath.c_str(), vrc);
7518 if (!RTPathExists(hostPathFull))
7519 fMissing = true;
7520
7521 /* Check whether the path is full (absolute) */
7522 if (RTPathCompare(aData.m_strHostPath.c_str(), hostPathFull) != 0)
7523 return setError(E_INVALIDARG,
7524 tr("Shared folder path '%s' is not absolute"),
7525 aData.m_strHostPath.c_str());
7526
7527 // now that we know the path is good, give it to HGCM
7528
7529 Bstr bstrName(strName);
7530 Bstr bstrHostPath(aData.m_strHostPath);
7531
7532 cbString = (bstrHostPath.length() + 1) * sizeof(RTUTF16);
7533 if (cbString >= UINT16_MAX)
7534 return setError(E_INVALIDARG, tr("The name is too long"));
7535 pFolderName = (SHFLSTRING*)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
7536 Assert(pFolderName);
7537 memcpy(pFolderName->String.ucs2, bstrHostPath.raw(), cbString);
7538
7539 pFolderName->u16Size = (uint16_t)cbString;
7540 pFolderName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
7541
7542 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
7543 parms[0].u.pointer.addr = pFolderName;
7544 parms[0].u.pointer.size = sizeof(SHFLSTRING) + (uint16_t)cbString;
7545
7546 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
7547 if (cbString >= UINT16_MAX)
7548 {
7549 RTMemFree(pFolderName);
7550 return setError(E_INVALIDARG, tr("The host path is too long"));
7551 }
7552 pMapName = (SHFLSTRING*)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
7553 Assert(pMapName);
7554 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
7555
7556 pMapName->u16Size = (uint16_t)cbString;
7557 pMapName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
7558
7559 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
7560 parms[1].u.pointer.addr = pMapName;
7561 parms[1].u.pointer.size = sizeof(SHFLSTRING) + (uint16_t)cbString;
7562
7563 parms[2].type = VBOX_HGCM_SVC_PARM_32BIT;
7564 parms[2].u.uint32 = (aData.m_fWritable ? SHFL_ADD_MAPPING_F_WRITABLE : 0)
7565 | (aData.m_fAutoMount ? SHFL_ADD_MAPPING_F_AUTOMOUNT : 0)
7566 | (fSymlinksCreate ? SHFL_ADD_MAPPING_F_CREATE_SYMLINKS : 0)
7567 | (fMissing ? SHFL_ADD_MAPPING_F_MISSING : 0)
7568 ;
7569
7570 vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders",
7571 SHFL_FN_ADD_MAPPING,
7572 SHFL_CPARMS_ADD_MAPPING, &parms[0]);
7573 RTMemFree(pFolderName);
7574 RTMemFree(pMapName);
7575
7576 if (RT_FAILURE(vrc))
7577 return setError(E_FAIL,
7578 tr("Could not create a shared folder '%s' mapped to '%s' (%Rrc)"),
7579 strName.c_str(), aData.m_strHostPath.c_str(), vrc);
7580
7581 if (fMissing)
7582 return setError(E_INVALIDARG,
7583 tr("Shared folder path '%s' does not exist on the host"),
7584 aData.m_strHostPath.c_str());
7585
7586 return S_OK;
7587}
7588
7589/**
7590 * Calls the HGCM service to remove the shared folder definition.
7591 *
7592 * @param aName Shared folder name.
7593 *
7594 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
7595 * @note Doesn't lock anything.
7596 */
7597HRESULT Console::removeSharedFolder(const Utf8Str &strName)
7598{
7599 ComAssertRet(strName.isNotEmpty(), E_FAIL);
7600
7601 /* sanity checks */
7602 AssertReturn(mpUVM, E_FAIL);
7603 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
7604
7605 VBOXHGCMSVCPARM parms;
7606 SHFLSTRING *pMapName;
7607 size_t cbString;
7608
7609 Log(("Removing shared folder '%s'\n", strName.c_str()));
7610
7611 Bstr bstrName(strName);
7612 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
7613 if (cbString >= UINT16_MAX)
7614 return setError(E_INVALIDARG, tr("The name is too long"));
7615 pMapName = (SHFLSTRING *) RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
7616 Assert(pMapName);
7617 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
7618
7619 pMapName->u16Size = (uint16_t)cbString;
7620 pMapName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
7621
7622 parms.type = VBOX_HGCM_SVC_PARM_PTR;
7623 parms.u.pointer.addr = pMapName;
7624 parms.u.pointer.size = sizeof(SHFLSTRING) + (uint16_t)cbString;
7625
7626 int vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders",
7627 SHFL_FN_REMOVE_MAPPING,
7628 1, &parms);
7629 RTMemFree(pMapName);
7630 if (RT_FAILURE(vrc))
7631 return setError(E_FAIL,
7632 tr("Could not remove the shared folder '%s' (%Rrc)"),
7633 strName.c_str(), vrc);
7634
7635 return S_OK;
7636}
7637
7638/** @callback_method_impl{FNVMATSTATE}
7639 *
7640 * @note Locks the Console object for writing.
7641 * @remarks The @a pUVM parameter can be NULL in one case where powerUpThread()
7642 * calls after the VM was destroyed.
7643 */
7644DECLCALLBACK(void) Console::vmstateChangeCallback(PUVM pUVM, VMSTATE enmState, VMSTATE enmOldState, void *pvUser)
7645{
7646 LogFlowFunc(("Changing state from %s to %s (pUVM=%p)\n",
7647 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState), pUVM));
7648
7649 Console *that = static_cast<Console *>(pvUser);
7650 AssertReturnVoid(that);
7651
7652 AutoCaller autoCaller(that);
7653
7654 /* Note that we must let this method proceed even if Console::uninit() has
7655 * been already called. In such case this VMSTATE change is a result of:
7656 * 1) powerDown() called from uninit() itself, or
7657 * 2) VM-(guest-)initiated power off. */
7658 AssertReturnVoid( autoCaller.isOk()
7659 || autoCaller.state() == InUninit);
7660
7661 switch (enmState)
7662 {
7663 /*
7664 * The VM has terminated
7665 */
7666 case VMSTATE_OFF:
7667 {
7668 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7669
7670 if (that->mVMStateChangeCallbackDisabled)
7671 break;
7672
7673 /* Do we still think that it is running? It may happen if this is a
7674 * VM-(guest-)initiated shutdown/poweroff.
7675 */
7676 if ( that->mMachineState != MachineState_Stopping
7677 && that->mMachineState != MachineState_Saving
7678 && that->mMachineState != MachineState_Restoring
7679 && that->mMachineState != MachineState_TeleportingIn
7680 && that->mMachineState != MachineState_FaultTolerantSyncing
7681 && that->mMachineState != MachineState_TeleportingPausedVM
7682 && !that->mVMIsAlreadyPoweringOff
7683 )
7684 {
7685 LogFlowFunc(("VM has powered itself off but Console still thinks it is running. Notifying.\n"));
7686
7687 /* prevent powerDown() from calling VMR3PowerOff() again */
7688 Assert(that->mVMPoweredOff == false);
7689 that->mVMPoweredOff = true;
7690
7691 /*
7692 * request a progress object from the server
7693 * (this will set the machine state to Stopping on the server
7694 * to block others from accessing this machine)
7695 */
7696 ComPtr<IProgress> pProgress;
7697 HRESULT rc = that->mControl->BeginPoweringDown(pProgress.asOutParam());
7698 AssertComRC(rc);
7699
7700 /* sync the state with the server */
7701 that->setMachineStateLocally(MachineState_Stopping);
7702
7703 /* Setup task object and thread to carry out the operation
7704 * asynchronously (if we call powerDown() right here but there
7705 * is one or more mpUVM callers (added with addVMCaller()) we'll
7706 * deadlock).
7707 */
7708 std::auto_ptr<VMPowerDownTask> task(new VMPowerDownTask(that, pProgress));
7709
7710 /* If creating a task failed, this can currently mean one of
7711 * two: either Console::uninit() has been called just a ms
7712 * before (so a powerDown() call is already on the way), or
7713 * powerDown() itself is being already executed. Just do
7714 * nothing.
7715 */
7716 if (!task->isOk())
7717 {
7718 LogFlowFunc(("Console is already being uninitialized.\n"));
7719 break;
7720 }
7721
7722 int vrc = RTThreadCreate(NULL, Console::powerDownThread,
7723 (void *)task.get(), 0,
7724 RTTHREADTYPE_MAIN_WORKER, 0,
7725 "VMPwrDwn");
7726 AssertMsgRCBreak(vrc, ("Could not create VMPowerDown thread (%Rrc)\n", vrc));
7727
7728 /* task is now owned by powerDownThread(), so release it */
7729 task.release();
7730 }
7731 break;
7732 }
7733
7734 /* The VM has been completely destroyed.
7735 *
7736 * Note: This state change can happen at two points:
7737 * 1) At the end of VMR3Destroy() if it was not called from EMT.
7738 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
7739 * called by EMT.
7740 */
7741 case VMSTATE_TERMINATED:
7742 {
7743 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7744
7745 if (that->mVMStateChangeCallbackDisabled)
7746 break;
7747
7748 /* Terminate host interface networking. If pUVM is NULL, we've been
7749 * manually called from powerUpThread() either before calling
7750 * VMR3Create() or after VMR3Create() failed, so no need to touch
7751 * networking.
7752 */
7753 if (pUVM)
7754 that->powerDownHostInterfaces();
7755
7756 /* From now on the machine is officially powered down or remains in
7757 * the Saved state.
7758 */
7759 switch (that->mMachineState)
7760 {
7761 default:
7762 AssertFailed();
7763 /* fall through */
7764 case MachineState_Stopping:
7765 /* successfully powered down */
7766 that->setMachineState(MachineState_PoweredOff);
7767 break;
7768 case MachineState_Saving:
7769 /* successfully saved */
7770 that->setMachineState(MachineState_Saved);
7771 break;
7772 case MachineState_Starting:
7773 /* failed to start, but be patient: set back to PoweredOff
7774 * (for similarity with the below) */
7775 that->setMachineState(MachineState_PoweredOff);
7776 break;
7777 case MachineState_Restoring:
7778 /* failed to load the saved state file, but be patient: set
7779 * back to Saved (to preserve the saved state file) */
7780 that->setMachineState(MachineState_Saved);
7781 break;
7782 case MachineState_TeleportingIn:
7783 /* Teleportation failed or was canceled. Back to powered off. */
7784 that->setMachineState(MachineState_PoweredOff);
7785 break;
7786 case MachineState_TeleportingPausedVM:
7787 /* Successfully teleported the VM. */
7788 that->setMachineState(MachineState_Teleported);
7789 break;
7790 case MachineState_FaultTolerantSyncing:
7791 /* Fault tolerant sync failed or was canceled. Back to powered off. */
7792 that->setMachineState(MachineState_PoweredOff);
7793 break;
7794 }
7795 break;
7796 }
7797
7798 case VMSTATE_RESETTING:
7799 {
7800#ifdef VBOX_WITH_GUEST_PROPS
7801 /* Do not take any read/write locks here! */
7802 that->guestPropertiesHandleVMReset();
7803#endif
7804 break;
7805 }
7806
7807 case VMSTATE_SUSPENDED:
7808 {
7809 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7810
7811 if (that->mVMStateChangeCallbackDisabled)
7812 break;
7813
7814 switch (that->mMachineState)
7815 {
7816 case MachineState_Teleporting:
7817 that->setMachineState(MachineState_TeleportingPausedVM);
7818 break;
7819
7820 case MachineState_LiveSnapshotting:
7821 that->setMachineState(MachineState_Saving);
7822 break;
7823
7824 case MachineState_TeleportingPausedVM:
7825 case MachineState_Saving:
7826 case MachineState_Restoring:
7827 case MachineState_Stopping:
7828 case MachineState_TeleportingIn:
7829 case MachineState_FaultTolerantSyncing:
7830 /* The worker thread handles the transition. */
7831 break;
7832
7833 default:
7834 AssertMsgFailed(("%s\n", Global::stringifyMachineState(that->mMachineState)));
7835 case MachineState_Running:
7836 that->setMachineState(MachineState_Paused);
7837 break;
7838
7839 case MachineState_Paused:
7840 /* Nothing to do. */
7841 break;
7842 }
7843 break;
7844 }
7845
7846 case VMSTATE_SUSPENDED_LS:
7847 case VMSTATE_SUSPENDED_EXT_LS:
7848 {
7849 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7850 if (that->mVMStateChangeCallbackDisabled)
7851 break;
7852 switch (that->mMachineState)
7853 {
7854 case MachineState_Teleporting:
7855 that->setMachineState(MachineState_TeleportingPausedVM);
7856 break;
7857
7858 case MachineState_LiveSnapshotting:
7859 that->setMachineState(MachineState_Saving);
7860 break;
7861
7862 case MachineState_TeleportingPausedVM:
7863 case MachineState_Saving:
7864 /* ignore */
7865 break;
7866
7867 default:
7868 AssertMsgFailed(("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState), VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
7869 that->setMachineState(MachineState_Paused);
7870 break;
7871 }
7872 break;
7873 }
7874
7875 case VMSTATE_RUNNING:
7876 {
7877 if ( enmOldState == VMSTATE_POWERING_ON
7878 || enmOldState == VMSTATE_RESUMING
7879 || enmOldState == VMSTATE_RUNNING_FT)
7880 {
7881 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7882
7883 if (that->mVMStateChangeCallbackDisabled)
7884 break;
7885
7886 Assert( ( ( that->mMachineState == MachineState_Starting
7887 || that->mMachineState == MachineState_Paused)
7888 && enmOldState == VMSTATE_POWERING_ON)
7889 || ( ( that->mMachineState == MachineState_Restoring
7890 || that->mMachineState == MachineState_TeleportingIn
7891 || that->mMachineState == MachineState_Paused
7892 || that->mMachineState == MachineState_Saving
7893 )
7894 && enmOldState == VMSTATE_RESUMING)
7895 || ( that->mMachineState == MachineState_FaultTolerantSyncing
7896 && enmOldState == VMSTATE_RUNNING_FT));
7897
7898 that->setMachineState(MachineState_Running);
7899 }
7900
7901 break;
7902 }
7903
7904 case VMSTATE_RUNNING_LS:
7905 AssertMsg( that->mMachineState == MachineState_LiveSnapshotting
7906 || that->mMachineState == MachineState_Teleporting,
7907 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState), VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
7908 break;
7909
7910 case VMSTATE_RUNNING_FT:
7911 AssertMsg(that->mMachineState == MachineState_FaultTolerantSyncing,
7912 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState), VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
7913 break;
7914
7915 case VMSTATE_FATAL_ERROR:
7916 {
7917 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7918
7919 if (that->mVMStateChangeCallbackDisabled)
7920 break;
7921
7922 /* Fatal errors are only for running VMs. */
7923 Assert(Global::IsOnline(that->mMachineState));
7924
7925 /* Note! 'Pause' is used here in want of something better. There
7926 * are currently only two places where fatal errors might be
7927 * raised, so it is not worth adding a new externally
7928 * visible state for this yet. */
7929 that->setMachineState(MachineState_Paused);
7930 break;
7931 }
7932
7933 case VMSTATE_GURU_MEDITATION:
7934 {
7935 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7936
7937 if (that->mVMStateChangeCallbackDisabled)
7938 break;
7939
7940 /* Guru are only for running VMs */
7941 Assert(Global::IsOnline(that->mMachineState));
7942
7943 that->setMachineState(MachineState_Stuck);
7944 break;
7945 }
7946
7947 default: /* shut up gcc */
7948 break;
7949 }
7950}
7951
7952/**
7953 * Changes the clipboard mode.
7954 *
7955 * @param aClipboardMode new clipboard mode.
7956 */
7957void Console::changeClipboardMode(ClipboardMode_T aClipboardMode)
7958{
7959 VMMDev *pVMMDev = m_pVMMDev;
7960 Assert(pVMMDev);
7961
7962 VBOXHGCMSVCPARM parm;
7963 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
7964
7965 switch (aClipboardMode)
7966 {
7967 default:
7968 case ClipboardMode_Disabled:
7969 LogRel(("Shared clipboard mode: Off\n"));
7970 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_OFF;
7971 break;
7972 case ClipboardMode_GuestToHost:
7973 LogRel(("Shared clipboard mode: Guest to Host\n"));
7974 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_GUEST_TO_HOST;
7975 break;
7976 case ClipboardMode_HostToGuest:
7977 LogRel(("Shared clipboard mode: Host to Guest\n"));
7978 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_HOST_TO_GUEST;
7979 break;
7980 case ClipboardMode_Bidirectional:
7981 LogRel(("Shared clipboard mode: Bidirectional\n"));
7982 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_BIDIRECTIONAL;
7983 break;
7984 }
7985
7986 pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE, 1, &parm);
7987}
7988
7989/**
7990 * Changes the drag'n_drop mode.
7991 *
7992 * @param aDragAndDropMode new drag'n'drop mode.
7993 */
7994void Console::changeDragAndDropMode(DragAndDropMode_T aDragAndDropMode)
7995{
7996 VMMDev *pVMMDev = m_pVMMDev;
7997 Assert(pVMMDev);
7998
7999 VBOXHGCMSVCPARM parm;
8000 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
8001
8002 switch (aDragAndDropMode)
8003 {
8004 default:
8005 case DragAndDropMode_Disabled:
8006 LogRel(("Drag'n'drop mode: Off\n"));
8007 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_OFF;
8008 break;
8009 case DragAndDropMode_GuestToHost:
8010 LogRel(("Drag'n'drop mode: Guest to Host\n"));
8011 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_GUEST_TO_HOST;
8012 break;
8013 case DragAndDropMode_HostToGuest:
8014 LogRel(("Drag'n'drop mode: Host to Guest\n"));
8015 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_HOST_TO_GUEST;
8016 break;
8017 case DragAndDropMode_Bidirectional:
8018 LogRel(("Drag'n'drop mode: Bidirectional\n"));
8019 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_BIDIRECTIONAL;
8020 break;
8021 }
8022
8023 pVMMDev->hgcmHostCall("VBoxDragAndDropSvc", DragAndDropSvc::HOST_DND_SET_MODE, 1, &parm);
8024}
8025
8026#ifdef VBOX_WITH_USB
8027/**
8028 * Sends a request to VMM to attach the given host device.
8029 * After this method succeeds, the attached device will appear in the
8030 * mUSBDevices collection.
8031 *
8032 * @param aHostDevice device to attach
8033 *
8034 * @note Synchronously calls EMT.
8035 */
8036HRESULT Console::attachUSBDevice(IUSBDevice *aHostDevice, ULONG aMaskedIfs)
8037{
8038 AssertReturn(aHostDevice, E_FAIL);
8039 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
8040
8041 HRESULT hrc;
8042
8043 /*
8044 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
8045 * method in EMT (using usbAttachCallback()).
8046 */
8047 Bstr BstrAddress;
8048 hrc = aHostDevice->COMGETTER(Address)(BstrAddress.asOutParam());
8049 ComAssertComRCRetRC(hrc);
8050
8051 Utf8Str Address(BstrAddress);
8052
8053 Bstr id;
8054 hrc = aHostDevice->COMGETTER(Id)(id.asOutParam());
8055 ComAssertComRCRetRC(hrc);
8056 Guid uuid(id);
8057
8058 BOOL fRemote = FALSE;
8059 hrc = aHostDevice->COMGETTER(Remote)(&fRemote);
8060 ComAssertComRCRetRC(hrc);
8061
8062 /* Get the VM handle. */
8063 SafeVMPtr ptrVM(this);
8064 if (!ptrVM.isOk())
8065 return ptrVM.rc();
8066
8067 LogFlowThisFunc(("Proxying USB device '%s' {%RTuuid}...\n",
8068 Address.c_str(), uuid.raw()));
8069
8070 void *pvRemoteBackend = NULL;
8071 if (fRemote)
8072 {
8073 RemoteUSBDevice *pRemoteUSBDevice = static_cast<RemoteUSBDevice *>(aHostDevice);
8074 pvRemoteBackend = consoleVRDPServer()->USBBackendRequestPointer(pRemoteUSBDevice->clientId(), &uuid);
8075 if (!pvRemoteBackend)
8076 return E_INVALIDARG; /* The clientId is invalid then. */
8077 }
8078
8079 USHORT portVersion = 1;
8080 hrc = aHostDevice->COMGETTER(PortVersion)(&portVersion);
8081 AssertComRCReturnRC(hrc);
8082 Assert(portVersion == 1 || portVersion == 2);
8083
8084 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
8085 (PFNRT)usbAttachCallback, 9,
8086 this, ptrVM.rawUVM(), aHostDevice, uuid.raw(), fRemote,
8087 Address.c_str(), pvRemoteBackend, portVersion, aMaskedIfs);
8088
8089 if (RT_SUCCESS(vrc))
8090 {
8091 /* Create a OUSBDevice and add it to the device list */
8092 ComObjPtr<OUSBDevice> pUSBDevice;
8093 pUSBDevice.createObject();
8094 hrc = pUSBDevice->init(aHostDevice);
8095 AssertComRC(hrc);
8096
8097 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8098 mUSBDevices.push_back(pUSBDevice);
8099 LogFlowFunc(("Attached device {%RTuuid}\n", pUSBDevice->id().raw()));
8100
8101 /* notify callbacks */
8102 alock.release();
8103 onUSBDeviceStateChange(pUSBDevice, true /* aAttached */, NULL);
8104 }
8105 else
8106 {
8107 LogWarningThisFunc(("Failed to create proxy device for '%s' {%RTuuid} (%Rrc)\n",
8108 Address.c_str(), uuid.raw(), vrc));
8109
8110 switch (vrc)
8111 {
8112 case VERR_VUSB_NO_PORTS:
8113 hrc = setError(E_FAIL, tr("Failed to attach the USB device. (No available ports on the USB controller)."));
8114 break;
8115 case VERR_VUSB_USBFS_PERMISSION:
8116 hrc = setError(E_FAIL, tr("Not permitted to open the USB device, check usbfs options"));
8117 break;
8118 default:
8119 hrc = setError(E_FAIL, tr("Failed to create a proxy device for the USB device. (Error: %Rrc)"), vrc);
8120 break;
8121 }
8122 }
8123
8124 return hrc;
8125}
8126
8127/**
8128 * USB device attach callback used by AttachUSBDevice().
8129 * Note that AttachUSBDevice() doesn't return until this callback is executed,
8130 * so we don't use AutoCaller and don't care about reference counters of
8131 * interface pointers passed in.
8132 *
8133 * @thread EMT
8134 * @note Locks the console object for writing.
8135 */
8136//static
8137DECLCALLBACK(int)
8138Console::usbAttachCallback(Console *that, PUVM pUVM, IUSBDevice *aHostDevice, PCRTUUID aUuid, bool aRemote,
8139 const char *aAddress, void *pvRemoteBackend, USHORT aPortVersion, ULONG aMaskedIfs)
8140{
8141 LogFlowFuncEnter();
8142 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
8143
8144 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
8145 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
8146
8147 int vrc = PDMR3UsbCreateProxyDevice(pUVM, aUuid, aRemote, aAddress, pvRemoteBackend,
8148 aPortVersion == 1 ? VUSB_STDVER_11 : VUSB_STDVER_20, aMaskedIfs);
8149 LogFlowFunc(("vrc=%Rrc\n", vrc));
8150 LogFlowFuncLeave();
8151 return vrc;
8152}
8153
8154/**
8155 * Sends a request to VMM to detach the given host device. After this method
8156 * succeeds, the detached device will disappear from the mUSBDevices
8157 * collection.
8158 *
8159 * @param aHostDevice device to attach
8160 *
8161 * @note Synchronously calls EMT.
8162 */
8163HRESULT Console::detachUSBDevice(const ComObjPtr<OUSBDevice> &aHostDevice)
8164{
8165 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
8166
8167 /* Get the VM handle. */
8168 SafeVMPtr ptrVM(this);
8169 if (!ptrVM.isOk())
8170 return ptrVM.rc();
8171
8172 /* if the device is attached, then there must at least one USB hub. */
8173 AssertReturn(PDMR3UsbHasHub(ptrVM.rawUVM()), E_FAIL);
8174
8175 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8176 LogFlowThisFunc(("Detaching USB proxy device {%RTuuid}...\n",
8177 aHostDevice->id().raw()));
8178
8179 /*
8180 * If this was a remote device, release the backend pointer.
8181 * The pointer was requested in usbAttachCallback.
8182 */
8183 BOOL fRemote = FALSE;
8184
8185 HRESULT hrc2 = aHostDevice->COMGETTER(Remote)(&fRemote);
8186 if (FAILED(hrc2))
8187 setErrorStatic(hrc2, "GetRemote() failed");
8188
8189 PCRTUUID pUuid = aHostDevice->id().raw();
8190 if (fRemote)
8191 {
8192 Guid guid(*pUuid);
8193 consoleVRDPServer()->USBBackendReleasePointer(&guid);
8194 }
8195
8196 alock.release();
8197 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
8198 (PFNRT)usbDetachCallback, 5,
8199 this, ptrVM.rawUVM(), pUuid);
8200 if (RT_SUCCESS(vrc))
8201 {
8202 LogFlowFunc(("Detached device {%RTuuid}\n", pUuid));
8203
8204 /* notify callbacks */
8205 onUSBDeviceStateChange(aHostDevice, false /* aAttached */, NULL);
8206 }
8207
8208 ComAssertRCRet(vrc, E_FAIL);
8209
8210 return S_OK;
8211}
8212
8213/**
8214 * USB device detach callback used by DetachUSBDevice().
8215 *
8216 * Note that DetachUSBDevice() doesn't return until this callback is executed,
8217 * so we don't use AutoCaller and don't care about reference counters of
8218 * interface pointers passed in.
8219 *
8220 * @thread EMT
8221 */
8222//static
8223DECLCALLBACK(int)
8224Console::usbDetachCallback(Console *that, PUVM pUVM, PCRTUUID aUuid)
8225{
8226 LogFlowFuncEnter();
8227 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
8228
8229 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
8230 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
8231
8232 int vrc = PDMR3UsbDetachDevice(pUVM, aUuid);
8233
8234 LogFlowFunc(("vrc=%Rrc\n", vrc));
8235 LogFlowFuncLeave();
8236 return vrc;
8237}
8238#endif /* VBOX_WITH_USB */
8239
8240/* Note: FreeBSD needs this whether netflt is used or not. */
8241#if ((defined(RT_OS_LINUX) && !defined(VBOX_WITH_NETFLT)) || defined(RT_OS_FREEBSD))
8242/**
8243 * Helper function to handle host interface device creation and attachment.
8244 *
8245 * @param networkAdapter the network adapter which attachment should be reset
8246 * @return COM status code
8247 *
8248 * @note The caller must lock this object for writing.
8249 *
8250 * @todo Move this back into the driver!
8251 */
8252HRESULT Console::attachToTapInterface(INetworkAdapter *networkAdapter)
8253{
8254 LogFlowThisFunc(("\n"));
8255 /* sanity check */
8256 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8257
8258# ifdef VBOX_STRICT
8259 /* paranoia */
8260 NetworkAttachmentType_T attachment;
8261 networkAdapter->COMGETTER(AttachmentType)(&attachment);
8262 Assert(attachment == NetworkAttachmentType_Bridged);
8263# endif /* VBOX_STRICT */
8264
8265 HRESULT rc = S_OK;
8266
8267 ULONG slot = 0;
8268 rc = networkAdapter->COMGETTER(Slot)(&slot);
8269 AssertComRC(rc);
8270
8271# ifdef RT_OS_LINUX
8272 /*
8273 * Allocate a host interface device
8274 */
8275 int rcVBox = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
8276 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
8277 if (RT_SUCCESS(rcVBox))
8278 {
8279 /*
8280 * Set/obtain the tap interface.
8281 */
8282 struct ifreq IfReq;
8283 memset(&IfReq, 0, sizeof(IfReq));
8284 /* The name of the TAP interface we are using */
8285 Bstr tapDeviceName;
8286 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
8287 if (FAILED(rc))
8288 tapDeviceName.setNull(); /* Is this necessary? */
8289 if (tapDeviceName.isEmpty())
8290 {
8291 LogRel(("No TAP device name was supplied.\n"));
8292 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
8293 }
8294
8295 if (SUCCEEDED(rc))
8296 {
8297 /* If we are using a static TAP device then try to open it. */
8298 Utf8Str str(tapDeviceName);
8299 if (str.length() <= sizeof(IfReq.ifr_name))
8300 strcpy(IfReq.ifr_name, str.c_str());
8301 else
8302 memcpy(IfReq.ifr_name, str.c_str(), sizeof(IfReq.ifr_name) - 1); /** @todo bitch about names which are too long... */
8303 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
8304 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
8305 if (rcVBox != 0)
8306 {
8307 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
8308 rc = setError(E_FAIL,
8309 tr("Failed to open the host network interface %ls"),
8310 tapDeviceName.raw());
8311 }
8312 }
8313 if (SUCCEEDED(rc))
8314 {
8315 /*
8316 * Make it pollable.
8317 */
8318 if (fcntl(maTapFD[slot], F_SETFL, O_NONBLOCK) != -1)
8319 {
8320 Log(("attachToTapInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
8321 /*
8322 * Here is the right place to communicate the TAP file descriptor and
8323 * the host interface name to the server if/when it becomes really
8324 * necessary.
8325 */
8326 maTAPDeviceName[slot] = tapDeviceName;
8327 rcVBox = VINF_SUCCESS;
8328 }
8329 else
8330 {
8331 int iErr = errno;
8332
8333 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
8334 rcVBox = VERR_HOSTIF_BLOCKING;
8335 rc = setError(E_FAIL,
8336 tr("could not set up the host networking device for non blocking access: %s"),
8337 strerror(errno));
8338 }
8339 }
8340 }
8341 else
8342 {
8343 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Rrc\n", rcVBox));
8344 switch (rcVBox)
8345 {
8346 case VERR_ACCESS_DENIED:
8347 /* will be handled by our caller */
8348 rc = rcVBox;
8349 break;
8350 default:
8351 rc = setError(E_FAIL,
8352 tr("Could not set up the host networking device: %Rrc"),
8353 rcVBox);
8354 break;
8355 }
8356 }
8357
8358# elif defined(RT_OS_FREEBSD)
8359 /*
8360 * Set/obtain the tap interface.
8361 */
8362 /* The name of the TAP interface we are using */
8363 Bstr tapDeviceName;
8364 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
8365 if (FAILED(rc))
8366 tapDeviceName.setNull(); /* Is this necessary? */
8367 if (tapDeviceName.isEmpty())
8368 {
8369 LogRel(("No TAP device name was supplied.\n"));
8370 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
8371 }
8372 char szTapdev[1024] = "/dev/";
8373 /* If we are using a static TAP device then try to open it. */
8374 Utf8Str str(tapDeviceName);
8375 if (str.length() + strlen(szTapdev) <= sizeof(szTapdev))
8376 strcat(szTapdev, str.c_str());
8377 else
8378 memcpy(szTapdev + strlen(szTapdev), str.c_str(),
8379 sizeof(szTapdev) - strlen(szTapdev) - 1); /** @todo bitch about names which are too long... */
8380 int rcVBox = RTFileOpen(&maTapFD[slot], szTapdev,
8381 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT | RTFILE_O_NON_BLOCK);
8382
8383 if (RT_SUCCESS(rcVBox))
8384 maTAPDeviceName[slot] = tapDeviceName;
8385 else
8386 {
8387 switch (rcVBox)
8388 {
8389 case VERR_ACCESS_DENIED:
8390 /* will be handled by our caller */
8391 rc = rcVBox;
8392 break;
8393 default:
8394 rc = setError(E_FAIL,
8395 tr("Failed to open the host network interface %ls"),
8396 tapDeviceName.raw());
8397 break;
8398 }
8399 }
8400# else
8401# error "huh?"
8402# endif
8403 /* in case of failure, cleanup. */
8404 if (RT_FAILURE(rcVBox) && SUCCEEDED(rc))
8405 {
8406 LogRel(("General failure attaching to host interface\n"));
8407 rc = setError(E_FAIL,
8408 tr("General failure attaching to host interface"));
8409 }
8410 LogFlowThisFunc(("rc=%d\n", rc));
8411 return rc;
8412}
8413
8414
8415/**
8416 * Helper function to handle detachment from a host interface
8417 *
8418 * @param networkAdapter the network adapter which attachment should be reset
8419 * @return COM status code
8420 *
8421 * @note The caller must lock this object for writing.
8422 *
8423 * @todo Move this back into the driver!
8424 */
8425HRESULT Console::detachFromTapInterface(INetworkAdapter *networkAdapter)
8426{
8427 /* sanity check */
8428 LogFlowThisFunc(("\n"));
8429 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8430
8431 HRESULT rc = S_OK;
8432# ifdef VBOX_STRICT
8433 /* paranoia */
8434 NetworkAttachmentType_T attachment;
8435 networkAdapter->COMGETTER(AttachmentType)(&attachment);
8436 Assert(attachment == NetworkAttachmentType_Bridged);
8437# endif /* VBOX_STRICT */
8438
8439 ULONG slot = 0;
8440 rc = networkAdapter->COMGETTER(Slot)(&slot);
8441 AssertComRC(rc);
8442
8443 /* is there an open TAP device? */
8444 if (maTapFD[slot] != NIL_RTFILE)
8445 {
8446 /*
8447 * Close the file handle.
8448 */
8449 Bstr tapDeviceName, tapTerminateApplication;
8450 bool isStatic = true;
8451 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
8452 if (FAILED(rc) || tapDeviceName.isEmpty())
8453 {
8454 /* If the name is empty, this is a dynamic TAP device, so close it now,
8455 so that the termination script can remove the interface. Otherwise we still
8456 need the FD to pass to the termination script. */
8457 isStatic = false;
8458 int rcVBox = RTFileClose(maTapFD[slot]);
8459 AssertRC(rcVBox);
8460 maTapFD[slot] = NIL_RTFILE;
8461 }
8462 if (isStatic)
8463 {
8464 /* If we are using a static TAP device, we close it now, after having called the
8465 termination script. */
8466 int rcVBox = RTFileClose(maTapFD[slot]);
8467 AssertRC(rcVBox);
8468 }
8469 /* the TAP device name and handle are no longer valid */
8470 maTapFD[slot] = NIL_RTFILE;
8471 maTAPDeviceName[slot] = "";
8472 }
8473 LogFlowThisFunc(("returning %d\n", rc));
8474 return rc;
8475}
8476#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
8477
8478/**
8479 * Called at power down to terminate host interface networking.
8480 *
8481 * @note The caller must lock this object for writing.
8482 */
8483HRESULT Console::powerDownHostInterfaces()
8484{
8485 LogFlowThisFunc(("\n"));
8486
8487 /* sanity check */
8488 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8489
8490 /*
8491 * host interface termination handling
8492 */
8493 HRESULT rc = S_OK;
8494 ComPtr<IVirtualBox> pVirtualBox;
8495 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
8496 ComPtr<ISystemProperties> pSystemProperties;
8497 if (pVirtualBox)
8498 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
8499 ChipsetType_T chipsetType = ChipsetType_PIIX3;
8500 mMachine->COMGETTER(ChipsetType)(&chipsetType);
8501 ULONG maxNetworkAdapters = 0;
8502 if (pSystemProperties)
8503 pSystemProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
8504
8505 for (ULONG slot = 0; slot < maxNetworkAdapters; slot++)
8506 {
8507 ComPtr<INetworkAdapter> pNetworkAdapter;
8508 rc = mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
8509 if (FAILED(rc)) break;
8510
8511 BOOL enabled = FALSE;
8512 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
8513 if (!enabled)
8514 continue;
8515
8516 NetworkAttachmentType_T attachment;
8517 pNetworkAdapter->COMGETTER(AttachmentType)(&attachment);
8518 if (attachment == NetworkAttachmentType_Bridged)
8519 {
8520#if ((defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT))
8521 HRESULT rc2 = detachFromTapInterface(pNetworkAdapter);
8522 if (FAILED(rc2) && SUCCEEDED(rc))
8523 rc = rc2;
8524#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
8525 }
8526 }
8527
8528 return rc;
8529}
8530
8531
8532/**
8533 * Process callback handler for VMR3LoadFromFile, VMR3LoadFromStream, VMR3Save
8534 * and VMR3Teleport.
8535 *
8536 * @param pUVM The user mode VM handle.
8537 * @param uPercent Completion percentage (0-100).
8538 * @param pvUser Pointer to an IProgress instance.
8539 * @return VINF_SUCCESS.
8540 */
8541/*static*/
8542DECLCALLBACK(int) Console::stateProgressCallback(PUVM pUVM, unsigned uPercent, void *pvUser)
8543{
8544 IProgress *pProgress = static_cast<IProgress *>(pvUser);
8545
8546 /* update the progress object */
8547 if (pProgress)
8548 pProgress->SetCurrentOperationProgress(uPercent);
8549
8550 NOREF(pUVM);
8551 return VINF_SUCCESS;
8552}
8553
8554/**
8555 * @copydoc FNVMATERROR
8556 *
8557 * @remarks Might be some tiny serialization concerns with access to the string
8558 * object here...
8559 */
8560/*static*/ DECLCALLBACK(void)
8561Console::genericVMSetErrorCallback(PUVM pUVM, void *pvUser, int rc, RT_SRC_POS_DECL,
8562 const char *pszErrorFmt, va_list va)
8563{
8564 Utf8Str *pErrorText = (Utf8Str *)pvUser;
8565 AssertPtr(pErrorText);
8566
8567 /* We ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users. */
8568 va_list va2;
8569 va_copy(va2, va);
8570
8571 /* Append to any the existing error message. */
8572 if (pErrorText->length())
8573 *pErrorText = Utf8StrFmt("%s.\n%N (%Rrc)", pErrorText->c_str(),
8574 pszErrorFmt, &va2, rc, rc);
8575 else
8576 *pErrorText = Utf8StrFmt("%N (%Rrc)", pszErrorFmt, &va2, rc, rc);
8577
8578 va_end(va2);
8579
8580 NOREF(pUVM);
8581}
8582
8583/**
8584 * VM runtime error callback function.
8585 * See VMSetRuntimeError for the detailed description of parameters.
8586 *
8587 * @param pUVM The user mode VM handle. Ignored, so passing NULL
8588 * is fine.
8589 * @param pvUser The user argument, pointer to the Console instance.
8590 * @param fFlags The action flags. See VMSETRTERR_FLAGS_*.
8591 * @param pszErrorId Error ID string.
8592 * @param pszFormat Error message format string.
8593 * @param va Error message arguments.
8594 * @thread EMT.
8595 */
8596/* static */ DECLCALLBACK(void)
8597Console::setVMRuntimeErrorCallback(PUVM pUVM, void *pvUser, uint32_t fFlags,
8598 const char *pszErrorId,
8599 const char *pszFormat, va_list va)
8600{
8601 bool const fFatal = !!(fFlags & VMSETRTERR_FLAGS_FATAL);
8602 LogFlowFuncEnter();
8603
8604 Console *that = static_cast<Console *>(pvUser);
8605 AssertReturnVoid(that);
8606
8607 Utf8Str message(pszFormat, va);
8608
8609 LogRel(("Console: VM runtime error: fatal=%RTbool, errorID=%s message=\"%s\"\n",
8610 fFatal, pszErrorId, message.c_str()));
8611
8612 that->onRuntimeError(BOOL(fFatal), Bstr(pszErrorId).raw(), Bstr(message).raw());
8613
8614 LogFlowFuncLeave(); NOREF(pUVM);
8615}
8616
8617/**
8618 * Captures USB devices that match filters of the VM.
8619 * Called at VM startup.
8620 *
8621 * @param pUVM The VM handle.
8622 */
8623HRESULT Console::captureUSBDevices(PUVM pUVM)
8624{
8625 LogFlowThisFunc(("\n"));
8626
8627 /* sanity check */
8628 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
8629 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8630
8631 /* If the machine has an USB controller, ask the USB proxy service to
8632 * capture devices */
8633 PPDMIBASE pBase;
8634 int vrc = PDMR3QueryLun(pUVM, "usb-ohci", 0, 0, &pBase);
8635 if (RT_SUCCESS(vrc))
8636 {
8637 /* release the lock before calling Host in VBoxSVC since Host may call
8638 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
8639 * produce an inter-process dead-lock otherwise. */
8640 alock.release();
8641
8642 HRESULT hrc = mControl->AutoCaptureUSBDevices();
8643 ComAssertComRCRetRC(hrc);
8644 }
8645 else if ( vrc == VERR_PDM_DEVICE_NOT_FOUND
8646 || vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
8647 vrc = VINF_SUCCESS;
8648 else
8649 AssertRC(vrc);
8650
8651 return RT_SUCCESS(vrc) ? S_OK : E_FAIL;
8652}
8653
8654
8655/**
8656 * Detach all USB device which are attached to the VM for the
8657 * purpose of clean up and such like.
8658 */
8659void Console::detachAllUSBDevices(bool aDone)
8660{
8661 LogFlowThisFunc(("aDone=%RTbool\n", aDone));
8662
8663 /* sanity check */
8664 AssertReturnVoid(!isWriteLockOnCurrentThread());
8665 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8666
8667 mUSBDevices.clear();
8668
8669 /* release the lock before calling Host in VBoxSVC since Host may call
8670 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
8671 * produce an inter-process dead-lock otherwise. */
8672 alock.release();
8673
8674 mControl->DetachAllUSBDevices(aDone);
8675}
8676
8677/**
8678 * @note Locks this object for writing.
8679 */
8680void Console::processRemoteUSBDevices(uint32_t u32ClientId, VRDEUSBDEVICEDESC *pDevList, uint32_t cbDevList, bool fDescExt)
8681{
8682 LogFlowThisFuncEnter();
8683 LogFlowThisFunc(("u32ClientId = %d, pDevList=%p, cbDevList = %d, fDescExt = %d\n", u32ClientId, pDevList, cbDevList, fDescExt));
8684
8685 AutoCaller autoCaller(this);
8686 if (!autoCaller.isOk())
8687 {
8688 /* Console has been already uninitialized, deny request */
8689 AssertMsgFailed(("Console is already uninitialized\n"));
8690 LogFlowThisFunc(("Console is already uninitialized\n"));
8691 LogFlowThisFuncLeave();
8692 return;
8693 }
8694
8695 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8696
8697 /*
8698 * Mark all existing remote USB devices as dirty.
8699 */
8700 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
8701 it != mRemoteUSBDevices.end();
8702 ++it)
8703 {
8704 (*it)->dirty(true);
8705 }
8706
8707 /*
8708 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
8709 */
8710 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
8711 VRDEUSBDEVICEDESC *e = pDevList;
8712
8713 /* The cbDevList condition must be checked first, because the function can
8714 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
8715 */
8716 while (cbDevList >= 2 && e->oNext)
8717 {
8718 /* Sanitize incoming strings in case they aren't valid UTF-8. */
8719 if (e->oManufacturer)
8720 RTStrPurgeEncoding((char *)e + e->oManufacturer);
8721 if (e->oProduct)
8722 RTStrPurgeEncoding((char *)e + e->oProduct);
8723 if (e->oSerialNumber)
8724 RTStrPurgeEncoding((char *)e + e->oSerialNumber);
8725
8726 LogFlowThisFunc(("vendor %04X, product %04X, name = %s\n",
8727 e->idVendor, e->idProduct,
8728 e->oProduct? (char *)e + e->oProduct: ""));
8729
8730 bool fNewDevice = true;
8731
8732 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
8733 it != mRemoteUSBDevices.end();
8734 ++it)
8735 {
8736 if ((*it)->devId() == e->id
8737 && (*it)->clientId() == u32ClientId)
8738 {
8739 /* The device is already in the list. */
8740 (*it)->dirty(false);
8741 fNewDevice = false;
8742 break;
8743 }
8744 }
8745
8746 if (fNewDevice)
8747 {
8748 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
8749 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""));
8750
8751 /* Create the device object and add the new device to list. */
8752 ComObjPtr<RemoteUSBDevice> pUSBDevice;
8753 pUSBDevice.createObject();
8754 pUSBDevice->init(u32ClientId, e, fDescExt);
8755
8756 mRemoteUSBDevices.push_back(pUSBDevice);
8757
8758 /* Check if the device is ok for current USB filters. */
8759 BOOL fMatched = FALSE;
8760 ULONG fMaskedIfs = 0;
8761
8762 HRESULT hrc = mControl->RunUSBDeviceFilters(pUSBDevice, &fMatched, &fMaskedIfs);
8763
8764 AssertComRC(hrc);
8765
8766 LogFlowThisFunc(("USB filters return %d %#x\n", fMatched, fMaskedIfs));
8767
8768 if (fMatched)
8769 {
8770 alock.release();
8771 hrc = onUSBDeviceAttach(pUSBDevice, NULL, fMaskedIfs);
8772 alock.acquire();
8773
8774 /// @todo (r=dmik) warning reporting subsystem
8775
8776 if (hrc == S_OK)
8777 {
8778 LogFlowThisFunc(("Device attached\n"));
8779 pUSBDevice->captured(true);
8780 }
8781 }
8782 }
8783
8784 if (cbDevList < e->oNext)
8785 {
8786 LogWarningThisFunc(("cbDevList %d > oNext %d\n",
8787 cbDevList, e->oNext));
8788 break;
8789 }
8790
8791 cbDevList -= e->oNext;
8792
8793 e = (VRDEUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
8794 }
8795
8796 /*
8797 * Remove dirty devices, that is those which are not reported by the server anymore.
8798 */
8799 for (;;)
8800 {
8801 ComObjPtr<RemoteUSBDevice> pUSBDevice;
8802
8803 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
8804 while (it != mRemoteUSBDevices.end())
8805 {
8806 if ((*it)->dirty())
8807 {
8808 pUSBDevice = *it;
8809 break;
8810 }
8811
8812 ++it;
8813 }
8814
8815 if (!pUSBDevice)
8816 {
8817 break;
8818 }
8819
8820 USHORT vendorId = 0;
8821 pUSBDevice->COMGETTER(VendorId)(&vendorId);
8822
8823 USHORT productId = 0;
8824 pUSBDevice->COMGETTER(ProductId)(&productId);
8825
8826 Bstr product;
8827 pUSBDevice->COMGETTER(Product)(product.asOutParam());
8828
8829 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
8830 vendorId, productId, product.raw()));
8831
8832 /* Detach the device from VM. */
8833 if (pUSBDevice->captured())
8834 {
8835 Bstr uuid;
8836 pUSBDevice->COMGETTER(Id)(uuid.asOutParam());
8837 alock.release();
8838 onUSBDeviceDetach(uuid.raw(), NULL);
8839 alock.acquire();
8840 }
8841
8842 /* And remove it from the list. */
8843 mRemoteUSBDevices.erase(it);
8844 }
8845
8846 LogFlowThisFuncLeave();
8847}
8848
8849/**
8850 * Progress cancelation callback for fault tolerance VM poweron
8851 */
8852static void faultToleranceProgressCancelCallback(void *pvUser)
8853{
8854 PUVM pUVM = (PUVM)pvUser;
8855
8856 if (pUVM)
8857 FTMR3CancelStandby(pUVM);
8858}
8859
8860/**
8861 * Thread function which starts the VM (also from saved state) and
8862 * track progress.
8863 *
8864 * @param Thread The thread id.
8865 * @param pvUser Pointer to a VMPowerUpTask structure.
8866 * @return VINF_SUCCESS (ignored).
8867 *
8868 * @note Locks the Console object for writing.
8869 */
8870/*static*/
8871DECLCALLBACK(int) Console::powerUpThread(RTTHREAD Thread, void *pvUser)
8872{
8873 LogFlowFuncEnter();
8874
8875 std::auto_ptr<VMPowerUpTask> task(static_cast<VMPowerUpTask *>(pvUser));
8876 AssertReturn(task.get(), VERR_INVALID_PARAMETER);
8877
8878 AssertReturn(!task->mConsole.isNull(), VERR_INVALID_PARAMETER);
8879 AssertReturn(!task->mProgress.isNull(), VERR_INVALID_PARAMETER);
8880
8881 VirtualBoxBase::initializeComForThread();
8882
8883 HRESULT rc = S_OK;
8884 int vrc = VINF_SUCCESS;
8885
8886 /* Set up a build identifier so that it can be seen from core dumps what
8887 * exact build was used to produce the core. */
8888 static char saBuildID[40];
8889 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
8890 "BU", "IL", "DI", "D", RTBldCfgVersion(), RTBldCfgRevision(), "BU", "IL", "DI", "D");
8891
8892 ComObjPtr<Console> pConsole = task->mConsole;
8893
8894 /* Note: no need to use addCaller() because VMPowerUpTask does that */
8895
8896 /* The lock is also used as a signal from the task initiator (which
8897 * releases it only after RTThreadCreate()) that we can start the job */
8898 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
8899
8900 /* sanity */
8901 Assert(pConsole->mpUVM == NULL);
8902
8903 try
8904 {
8905 // Create the VMM device object, which starts the HGCM thread; do this only
8906 // once for the console, for the pathological case that the same console
8907 // object is used to power up a VM twice. VirtualBox 4.0: we now do that
8908 // here instead of the Console constructor (see Console::init())
8909 if (!pConsole->m_pVMMDev)
8910 {
8911 pConsole->m_pVMMDev = new VMMDev(pConsole);
8912 AssertReturn(pConsole->m_pVMMDev, E_FAIL);
8913 }
8914
8915 /* wait for auto reset ops to complete so that we can successfully lock
8916 * the attached hard disks by calling LockMedia() below */
8917 for (VMPowerUpTask::ProgressList::const_iterator
8918 it = task->hardDiskProgresses.begin();
8919 it != task->hardDiskProgresses.end(); ++it)
8920 {
8921 HRESULT rc2 = (*it)->WaitForCompletion(-1);
8922 AssertComRC(rc2);
8923
8924 rc = task->mProgress->SetNextOperation(BstrFmt(tr("Disk Image Reset Operation - Immutable Image")).raw(), 1);
8925 AssertComRCReturnRC(rc);
8926 }
8927
8928 /*
8929 * Lock attached media. This method will also check their accessibility.
8930 * If we're a teleporter, we'll have to postpone this action so we can
8931 * migrate between local processes.
8932 *
8933 * Note! The media will be unlocked automatically by
8934 * SessionMachine::setMachineState() when the VM is powered down.
8935 */
8936 if ( !task->mTeleporterEnabled
8937 && task->mEnmFaultToleranceState != FaultToleranceState_Standby)
8938 {
8939 rc = pConsole->mControl->LockMedia();
8940 if (FAILED(rc)) throw rc;
8941 }
8942
8943 /* Create the VRDP server. In case of headless operation, this will
8944 * also create the framebuffer, required at VM creation.
8945 */
8946 ConsoleVRDPServer *server = pConsole->consoleVRDPServer();
8947 Assert(server);
8948
8949 /* Does VRDP server call Console from the other thread?
8950 * Not sure (and can change), so release the lock just in case.
8951 */
8952 alock.release();
8953 vrc = server->Launch();
8954 alock.acquire();
8955
8956 if (vrc == VERR_NET_ADDRESS_IN_USE)
8957 {
8958 Utf8Str errMsg;
8959 Bstr bstr;
8960 pConsole->mVRDEServer->GetVRDEProperty(Bstr("TCP/Ports").raw(), bstr.asOutParam());
8961 Utf8Str ports = bstr;
8962 errMsg = Utf8StrFmt(tr("VirtualBox Remote Desktop Extension server can't bind to the port: %s"),
8963 ports.c_str());
8964 LogRel(("VRDE: Warning: failed to launch VRDE server (%Rrc): '%s'\n",
8965 vrc, errMsg.c_str()));
8966 }
8967 else if (vrc == VINF_NOT_SUPPORTED)
8968 {
8969 /* This means that the VRDE is not installed. */
8970 LogRel(("VRDE: VirtualBox Remote Desktop Extension is not available.\n"));
8971 }
8972 else if (RT_FAILURE(vrc))
8973 {
8974 /* Fail, if the server is installed but can't start. */
8975 Utf8Str errMsg;
8976 switch (vrc)
8977 {
8978 case VERR_FILE_NOT_FOUND:
8979 {
8980 /* VRDE library file is missing. */
8981 errMsg = Utf8StrFmt(tr("Could not find the VirtualBox Remote Desktop Extension library."));
8982 break;
8983 }
8984 default:
8985 errMsg = Utf8StrFmt(tr("Failed to launch Remote Desktop Extension server (%Rrc)"),
8986 vrc);
8987 }
8988 LogRel(("VRDE: Failed: (%Rrc), error message: '%s'\n",
8989 vrc, errMsg.c_str()));
8990 throw setErrorStatic(E_FAIL, errMsg.c_str());
8991 }
8992
8993 ComPtr<IMachine> pMachine = pConsole->machine();
8994 ULONG cCpus = 1;
8995 pMachine->COMGETTER(CPUCount)(&cCpus);
8996
8997 /*
8998 * Create the VM
8999 *
9000 * Note! Release the lock since EMT will call Console. It's safe because
9001 * mMachineState is either Starting or Restoring state here.
9002 */
9003 alock.release();
9004
9005 PVM pVM;
9006 vrc = VMR3Create(cCpus,
9007 pConsole->mpVmm2UserMethods,
9008 Console::genericVMSetErrorCallback,
9009 &task->mErrorMsg,
9010 task->mConfigConstructor,
9011 static_cast<Console *>(pConsole),
9012 &pVM, NULL);
9013
9014 alock.acquire();
9015
9016 /* Enable client connections to the server. */
9017 pConsole->consoleVRDPServer()->EnableConnections();
9018
9019 if (RT_SUCCESS(vrc))
9020 {
9021 do
9022 {
9023 /*
9024 * Register our load/save state file handlers
9025 */
9026 vrc = SSMR3RegisterExternal(pConsole->mpUVM, sSSMConsoleUnit, 0 /*iInstance*/, sSSMConsoleVer, 0 /* cbGuess */,
9027 NULL, NULL, NULL,
9028 NULL, saveStateFileExec, NULL,
9029 NULL, loadStateFileExec, NULL,
9030 static_cast<Console *>(pConsole));
9031 AssertRCBreak(vrc);
9032
9033 vrc = static_cast<Console *>(pConsole)->getDisplay()->registerSSM(pConsole->mpUVM);
9034 AssertRC(vrc);
9035 if (RT_FAILURE(vrc))
9036 break;
9037
9038 /*
9039 * Synchronize debugger settings
9040 */
9041 MachineDebugger *machineDebugger = pConsole->getMachineDebugger();
9042 if (machineDebugger)
9043 machineDebugger->flushQueuedSettings();
9044
9045 /*
9046 * Shared Folders
9047 */
9048 if (pConsole->m_pVMMDev->isShFlActive())
9049 {
9050 /* Does the code below call Console from the other thread?
9051 * Not sure, so release the lock just in case. */
9052 alock.release();
9053
9054 for (SharedFolderDataMap::const_iterator it = task->mSharedFolders.begin();
9055 it != task->mSharedFolders.end();
9056 ++it)
9057 {
9058 const SharedFolderData &d = it->second;
9059 rc = pConsole->createSharedFolder(it->first, d);
9060 if (FAILED(rc))
9061 {
9062 ErrorInfoKeeper eik;
9063 pConsole->setVMRuntimeErrorCallbackF(0, "BrokenSharedFolder",
9064 N_("The shared folder '%s' could not be set up: %ls.\n"
9065 "The shared folder setup will not be complete. It is recommended to power down the virtual "
9066 "machine and fix the shared folder settings while the machine is not running"),
9067 it->first.c_str(), eik.getText().raw());
9068 }
9069 }
9070 if (FAILED(rc))
9071 rc = S_OK; // do not fail with broken shared folders
9072
9073 /* acquire the lock again */
9074 alock.acquire();
9075 }
9076
9077 /* release the lock before a lengthy operation */
9078 alock.release();
9079
9080 /*
9081 * Capture USB devices.
9082 */
9083 rc = pConsole->captureUSBDevices(pConsole->mpUVM);
9084 if (FAILED(rc))
9085 break;
9086
9087 /* Load saved state? */
9088 if (task->mSavedStateFile.length())
9089 {
9090 LogFlowFunc(("Restoring saved state from '%s'...\n",
9091 task->mSavedStateFile.c_str()));
9092
9093 vrc = VMR3LoadFromFile(pConsole->mpUVM,
9094 task->mSavedStateFile.c_str(),
9095 Console::stateProgressCallback,
9096 static_cast<IProgress *>(task->mProgress));
9097
9098 if (RT_SUCCESS(vrc))
9099 {
9100 if (task->mStartPaused)
9101 /* done */
9102 pConsole->setMachineState(MachineState_Paused);
9103 else
9104 {
9105 /* Start/Resume the VM execution */
9106#ifdef VBOX_WITH_EXTPACK
9107 vrc = pConsole->mptrExtPackManager->callAllVmPowerOnHooks(pConsole, pVM);
9108#endif
9109 if (RT_SUCCESS(vrc))
9110 vrc = VMR3Resume(pConsole->mpUVM, VMRESUMEREASON_STATE_RESTORED);
9111 AssertLogRelRC(vrc);
9112 }
9113 }
9114
9115 /* Power off in case we failed loading or resuming the VM */
9116 if (RT_FAILURE(vrc))
9117 {
9118 int vrc2 = VMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
9119#ifdef VBOX_WITH_EXTPACK
9120 pConsole->mptrExtPackManager->callAllVmPowerOffHooks(pConsole, pVM);
9121#endif
9122 }
9123 }
9124 else if (task->mTeleporterEnabled)
9125 {
9126 /* -> ConsoleImplTeleporter.cpp */
9127 bool fPowerOffOnFailure;
9128 rc = pConsole->teleporterTrg(pConsole->mpUVM, pMachine, &task->mErrorMsg, task->mStartPaused,
9129 task->mProgress, &fPowerOffOnFailure);
9130 if (FAILED(rc) && fPowerOffOnFailure)
9131 {
9132 ErrorInfoKeeper eik;
9133 int vrc2 = VMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
9134#ifdef VBOX_WITH_EXTPACK
9135 pConsole->mptrExtPackManager->callAllVmPowerOffHooks(pConsole, pVM);
9136#endif
9137 }
9138 }
9139 else if (task->mEnmFaultToleranceState != FaultToleranceState_Inactive)
9140 {
9141 /*
9142 * Get the config.
9143 */
9144 ULONG uPort;
9145 ULONG uInterval;
9146 Bstr bstrAddress, bstrPassword;
9147
9148 rc = pMachine->COMGETTER(FaultTolerancePort)(&uPort);
9149 if (SUCCEEDED(rc))
9150 {
9151 rc = pMachine->COMGETTER(FaultToleranceSyncInterval)(&uInterval);
9152 if (SUCCEEDED(rc))
9153 rc = pMachine->COMGETTER(FaultToleranceAddress)(bstrAddress.asOutParam());
9154 if (SUCCEEDED(rc))
9155 rc = pMachine->COMGETTER(FaultTolerancePassword)(bstrPassword.asOutParam());
9156 }
9157 if (task->mProgress->setCancelCallback(faultToleranceProgressCancelCallback, pConsole->mpUVM))
9158 {
9159 if (SUCCEEDED(rc))
9160 {
9161 Utf8Str strAddress(bstrAddress);
9162 const char *pszAddress = strAddress.isEmpty() ? NULL : strAddress.c_str();
9163 Utf8Str strPassword(bstrPassword);
9164 const char *pszPassword = strPassword.isEmpty() ? NULL : strPassword.c_str();
9165
9166 /* Power on the FT enabled VM. */
9167#ifdef VBOX_WITH_EXTPACK
9168 vrc = pConsole->mptrExtPackManager->callAllVmPowerOnHooks(pConsole, pVM);
9169#endif
9170 if (RT_SUCCESS(vrc))
9171 vrc = FTMR3PowerOn(pConsole->mpUVM,
9172 task->mEnmFaultToleranceState == FaultToleranceState_Master /* fMaster */,
9173 uInterval,
9174 pszAddress,
9175 uPort,
9176 pszPassword);
9177 AssertLogRelRC(vrc);
9178 }
9179 task->mProgress->setCancelCallback(NULL, NULL);
9180 }
9181 else
9182 rc = E_FAIL;
9183 }
9184 else if (task->mStartPaused)
9185 /* done */
9186 pConsole->setMachineState(MachineState_Paused);
9187 else
9188 {
9189 /* Power on the VM (i.e. start executing) */
9190#ifdef VBOX_WITH_EXTPACK
9191 vrc = pConsole->mptrExtPackManager->callAllVmPowerOnHooks(pConsole, pVM);
9192#endif
9193 if (RT_SUCCESS(vrc))
9194 vrc = VMR3PowerOn(pConsole->mpUVM);
9195 AssertLogRelRC(vrc);
9196 }
9197
9198 /* acquire the lock again */
9199 alock.acquire();
9200 }
9201 while (0);
9202
9203 /* On failure, destroy the VM */
9204 if (FAILED(rc) || RT_FAILURE(vrc))
9205 {
9206 /* preserve existing error info */
9207 ErrorInfoKeeper eik;
9208
9209 /* powerDown() will call VMR3Destroy() and do all necessary
9210 * cleanup (VRDP, USB devices) */
9211 alock.release();
9212 HRESULT rc2 = pConsole->powerDown();
9213 alock.acquire();
9214 AssertComRC(rc2);
9215 }
9216 else
9217 {
9218 /*
9219 * Deregister the VMSetError callback. This is necessary as the
9220 * pfnVMAtError() function passed to VMR3Create() is supposed to
9221 * be sticky but our error callback isn't.
9222 */
9223 alock.release();
9224 VMR3AtErrorDeregister(pConsole->mpUVM, Console::genericVMSetErrorCallback, &task->mErrorMsg);
9225 /** @todo register another VMSetError callback? */
9226 alock.acquire();
9227 }
9228 }
9229 else
9230 {
9231 /*
9232 * If VMR3Create() failed it has released the VM memory.
9233 */
9234 VMR3ReleaseUVM(pConsole->mpUVM);
9235 pConsole->mpUVM = NULL;
9236 }
9237
9238 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
9239 {
9240 /* If VMR3Create() or one of the other calls in this function fail,
9241 * an appropriate error message has been set in task->mErrorMsg.
9242 * However since that happens via a callback, the rc status code in
9243 * this function is not updated.
9244 */
9245 if (!task->mErrorMsg.length())
9246 {
9247 /* If the error message is not set but we've got a failure,
9248 * convert the VBox status code into a meaningful error message.
9249 * This becomes unused once all the sources of errors set the
9250 * appropriate error message themselves.
9251 */
9252 AssertMsgFailed(("Missing error message during powerup for status code %Rrc\n", vrc));
9253 task->mErrorMsg = Utf8StrFmt(tr("Failed to start VM execution (%Rrc)"),
9254 vrc);
9255 }
9256
9257 /* Set the error message as the COM error.
9258 * Progress::notifyComplete() will pick it up later. */
9259 throw setErrorStatic(E_FAIL, task->mErrorMsg.c_str());
9260 }
9261 }
9262 catch (HRESULT aRC) { rc = aRC; }
9263
9264 if ( pConsole->mMachineState == MachineState_Starting
9265 || pConsole->mMachineState == MachineState_Restoring
9266 || pConsole->mMachineState == MachineState_TeleportingIn
9267 )
9268 {
9269 /* We are still in the Starting/Restoring state. This means one of:
9270 *
9271 * 1) we failed before VMR3Create() was called;
9272 * 2) VMR3Create() failed.
9273 *
9274 * In both cases, there is no need to call powerDown(), but we still
9275 * need to go back to the PoweredOff/Saved state. Reuse
9276 * vmstateChangeCallback() for that purpose.
9277 */
9278
9279 /* preserve existing error info */
9280 ErrorInfoKeeper eik;
9281
9282 Assert(pConsole->mpUVM == NULL);
9283 vmstateChangeCallback(NULL, VMSTATE_TERMINATED, VMSTATE_CREATING, pConsole);
9284 }
9285
9286 /*
9287 * Evaluate the final result. Note that the appropriate mMachineState value
9288 * is already set by vmstateChangeCallback() in all cases.
9289 */
9290
9291 /* release the lock, don't need it any more */
9292 alock.release();
9293
9294 if (SUCCEEDED(rc))
9295 {
9296 /* Notify the progress object of the success */
9297 task->mProgress->notifyComplete(S_OK);
9298 }
9299 else
9300 {
9301 /* The progress object will fetch the current error info */
9302 task->mProgress->notifyComplete(rc);
9303 LogRel(("Power up failed (vrc=%Rrc, rc=%Rhrc (%#08X))\n", vrc, rc, rc));
9304 }
9305
9306 /* Notify VBoxSVC and any waiting openRemoteSession progress object. */
9307 pConsole->mControl->EndPowerUp(rc);
9308
9309#if defined(RT_OS_WINDOWS)
9310 /* uninitialize COM */
9311 CoUninitialize();
9312#endif
9313
9314 LogFlowFuncLeave();
9315
9316 return VINF_SUCCESS;
9317}
9318
9319
9320/**
9321 * Reconfigures a medium attachment (part of taking or deleting an online snapshot).
9322 *
9323 * @param pConsole Reference to the console object.
9324 * @param pUVM The VM handle.
9325 * @param lInstance The instance of the controller.
9326 * @param pcszDevice The name of the controller type.
9327 * @param enmBus The storage bus type of the controller.
9328 * @param fSetupMerge Whether to set up a medium merge
9329 * @param uMergeSource Merge source image index
9330 * @param uMergeTarget Merge target image index
9331 * @param aMediumAtt The medium attachment.
9332 * @param aMachineState The current machine state.
9333 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
9334 * @return VBox status code.
9335 */
9336/* static */
9337DECLCALLBACK(int) Console::reconfigureMediumAttachment(Console *pConsole,
9338 PUVM pUVM,
9339 const char *pcszDevice,
9340 unsigned uInstance,
9341 StorageBus_T enmBus,
9342 bool fUseHostIOCache,
9343 bool fBuiltinIOCache,
9344 bool fSetupMerge,
9345 unsigned uMergeSource,
9346 unsigned uMergeTarget,
9347 IMediumAttachment *aMediumAtt,
9348 MachineState_T aMachineState,
9349 HRESULT *phrc)
9350{
9351 LogFlowFunc(("pUVM=%p aMediumAtt=%p phrc=%p\n", pUVM, aMediumAtt, phrc));
9352
9353 int rc;
9354 HRESULT hrc;
9355 Bstr bstr;
9356 *phrc = S_OK;
9357#define RC_CHECK() do { if (RT_FAILURE(rc)) { AssertMsgFailed(("rc=%Rrc\n", rc)); return rc; } } while (0)
9358#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
9359
9360 /* Ignore attachments other than hard disks, since at the moment they are
9361 * not subject to snapshotting in general. */
9362 DeviceType_T lType;
9363 hrc = aMediumAtt->COMGETTER(Type)(&lType); H();
9364 if (lType != DeviceType_HardDisk)
9365 return VINF_SUCCESS;
9366
9367 /* Determine the base path for the device instance. */
9368 PCFGMNODE pCtlInst;
9369 pCtlInst = CFGMR3GetChildF(CFGMR3GetRootU(pUVM), "Devices/%s/%u/", pcszDevice, uInstance);
9370 AssertReturn(pCtlInst, VERR_INTERNAL_ERROR);
9371
9372 /* Update the device instance configuration. */
9373 rc = pConsole->configMediumAttachment(pCtlInst,
9374 pcszDevice,
9375 uInstance,
9376 enmBus,
9377 fUseHostIOCache,
9378 fBuiltinIOCache,
9379 fSetupMerge,
9380 uMergeSource,
9381 uMergeTarget,
9382 aMediumAtt,
9383 aMachineState,
9384 phrc,
9385 true /* fAttachDetach */,
9386 false /* fForceUnmount */,
9387 false /* fHotplug */,
9388 pUVM,
9389 NULL /* paLedDevType */);
9390 /** @todo this dumps everything attached to this device instance, which
9391 * is more than necessary. Dumping the changed LUN would be enough. */
9392 CFGMR3Dump(pCtlInst);
9393 RC_CHECK();
9394
9395#undef RC_CHECK
9396#undef H
9397
9398 LogFlowFunc(("Returns success\n"));
9399 return VINF_SUCCESS;
9400}
9401
9402/**
9403 * Progress cancelation callback employed by Console::fntTakeSnapshotWorker.
9404 */
9405static void takesnapshotProgressCancelCallback(void *pvUser)
9406{
9407 PUVM pUVM = (PUVM)pvUser;
9408 SSMR3Cancel(pUVM);
9409}
9410
9411/**
9412 * Worker thread created by Console::TakeSnapshot.
9413 * @param Thread The current thread (ignored).
9414 * @param pvUser The task.
9415 * @return VINF_SUCCESS (ignored).
9416 */
9417/*static*/
9418DECLCALLBACK(int) Console::fntTakeSnapshotWorker(RTTHREAD Thread, void *pvUser)
9419{
9420 VMTakeSnapshotTask *pTask = (VMTakeSnapshotTask*)pvUser;
9421
9422 // taking a snapshot consists of the following:
9423
9424 // 1) creating a diff image for each virtual hard disk, into which write operations go after
9425 // the snapshot has been created (done in VBoxSVC, in SessionMachine::BeginTakingSnapshot)
9426 // 2) creating a Snapshot object with the state of the machine (hardware + storage,
9427 // done in VBoxSVC, also in SessionMachine::BeginTakingSnapshot)
9428 // 3) saving the state of the virtual machine (here, in the VM process, if the machine is online)
9429
9430 Console *that = pTask->mConsole;
9431 bool fBeganTakingSnapshot = false;
9432 bool fSuspenededBySave = false;
9433
9434 AutoCaller autoCaller(that);
9435 if (FAILED(autoCaller.rc()))
9436 {
9437 that->mptrCancelableProgress.setNull();
9438 return autoCaller.rc();
9439 }
9440
9441 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9442
9443 HRESULT rc = S_OK;
9444
9445 try
9446 {
9447 /* STEP 1 + 2:
9448 * request creating the diff images on the server and create the snapshot object
9449 * (this will set the machine state to Saving on the server to block
9450 * others from accessing this machine)
9451 */
9452 rc = that->mControl->BeginTakingSnapshot(that,
9453 pTask->bstrName.raw(),
9454 pTask->bstrDescription.raw(),
9455 pTask->mProgress,
9456 pTask->fTakingSnapshotOnline,
9457 pTask->bstrSavedStateFile.asOutParam());
9458 if (FAILED(rc))
9459 throw rc;
9460
9461 fBeganTakingSnapshot = true;
9462
9463 /* Check sanity: for offline snapshots there must not be a saved state
9464 * file name. All other combinations are valid (even though online
9465 * snapshots without saved state file seems inconsistent - there are
9466 * some exotic use cases, which need to be explicitly enabled, see the
9467 * code of SessionMachine::BeginTakingSnapshot. */
9468 if ( !pTask->fTakingSnapshotOnline
9469 && !pTask->bstrSavedStateFile.isEmpty())
9470 throw setErrorStatic(E_FAIL, "Invalid state of saved state file");
9471
9472 /* sync the state with the server */
9473 if (pTask->lastMachineState == MachineState_Running)
9474 that->setMachineStateLocally(MachineState_LiveSnapshotting);
9475 else
9476 that->setMachineStateLocally(MachineState_Saving);
9477
9478 // STEP 3: save the VM state (if online)
9479 if (pTask->fTakingSnapshotOnline)
9480 {
9481 int vrc;
9482 SafeVMPtr ptrVM(that);
9483 if (!ptrVM.isOk())
9484 throw ptrVM.rc();
9485
9486 pTask->mProgress->SetNextOperation(Bstr(tr("Saving the machine state")).raw(),
9487 pTask->ulMemSize); // operation weight, same as computed when setting up progress object
9488 if (!pTask->bstrSavedStateFile.isEmpty())
9489 {
9490 Utf8Str strSavedStateFile(pTask->bstrSavedStateFile);
9491
9492 pTask->mProgress->setCancelCallback(takesnapshotProgressCancelCallback, ptrVM.rawUVM());
9493
9494 alock.release();
9495 LogFlowFunc(("VMR3Save...\n"));
9496 vrc = VMR3Save(ptrVM.rawUVM(),
9497 strSavedStateFile.c_str(),
9498 true /*fContinueAfterwards*/,
9499 Console::stateProgressCallback,
9500 static_cast<IProgress *>(pTask->mProgress),
9501 &fSuspenededBySave);
9502 alock.acquire();
9503 if (RT_FAILURE(vrc))
9504 throw setErrorStatic(E_FAIL,
9505 tr("Failed to save the machine state to '%s' (%Rrc)"),
9506 strSavedStateFile.c_str(), vrc);
9507
9508 pTask->mProgress->setCancelCallback(NULL, NULL);
9509 }
9510 else
9511 LogRel(("Console: skipped saving state as part of online snapshot\n"));
9512
9513 if (!pTask->mProgress->notifyPointOfNoReturn())
9514 throw setErrorStatic(E_FAIL, tr("Canceled"));
9515 that->mptrCancelableProgress.setNull();
9516
9517 // STEP 4: reattach hard disks
9518 LogFlowFunc(("Reattaching new differencing hard disks...\n"));
9519
9520 pTask->mProgress->SetNextOperation(Bstr(tr("Reconfiguring medium attachments")).raw(),
9521 1); // operation weight, same as computed when setting up progress object
9522
9523 com::SafeIfaceArray<IMediumAttachment> atts;
9524 rc = that->mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
9525 if (FAILED(rc))
9526 throw rc;
9527
9528 for (size_t i = 0;
9529 i < atts.size();
9530 ++i)
9531 {
9532 ComPtr<IStorageController> pStorageController;
9533 Bstr controllerName;
9534 ULONG lInstance;
9535 StorageControllerType_T enmController;
9536 StorageBus_T enmBus;
9537 BOOL fUseHostIOCache;
9538
9539 /*
9540 * We can't pass a storage controller object directly
9541 * (g++ complains about not being able to pass non POD types through '...')
9542 * so we have to query needed values here and pass them.
9543 */
9544 rc = atts[i]->COMGETTER(Controller)(controllerName.asOutParam());
9545 if (FAILED(rc))
9546 throw rc;
9547
9548 rc = that->mMachine->GetStorageControllerByName(controllerName.raw(),
9549 pStorageController.asOutParam());
9550 if (FAILED(rc))
9551 throw rc;
9552
9553 rc = pStorageController->COMGETTER(ControllerType)(&enmController);
9554 if (FAILED(rc))
9555 throw rc;
9556 rc = pStorageController->COMGETTER(Instance)(&lInstance);
9557 if (FAILED(rc))
9558 throw rc;
9559 rc = pStorageController->COMGETTER(Bus)(&enmBus);
9560 if (FAILED(rc))
9561 throw rc;
9562 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
9563 if (FAILED(rc))
9564 throw rc;
9565
9566 const char *pcszDevice = Console::convertControllerTypeToDev(enmController);
9567
9568 BOOL fBuiltinIOCache;
9569 rc = that->mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
9570 if (FAILED(rc))
9571 throw rc;
9572
9573 /*
9574 * don't release the lock since reconfigureMediumAttachment
9575 * isn't going to need the Console lock.
9576 */
9577 vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(),
9578 VMCPUID_ANY,
9579 (PFNRT)reconfigureMediumAttachment,
9580 13,
9581 that,
9582 ptrVM.rawUVM(),
9583 pcszDevice,
9584 lInstance,
9585 enmBus,
9586 fUseHostIOCache,
9587 fBuiltinIOCache,
9588 false /* fSetupMerge */,
9589 0 /* uMergeSource */,
9590 0 /* uMergeTarget */,
9591 atts[i],
9592 that->mMachineState,
9593 &rc);
9594 if (RT_FAILURE(vrc))
9595 throw setErrorStatic(E_FAIL, Console::tr("%Rrc"), vrc);
9596 if (FAILED(rc))
9597 throw rc;
9598 }
9599 }
9600
9601 /*
9602 * finalize the requested snapshot object.
9603 * This will reset the machine state to the state it had right
9604 * before calling mControl->BeginTakingSnapshot().
9605 */
9606 rc = that->mControl->EndTakingSnapshot(TRUE /*aSuccess*/);
9607 // do not throw rc here because we can't call EndTakingSnapshot() twice
9608 LogFlowFunc(("EndTakingSnapshot -> %Rhrc [mMachineState=%s]\n", rc, Global::stringifyMachineState(that->mMachineState)));
9609 }
9610 catch (HRESULT rcThrown)
9611 {
9612 /* preserve existing error info */
9613 ErrorInfoKeeper eik;
9614
9615 if (fBeganTakingSnapshot)
9616 that->mControl->EndTakingSnapshot(FALSE /*aSuccess*/);
9617
9618 rc = rcThrown;
9619 LogFunc(("Caught %Rhrc [mMachineState=%s]\n", rc, Global::stringifyMachineState(that->mMachineState)));
9620 }
9621 Assert(alock.isWriteLockOnCurrentThread());
9622
9623 if (FAILED(rc)) /* Must come before calling setMachineState. */
9624 pTask->mProgress->notifyComplete(rc);
9625
9626 /*
9627 * Fix up the machine state.
9628 *
9629 * For live snapshots we do all the work, for the two other variations we
9630 * just update the local copy.
9631 */
9632 MachineState_T enmMachineState;
9633 that->mMachine->COMGETTER(State)(&enmMachineState);
9634 if ( that->mMachineState == MachineState_LiveSnapshotting
9635 || that->mMachineState == MachineState_Saving)
9636 {
9637
9638 if (!pTask->fTakingSnapshotOnline)
9639 that->setMachineStateLocally(pTask->lastMachineState);
9640 else if (SUCCEEDED(rc))
9641 {
9642 Assert( pTask->lastMachineState == MachineState_Running
9643 || pTask->lastMachineState == MachineState_Paused);
9644 Assert(that->mMachineState == MachineState_Saving);
9645 if (pTask->lastMachineState == MachineState_Running)
9646 {
9647 LogFlowFunc(("VMR3Resume...\n"));
9648 SafeVMPtr ptrVM(that);
9649 alock.release();
9650 int vrc = VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_STATE_SAVED);
9651 alock.acquire();
9652 if (RT_FAILURE(vrc))
9653 {
9654 rc = setErrorStatic(VBOX_E_VM_ERROR, tr("Could not resume the machine execution (%Rrc)"), vrc);
9655 pTask->mProgress->notifyComplete(rc);
9656 if (that->mMachineState == MachineState_Saving)
9657 that->setMachineStateLocally(MachineState_Paused);
9658 }
9659 }
9660 else
9661 that->setMachineStateLocally(MachineState_Paused);
9662 }
9663 else
9664 {
9665 /** @todo this could probably be made more generic and reused elsewhere. */
9666 /* paranoid cleanup on for a failed online snapshot. */
9667 VMSTATE enmVMState = VMR3GetStateU(that->mpUVM);
9668 switch (enmVMState)
9669 {
9670 case VMSTATE_RUNNING:
9671 case VMSTATE_RUNNING_LS:
9672 case VMSTATE_DEBUGGING:
9673 case VMSTATE_DEBUGGING_LS:
9674 case VMSTATE_POWERING_OFF:
9675 case VMSTATE_POWERING_OFF_LS:
9676 case VMSTATE_RESETTING:
9677 case VMSTATE_RESETTING_LS:
9678 Assert(!fSuspenededBySave);
9679 that->setMachineState(MachineState_Running);
9680 break;
9681
9682 case VMSTATE_GURU_MEDITATION:
9683 case VMSTATE_GURU_MEDITATION_LS:
9684 that->setMachineState(MachineState_Stuck);
9685 break;
9686
9687 case VMSTATE_FATAL_ERROR:
9688 case VMSTATE_FATAL_ERROR_LS:
9689 if (pTask->lastMachineState == MachineState_Paused)
9690 that->setMachineStateLocally(pTask->lastMachineState);
9691 else
9692 that->setMachineState(MachineState_Paused);
9693 break;
9694
9695 default:
9696 AssertMsgFailed(("%s\n", VMR3GetStateName(enmVMState)));
9697 case VMSTATE_SUSPENDED:
9698 case VMSTATE_SUSPENDED_LS:
9699 case VMSTATE_SUSPENDING:
9700 case VMSTATE_SUSPENDING_LS:
9701 case VMSTATE_SUSPENDING_EXT_LS:
9702 if (fSuspenededBySave)
9703 {
9704 Assert(pTask->lastMachineState == MachineState_Running);
9705 LogFlowFunc(("VMR3Resume (on failure)...\n"));
9706 SafeVMPtr ptrVM(that);
9707 alock.release();
9708 int vrc = VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_STATE_SAVED); AssertLogRelRC(vrc);
9709 alock.acquire();
9710 if (RT_FAILURE(vrc))
9711 that->setMachineState(MachineState_Paused);
9712 }
9713 else if (pTask->lastMachineState == MachineState_Paused)
9714 that->setMachineStateLocally(pTask->lastMachineState);
9715 else
9716 that->setMachineState(MachineState_Paused);
9717 break;
9718 }
9719
9720 }
9721 }
9722 /*else: somebody else has change the state... Leave it. */
9723
9724 /* check the remote state to see that we got it right. */
9725 that->mMachine->COMGETTER(State)(&enmMachineState);
9726 AssertLogRelMsg(that->mMachineState == enmMachineState,
9727 ("mMachineState=%s enmMachineState=%s\n", Global::stringifyMachineState(that->mMachineState),
9728 Global::stringifyMachineState(enmMachineState) ));
9729
9730
9731 if (SUCCEEDED(rc)) /* The failure cases are handled above. */
9732 pTask->mProgress->notifyComplete(rc);
9733
9734 delete pTask;
9735
9736 LogFlowFuncLeave();
9737 return VINF_SUCCESS;
9738}
9739
9740/**
9741 * Thread for executing the saved state operation.
9742 *
9743 * @param Thread The thread handle.
9744 * @param pvUser Pointer to a VMSaveTask structure.
9745 * @return VINF_SUCCESS (ignored).
9746 *
9747 * @note Locks the Console object for writing.
9748 */
9749/*static*/
9750DECLCALLBACK(int) Console::saveStateThread(RTTHREAD Thread, void *pvUser)
9751{
9752 LogFlowFuncEnter();
9753
9754 std::auto_ptr<VMSaveTask> task(static_cast<VMSaveTask*>(pvUser));
9755 AssertReturn(task.get(), VERR_INVALID_PARAMETER);
9756
9757 Assert(task->mSavedStateFile.length());
9758 Assert(task->mProgress.isNull());
9759 Assert(!task->mServerProgress.isNull());
9760
9761 const ComObjPtr<Console> &that = task->mConsole;
9762 Utf8Str errMsg;
9763 HRESULT rc = S_OK;
9764
9765 LogFlowFunc(("Saving the state to '%s'...\n", task->mSavedStateFile.c_str()));
9766
9767 bool fSuspenededBySave;
9768 int vrc = VMR3Save(task->mpUVM,
9769 task->mSavedStateFile.c_str(),
9770 false, /*fContinueAfterwards*/
9771 Console::stateProgressCallback,
9772 static_cast<IProgress *>(task->mServerProgress),
9773 &fSuspenededBySave);
9774 if (RT_FAILURE(vrc))
9775 {
9776 errMsg = Utf8StrFmt(Console::tr("Failed to save the machine state to '%s' (%Rrc)"),
9777 task->mSavedStateFile.c_str(), vrc);
9778 rc = E_FAIL;
9779 }
9780 Assert(!fSuspenededBySave);
9781
9782 /* lock the console once we're going to access it */
9783 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
9784
9785 /* synchronize the state with the server */
9786 if (SUCCEEDED(rc))
9787 {
9788 /*
9789 * The machine has been successfully saved, so power it down
9790 * (vmstateChangeCallback() will set state to Saved on success).
9791 * Note: we release the task's VM caller, otherwise it will
9792 * deadlock.
9793 */
9794 task->releaseVMCaller();
9795 thatLock.release();
9796 rc = that->powerDown();
9797 thatLock.acquire();
9798 }
9799
9800 /*
9801 * If we failed, reset the local machine state.
9802 */
9803 if (FAILED(rc))
9804 that->setMachineStateLocally(task->mMachineStateBefore);
9805
9806 /*
9807 * Finalize the requested save state procedure. In case of failure it will
9808 * reset the machine state to the state it had right before calling
9809 * mControl->BeginSavingState(). This must be the last thing because it
9810 * will set the progress to completed, and that means that the frontend
9811 * can immediately uninit the associated console object.
9812 */
9813 that->mControl->EndSavingState(rc, Bstr(errMsg).raw());
9814
9815 LogFlowFuncLeave();
9816 return VINF_SUCCESS;
9817}
9818
9819/**
9820 * Thread for powering down the Console.
9821 *
9822 * @param Thread The thread handle.
9823 * @param pvUser Pointer to the VMTask structure.
9824 * @return VINF_SUCCESS (ignored).
9825 *
9826 * @note Locks the Console object for writing.
9827 */
9828/*static*/
9829DECLCALLBACK(int) Console::powerDownThread(RTTHREAD Thread, void *pvUser)
9830{
9831 LogFlowFuncEnter();
9832
9833 std::auto_ptr<VMPowerDownTask> task(static_cast<VMPowerDownTask *>(pvUser));
9834 AssertReturn(task.get(), VERR_INVALID_PARAMETER);
9835
9836 AssertReturn(task->isOk(), VERR_GENERAL_FAILURE);
9837
9838 Assert(task->mProgress.isNull());
9839
9840 const ComObjPtr<Console> &that = task->mConsole;
9841
9842 /* Note: no need to use addCaller() to protect Console because VMTask does
9843 * that */
9844
9845 /* wait until the method tat started us returns */
9846 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
9847
9848 /* release VM caller to avoid the powerDown() deadlock */
9849 task->releaseVMCaller();
9850
9851 thatLock.release();
9852
9853 that->powerDown(task->mServerProgress);
9854
9855 /* complete the operation */
9856 that->mControl->EndPoweringDown(S_OK, Bstr().raw());
9857
9858 LogFlowFuncLeave();
9859 return VINF_SUCCESS;
9860}
9861
9862
9863/**
9864 * @interface_method_impl{VMM2USERMETHODS,pfnSaveState}
9865 */
9866/*static*/ DECLCALLBACK(int)
9867Console::vmm2User_SaveState(PCVMM2USERMETHODS pThis, PUVM pUVM)
9868{
9869 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
9870 NOREF(pUVM);
9871
9872 /*
9873 * For now, just call SaveState. We should probably try notify the GUI so
9874 * it can pop up a progress object and stuff.
9875 */
9876 HRESULT hrc = pConsole->SaveState(NULL);
9877 return SUCCEEDED(hrc) ? VINF_SUCCESS : Global::vboxStatusCodeFromCOM(hrc);
9878}
9879
9880/**
9881 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtInit}
9882 */
9883/*static*/ DECLCALLBACK(void)
9884Console::vmm2User_NotifyEmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
9885{
9886 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
9887 VirtualBoxBase::initializeComForThread();
9888}
9889
9890/**
9891 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtTerm}
9892 */
9893/*static*/ DECLCALLBACK(void)
9894Console::vmm2User_NotifyEmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
9895{
9896 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
9897 VirtualBoxBase::uninitializeComForThread();
9898}
9899
9900/**
9901 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtInit}
9902 */
9903/*static*/ DECLCALLBACK(void)
9904Console::vmm2User_NotifyPdmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM)
9905{
9906 NOREF(pThis); NOREF(pUVM);
9907 VirtualBoxBase::initializeComForThread();
9908}
9909
9910/**
9911 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtTerm}
9912 */
9913/*static*/ DECLCALLBACK(void)
9914Console::vmm2User_NotifyPdmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM)
9915{
9916 NOREF(pThis); NOREF(pUVM);
9917 VirtualBoxBase::uninitializeComForThread();
9918}
9919
9920
9921
9922
9923/**
9924 * The Main status driver instance data.
9925 */
9926typedef struct DRVMAINSTATUS
9927{
9928 /** The LED connectors. */
9929 PDMILEDCONNECTORS ILedConnectors;
9930 /** Pointer to the LED ports interface above us. */
9931 PPDMILEDPORTS pLedPorts;
9932 /** Pointer to the array of LED pointers. */
9933 PPDMLED *papLeds;
9934 /** The unit number corresponding to the first entry in the LED array. */
9935 RTUINT iFirstLUN;
9936 /** The unit number corresponding to the last entry in the LED array.
9937 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
9938 RTUINT iLastLUN;
9939 /** Pointer to the driver instance. */
9940 PPDMDRVINS pDrvIns;
9941 /** The Media Notify interface. */
9942 PDMIMEDIANOTIFY IMediaNotify;
9943 /** Map for translating PDM storage controller/LUN information to
9944 * IMediumAttachment references. */
9945 Console::MediumAttachmentMap *pmapMediumAttachments;
9946 /** Device name+instance for mapping */
9947 char *pszDeviceInstance;
9948 /** Pointer to the Console object, for driver triggered activities. */
9949 Console *pConsole;
9950} DRVMAINSTATUS, *PDRVMAINSTATUS;
9951
9952
9953/**
9954 * Notification about a unit which have been changed.
9955 *
9956 * The driver must discard any pointers to data owned by
9957 * the unit and requery it.
9958 *
9959 * @param pInterface Pointer to the interface structure containing the called function pointer.
9960 * @param iLUN The unit number.
9961 */
9962DECLCALLBACK(void) Console::drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
9963{
9964 PDRVMAINSTATUS pThis = (PDRVMAINSTATUS)((uintptr_t)pInterface - RT_OFFSETOF(DRVMAINSTATUS, ILedConnectors));
9965 if (iLUN >= pThis->iFirstLUN && iLUN <= pThis->iLastLUN)
9966 {
9967 PPDMLED pLed;
9968 int rc = pThis->pLedPorts->pfnQueryStatusLed(pThis->pLedPorts, iLUN, &pLed);
9969 if (RT_FAILURE(rc))
9970 pLed = NULL;
9971 ASMAtomicWritePtr(&pThis->papLeds[iLUN - pThis->iFirstLUN], pLed);
9972 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
9973 }
9974}
9975
9976
9977/**
9978 * Notification about a medium eject.
9979 *
9980 * @returns VBox status.
9981 * @param pInterface Pointer to the interface structure containing the called function pointer.
9982 * @param uLUN The unit number.
9983 */
9984DECLCALLBACK(int) Console::drvStatus_MediumEjected(PPDMIMEDIANOTIFY pInterface, unsigned uLUN)
9985{
9986 PDRVMAINSTATUS pThis = (PDRVMAINSTATUS)((uintptr_t)pInterface - RT_OFFSETOF(DRVMAINSTATUS, IMediaNotify));
9987 PPDMDRVINS pDrvIns = pThis->pDrvIns;
9988 LogFunc(("uLUN=%d\n", uLUN));
9989 if (pThis->pmapMediumAttachments)
9990 {
9991 AutoWriteLock alock(pThis->pConsole COMMA_LOCKVAL_SRC_POS);
9992
9993 ComPtr<IMediumAttachment> pMediumAtt;
9994 Utf8Str devicePath = Utf8StrFmt("%s/LUN#%u", pThis->pszDeviceInstance, uLUN);
9995 Console::MediumAttachmentMap::const_iterator end = pThis->pmapMediumAttachments->end();
9996 Console::MediumAttachmentMap::const_iterator it = pThis->pmapMediumAttachments->find(devicePath);
9997 if (it != end)
9998 pMediumAtt = it->second;
9999 Assert(!pMediumAtt.isNull());
10000 if (!pMediumAtt.isNull())
10001 {
10002 IMedium *pMedium = NULL;
10003 HRESULT rc = pMediumAtt->COMGETTER(Medium)(&pMedium);
10004 AssertComRC(rc);
10005 if (SUCCEEDED(rc) && pMedium)
10006 {
10007 BOOL fHostDrive = FALSE;
10008 rc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
10009 AssertComRC(rc);
10010 if (!fHostDrive)
10011 {
10012 alock.release();
10013
10014 ComPtr<IMediumAttachment> pNewMediumAtt;
10015 rc = pThis->pConsole->mControl->EjectMedium(pMediumAtt, pNewMediumAtt.asOutParam());
10016 if (SUCCEEDED(rc))
10017 fireMediumChangedEvent(pThis->pConsole->mEventSource, pNewMediumAtt);
10018
10019 alock.acquire();
10020 if (pNewMediumAtt != pMediumAtt)
10021 {
10022 pThis->pmapMediumAttachments->erase(devicePath);
10023 pThis->pmapMediumAttachments->insert(std::make_pair(devicePath, pNewMediumAtt));
10024 }
10025 }
10026 }
10027 }
10028 }
10029 return VINF_SUCCESS;
10030}
10031
10032
10033/**
10034 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
10035 */
10036DECLCALLBACK(void *) Console::drvStatus_QueryInterface(PPDMIBASE pInterface, const char *pszIID)
10037{
10038 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
10039 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10040 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
10041 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDCONNECTORS, &pThis->ILedConnectors);
10042 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIANOTIFY, &pThis->IMediaNotify);
10043 return NULL;
10044}
10045
10046
10047/**
10048 * Destruct a status driver instance.
10049 *
10050 * @returns VBox status.
10051 * @param pDrvIns The driver instance data.
10052 */
10053DECLCALLBACK(void) Console::drvStatus_Destruct(PPDMDRVINS pDrvIns)
10054{
10055 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
10056 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10057 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
10058
10059 if (pThis->papLeds)
10060 {
10061 unsigned iLed = pThis->iLastLUN - pThis->iFirstLUN + 1;
10062 while (iLed-- > 0)
10063 ASMAtomicWriteNullPtr(&pThis->papLeds[iLed]);
10064 }
10065}
10066
10067
10068/**
10069 * Construct a status driver instance.
10070 *
10071 * @copydoc FNPDMDRVCONSTRUCT
10072 */
10073DECLCALLBACK(int) Console::drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
10074{
10075 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
10076 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10077 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
10078
10079 /*
10080 * Validate configuration.
10081 */
10082 if (!CFGMR3AreValuesValid(pCfg, "papLeds\0pmapMediumAttachments\0DeviceInstance\0pConsole\0First\0Last\0"))
10083 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
10084 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
10085 ("Configuration error: Not possible to attach anything to this driver!\n"),
10086 VERR_PDM_DRVINS_NO_ATTACH);
10087
10088 /*
10089 * Data.
10090 */
10091 pDrvIns->IBase.pfnQueryInterface = Console::drvStatus_QueryInterface;
10092 pThis->ILedConnectors.pfnUnitChanged = Console::drvStatus_UnitChanged;
10093 pThis->IMediaNotify.pfnEjected = Console::drvStatus_MediumEjected;
10094 pThis->pDrvIns = pDrvIns;
10095 pThis->pszDeviceInstance = NULL;
10096
10097 /*
10098 * Read config.
10099 */
10100 int rc = CFGMR3QueryPtr(pCfg, "papLeds", (void **)&pThis->papLeds);
10101 if (RT_FAILURE(rc))
10102 {
10103 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Rrc\n", rc));
10104 return rc;
10105 }
10106
10107 rc = CFGMR3QueryPtrDef(pCfg, "pmapMediumAttachments", (void **)&pThis->pmapMediumAttachments, NULL);
10108 if (RT_FAILURE(rc))
10109 {
10110 AssertMsgFailed(("Configuration error: Failed to query the \"pmapMediumAttachments\" value! rc=%Rrc\n", rc));
10111 return rc;
10112 }
10113 if (pThis->pmapMediumAttachments)
10114 {
10115 rc = CFGMR3QueryStringAlloc(pCfg, "DeviceInstance", &pThis->pszDeviceInstance);
10116 if (RT_FAILURE(rc))
10117 {
10118 AssertMsgFailed(("Configuration error: Failed to query the \"DeviceInstance\" value! rc=%Rrc\n", rc));
10119 return rc;
10120 }
10121 rc = CFGMR3QueryPtr(pCfg, "pConsole", (void **)&pThis->pConsole);
10122 if (RT_FAILURE(rc))
10123 {
10124 AssertMsgFailed(("Configuration error: Failed to query the \"pConsole\" value! rc=%Rrc\n", rc));
10125 return rc;
10126 }
10127 }
10128
10129 rc = CFGMR3QueryU32(pCfg, "First", &pThis->iFirstLUN);
10130 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
10131 pThis->iFirstLUN = 0;
10132 else if (RT_FAILURE(rc))
10133 {
10134 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Rrc\n", rc));
10135 return rc;
10136 }
10137
10138 rc = CFGMR3QueryU32(pCfg, "Last", &pThis->iLastLUN);
10139 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
10140 pThis->iLastLUN = 0;
10141 else if (RT_FAILURE(rc))
10142 {
10143 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Rrc\n", rc));
10144 return rc;
10145 }
10146 if (pThis->iFirstLUN > pThis->iLastLUN)
10147 {
10148 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pThis->iFirstLUN, pThis->iLastLUN));
10149 return VERR_GENERAL_FAILURE;
10150 }
10151
10152 /*
10153 * Get the ILedPorts interface of the above driver/device and
10154 * query the LEDs we want.
10155 */
10156 pThis->pLedPorts = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMILEDPORTS);
10157 AssertMsgReturn(pThis->pLedPorts, ("Configuration error: No led ports interface above!\n"),
10158 VERR_PDM_MISSING_INTERFACE_ABOVE);
10159
10160 for (unsigned i = pThis->iFirstLUN; i <= pThis->iLastLUN; ++i)
10161 Console::drvStatus_UnitChanged(&pThis->ILedConnectors, i);
10162
10163 return VINF_SUCCESS;
10164}
10165
10166
10167/**
10168 * Console status driver (LED) registration record.
10169 */
10170const PDMDRVREG Console::DrvStatusReg =
10171{
10172 /* u32Version */
10173 PDM_DRVREG_VERSION,
10174 /* szName */
10175 "MainStatus",
10176 /* szRCMod */
10177 "",
10178 /* szR0Mod */
10179 "",
10180 /* pszDescription */
10181 "Main status driver (Main as in the API).",
10182 /* fFlags */
10183 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
10184 /* fClass. */
10185 PDM_DRVREG_CLASS_STATUS,
10186 /* cMaxInstances */
10187 ~0U,
10188 /* cbInstance */
10189 sizeof(DRVMAINSTATUS),
10190 /* pfnConstruct */
10191 Console::drvStatus_Construct,
10192 /* pfnDestruct */
10193 Console::drvStatus_Destruct,
10194 /* pfnRelocate */
10195 NULL,
10196 /* pfnIOCtl */
10197 NULL,
10198 /* pfnPowerOn */
10199 NULL,
10200 /* pfnReset */
10201 NULL,
10202 /* pfnSuspend */
10203 NULL,
10204 /* pfnResume */
10205 NULL,
10206 /* pfnAttach */
10207 NULL,
10208 /* pfnDetach */
10209 NULL,
10210 /* pfnPowerOff */
10211 NULL,
10212 /* pfnSoftReset */
10213 NULL,
10214 /* u32EndVersion */
10215 PDM_DRVREG_VERSION
10216};
10217
10218/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

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