VirtualBox

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

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

Main/Multi-touch: extend OnMouseCapabilityChanged event.

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