VirtualBox

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

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

Main/Host(HostPower)+Session+Console: convert HostPower code to signal pause/resume/savestate through internal methods, conveying information why the method was called, preparing for VM/PDM passing this information to devices and drivers

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