VirtualBox

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

Last change on this file since 48328 was 48313, checked in by vboxsync, 11 years ago

Main/ExtPackManager+Console: add a way to load HGCM modules from an extension pack, contributed by Jeff Westphal (partially rewritten). Thanks!

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

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