VirtualBox

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

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

Main: properly fixed the return code of VRDEServer::COMSETTER(Enabled) and fixed locking + some comments in ConsoleImpl

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

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