VirtualBox

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

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

Main/VBoxManage: allow to enable video recording at VM runtime

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