VirtualBox

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

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

VMM: Suspend and resume reasons.

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