VirtualBox

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

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

Devices/Input: most of the Main plumbing for guest multi-touch.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 338.7 KB
Line 
1/* $Id: ConsoleImpl.cpp 47174 2013-07-16 03:27:24Z vboxsync $ */
2/** @file
3 * VBox Console COM Class implementation
4 */
5
6/*
7 * Copyright (C) 2005-2013 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/** @todo Move the TAP mess back into the driver! */
19#if defined(RT_OS_WINDOWS)
20#elif defined(RT_OS_LINUX)
21# include <errno.h>
22# include <sys/ioctl.h>
23# include <sys/poll.h>
24# include <sys/fcntl.h>
25# include <sys/types.h>
26# include <sys/wait.h>
27# include <net/if.h>
28# include <linux/if_tun.h>
29# include <stdio.h>
30# include <stdlib.h>
31# include <string.h>
32#elif defined(RT_OS_FREEBSD)
33# include <errno.h>
34# include <sys/ioctl.h>
35# include <sys/poll.h>
36# include <sys/fcntl.h>
37# include <sys/types.h>
38# include <sys/wait.h>
39# include <stdio.h>
40# include <stdlib.h>
41# include <string.h>
42#elif defined(RT_OS_SOLARIS)
43# include <iprt/coredumper.h>
44#endif
45
46#include "ConsoleImpl.h"
47
48#include "Global.h"
49#include "VirtualBoxErrorInfoImpl.h"
50#include "GuestImpl.h"
51#include "KeyboardImpl.h"
52#include "MouseImpl.h"
53#include "DisplayImpl.h"
54#include "MachineDebuggerImpl.h"
55#include "USBDeviceImpl.h"
56#include "RemoteUSBDeviceImpl.h"
57#include "SharedFolderImpl.h"
58#include "AudioSnifferInterface.h"
59#include "Nvram.h"
60#ifdef VBOX_WITH_USB_VIDEO
61# include "UsbWebcamInterface.h"
62#endif
63#ifdef VBOX_WITH_USB_CARDREADER
64# include "UsbCardReader.h"
65#endif
66#include "ProgressImpl.h"
67#include "ConsoleVRDPServer.h"
68#include "VMMDev.h"
69#ifdef VBOX_WITH_EXTPACK
70# include "ExtPackManagerImpl.h"
71#endif
72#include "BusAssignmentManager.h"
73
74#include "VBoxEvents.h"
75#include "AutoCaller.h"
76#include "Logging.h"
77
78#include <VBox/com/array.h>
79#include "VBox/com/ErrorInfo.h"
80#include <VBox/com/listeners.h>
81
82#include <iprt/asm.h>
83#include <iprt/buildconfig.h>
84#include <iprt/cpp/utils.h>
85#include <iprt/dir.h>
86#include <iprt/file.h>
87#include <iprt/ldr.h>
88#include <iprt/path.h>
89#include <iprt/process.h>
90#include <iprt/string.h>
91#include <iprt/system.h>
92
93#include <VBox/vmm/vmapi.h>
94#include <VBox/vmm/vmm.h>
95#include <VBox/vmm/pdmapi.h>
96#include <VBox/vmm/pdmasynccompletion.h>
97#include <VBox/vmm/pdmnetifs.h>
98#ifdef VBOX_WITH_USB
99# include <VBox/vmm/pdmusb.h>
100#endif
101#ifdef VBOX_WITH_NETSHAPER
102# include <VBox/vmm/pdmnetshaper.h>
103#endif /* VBOX_WITH_NETSHAPER */
104#include <VBox/vmm/mm.h>
105#include <VBox/vmm/ftm.h>
106#include <VBox/vmm/ssm.h>
107#include <VBox/err.h>
108#include <VBox/param.h>
109#include <VBox/vusb.h>
110
111#include <VBox/VMMDev.h>
112
113#include <VBox/HostServices/VBoxClipboardSvc.h>
114#include <VBox/HostServices/DragAndDropSvc.h>
115#ifdef VBOX_WITH_GUEST_PROPS
116# include <VBox/HostServices/GuestPropertySvc.h>
117# include <VBox/com/array.h>
118#endif
119
120#include <set>
121#include <algorithm>
122#include <memory> // for auto_ptr
123#include <vector>
124
125
126// VMTask and friends
127////////////////////////////////////////////////////////////////////////////////
128
129/**
130 * Task structure for asynchronous VM operations.
131 *
132 * Once created, the task structure adds itself as a Console caller. This means:
133 *
134 * 1. The user must check for #rc() before using the created structure
135 * (e.g. passing it as a thread function argument). If #rc() returns a
136 * failure, the Console object may not be used by the task (see
137 * Console::addCaller() for more details).
138 * 2. On successful initialization, the structure keeps the Console caller
139 * until destruction (to ensure Console remains in the Ready state and won't
140 * be accidentally uninitialized). Forgetting to delete the created task
141 * will lead to Console::uninit() stuck waiting for releasing all added
142 * callers.
143 *
144 * If \a aUsesVMPtr parameter is true, the task structure will also add itself
145 * as a Console::mpUVM caller with the same meaning as above. See
146 * Console::addVMCaller() for more info.
147 */
148struct VMTask
149{
150 VMTask(Console *aConsole,
151 Progress *aProgress,
152 const ComPtr<IProgress> &aServerProgress,
153 bool aUsesVMPtr)
154 : mConsole(aConsole),
155 mConsoleCaller(aConsole),
156 mProgress(aProgress),
157 mServerProgress(aServerProgress),
158 mpUVM(NULL),
159 mRC(E_FAIL),
160 mpSafeVMPtr(NULL)
161 {
162 AssertReturnVoid(aConsole);
163 mRC = mConsoleCaller.rc();
164 if (FAILED(mRC))
165 return;
166 if (aUsesVMPtr)
167 {
168 mpSafeVMPtr = new Console::SafeVMPtr(aConsole);
169 if (mpSafeVMPtr->isOk())
170 mpUVM = mpSafeVMPtr->rawUVM();
171 else
172 mRC = mpSafeVMPtr->rc();
173 }
174 }
175
176 ~VMTask()
177 {
178 releaseVMCaller();
179 }
180
181 HRESULT rc() const { return mRC; }
182 bool isOk() const { return SUCCEEDED(rc()); }
183
184 /** Releases the VM caller before destruction. Not normally necessary. */
185 void releaseVMCaller()
186 {
187 if (mpSafeVMPtr)
188 {
189 delete mpSafeVMPtr;
190 mpSafeVMPtr = NULL;
191 }
192 }
193
194 const ComObjPtr<Console> mConsole;
195 AutoCaller mConsoleCaller;
196 const ComObjPtr<Progress> mProgress;
197 Utf8Str mErrorMsg;
198 const ComPtr<IProgress> mServerProgress;
199 PUVM mpUVM;
200
201private:
202 HRESULT mRC;
203 Console::SafeVMPtr *mpSafeVMPtr;
204};
205
206struct VMTakeSnapshotTask : public VMTask
207{
208 VMTakeSnapshotTask(Console *aConsole,
209 Progress *aProgress,
210 IN_BSTR aName,
211 IN_BSTR aDescription)
212 : VMTask(aConsole, aProgress, NULL /* aServerProgress */,
213 false /* aUsesVMPtr */),
214 bstrName(aName),
215 bstrDescription(aDescription),
216 lastMachineState(MachineState_Null)
217 {}
218
219 Bstr bstrName,
220 bstrDescription;
221 Bstr bstrSavedStateFile; // received from BeginTakeSnapshot()
222 MachineState_T lastMachineState;
223 bool fTakingSnapshotOnline;
224 ULONG ulMemSize;
225};
226
227struct VMPowerUpTask : public VMTask
228{
229 VMPowerUpTask(Console *aConsole,
230 Progress *aProgress)
231 : VMTask(aConsole, aProgress, NULL /* aServerProgress */,
232 false /* aUsesVMPtr */),
233 mConfigConstructor(NULL),
234 mStartPaused(false),
235 mTeleporterEnabled(FALSE),
236 mEnmFaultToleranceState(FaultToleranceState_Inactive)
237 {}
238
239 PFNCFGMCONSTRUCTOR mConfigConstructor;
240 Utf8Str mSavedStateFile;
241 Console::SharedFolderDataMap mSharedFolders;
242 bool mStartPaused;
243 BOOL mTeleporterEnabled;
244 FaultToleranceState_T mEnmFaultToleranceState;
245
246 /* array of progress objects for hard disk reset operations */
247 typedef std::list<ComPtr<IProgress> > ProgressList;
248 ProgressList hardDiskProgresses;
249};
250
251struct VMPowerDownTask : public VMTask
252{
253 VMPowerDownTask(Console *aConsole,
254 const ComPtr<IProgress> &aServerProgress)
255 : VMTask(aConsole, NULL /* aProgress */, aServerProgress,
256 true /* aUsesVMPtr */)
257 {}
258};
259
260struct VMSaveTask : public VMTask
261{
262 VMSaveTask(Console *aConsole,
263 const ComPtr<IProgress> &aServerProgress,
264 const Utf8Str &aSavedStateFile,
265 MachineState_T aMachineStateBefore,
266 Reason_T aReason)
267 : VMTask(aConsole, NULL /* aProgress */, aServerProgress,
268 true /* aUsesVMPtr */),
269 mSavedStateFile(aSavedStateFile),
270 mMachineStateBefore(aMachineStateBefore),
271 mReason(aReason)
272 {}
273
274 Utf8Str mSavedStateFile;
275 /* The local machine state we had before. Required if something fails */
276 MachineState_T mMachineStateBefore;
277 /* The reason for saving state */
278 Reason_T mReason;
279};
280
281// Handler for global events
282////////////////////////////////////////////////////////////////////////////////
283inline static const char *networkAdapterTypeToName(NetworkAdapterType_T adapterType);
284
285class VmEventListener {
286public:
287 VmEventListener()
288 {}
289
290
291 HRESULT init(Console *aConsole)
292 {
293 mConsole = aConsole;
294 return S_OK;
295 }
296
297 void uninit()
298 {
299 }
300
301 virtual ~VmEventListener()
302 {
303 }
304
305 STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent * aEvent)
306 {
307 switch(aType)
308 {
309 case VBoxEventType_OnNATRedirect:
310 {
311 Bstr id;
312 ComPtr<IMachine> pMachine = mConsole->machine();
313 ComPtr<INATRedirectEvent> pNREv = aEvent;
314 HRESULT rc = E_FAIL;
315 Assert(pNREv);
316
317 Bstr interestedId;
318 rc = pMachine->COMGETTER(Id)(interestedId.asOutParam());
319 AssertComRC(rc);
320 rc = pNREv->COMGETTER(MachineId)(id.asOutParam());
321 AssertComRC(rc);
322 if (id != interestedId)
323 break;
324 /* now we can operate with redirects */
325 NATProtocol_T proto;
326 pNREv->COMGETTER(Proto)(&proto);
327 BOOL fRemove;
328 pNREv->COMGETTER(Remove)(&fRemove);
329 bool fUdp = (proto == NATProtocol_UDP);
330 Bstr hostIp, guestIp;
331 LONG hostPort, guestPort;
332 pNREv->COMGETTER(HostIP)(hostIp.asOutParam());
333 pNREv->COMGETTER(HostPort)(&hostPort);
334 pNREv->COMGETTER(GuestIP)(guestIp.asOutParam());
335 pNREv->COMGETTER(GuestPort)(&guestPort);
336 ULONG ulSlot;
337 rc = pNREv->COMGETTER(Slot)(&ulSlot);
338 AssertComRC(rc);
339 if (FAILED(rc))
340 break;
341 mConsole->onNATRedirectRuleChange(ulSlot, fRemove, proto, hostIp.raw(), hostPort, guestIp.raw(), guestPort);
342 }
343 break;
344
345 case VBoxEventType_OnHostPCIDevicePlug:
346 {
347 // handle if needed
348 break;
349 }
350
351 default:
352 AssertFailed();
353 }
354 return S_OK;
355 }
356private:
357 Console *mConsole;
358};
359
360typedef ListenerImpl<VmEventListener, Console*> VmEventListenerImpl;
361
362
363VBOX_LISTENER_DECLARE(VmEventListenerImpl)
364
365
366// constructor / destructor
367/////////////////////////////////////////////////////////////////////////////
368
369Console::Console()
370 : mSavedStateDataLoaded(false)
371 , mConsoleVRDPServer(NULL)
372 , 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
4422
4423/**
4424 * Process a network adaptor change.
4425 *
4426 * @returns COM status code.
4427 *
4428 * @parma pUVM The VM handle (caller hold this safely).
4429 * @param pszDevice The PDM device name.
4430 * @param uInstance The PDM device instance.
4431 * @param uLun The PDM LUN number of the drive.
4432 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
4433 */
4434HRESULT Console::doNetworkAdapterChange(PUVM pUVM,
4435 const char *pszDevice,
4436 unsigned uInstance,
4437 unsigned uLun,
4438 INetworkAdapter *aNetworkAdapter)
4439{
4440 LogFlowThisFunc(("pszDevice=%p:{%s} uInstance=%u uLun=%u aNetworkAdapter=%p\n",
4441 pszDevice, pszDevice, uInstance, uLun, aNetworkAdapter));
4442
4443 AutoCaller autoCaller(this);
4444 AssertComRCReturnRC(autoCaller.rc());
4445
4446 /*
4447 * Call worker in EMT, that's faster and safer than doing everything
4448 * using VM3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
4449 * here to make requests from under the lock in order to serialize them.
4450 */
4451 PVMREQ pReq;
4452 int vrc = VMR3ReqCallU(pUVM, 0 /*idDstCpu*/, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS,
4453 (PFNRT)Console::changeNetworkAttachment, 6,
4454 this, pUVM, pszDevice, uInstance, uLun, aNetworkAdapter);
4455
4456 if (vrc == VERR_TIMEOUT || RT_SUCCESS(vrc))
4457 {
4458 vrc = VMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
4459 AssertRC(vrc);
4460 if (RT_SUCCESS(vrc))
4461 vrc = pReq->iStatus;
4462 }
4463 VMR3ReqFree(pReq);
4464
4465 if (RT_SUCCESS(vrc))
4466 {
4467 LogFlowThisFunc(("Returns S_OK\n"));
4468 return S_OK;
4469 }
4470
4471 return setError(E_FAIL,
4472 tr("Could not change the network adaptor attachement type (%Rrc)"),
4473 vrc);
4474}
4475
4476
4477/**
4478 * Performs the Network Adaptor change in EMT.
4479 *
4480 * @returns VBox status code.
4481 *
4482 * @param pThis Pointer to the Console object.
4483 * @param pUVM The VM handle.
4484 * @param pszDevice The PDM device name.
4485 * @param uInstance The PDM device instance.
4486 * @param uLun The PDM LUN number of the drive.
4487 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
4488 *
4489 * @thread EMT
4490 * @note Locks the Console object for writing.
4491 */
4492DECLCALLBACK(int) Console::changeNetworkAttachment(Console *pThis,
4493 PUVM pUVM,
4494 const char *pszDevice,
4495 unsigned uInstance,
4496 unsigned uLun,
4497 INetworkAdapter *aNetworkAdapter)
4498{
4499 LogFlowFunc(("pThis=%p pszDevice=%p:{%s} uInstance=%u uLun=%u aNetworkAdapter=%p\n",
4500 pThis, pszDevice, pszDevice, uInstance, uLun, aNetworkAdapter));
4501
4502 AssertReturn(pThis, VERR_INVALID_PARAMETER);
4503
4504 AutoCaller autoCaller(pThis);
4505 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
4506
4507 ComPtr<IVirtualBox> pVirtualBox;
4508 pThis->mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
4509 ComPtr<ISystemProperties> pSystemProperties;
4510 if (pVirtualBox)
4511 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
4512 ChipsetType_T chipsetType = ChipsetType_PIIX3;
4513 pThis->mMachine->COMGETTER(ChipsetType)(&chipsetType);
4514 ULONG maxNetworkAdapters = 0;
4515 if (pSystemProperties)
4516 pSystemProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
4517 AssertMsg( ( !strcmp(pszDevice, "pcnet")
4518 || !strcmp(pszDevice, "e1000")
4519 || !strcmp(pszDevice, "virtio-net"))
4520 && uLun == 0
4521 && uInstance < maxNetworkAdapters,
4522 ("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
4523 Log(("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
4524
4525 /*
4526 * Suspend the VM first.
4527 *
4528 * The VM must not be running since it might have pending I/O to
4529 * the drive which is being changed.
4530 */
4531 bool fResume;
4532 VMSTATE enmVMState = VMR3GetStateU(pUVM);
4533 switch (enmVMState)
4534 {
4535 case VMSTATE_RESETTING:
4536 case VMSTATE_RUNNING:
4537 {
4538 LogFlowFunc(("Suspending the VM...\n"));
4539 /* disable the callback to prevent Console-level state change */
4540 pThis->mVMStateChangeCallbackDisabled = true;
4541 int rc = VMR3Suspend(pUVM, VMSUSPENDREASON_RECONFIG);
4542 pThis->mVMStateChangeCallbackDisabled = false;
4543 AssertRCReturn(rc, rc);
4544 fResume = true;
4545 break;
4546 }
4547
4548 case VMSTATE_SUSPENDED:
4549 case VMSTATE_CREATED:
4550 case VMSTATE_OFF:
4551 fResume = false;
4552 break;
4553
4554 default:
4555 AssertLogRelMsgFailedReturn(("enmVMState=%d\n", enmVMState), VERR_ACCESS_DENIED);
4556 }
4557
4558 int rc = VINF_SUCCESS;
4559 int rcRet = VINF_SUCCESS;
4560
4561 PCFGMNODE pCfg = NULL; /* /Devices/Dev/.../Config/ */
4562 PCFGMNODE pLunL0 = NULL; /* /Devices/Dev/0/LUN#0/ */
4563 PCFGMNODE pInst = CFGMR3GetChildF(CFGMR3GetRootU(pUVM), "Devices/%s/%d/", pszDevice, uInstance);
4564 AssertRelease(pInst);
4565
4566 rcRet = pThis->configNetwork(pszDevice, uInstance, uLun, aNetworkAdapter, pCfg, pLunL0, pInst,
4567 true /*fAttachDetach*/, false /*fIgnoreConnectFailure*/);
4568
4569 /*
4570 * Resume the VM if necessary.
4571 */
4572 if (fResume)
4573 {
4574 LogFlowFunc(("Resuming the VM...\n"));
4575 /* disable the callback to prevent Console-level state change */
4576 pThis->mVMStateChangeCallbackDisabled = true;
4577 rc = VMR3Resume(pUVM, VMRESUMEREASON_RECONFIG);
4578 pThis->mVMStateChangeCallbackDisabled = false;
4579 AssertRC(rc);
4580 if (RT_FAILURE(rc))
4581 {
4582 /* too bad, we failed. try to sync the console state with the VMM state */
4583 vmstateChangeCallback(pUVM, VMSTATE_SUSPENDED, enmVMState, pThis);
4584 }
4585 /// @todo (r=dmik) if we failed with drive mount, then the VMR3Resume
4586 // error (if any) will be hidden from the caller. For proper reporting
4587 // of such multiple errors to the caller we need to enhance the
4588 // IVirtualBoxError interface. For now, give the first error the higher
4589 // priority.
4590 if (RT_SUCCESS(rcRet))
4591 rcRet = rc;
4592 }
4593
4594 LogFlowFunc(("Returning %Rrc\n", rcRet));
4595 return rcRet;
4596}
4597
4598
4599/**
4600 * Called by IInternalSessionControl::OnSerialPortChange().
4601 */
4602HRESULT Console::onSerialPortChange(ISerialPort *aSerialPort)
4603{
4604 LogFlowThisFunc(("\n"));
4605
4606 AutoCaller autoCaller(this);
4607 AssertComRCReturnRC(autoCaller.rc());
4608
4609 fireSerialPortChangedEvent(mEventSource, aSerialPort);
4610
4611 LogFlowThisFunc(("Leaving rc=%#x\n", S_OK));
4612 return S_OK;
4613}
4614
4615/**
4616 * Called by IInternalSessionControl::OnParallelPortChange().
4617 */
4618HRESULT Console::onParallelPortChange(IParallelPort *aParallelPort)
4619{
4620 LogFlowThisFunc(("\n"));
4621
4622 AutoCaller autoCaller(this);
4623 AssertComRCReturnRC(autoCaller.rc());
4624
4625 fireParallelPortChangedEvent(mEventSource, aParallelPort);
4626
4627 LogFlowThisFunc(("Leaving rc=%#x\n", S_OK));
4628 return S_OK;
4629}
4630
4631/**
4632 * Called by IInternalSessionControl::OnStorageControllerChange().
4633 */
4634HRESULT Console::onStorageControllerChange()
4635{
4636 LogFlowThisFunc(("\n"));
4637
4638 AutoCaller autoCaller(this);
4639 AssertComRCReturnRC(autoCaller.rc());
4640
4641 fireStorageControllerChangedEvent(mEventSource);
4642
4643 LogFlowThisFunc(("Leaving rc=%#x\n", S_OK));
4644 return S_OK;
4645}
4646
4647/**
4648 * Called by IInternalSessionControl::OnMediumChange().
4649 */
4650HRESULT Console::onMediumChange(IMediumAttachment *aMediumAttachment, BOOL aForce)
4651{
4652 LogFlowThisFunc(("\n"));
4653
4654 AutoCaller autoCaller(this);
4655 AssertComRCReturnRC(autoCaller.rc());
4656
4657 HRESULT rc = S_OK;
4658
4659 /* don't trigger medium changes if the VM isn't running */
4660 SafeVMPtrQuiet ptrVM(this);
4661 if (ptrVM.isOk())
4662 {
4663 rc = doMediumChange(aMediumAttachment, !!aForce, ptrVM.rawUVM());
4664 ptrVM.release();
4665 }
4666
4667 /* notify console callbacks on success */
4668 if (SUCCEEDED(rc))
4669 fireMediumChangedEvent(mEventSource, aMediumAttachment);
4670
4671 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4672 return rc;
4673}
4674
4675/**
4676 * Called by IInternalSessionControl::OnCPUChange().
4677 *
4678 * @note Locks this object for writing.
4679 */
4680HRESULT Console::onCPUChange(ULONG aCPU, BOOL aRemove)
4681{
4682 LogFlowThisFunc(("\n"));
4683
4684 AutoCaller autoCaller(this);
4685 AssertComRCReturnRC(autoCaller.rc());
4686
4687 HRESULT rc = S_OK;
4688
4689 /* don't trigger CPU changes if the VM isn't running */
4690 SafeVMPtrQuiet ptrVM(this);
4691 if (ptrVM.isOk())
4692 {
4693 if (aRemove)
4694 rc = doCPURemove(aCPU, ptrVM.rawUVM());
4695 else
4696 rc = doCPUAdd(aCPU, ptrVM.rawUVM());
4697 ptrVM.release();
4698 }
4699
4700 /* notify console callbacks on success */
4701 if (SUCCEEDED(rc))
4702 fireCPUChangedEvent(mEventSource, aCPU, aRemove);
4703
4704 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4705 return rc;
4706}
4707
4708/**
4709 * Called by IInternalSessionControl::OnCpuExecutionCapChange().
4710 *
4711 * @note Locks this object for writing.
4712 */
4713HRESULT Console::onCPUExecutionCapChange(ULONG aExecutionCap)
4714{
4715 LogFlowThisFunc(("\n"));
4716
4717 AutoCaller autoCaller(this);
4718 AssertComRCReturnRC(autoCaller.rc());
4719
4720 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4721
4722 HRESULT rc = S_OK;
4723
4724 /* don't trigger the CPU priority change if the VM isn't running */
4725 SafeVMPtrQuiet ptrVM(this);
4726 if (ptrVM.isOk())
4727 {
4728 if ( mMachineState == MachineState_Running
4729 || mMachineState == MachineState_Teleporting
4730 || mMachineState == MachineState_LiveSnapshotting
4731 )
4732 {
4733 /* No need to call in the EMT thread. */
4734 rc = VMR3SetCpuExecutionCap(ptrVM.rawUVM(), aExecutionCap);
4735 }
4736 else
4737 rc = setInvalidMachineStateError();
4738 ptrVM.release();
4739 }
4740
4741 /* notify console callbacks on success */
4742 if (SUCCEEDED(rc))
4743 {
4744 alock.release();
4745 fireCPUExecutionCapChangedEvent(mEventSource, aExecutionCap);
4746 }
4747
4748 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4749 return rc;
4750}
4751
4752/**
4753 * Called by IInternalSessionControl::OnClipboardModeChange().
4754 *
4755 * @note Locks this object for writing.
4756 */
4757HRESULT Console::onClipboardModeChange(ClipboardMode_T aClipboardMode)
4758{
4759 LogFlowThisFunc(("\n"));
4760
4761 AutoCaller autoCaller(this);
4762 AssertComRCReturnRC(autoCaller.rc());
4763
4764 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4765
4766 HRESULT rc = S_OK;
4767
4768 /* don't trigger the clipboard mode change if the VM isn't running */
4769 SafeVMPtrQuiet ptrVM(this);
4770 if (ptrVM.isOk())
4771 {
4772 if ( mMachineState == MachineState_Running
4773 || mMachineState == MachineState_Teleporting
4774 || mMachineState == MachineState_LiveSnapshotting)
4775 changeClipboardMode(aClipboardMode);
4776 else
4777 rc = setInvalidMachineStateError();
4778 ptrVM.release();
4779 }
4780
4781 /* notify console callbacks on success */
4782 if (SUCCEEDED(rc))
4783 {
4784 alock.release();
4785 fireClipboardModeChangedEvent(mEventSource, aClipboardMode);
4786 }
4787
4788 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4789 return rc;
4790}
4791
4792/**
4793 * Called by IInternalSessionControl::OnDragAndDropModeChange().
4794 *
4795 * @note Locks this object for writing.
4796 */
4797HRESULT Console::onDragAndDropModeChange(DragAndDropMode_T aDragAndDropMode)
4798{
4799 LogFlowThisFunc(("\n"));
4800
4801 AutoCaller autoCaller(this);
4802 AssertComRCReturnRC(autoCaller.rc());
4803
4804 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4805
4806 HRESULT rc = S_OK;
4807
4808 /* don't trigger the drag'n'drop mode change if the VM isn't running */
4809 SafeVMPtrQuiet ptrVM(this);
4810 if (ptrVM.isOk())
4811 {
4812 if ( mMachineState == MachineState_Running
4813 || mMachineState == MachineState_Teleporting
4814 || mMachineState == MachineState_LiveSnapshotting)
4815 changeDragAndDropMode(aDragAndDropMode);
4816 else
4817 rc = setInvalidMachineStateError();
4818 ptrVM.release();
4819 }
4820
4821 /* notify console callbacks on success */
4822 if (SUCCEEDED(rc))
4823 {
4824 alock.release();
4825 fireDragAndDropModeChangedEvent(mEventSource, aDragAndDropMode);
4826 }
4827
4828 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4829 return rc;
4830}
4831
4832/**
4833 * Called by IInternalSessionControl::OnVRDEServerChange().
4834 *
4835 * @note Locks this object for writing.
4836 */
4837HRESULT Console::onVRDEServerChange(BOOL aRestart)
4838{
4839 AutoCaller autoCaller(this);
4840 AssertComRCReturnRC(autoCaller.rc());
4841
4842 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4843
4844 HRESULT rc = S_OK;
4845
4846 /* don't trigger VRDE server changes if the VM isn't running */
4847 SafeVMPtrQuiet ptrVM(this);
4848 if (ptrVM.isOk())
4849 {
4850 /* Serialize. */
4851 if (mfVRDEChangeInProcess)
4852 mfVRDEChangePending = true;
4853 else
4854 {
4855 do {
4856 mfVRDEChangeInProcess = true;
4857 mfVRDEChangePending = false;
4858
4859 if ( mVRDEServer
4860 && ( mMachineState == MachineState_Running
4861 || mMachineState == MachineState_Teleporting
4862 || mMachineState == MachineState_LiveSnapshotting
4863 || mMachineState == MachineState_Paused
4864 )
4865 )
4866 {
4867 BOOL vrdpEnabled = FALSE;
4868
4869 rc = mVRDEServer->COMGETTER(Enabled)(&vrdpEnabled);
4870 ComAssertComRCRetRC(rc);
4871
4872 if (aRestart)
4873 {
4874 /* VRDP server may call this Console object back from other threads (VRDP INPUT or OUTPUT). */
4875 alock.release();
4876
4877 if (vrdpEnabled)
4878 {
4879 // If there was no VRDP server started the 'stop' will do nothing.
4880 // However if a server was started and this notification was called,
4881 // we have to restart the server.
4882 mConsoleVRDPServer->Stop();
4883
4884 if (RT_FAILURE(mConsoleVRDPServer->Launch()))
4885 rc = E_FAIL;
4886 else
4887 mConsoleVRDPServer->EnableConnections();
4888 }
4889 else
4890 mConsoleVRDPServer->Stop();
4891
4892 alock.acquire();
4893 }
4894 }
4895 else
4896 rc = setInvalidMachineStateError();
4897
4898 mfVRDEChangeInProcess = false;
4899 } while (mfVRDEChangePending && SUCCEEDED(rc));
4900 }
4901
4902 ptrVM.release();
4903 }
4904
4905 /* notify console callbacks on success */
4906 if (SUCCEEDED(rc))
4907 {
4908 alock.release();
4909 fireVRDEServerChangedEvent(mEventSource);
4910 }
4911
4912 return rc;
4913}
4914
4915void Console::onVRDEServerInfoChange()
4916{
4917 AutoCaller autoCaller(this);
4918 AssertComRCReturnVoid(autoCaller.rc());
4919
4920 fireVRDEServerInfoChangedEvent(mEventSource);
4921}
4922
4923HRESULT Console::onVideoCaptureChange()
4924{
4925 AutoCaller autoCaller(this);
4926 AssertComRCReturnRC(autoCaller.rc());
4927
4928 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4929
4930 HRESULT rc = S_OK;
4931
4932 /* don't trigger video capture changes if the VM isn't running */
4933 SafeVMPtrQuiet ptrVM(this);
4934 if (ptrVM.isOk())
4935 {
4936 BOOL fEnabled;
4937 rc = mMachine->COMGETTER(VideoCaptureEnabled)(&fEnabled);
4938 SafeArray<BOOL> screens;
4939 if (SUCCEEDED(rc))
4940 rc = mMachine->COMGETTER(VideoCaptureScreens)(ComSafeArrayAsOutParam(screens));
4941 if (mDisplay)
4942 {
4943 int vrc = VINF_SUCCESS;
4944 if (SUCCEEDED(rc))
4945 vrc = mDisplay->VideoCaptureEnableScreens(ComSafeArrayAsInParam(screens));
4946 if (RT_SUCCESS(vrc))
4947 {
4948 if (fEnabled)
4949 {
4950 vrc = mDisplay->VideoCaptureStart();
4951 if (RT_FAILURE(vrc))
4952 rc = setError(E_FAIL, tr("Unable to start video capturing (%Rrc)"), vrc);
4953 }
4954 else
4955 mDisplay->VideoCaptureStop();
4956 }
4957 else
4958 rc = setError(E_FAIL, tr("Unable to set screens for capturing (%Rrc)"), vrc);
4959 }
4960 ptrVM.release();
4961 }
4962
4963 /* notify console callbacks on success */
4964 if (SUCCEEDED(rc))
4965 {
4966 alock.release();
4967 fireVideoCaptureChangedEvent(mEventSource);
4968 }
4969
4970 return rc;
4971}
4972
4973/**
4974 * Called by IInternalSessionControl::OnUSBControllerChange().
4975 */
4976HRESULT Console::onUSBControllerChange()
4977{
4978 LogFlowThisFunc(("\n"));
4979
4980 AutoCaller autoCaller(this);
4981 AssertComRCReturnRC(autoCaller.rc());
4982
4983 fireUSBControllerChangedEvent(mEventSource);
4984
4985 return S_OK;
4986}
4987
4988/**
4989 * Called by IInternalSessionControl::OnSharedFolderChange().
4990 *
4991 * @note Locks this object for writing.
4992 */
4993HRESULT Console::onSharedFolderChange(BOOL aGlobal)
4994{
4995 LogFlowThisFunc(("aGlobal=%RTbool\n", aGlobal));
4996
4997 AutoCaller autoCaller(this);
4998 AssertComRCReturnRC(autoCaller.rc());
4999
5000 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5001
5002 HRESULT rc = fetchSharedFolders(aGlobal);
5003
5004 /* notify console callbacks on success */
5005 if (SUCCEEDED(rc))
5006 {
5007 alock.release();
5008 fireSharedFolderChangedEvent(mEventSource, aGlobal ? (Scope_T)Scope_Global : (Scope_T)Scope_Machine);
5009 }
5010
5011 return rc;
5012}
5013
5014/**
5015 * Called by IInternalSessionControl::OnUSBDeviceAttach() or locally by
5016 * processRemoteUSBDevices() after IInternalMachineControl::RunUSBDeviceFilters()
5017 * returns TRUE for a given remote USB device.
5018 *
5019 * @return S_OK if the device was attached to the VM.
5020 * @return failure if not attached.
5021 *
5022 * @param aDevice
5023 * The device in question.
5024 * @param aMaskedIfs
5025 * The interfaces to hide from the guest.
5026 *
5027 * @note Locks this object for writing.
5028 */
5029HRESULT Console::onUSBDeviceAttach(IUSBDevice *aDevice, IVirtualBoxErrorInfo *aError, ULONG aMaskedIfs)
5030{
5031#ifdef VBOX_WITH_USB
5032 LogFlowThisFunc(("aDevice=%p aError=%p\n", aDevice, aError));
5033
5034 AutoCaller autoCaller(this);
5035 ComAssertComRCRetRC(autoCaller.rc());
5036
5037 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5038
5039 /* Get the VM pointer (we don't need error info, since it's a callback). */
5040 SafeVMPtrQuiet ptrVM(this);
5041 if (!ptrVM.isOk())
5042 {
5043 /* The VM may be no more operational when this message arrives
5044 * (e.g. it may be Saving or Stopping or just PoweredOff) --
5045 * autoVMCaller.rc() will return a failure in this case. */
5046 LogFlowThisFunc(("Attach request ignored (mMachineState=%d).\n",
5047 mMachineState));
5048 return ptrVM.rc();
5049 }
5050
5051 if (aError != NULL)
5052 {
5053 /* notify callbacks about the error */
5054 alock.release();
5055 onUSBDeviceStateChange(aDevice, true /* aAttached */, aError);
5056 return S_OK;
5057 }
5058
5059 /* Don't proceed unless there's at least one USB hub. */
5060 if (!PDMR3UsbHasHub(ptrVM.rawUVM()))
5061 {
5062 LogFlowThisFunc(("Attach request ignored (no USB controller).\n"));
5063 return E_FAIL;
5064 }
5065
5066 alock.release();
5067 HRESULT rc = attachUSBDevice(aDevice, aMaskedIfs);
5068 if (FAILED(rc))
5069 {
5070 /* take the current error info */
5071 com::ErrorInfoKeeper eik;
5072 /* the error must be a VirtualBoxErrorInfo instance */
5073 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
5074 Assert(!pError.isNull());
5075 if (!pError.isNull())
5076 {
5077 /* notify callbacks about the error */
5078 onUSBDeviceStateChange(aDevice, true /* aAttached */, pError);
5079 }
5080 }
5081
5082 return rc;
5083
5084#else /* !VBOX_WITH_USB */
5085 return E_FAIL;
5086#endif /* !VBOX_WITH_USB */
5087}
5088
5089/**
5090 * Called by IInternalSessionControl::OnUSBDeviceDetach() and locally by
5091 * processRemoteUSBDevices().
5092 *
5093 * @note Locks this object for writing.
5094 */
5095HRESULT Console::onUSBDeviceDetach(IN_BSTR aId,
5096 IVirtualBoxErrorInfo *aError)
5097{
5098#ifdef VBOX_WITH_USB
5099 Guid Uuid(aId);
5100 LogFlowThisFunc(("aId={%RTuuid} aError=%p\n", Uuid.raw(), aError));
5101
5102 AutoCaller autoCaller(this);
5103 AssertComRCReturnRC(autoCaller.rc());
5104
5105 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5106
5107 /* Find the device. */
5108 ComObjPtr<OUSBDevice> pUSBDevice;
5109 USBDeviceList::iterator it = mUSBDevices.begin();
5110 while (it != mUSBDevices.end())
5111 {
5112 LogFlowThisFunc(("it={%RTuuid}\n", (*it)->id().raw()));
5113 if ((*it)->id() == Uuid)
5114 {
5115 pUSBDevice = *it;
5116 break;
5117 }
5118 ++it;
5119 }
5120
5121
5122 if (pUSBDevice.isNull())
5123 {
5124 LogFlowThisFunc(("USB device not found.\n"));
5125
5126 /* The VM may be no more operational when this message arrives
5127 * (e.g. it may be Saving or Stopping or just PoweredOff). Use
5128 * AutoVMCaller to detect it -- AutoVMCaller::rc() will return a
5129 * failure in this case. */
5130
5131 AutoVMCallerQuiet autoVMCaller(this);
5132 if (FAILED(autoVMCaller.rc()))
5133 {
5134 LogFlowThisFunc(("Detach request ignored (mMachineState=%d).\n",
5135 mMachineState));
5136 return autoVMCaller.rc();
5137 }
5138
5139 /* the device must be in the list otherwise */
5140 AssertFailedReturn(E_FAIL);
5141 }
5142
5143 if (aError != NULL)
5144 {
5145 /* notify callback about an error */
5146 alock.release();
5147 onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, aError);
5148 return S_OK;
5149 }
5150
5151 /* Remove the device from the collection, it is re-added below for failures */
5152 mUSBDevices.erase(it);
5153
5154 alock.release();
5155 HRESULT rc = detachUSBDevice(pUSBDevice);
5156 if (FAILED(rc))
5157 {
5158 /* Re-add the device to the collection */
5159 alock.acquire();
5160 mUSBDevices.push_back(pUSBDevice);
5161 alock.release();
5162 /* take the current error info */
5163 com::ErrorInfoKeeper eik;
5164 /* the error must be a VirtualBoxErrorInfo instance */
5165 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
5166 Assert(!pError.isNull());
5167 if (!pError.isNull())
5168 {
5169 /* notify callbacks about the error */
5170 onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, pError);
5171 }
5172 }
5173
5174 return rc;
5175
5176#else /* !VBOX_WITH_USB */
5177 return E_FAIL;
5178#endif /* !VBOX_WITH_USB */
5179}
5180
5181/**
5182 * Called by IInternalSessionControl::OnBandwidthGroupChange().
5183 *
5184 * @note Locks this object for writing.
5185 */
5186HRESULT Console::onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
5187{
5188 LogFlowThisFunc(("\n"));
5189
5190 AutoCaller autoCaller(this);
5191 AssertComRCReturnRC(autoCaller.rc());
5192
5193 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5194
5195 HRESULT rc = S_OK;
5196
5197 /* don't trigger bandwidth group changes if the VM isn't running */
5198 SafeVMPtrQuiet ptrVM(this);
5199 if (ptrVM.isOk())
5200 {
5201 if ( mMachineState == MachineState_Running
5202 || mMachineState == MachineState_Teleporting
5203 || mMachineState == MachineState_LiveSnapshotting
5204 )
5205 {
5206 /* No need to call in the EMT thread. */
5207 LONG64 cMax;
5208 Bstr strName;
5209 BandwidthGroupType_T enmType;
5210 rc = aBandwidthGroup->COMGETTER(Name)(strName.asOutParam());
5211 if (SUCCEEDED(rc))
5212 rc = aBandwidthGroup->COMGETTER(MaxBytesPerSec)(&cMax);
5213 if (SUCCEEDED(rc))
5214 rc = aBandwidthGroup->COMGETTER(Type)(&enmType);
5215
5216 if (SUCCEEDED(rc))
5217 {
5218 int vrc = VINF_SUCCESS;
5219 if (enmType == BandwidthGroupType_Disk)
5220 vrc = PDMR3AsyncCompletionBwMgrSetMaxForFile(ptrVM.rawUVM(), Utf8Str(strName).c_str(), cMax);
5221#ifdef VBOX_WITH_NETSHAPER
5222 else if (enmType == BandwidthGroupType_Network)
5223 vrc = PDMR3NsBwGroupSetLimit(ptrVM.rawUVM(), Utf8Str(strName).c_str(), cMax);
5224 else
5225 rc = E_NOTIMPL;
5226#endif /* VBOX_WITH_NETSHAPER */
5227 AssertRC(vrc);
5228 }
5229 }
5230 else
5231 rc = setInvalidMachineStateError();
5232 ptrVM.release();
5233 }
5234
5235 /* notify console callbacks on success */
5236 if (SUCCEEDED(rc))
5237 {
5238 alock.release();
5239 fireBandwidthGroupChangedEvent(mEventSource, aBandwidthGroup);
5240 }
5241
5242 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
5243 return rc;
5244}
5245
5246/**
5247 * Called by IInternalSessionControl::OnStorageDeviceChange().
5248 *
5249 * @note Locks this object for writing.
5250 */
5251HRESULT Console::onStorageDeviceChange(IMediumAttachment *aMediumAttachment, BOOL aRemove, BOOL aSilent)
5252{
5253 LogFlowThisFunc(("\n"));
5254
5255 AutoCaller autoCaller(this);
5256 AssertComRCReturnRC(autoCaller.rc());
5257
5258 HRESULT rc = S_OK;
5259
5260 /* don't trigger medium changes if the VM isn't running */
5261 SafeVMPtrQuiet ptrVM(this);
5262 if (ptrVM.isOk())
5263 {
5264 if (aRemove)
5265 rc = doStorageDeviceDetach(aMediumAttachment, ptrVM.rawUVM(), RT_BOOL(aSilent));
5266 else
5267 rc = doStorageDeviceAttach(aMediumAttachment, ptrVM.rawUVM(), RT_BOOL(aSilent));
5268 ptrVM.release();
5269 }
5270
5271 /* notify console callbacks on success */
5272 if (SUCCEEDED(rc))
5273 fireStorageDeviceChangedEvent(mEventSource, aMediumAttachment, aRemove, aSilent);
5274
5275 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
5276 return rc;
5277}
5278
5279/**
5280 * @note Temporarily locks this object for writing.
5281 */
5282HRESULT Console::getGuestProperty(IN_BSTR aName, BSTR *aValue,
5283 LONG64 *aTimestamp, BSTR *aFlags)
5284{
5285#ifndef VBOX_WITH_GUEST_PROPS
5286 ReturnComNotImplemented();
5287#else /* VBOX_WITH_GUEST_PROPS */
5288 if (!VALID_PTR(aName))
5289 return E_INVALIDARG;
5290 if (!VALID_PTR(aValue))
5291 return E_POINTER;
5292 if ((aTimestamp != NULL) && !VALID_PTR(aTimestamp))
5293 return E_POINTER;
5294 if ((aFlags != NULL) && !VALID_PTR(aFlags))
5295 return E_POINTER;
5296
5297 AutoCaller autoCaller(this);
5298 AssertComRCReturnRC(autoCaller.rc());
5299
5300 /* protect mpUVM (if not NULL) */
5301 SafeVMPtrQuiet ptrVM(this);
5302 if (FAILED(ptrVM.rc()))
5303 return ptrVM.rc();
5304
5305 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
5306 * ptrVM, so there is no need to hold a lock of this */
5307
5308 HRESULT rc = E_UNEXPECTED;
5309 using namespace guestProp;
5310
5311 try
5312 {
5313 VBOXHGCMSVCPARM parm[4];
5314 Utf8Str Utf8Name = aName;
5315 char szBuffer[MAX_VALUE_LEN + MAX_FLAGS_LEN];
5316
5317 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
5318 parm[0].u.pointer.addr = (void*)Utf8Name.c_str();
5319 /* The + 1 is the null terminator */
5320 parm[0].u.pointer.size = (uint32_t)Utf8Name.length() + 1;
5321 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
5322 parm[1].u.pointer.addr = szBuffer;
5323 parm[1].u.pointer.size = sizeof(szBuffer);
5324 int vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GET_PROP_HOST,
5325 4, &parm[0]);
5326 /* The returned string should never be able to be greater than our buffer */
5327 AssertLogRel(vrc != VERR_BUFFER_OVERFLOW);
5328 AssertLogRel(RT_FAILURE(vrc) || VBOX_HGCM_SVC_PARM_64BIT == parm[2].type);
5329 if (RT_SUCCESS(vrc) || (VERR_NOT_FOUND == vrc))
5330 {
5331 rc = S_OK;
5332 if (vrc != VERR_NOT_FOUND)
5333 {
5334 Utf8Str strBuffer(szBuffer);
5335 strBuffer.cloneTo(aValue);
5336
5337 if (aTimestamp)
5338 *aTimestamp = parm[2].u.uint64;
5339
5340 if (aFlags)
5341 {
5342 size_t iFlags = strBuffer.length() + 1;
5343 Utf8Str(szBuffer + iFlags).cloneTo(aFlags);
5344 }
5345 }
5346 else
5347 aValue = NULL;
5348 }
5349 else
5350 rc = setError(E_UNEXPECTED,
5351 tr("The service call failed with the error %Rrc"),
5352 vrc);
5353 }
5354 catch(std::bad_alloc & /*e*/)
5355 {
5356 rc = E_OUTOFMEMORY;
5357 }
5358 return rc;
5359#endif /* VBOX_WITH_GUEST_PROPS */
5360}
5361
5362/**
5363 * @note Temporarily locks this object for writing.
5364 */
5365HRESULT Console::setGuestProperty(IN_BSTR aName, IN_BSTR aValue, IN_BSTR aFlags)
5366{
5367#ifndef VBOX_WITH_GUEST_PROPS
5368 ReturnComNotImplemented();
5369#else /* VBOX_WITH_GUEST_PROPS */
5370 if (!RT_VALID_PTR(aName))
5371 return setError(E_INVALIDARG, tr("Name cannot be NULL or an invalid pointer"));
5372 if (aValue != NULL && !RT_VALID_PTR(aValue))
5373 return setError(E_INVALIDARG, tr("Invalid value pointer"));
5374 if (aFlags != NULL && !RT_VALID_PTR(aFlags))
5375 return setError(E_INVALIDARG, tr("Invalid flags pointer"));
5376
5377 AutoCaller autoCaller(this);
5378 AssertComRCReturnRC(autoCaller.rc());
5379
5380 /* protect mpUVM (if not NULL) */
5381 SafeVMPtrQuiet ptrVM(this);
5382 if (FAILED(ptrVM.rc()))
5383 return ptrVM.rc();
5384
5385 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
5386 * ptrVM, so there is no need to hold a lock of this */
5387
5388 using namespace guestProp;
5389
5390 VBOXHGCMSVCPARM parm[3];
5391
5392 Utf8Str Utf8Name = aName;
5393 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
5394 parm[0].u.pointer.addr = (void*)Utf8Name.c_str();
5395 /* The + 1 is the null terminator */
5396 parm[0].u.pointer.size = (uint32_t)Utf8Name.length() + 1;
5397
5398 Utf8Str Utf8Value;
5399 if (aValue != NULL)
5400 {
5401 Utf8Value = aValue;
5402 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
5403 parm[1].u.pointer.addr = (void *)Utf8Value.c_str();
5404 /* The + 1 is the null terminator */
5405 parm[1].u.pointer.size = (uint32_t)Utf8Value.length() + 1;
5406 }
5407
5408 Utf8Str Utf8Flags;
5409 if (aFlags != NULL)
5410 {
5411 Utf8Flags = aFlags;
5412 parm[2].type = VBOX_HGCM_SVC_PARM_PTR;
5413 parm[2].u.pointer.addr = (void*)Utf8Flags.c_str();
5414 /* The + 1 is the null terminator */
5415 parm[2].u.pointer.size = (uint32_t)Utf8Flags.length() + 1;
5416 }
5417
5418 int vrc;
5419 if (aValue != NULL && aFlags != NULL)
5420 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", SET_PROP_HOST,
5421 3, &parm[0]);
5422 else if (aValue != NULL)
5423 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", SET_PROP_VALUE_HOST,
5424 2, &parm[0]);
5425 else
5426 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", DEL_PROP_HOST,
5427 1, &parm[0]);
5428 HRESULT hrc;
5429 if (RT_SUCCESS(vrc))
5430 hrc = S_OK;
5431 else
5432 hrc = setError(E_UNEXPECTED, tr("The service call failed with the error %Rrc"), vrc);
5433 return hrc;
5434#endif /* VBOX_WITH_GUEST_PROPS */
5435}
5436
5437
5438/**
5439 * @note Temporarily locks this object for writing.
5440 */
5441HRESULT Console::enumerateGuestProperties(IN_BSTR aPatterns,
5442 ComSafeArrayOut(BSTR, aNames),
5443 ComSafeArrayOut(BSTR, aValues),
5444 ComSafeArrayOut(LONG64, aTimestamps),
5445 ComSafeArrayOut(BSTR, aFlags))
5446{
5447#ifndef VBOX_WITH_GUEST_PROPS
5448 ReturnComNotImplemented();
5449#else /* VBOX_WITH_GUEST_PROPS */
5450 if (!VALID_PTR(aPatterns) && (aPatterns != NULL))
5451 return E_POINTER;
5452 if (ComSafeArrayOutIsNull(aNames))
5453 return E_POINTER;
5454 if (ComSafeArrayOutIsNull(aValues))
5455 return E_POINTER;
5456 if (ComSafeArrayOutIsNull(aTimestamps))
5457 return E_POINTER;
5458 if (ComSafeArrayOutIsNull(aFlags))
5459 return E_POINTER;
5460
5461 AutoCaller autoCaller(this);
5462 AssertComRCReturnRC(autoCaller.rc());
5463
5464 /* protect mpUVM (if not NULL) */
5465 AutoVMCallerWeak autoVMCaller(this);
5466 if (FAILED(autoVMCaller.rc()))
5467 return autoVMCaller.rc();
5468
5469 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
5470 * autoVMCaller, so there is no need to hold a lock of this */
5471
5472 return doEnumerateGuestProperties(aPatterns, ComSafeArrayOutArg(aNames),
5473 ComSafeArrayOutArg(aValues),
5474 ComSafeArrayOutArg(aTimestamps),
5475 ComSafeArrayOutArg(aFlags));
5476#endif /* VBOX_WITH_GUEST_PROPS */
5477}
5478
5479
5480/*
5481 * Internal: helper function for connecting progress reporting
5482 */
5483static int onlineMergeMediumProgress(void *pvUser, unsigned uPercentage)
5484{
5485 HRESULT rc = S_OK;
5486 IProgress *pProgress = static_cast<IProgress *>(pvUser);
5487 if (pProgress)
5488 rc = pProgress->SetCurrentOperationProgress(uPercentage);
5489 return SUCCEEDED(rc) ? VINF_SUCCESS : VERR_GENERAL_FAILURE;
5490}
5491
5492/**
5493 * @note Temporarily locks this object for writing. bird: And/or reading?
5494 */
5495HRESULT Console::onlineMergeMedium(IMediumAttachment *aMediumAttachment,
5496 ULONG aSourceIdx, ULONG aTargetIdx,
5497 IMedium *aSource, IMedium *aTarget,
5498 BOOL aMergeForward,
5499 IMedium *aParentForTarget,
5500 ComSafeArrayIn(IMedium *, aChildrenToReparent),
5501 IProgress *aProgress)
5502{
5503 AutoCaller autoCaller(this);
5504 AssertComRCReturnRC(autoCaller.rc());
5505
5506 HRESULT rc = S_OK;
5507 int vrc = VINF_SUCCESS;
5508
5509 /* Get the VM - must be done before the read-locking. */
5510 SafeVMPtr ptrVM(this);
5511 if (!ptrVM.isOk())
5512 return ptrVM.rc();
5513
5514 /* We will need to release the lock before doing the actual merge */
5515 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5516
5517 /* paranoia - we don't want merges to happen while teleporting etc. */
5518 switch (mMachineState)
5519 {
5520 case MachineState_DeletingSnapshotOnline:
5521 case MachineState_DeletingSnapshotPaused:
5522 break;
5523
5524 default:
5525 return setInvalidMachineStateError();
5526 }
5527
5528 /** @todo AssertComRC -> AssertComRCReturn! Could potentially end up
5529 * using uninitialized variables here. */
5530 BOOL fBuiltinIOCache;
5531 rc = mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
5532 AssertComRC(rc);
5533 SafeIfaceArray<IStorageController> ctrls;
5534 rc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
5535 AssertComRC(rc);
5536 LONG lDev;
5537 rc = aMediumAttachment->COMGETTER(Device)(&lDev);
5538 AssertComRC(rc);
5539 LONG lPort;
5540 rc = aMediumAttachment->COMGETTER(Port)(&lPort);
5541 AssertComRC(rc);
5542 IMedium *pMedium;
5543 rc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
5544 AssertComRC(rc);
5545 Bstr mediumLocation;
5546 if (pMedium)
5547 {
5548 rc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
5549 AssertComRC(rc);
5550 }
5551
5552 Bstr attCtrlName;
5553 rc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
5554 AssertComRC(rc);
5555 ComPtr<IStorageController> pStorageController;
5556 for (size_t i = 0; i < ctrls.size(); ++i)
5557 {
5558 Bstr ctrlName;
5559 rc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
5560 AssertComRC(rc);
5561 if (attCtrlName == ctrlName)
5562 {
5563 pStorageController = ctrls[i];
5564 break;
5565 }
5566 }
5567 if (pStorageController.isNull())
5568 return setError(E_FAIL,
5569 tr("Could not find storage controller '%ls'"),
5570 attCtrlName.raw());
5571
5572 StorageControllerType_T enmCtrlType;
5573 rc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
5574 AssertComRC(rc);
5575 const char *pcszDevice = convertControllerTypeToDev(enmCtrlType);
5576
5577 StorageBus_T enmBus;
5578 rc = pStorageController->COMGETTER(Bus)(&enmBus);
5579 AssertComRC(rc);
5580 ULONG uInstance;
5581 rc = pStorageController->COMGETTER(Instance)(&uInstance);
5582 AssertComRC(rc);
5583 BOOL fUseHostIOCache;
5584 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
5585 AssertComRC(rc);
5586
5587 unsigned uLUN;
5588 rc = Console::convertBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);
5589 AssertComRCReturnRC(rc);
5590
5591 alock.release();
5592
5593 /* Pause the VM, as it might have pending IO on this drive */
5594 VMSTATE enmVMState = VMR3GetStateU(ptrVM.rawUVM());
5595 if (mMachineState == MachineState_DeletingSnapshotOnline)
5596 {
5597 LogFlowFunc(("Suspending the VM...\n"));
5598 /* disable the callback to prevent Console-level state change */
5599 mVMStateChangeCallbackDisabled = true;
5600 int vrc2 = VMR3Suspend(ptrVM.rawUVM(), VMSUSPENDREASON_RECONFIG);
5601 mVMStateChangeCallbackDisabled = false;
5602 AssertRCReturn(vrc2, E_FAIL);
5603 }
5604
5605 vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(),
5606 VMCPUID_ANY,
5607 (PFNRT)reconfigureMediumAttachment,
5608 13,
5609 this,
5610 ptrVM.rawUVM(),
5611 pcszDevice,
5612 uInstance,
5613 enmBus,
5614 fUseHostIOCache,
5615 fBuiltinIOCache,
5616 true /* fSetupMerge */,
5617 aSourceIdx,
5618 aTargetIdx,
5619 aMediumAttachment,
5620 mMachineState,
5621 &rc);
5622 /* error handling is after resuming the VM */
5623
5624 if (mMachineState == MachineState_DeletingSnapshotOnline)
5625 {
5626 LogFlowFunc(("Resuming the VM...\n"));
5627 /* disable the callback to prevent Console-level state change */
5628 mVMStateChangeCallbackDisabled = true;
5629 int vrc2 = VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_RECONFIG);
5630 mVMStateChangeCallbackDisabled = false;
5631 if (RT_FAILURE(vrc2))
5632 {
5633 /* too bad, we failed. try to sync the console state with the VMM state */
5634 AssertLogRelRC(vrc2);
5635 vmstateChangeCallback(ptrVM.rawUVM(), VMSTATE_SUSPENDED, enmVMState, this);
5636 }
5637 }
5638
5639 if (RT_FAILURE(vrc))
5640 return setError(E_FAIL, tr("%Rrc"), vrc);
5641 if (FAILED(rc))
5642 return rc;
5643
5644 PPDMIBASE pIBase = NULL;
5645 PPDMIMEDIA pIMedium = NULL;
5646 vrc = PDMR3QueryDriverOnLun(ptrVM.rawUVM(), pcszDevice, uInstance, uLUN, "VD", &pIBase);
5647 if (RT_SUCCESS(vrc))
5648 {
5649 if (pIBase)
5650 {
5651 pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
5652 if (!pIMedium)
5653 return setError(E_FAIL, tr("could not query medium interface of controller"));
5654 }
5655 else
5656 return setError(E_FAIL, tr("could not query base interface of controller"));
5657 }
5658
5659 /* Finally trigger the merge. */
5660 vrc = pIMedium->pfnMerge(pIMedium, onlineMergeMediumProgress, aProgress);
5661 if (RT_FAILURE(vrc))
5662 return setError(E_FAIL, tr("Failed to perform an online medium merge (%Rrc)"), vrc);
5663
5664 /* Pause the VM, as it might have pending IO on this drive */
5665 enmVMState = VMR3GetStateU(ptrVM.rawUVM());
5666 if (mMachineState == MachineState_DeletingSnapshotOnline)
5667 {
5668 LogFlowFunc(("Suspending the VM...\n"));
5669 /* disable the callback to prevent Console-level state change */
5670 mVMStateChangeCallbackDisabled = true;
5671 int vrc2 = VMR3Suspend(ptrVM.rawUVM(), VMSUSPENDREASON_RECONFIG);
5672 mVMStateChangeCallbackDisabled = false;
5673 AssertRCReturn(vrc2, E_FAIL);
5674 }
5675
5676 /* Update medium chain and state now, so that the VM can continue. */
5677 rc = mControl->FinishOnlineMergeMedium(aMediumAttachment, aSource, aTarget,
5678 aMergeForward, aParentForTarget,
5679 ComSafeArrayInArg(aChildrenToReparent));
5680
5681 vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(),
5682 VMCPUID_ANY,
5683 (PFNRT)reconfigureMediumAttachment,
5684 13,
5685 this,
5686 ptrVM.rawUVM(),
5687 pcszDevice,
5688 uInstance,
5689 enmBus,
5690 fUseHostIOCache,
5691 fBuiltinIOCache,
5692 false /* fSetupMerge */,
5693 0 /* uMergeSource */,
5694 0 /* uMergeTarget */,
5695 aMediumAttachment,
5696 mMachineState,
5697 &rc);
5698 /* error handling is after resuming the VM */
5699
5700 if (mMachineState == MachineState_DeletingSnapshotOnline)
5701 {
5702 LogFlowFunc(("Resuming the VM...\n"));
5703 /* disable the callback to prevent Console-level state change */
5704 mVMStateChangeCallbackDisabled = true;
5705 int vrc2 = VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_RECONFIG);
5706 mVMStateChangeCallbackDisabled = false;
5707 AssertRC(vrc2);
5708 if (RT_FAILURE(vrc2))
5709 {
5710 /* too bad, we failed. try to sync the console state with the VMM state */
5711 vmstateChangeCallback(ptrVM.rawUVM(), VMSTATE_SUSPENDED, enmVMState, this);
5712 }
5713 }
5714
5715 if (RT_FAILURE(vrc))
5716 return setError(E_FAIL, tr("%Rrc"), vrc);
5717 if (FAILED(rc))
5718 return rc;
5719
5720 return rc;
5721}
5722
5723
5724/**
5725 * Merely passes the call to Guest::enableVMMStatistics().
5726 */
5727void Console::enableVMMStatistics(BOOL aEnable)
5728{
5729 if (mGuest)
5730 mGuest->enableVMMStatistics(aEnable);
5731}
5732
5733/**
5734 * Worker for Console::Pause and internal entry point for pausing a VM for
5735 * a specific reason.
5736 */
5737HRESULT Console::pause(Reason_T aReason)
5738{
5739 LogFlowThisFuncEnter();
5740
5741 AutoCaller autoCaller(this);
5742 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5743
5744 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5745
5746 switch (mMachineState)
5747 {
5748 case MachineState_Running:
5749 case MachineState_Teleporting:
5750 case MachineState_LiveSnapshotting:
5751 break;
5752
5753 case MachineState_Paused:
5754 case MachineState_TeleportingPausedVM:
5755 case MachineState_Saving:
5756 return setError(VBOX_E_INVALID_VM_STATE, tr("Already paused"));
5757
5758 default:
5759 return setInvalidMachineStateError();
5760 }
5761
5762 /* get the VM handle. */
5763 SafeVMPtr ptrVM(this);
5764 if (!ptrVM.isOk())
5765 return ptrVM.rc();
5766
5767 /* release the lock before a VMR3* call (EMT will call us back)! */
5768 alock.release();
5769
5770 LogFlowThisFunc(("Sending PAUSE request...\n"));
5771 if (aReason != Reason_Unspecified)
5772 LogRel(("Pausing VM execution, reason \"%s\"\n", Global::stringifyReason(aReason)));
5773
5774 /** @todo r=klaus make use of aReason */
5775 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
5776 if (aReason == Reason_HostSuspend)
5777 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
5778 else if (aReason == Reason_HostBatteryLow)
5779 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
5780 int vrc = VMR3Suspend(ptrVM.rawUVM(), enmReason);
5781
5782 HRESULT hrc = S_OK;
5783 if (RT_FAILURE(vrc))
5784 hrc = setError(VBOX_E_VM_ERROR, tr("Could not suspend the machine execution (%Rrc)"), vrc);
5785
5786 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
5787 LogFlowThisFuncLeave();
5788 return hrc;
5789}
5790
5791/**
5792 * Worker for Console::Resume and internal entry point for resuming a VM for
5793 * a specific reason.
5794 */
5795HRESULT Console::resume(Reason_T aReason)
5796{
5797 LogFlowThisFuncEnter();
5798
5799 AutoCaller autoCaller(this);
5800 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5801
5802 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5803
5804 if (mMachineState != MachineState_Paused)
5805 return setError(VBOX_E_INVALID_VM_STATE,
5806 tr("Cannot resume the machine as it is not paused (machine state: %s)"),
5807 Global::stringifyMachineState(mMachineState));
5808
5809 /* get the VM handle. */
5810 SafeVMPtr ptrVM(this);
5811 if (!ptrVM.isOk())
5812 return ptrVM.rc();
5813
5814 /* release the lock before a VMR3* call (EMT will call us back)! */
5815 alock.release();
5816
5817 LogFlowThisFunc(("Sending RESUME request...\n"));
5818 if (aReason != Reason_Unspecified)
5819 LogRel(("Resuming VM execution, reason \"%s\"\n", Global::stringifyReason(aReason)));
5820
5821 int vrc;
5822 if (VMR3GetStateU(ptrVM.rawUVM()) == VMSTATE_CREATED)
5823 {
5824#ifdef VBOX_WITH_EXTPACK
5825 vrc = mptrExtPackManager->callAllVmPowerOnHooks(this, VMR3GetVM(ptrVM.rawUVM()));
5826#else
5827 vrc = VINF_SUCCESS;
5828#endif
5829 if (RT_SUCCESS(vrc))
5830 vrc = VMR3PowerOn(ptrVM.rawUVM()); /* (PowerUpPaused) */
5831 }
5832 else
5833 {
5834 VMRESUMEREASON enmReason = VMRESUMEREASON_USER;
5835 if (aReason == Reason_HostResume)
5836 enmReason = VMRESUMEREASON_HOST_RESUME;
5837 vrc = VMR3Resume(ptrVM.rawUVM(), enmReason);
5838 }
5839
5840 HRESULT rc = RT_SUCCESS(vrc) ? S_OK :
5841 setError(VBOX_E_VM_ERROR,
5842 tr("Could not resume the machine execution (%Rrc)"),
5843 vrc);
5844
5845 LogFlowThisFunc(("rc=%Rhrc\n", rc));
5846 LogFlowThisFuncLeave();
5847 return rc;
5848}
5849
5850/**
5851 * Worker for Console::SaveState and internal entry point for saving state of
5852 * a VM for a specific reason.
5853 */
5854HRESULT Console::saveState(Reason_T aReason, IProgress **aProgress)
5855{
5856 LogFlowThisFuncEnter();
5857
5858 CheckComArgOutPointerValid(aProgress);
5859
5860 AutoCaller autoCaller(this);
5861 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5862
5863 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5864
5865 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
5866 if ( mMachineState != MachineState_Running
5867 && mMachineState != MachineState_Paused)
5868 {
5869 return setError(VBOX_E_INVALID_VM_STATE,
5870 tr("Cannot save the execution state as the machine is not running or paused (machine state: %s)"),
5871 Global::stringifyMachineState(mMachineState));
5872 }
5873
5874 if (aReason != Reason_Unspecified)
5875 LogRel(("Saving state of VM, reason \"%s\"\n", Global::stringifyReason(aReason)));
5876
5877 /* memorize the current machine state */
5878 MachineState_T lastMachineState = mMachineState;
5879
5880 if (mMachineState == MachineState_Running)
5881 {
5882 /* get the VM handle. */
5883 SafeVMPtr ptrVM(this);
5884 if (!ptrVM.isOk())
5885 return ptrVM.rc();
5886
5887 /* release the lock before a VMR3* call (EMT will call us back)! */
5888 alock.release();
5889 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
5890 if (aReason == Reason_HostSuspend)
5891 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
5892 else if (aReason == Reason_HostBatteryLow)
5893 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
5894 int vrc = VMR3Suspend(ptrVM.rawUVM(), enmReason);
5895 alock.acquire();
5896
5897 HRESULT hrc = S_OK;
5898 if (RT_FAILURE(vrc))
5899 hrc = setError(VBOX_E_VM_ERROR, tr("Could not suspend the machine execution (%Rrc)"), vrc);
5900 if (FAILED(hrc))
5901 return hrc;
5902 }
5903
5904 HRESULT rc = S_OK;
5905 bool fBeganSavingState = false;
5906 bool fTaskCreationFailed = false;
5907
5908 do
5909 {
5910 ComPtr<IProgress> pProgress;
5911 Bstr stateFilePath;
5912
5913 /*
5914 * request a saved state file path from the server
5915 * (this will set the machine state to Saving on the server to block
5916 * others from accessing this machine)
5917 */
5918 rc = mControl->BeginSavingState(pProgress.asOutParam(),
5919 stateFilePath.asOutParam());
5920 if (FAILED(rc))
5921 break;
5922
5923 fBeganSavingState = true;
5924
5925 /* sync the state with the server */
5926 setMachineStateLocally(MachineState_Saving);
5927
5928 /* ensure the directory for the saved state file exists */
5929 {
5930 Utf8Str dir = stateFilePath;
5931 dir.stripFilename();
5932 if (!RTDirExists(dir.c_str()))
5933 {
5934 int vrc = RTDirCreateFullPath(dir.c_str(), 0700);
5935 if (RT_FAILURE(vrc))
5936 {
5937 rc = setError(VBOX_E_FILE_ERROR,
5938 tr("Could not create a directory '%s' to save the state to (%Rrc)"),
5939 dir.c_str(), vrc);
5940 break;
5941 }
5942 }
5943 }
5944
5945 /* Create a task object early to ensure mpUVM protection is successful. */
5946 std::auto_ptr<VMSaveTask> task(new VMSaveTask(this, pProgress,
5947 stateFilePath,
5948 lastMachineState,
5949 aReason));
5950 rc = task->rc();
5951 /*
5952 * If we fail here it means a PowerDown() call happened on another
5953 * thread while we were doing Pause() (which releases the Console lock).
5954 * We assign PowerDown() a higher precedence than SaveState(),
5955 * therefore just return the error to the caller.
5956 */
5957 if (FAILED(rc))
5958 {
5959 fTaskCreationFailed = true;
5960 break;
5961 }
5962
5963 /* create a thread to wait until the VM state is saved */
5964 int vrc = RTThreadCreate(NULL, Console::saveStateThread, (void *)task.get(),
5965 0, RTTHREADTYPE_MAIN_WORKER, 0, "VMSave");
5966 if (RT_FAILURE(vrc))
5967 {
5968 rc = setError(E_FAIL, "Could not create VMSave thread (%Rrc)", vrc);
5969 break;
5970 }
5971
5972 /* task is now owned by saveStateThread(), so release it */
5973 task.release();
5974
5975 /* return the progress to the caller */
5976 pProgress.queryInterfaceTo(aProgress);
5977 } while (0);
5978
5979 if (FAILED(rc) && !fTaskCreationFailed)
5980 {
5981 /* preserve existing error info */
5982 ErrorInfoKeeper eik;
5983
5984 if (fBeganSavingState)
5985 {
5986 /*
5987 * cancel the requested save state procedure.
5988 * This will reset the machine state to the state it had right
5989 * before calling mControl->BeginSavingState().
5990 */
5991 mControl->EndSavingState(eik.getResultCode(), eik.getText().raw());
5992 }
5993
5994 if (lastMachineState == MachineState_Running)
5995 {
5996 /* restore the paused state if appropriate */
5997 setMachineStateLocally(MachineState_Paused);
5998 /* restore the running state if appropriate */
5999 SafeVMPtr ptrVM(this);
6000 if (ptrVM.isOk())
6001 {
6002 alock.release();
6003 VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_STATE_RESTORED);
6004 alock.acquire();
6005 }
6006 }
6007 else
6008 setMachineStateLocally(lastMachineState);
6009 }
6010
6011 LogFlowThisFunc(("rc=%Rhrc\n", rc));
6012 LogFlowThisFuncLeave();
6013 return rc;
6014}
6015
6016/**
6017 * Gets called by Session::UpdateMachineState()
6018 * (IInternalSessionControl::updateMachineState()).
6019 *
6020 * Must be called only in certain cases (see the implementation).
6021 *
6022 * @note Locks this object for writing.
6023 */
6024HRESULT Console::updateMachineState(MachineState_T aMachineState)
6025{
6026 AutoCaller autoCaller(this);
6027 AssertComRCReturnRC(autoCaller.rc());
6028
6029 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6030
6031 AssertReturn( mMachineState == MachineState_Saving
6032 || mMachineState == MachineState_LiveSnapshotting
6033 || mMachineState == MachineState_RestoringSnapshot
6034 || mMachineState == MachineState_DeletingSnapshot
6035 || mMachineState == MachineState_DeletingSnapshotOnline
6036 || mMachineState == MachineState_DeletingSnapshotPaused
6037 , E_FAIL);
6038
6039 return setMachineStateLocally(aMachineState);
6040}
6041
6042#ifdef CONSOLE_WITH_EVENT_CACHE
6043/**
6044 * @note Locks this object for writing.
6045 */
6046#endif
6047void Console::onMousePointerShapeChange(bool fVisible, bool fAlpha,
6048 uint32_t xHot, uint32_t yHot,
6049 uint32_t width, uint32_t height,
6050 ComSafeArrayIn(BYTE,pShape))
6051{
6052#if 0
6053 LogFlowThisFuncEnter();
6054 LogFlowThisFunc(("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, height=%d, shape=%p\n",
6055 fVisible, fAlpha, xHot, yHot, width, height, pShape));
6056#endif
6057
6058 AutoCaller autoCaller(this);
6059 AssertComRCReturnVoid(autoCaller.rc());
6060
6061#ifdef CONSOLE_WITH_EVENT_CACHE
6062 {
6063 /* We need a write lock because we alter the cached callback data */
6064 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6065
6066 /* Save the callback arguments */
6067 mCallbackData.mpsc.visible = fVisible;
6068 mCallbackData.mpsc.alpha = fAlpha;
6069 mCallbackData.mpsc.xHot = xHot;
6070 mCallbackData.mpsc.yHot = yHot;
6071 mCallbackData.mpsc.width = width;
6072 mCallbackData.mpsc.height = height;
6073
6074 /* start with not valid */
6075 bool wasValid = mCallbackData.mpsc.valid;
6076 mCallbackData.mpsc.valid = false;
6077
6078 com::SafeArray<BYTE> aShape(ComSafeArrayInArg(pShape));
6079 if (aShape.size() != 0)
6080 mCallbackData.mpsc.shape.initFrom(aShape);
6081 else
6082 mCallbackData.mpsc.shape.resize(0);
6083 mCallbackData.mpsc.valid = true;
6084 }
6085#endif
6086
6087 fireMousePointerShapeChangedEvent(mEventSource, fVisible, fAlpha, xHot, yHot, width, height, ComSafeArrayInArg(pShape));
6088
6089#if 0
6090 LogFlowThisFuncLeave();
6091#endif
6092}
6093
6094#ifdef CONSOLE_WITH_EVENT_CACHE
6095/**
6096 * @note Locks this object for writing.
6097 */
6098#endif
6099void Console::onMouseCapabilityChange(BOOL supportsAbsolute, BOOL supportsRelative,
6100 BOOL supportsMT, BOOL needsHostCursor)
6101{
6102 LogFlowThisFunc(("supportsAbsolute=%d supportsRelative=%d needsHostCursor=%d\n",
6103 supportsAbsolute, supportsRelative, needsHostCursor));
6104
6105 AutoCaller autoCaller(this);
6106 AssertComRCReturnVoid(autoCaller.rc());
6107
6108#ifdef CONSOLE_WITH_EVENT_CACHE
6109 {
6110 /* We need a write lock because we alter the cached callback data */
6111 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6112
6113 /* save the callback arguments */
6114 mCallbackData.mcc.supportsAbsolute = supportsAbsolute;
6115 mCallbackData.mcc.supportsRelative = supportsRelative;
6116 mCallbackData.mcc.needsHostCursor = needsHostCursor;
6117 mCallbackData.mcc.valid = true;
6118 }
6119#endif
6120
6121 fireMouseCapabilityChangedEvent(mEventSource, supportsAbsolute, supportsRelative, needsHostCursor);
6122}
6123
6124void Console::onStateChange(MachineState_T machineState)
6125{
6126 AutoCaller autoCaller(this);
6127 AssertComRCReturnVoid(autoCaller.rc());
6128 fireStateChangedEvent(mEventSource, machineState);
6129}
6130
6131void Console::onAdditionsStateChange()
6132{
6133 AutoCaller autoCaller(this);
6134 AssertComRCReturnVoid(autoCaller.rc());
6135
6136 fireAdditionsStateChangedEvent(mEventSource);
6137}
6138
6139/**
6140 * @remarks This notification only is for reporting an incompatible
6141 * Guest Additions interface, *not* the Guest Additions version!
6142 *
6143 * The user will be notified inside the guest if new Guest
6144 * Additions are available (via VBoxTray/VBoxClient).
6145 */
6146void Console::onAdditionsOutdated()
6147{
6148 AutoCaller autoCaller(this);
6149 AssertComRCReturnVoid(autoCaller.rc());
6150
6151 /** @todo implement this */
6152}
6153
6154#ifdef CONSOLE_WITH_EVENT_CACHE
6155/**
6156 * @note Locks this object for writing.
6157 */
6158#endif
6159void Console::onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
6160{
6161 AutoCaller autoCaller(this);
6162 AssertComRCReturnVoid(autoCaller.rc());
6163
6164#ifdef CONSOLE_WITH_EVENT_CACHE
6165 {
6166 /* We need a write lock because we alter the cached callback data */
6167 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6168
6169 /* save the callback arguments */
6170 mCallbackData.klc.numLock = fNumLock;
6171 mCallbackData.klc.capsLock = fCapsLock;
6172 mCallbackData.klc.scrollLock = fScrollLock;
6173 mCallbackData.klc.valid = true;
6174 }
6175#endif
6176
6177 fireKeyboardLedsChangedEvent(mEventSource, fNumLock, fCapsLock, fScrollLock);
6178}
6179
6180void Console::onUSBDeviceStateChange(IUSBDevice *aDevice, bool aAttached,
6181 IVirtualBoxErrorInfo *aError)
6182{
6183 AutoCaller autoCaller(this);
6184 AssertComRCReturnVoid(autoCaller.rc());
6185
6186 fireUSBDeviceStateChangedEvent(mEventSource, aDevice, aAttached, aError);
6187}
6188
6189void Console::onRuntimeError(BOOL aFatal, IN_BSTR aErrorID, IN_BSTR aMessage)
6190{
6191 AutoCaller autoCaller(this);
6192 AssertComRCReturnVoid(autoCaller.rc());
6193
6194 fireRuntimeErrorEvent(mEventSource, aFatal, aErrorID, aMessage);
6195}
6196
6197HRESULT Console::onShowWindow(BOOL aCheck, BOOL *aCanShow, LONG64 *aWinId)
6198{
6199 AssertReturn(aCanShow, E_POINTER);
6200 AssertReturn(aWinId, E_POINTER);
6201
6202 *aCanShow = FALSE;
6203 *aWinId = 0;
6204
6205 AutoCaller autoCaller(this);
6206 AssertComRCReturnRC(autoCaller.rc());
6207
6208 VBoxEventDesc evDesc;
6209 if (aCheck)
6210 {
6211 evDesc.init(mEventSource, VBoxEventType_OnCanShowWindow);
6212 BOOL fDelivered = evDesc.fire(5000); /* Wait up to 5 secs for delivery */
6213 //Assert(fDelivered);
6214 if (fDelivered)
6215 {
6216 ComPtr<IEvent> pEvent;
6217 evDesc.getEvent(pEvent.asOutParam());
6218 // bit clumsy
6219 ComPtr<ICanShowWindowEvent> pCanShowEvent = pEvent;
6220 if (pCanShowEvent)
6221 {
6222 BOOL fVetoed = FALSE;
6223 pCanShowEvent->IsVetoed(&fVetoed);
6224 *aCanShow = !fVetoed;
6225 }
6226 else
6227 {
6228 AssertFailed();
6229 *aCanShow = TRUE;
6230 }
6231 }
6232 else
6233 *aCanShow = TRUE;
6234 }
6235 else
6236 {
6237 evDesc.init(mEventSource, VBoxEventType_OnShowWindow, INT64_C(0));
6238 BOOL fDelivered = evDesc.fire(5000); /* Wait up to 5 secs for delivery */
6239 //Assert(fDelivered);
6240 if (fDelivered)
6241 {
6242 ComPtr<IEvent> pEvent;
6243 evDesc.getEvent(pEvent.asOutParam());
6244 ComPtr<IShowWindowEvent> pShowEvent = pEvent;
6245 if (pShowEvent)
6246 {
6247 LONG64 iEvWinId = 0;
6248 pShowEvent->COMGETTER(WinId)(&iEvWinId);
6249 if (iEvWinId != 0 && *aWinId == 0)
6250 *aWinId = iEvWinId;
6251 }
6252 else
6253 AssertFailed();
6254 }
6255 }
6256
6257 return S_OK;
6258}
6259
6260// private methods
6261////////////////////////////////////////////////////////////////////////////////
6262
6263/**
6264 * Increases the usage counter of the mpUVM pointer.
6265 *
6266 * Guarantees that VMR3Destroy() will not be called on it at least until
6267 * releaseVMCaller() is called.
6268 *
6269 * If this method returns a failure, the caller is not allowed to use mpUVM and
6270 * may return the failed result code to the upper level. This method sets the
6271 * extended error info on failure if \a aQuiet is false.
6272 *
6273 * Setting \a aQuiet to true is useful for methods that don't want to return
6274 * the failed result code to the caller when this method fails (e.g. need to
6275 * silently check for the mpUVM availability).
6276 *
6277 * When mpUVM is NULL but \a aAllowNullVM is true, a corresponding error will be
6278 * returned instead of asserting. Having it false is intended as a sanity check
6279 * for methods that have checked mMachineState and expect mpUVM *NOT* to be
6280 * NULL.
6281 *
6282 * @param aQuiet true to suppress setting error info
6283 * @param aAllowNullVM true to accept mpUVM being NULL and return a failure
6284 * (otherwise this method will assert if mpUVM is NULL)
6285 *
6286 * @note Locks this object for writing.
6287 */
6288HRESULT Console::addVMCaller(bool aQuiet /* = false */,
6289 bool aAllowNullVM /* = false */)
6290{
6291 AutoCaller autoCaller(this);
6292 /** @todo Fix race during console/VM reference destruction, refer @bugref{6318}
6293 * comment 25. */
6294 if (FAILED(autoCaller.rc()))
6295 return autoCaller.rc();
6296
6297 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6298
6299 if (mVMDestroying)
6300 {
6301 /* powerDown() is waiting for all callers to finish */
6302 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED,
6303 tr("The virtual machine is being powered down"));
6304 }
6305
6306 if (mpUVM == NULL)
6307 {
6308 Assert(aAllowNullVM == true);
6309
6310 /* The machine is not powered up */
6311 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED,
6312 tr("The virtual machine is not powered up"));
6313 }
6314
6315 ++mVMCallers;
6316
6317 return S_OK;
6318}
6319
6320/**
6321 * Decreases the usage counter of the mpUVM pointer.
6322 *
6323 * Must always complete the addVMCaller() call after the mpUVM pointer is no
6324 * more necessary.
6325 *
6326 * @note Locks this object for writing.
6327 */
6328void Console::releaseVMCaller()
6329{
6330 AutoCaller autoCaller(this);
6331 AssertComRCReturnVoid(autoCaller.rc());
6332
6333 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6334
6335 AssertReturnVoid(mpUVM != NULL);
6336
6337 Assert(mVMCallers > 0);
6338 --mVMCallers;
6339
6340 if (mVMCallers == 0 && mVMDestroying)
6341 {
6342 /* inform powerDown() there are no more callers */
6343 RTSemEventSignal(mVMZeroCallersSem);
6344 }
6345}
6346
6347
6348HRESULT Console::safeVMPtrRetainer(PUVM *a_ppUVM, bool a_Quiet)
6349{
6350 *a_ppUVM = NULL;
6351
6352 AutoCaller autoCaller(this);
6353 AssertComRCReturnRC(autoCaller.rc());
6354 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6355
6356 /*
6357 * Repeat the checks done by addVMCaller.
6358 */
6359 if (mVMDestroying) /* powerDown() is waiting for all callers to finish */
6360 return a_Quiet
6361 ? E_ACCESSDENIED
6362 : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
6363 PUVM pUVM = mpUVM;
6364 if (!pUVM)
6365 return a_Quiet
6366 ? E_ACCESSDENIED
6367 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
6368
6369 /*
6370 * Retain a reference to the user mode VM handle and get the global handle.
6371 */
6372 uint32_t cRefs = VMR3RetainUVM(pUVM);
6373 if (cRefs == UINT32_MAX)
6374 return a_Quiet
6375 ? E_ACCESSDENIED
6376 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
6377
6378 /* done */
6379 *a_ppUVM = pUVM;
6380 return S_OK;
6381}
6382
6383void Console::safeVMPtrReleaser(PUVM *a_ppUVM)
6384{
6385 if (*a_ppUVM)
6386 VMR3ReleaseUVM(*a_ppUVM);
6387 *a_ppUVM = NULL;
6388}
6389
6390
6391/**
6392 * Initialize the release logging facility. In case something
6393 * goes wrong, there will be no release logging. Maybe in the future
6394 * we can add some logic to use different file names in this case.
6395 * Note that the logic must be in sync with Machine::DeleteSettings().
6396 */
6397HRESULT Console::consoleInitReleaseLog(const ComPtr<IMachine> aMachine)
6398{
6399 HRESULT hrc = S_OK;
6400
6401 Bstr logFolder;
6402 hrc = aMachine->COMGETTER(LogFolder)(logFolder.asOutParam());
6403 if (FAILED(hrc))
6404 return hrc;
6405
6406 Utf8Str logDir = logFolder;
6407
6408 /* make sure the Logs folder exists */
6409 Assert(logDir.length());
6410 if (!RTDirExists(logDir.c_str()))
6411 RTDirCreateFullPath(logDir.c_str(), 0700);
6412
6413 Utf8Str logFile = Utf8StrFmt("%s%cVBox.log",
6414 logDir.c_str(), RTPATH_DELIMITER);
6415 Utf8Str pngFile = Utf8StrFmt("%s%cVBox.png",
6416 logDir.c_str(), RTPATH_DELIMITER);
6417
6418 /*
6419 * Age the old log files
6420 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
6421 * Overwrite target files in case they exist.
6422 */
6423 ComPtr<IVirtualBox> pVirtualBox;
6424 aMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
6425 ComPtr<ISystemProperties> pSystemProperties;
6426 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
6427 ULONG cHistoryFiles = 3;
6428 pSystemProperties->COMGETTER(LogHistoryCount)(&cHistoryFiles);
6429 if (cHistoryFiles)
6430 {
6431 for (int i = cHistoryFiles-1; i >= 0; i--)
6432 {
6433 Utf8Str *files[] = { &logFile, &pngFile };
6434 Utf8Str oldName, newName;
6435
6436 for (unsigned int j = 0; j < RT_ELEMENTS(files); ++j)
6437 {
6438 if (i > 0)
6439 oldName = Utf8StrFmt("%s.%d", files[j]->c_str(), i);
6440 else
6441 oldName = *files[j];
6442 newName = Utf8StrFmt("%s.%d", files[j]->c_str(), i + 1);
6443 /* If the old file doesn't exist, delete the new file (if it
6444 * exists) to provide correct rotation even if the sequence is
6445 * broken */
6446 if ( RTFileRename(oldName.c_str(), newName.c_str(), RTFILEMOVE_FLAGS_REPLACE)
6447 == VERR_FILE_NOT_FOUND)
6448 RTFileDelete(newName.c_str());
6449 }
6450 }
6451 }
6452
6453 char szError[RTPATH_MAX + 128];
6454 int vrc = com::VBoxLogRelCreate("VM", logFile.c_str(),
6455 RTLOGFLAGS_PREFIX_TIME_PROG | RTLOGFLAGS_RESTRICT_GROUPS,
6456 "all all.restrict -default.restrict",
6457 "VBOX_RELEASE_LOG", RTLOGDEST_FILE,
6458 32768 /* cMaxEntriesPerGroup */,
6459 0 /* cHistory */, 0 /* uHistoryFileTime */,
6460 0 /* uHistoryFileSize */, szError, sizeof(szError));
6461 if (RT_FAILURE(vrc))
6462 hrc = setError(E_FAIL, tr("Failed to open release log (%s, %Rrc)"),
6463 szError, vrc);
6464
6465 /* If we've made any directory changes, flush the directory to increase
6466 the likelihood that the log file will be usable after a system panic.
6467
6468 Tip: Try 'export VBOX_RELEASE_LOG_FLAGS=flush' if the last bits of the log
6469 is missing. Just don't have too high hopes for this to help. */
6470 if (SUCCEEDED(hrc) || cHistoryFiles)
6471 RTDirFlush(logDir.c_str());
6472
6473 return hrc;
6474}
6475
6476/**
6477 * Common worker for PowerUp and PowerUpPaused.
6478 *
6479 * @returns COM status code.
6480 *
6481 * @param aProgress Where to return the progress object.
6482 * @param aPaused true if PowerUpPaused called.
6483 */
6484HRESULT Console::powerUp(IProgress **aProgress, bool aPaused)
6485{
6486
6487 LogFlowThisFuncEnter();
6488
6489 CheckComArgOutPointerValid(aProgress);
6490
6491 AutoCaller autoCaller(this);
6492 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6493
6494 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6495
6496 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
6497 HRESULT rc = S_OK;
6498 ComObjPtr<Progress> pPowerupProgress;
6499 bool fBeganPoweringUp = false;
6500
6501 LONG cOperations = 1;
6502 LONG ulTotalOperationsWeight = 1;
6503
6504 try
6505 {
6506
6507 if (Global::IsOnlineOrTransient(mMachineState))
6508 throw setError(VBOX_E_INVALID_VM_STATE,
6509 tr("The virtual machine is already running or busy (machine state: %s)"),
6510 Global::stringifyMachineState(mMachineState));
6511
6512 /* Set up release logging as early as possible after the check if
6513 * there is already a running VM which we shouldn't disturb. */
6514 rc = consoleInitReleaseLog(mMachine);
6515 if (FAILED(rc))
6516 throw rc;
6517
6518 /* test and clear the TeleporterEnabled property */
6519 BOOL fTeleporterEnabled;
6520 rc = mMachine->COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
6521 if (FAILED(rc))
6522 throw rc;
6523
6524#if 0 /** @todo we should save it afterwards, but that isn't necessarily a good idea. Find a better place for this (VBoxSVC). */
6525 if (fTeleporterEnabled)
6526 {
6527 rc = mMachine->COMSETTER(TeleporterEnabled)(FALSE);
6528 if (FAILED(rc))
6529 throw rc;
6530 }
6531#endif
6532
6533 /* test the FaultToleranceState property */
6534 FaultToleranceState_T enmFaultToleranceState;
6535 rc = mMachine->COMGETTER(FaultToleranceState)(&enmFaultToleranceState);
6536 if (FAILED(rc))
6537 throw rc;
6538 BOOL fFaultToleranceSyncEnabled = (enmFaultToleranceState == FaultToleranceState_Standby);
6539
6540 /* Create a progress object to track progress of this operation. Must
6541 * be done as early as possible (together with BeginPowerUp()) as this
6542 * is vital for communicating as much as possible early powerup
6543 * failure information to the API caller */
6544 pPowerupProgress.createObject();
6545 Bstr progressDesc;
6546 if (mMachineState == MachineState_Saved)
6547 progressDesc = tr("Restoring virtual machine");
6548 else if (fTeleporterEnabled)
6549 progressDesc = tr("Teleporting virtual machine");
6550 else if (fFaultToleranceSyncEnabled)
6551 progressDesc = tr("Fault Tolerance syncing of remote virtual machine");
6552 else
6553 progressDesc = tr("Starting virtual machine");
6554
6555 /* Check all types of shared folders and compose a single list */
6556 SharedFolderDataMap sharedFolders;
6557 {
6558 /* first, insert global folders */
6559 for (SharedFolderDataMap::const_iterator it = m_mapGlobalSharedFolders.begin();
6560 it != m_mapGlobalSharedFolders.end();
6561 ++it)
6562 {
6563 const SharedFolderData &d = it->second;
6564 sharedFolders[it->first] = d;
6565 }
6566
6567 /* second, insert machine folders */
6568 for (SharedFolderDataMap::const_iterator it = m_mapMachineSharedFolders.begin();
6569 it != m_mapMachineSharedFolders.end();
6570 ++it)
6571 {
6572 const SharedFolderData &d = it->second;
6573 sharedFolders[it->first] = d;
6574 }
6575
6576 /* third, insert console folders */
6577 for (SharedFolderMap::const_iterator it = m_mapSharedFolders.begin();
6578 it != m_mapSharedFolders.end();
6579 ++it)
6580 {
6581 SharedFolder *pSF = it->second;
6582 AutoCaller sfCaller(pSF);
6583 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
6584 sharedFolders[it->first] = SharedFolderData(pSF->getHostPath(),
6585 pSF->isWritable(),
6586 pSF->isAutoMounted());
6587 }
6588 }
6589
6590 Bstr savedStateFile;
6591
6592 /*
6593 * Saved VMs will have to prove that their saved states seem kosher.
6594 */
6595 if (mMachineState == MachineState_Saved)
6596 {
6597 rc = mMachine->COMGETTER(StateFilePath)(savedStateFile.asOutParam());
6598 if (FAILED(rc))
6599 throw rc;
6600 ComAssertRet(!savedStateFile.isEmpty(), E_FAIL);
6601 int vrc = SSMR3ValidateFile(Utf8Str(savedStateFile).c_str(), false /* fChecksumIt */);
6602 if (RT_FAILURE(vrc))
6603 throw setError(VBOX_E_FILE_ERROR,
6604 tr("VM cannot start because the saved state file '%ls' is invalid (%Rrc). Delete the saved state prior to starting the VM"),
6605 savedStateFile.raw(), vrc);
6606 }
6607
6608 /* Setup task object and thread to carry out the operaton
6609 * Asycnhronously */
6610 std::auto_ptr<VMPowerUpTask> task(new VMPowerUpTask(this, pPowerupProgress));
6611 ComAssertComRCRetRC(task->rc());
6612
6613 task->mConfigConstructor = configConstructor;
6614 task->mSharedFolders = sharedFolders;
6615 task->mStartPaused = aPaused;
6616 if (mMachineState == MachineState_Saved)
6617 task->mSavedStateFile = savedStateFile;
6618 task->mTeleporterEnabled = fTeleporterEnabled;
6619 task->mEnmFaultToleranceState = enmFaultToleranceState;
6620
6621 /* Reset differencing hard disks for which autoReset is true,
6622 * but only if the machine has no snapshots OR the current snapshot
6623 * is an OFFLINE snapshot; otherwise we would reset the current
6624 * differencing image of an ONLINE snapshot which contains the disk
6625 * state of the machine while it was previously running, but without
6626 * the corresponding machine state, which is equivalent to powering
6627 * off a running machine and not good idea
6628 */
6629 ComPtr<ISnapshot> pCurrentSnapshot;
6630 rc = mMachine->COMGETTER(CurrentSnapshot)(pCurrentSnapshot.asOutParam());
6631 if (FAILED(rc))
6632 throw rc;
6633
6634 BOOL fCurrentSnapshotIsOnline = false;
6635 if (pCurrentSnapshot)
6636 {
6637 rc = pCurrentSnapshot->COMGETTER(Online)(&fCurrentSnapshotIsOnline);
6638 if (FAILED(rc))
6639 throw rc;
6640 }
6641
6642 if (!fCurrentSnapshotIsOnline)
6643 {
6644 LogFlowThisFunc(("Looking for immutable images to reset\n"));
6645
6646 com::SafeIfaceArray<IMediumAttachment> atts;
6647 rc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
6648 if (FAILED(rc))
6649 throw rc;
6650
6651 for (size_t i = 0;
6652 i < atts.size();
6653 ++i)
6654 {
6655 DeviceType_T devType;
6656 rc = atts[i]->COMGETTER(Type)(&devType);
6657 /** @todo later applies to floppies as well */
6658 if (devType == DeviceType_HardDisk)
6659 {
6660 ComPtr<IMedium> pMedium;
6661 rc = atts[i]->COMGETTER(Medium)(pMedium.asOutParam());
6662 if (FAILED(rc))
6663 throw rc;
6664
6665 /* needs autoreset? */
6666 BOOL autoReset = FALSE;
6667 rc = pMedium->COMGETTER(AutoReset)(&autoReset);
6668 if (FAILED(rc))
6669 throw rc;
6670
6671 if (autoReset)
6672 {
6673 ComPtr<IProgress> pResetProgress;
6674 rc = pMedium->Reset(pResetProgress.asOutParam());
6675 if (FAILED(rc))
6676 throw rc;
6677
6678 /* save for later use on the powerup thread */
6679 task->hardDiskProgresses.push_back(pResetProgress);
6680 }
6681 }
6682 }
6683 }
6684 else
6685 LogFlowThisFunc(("Machine has a current snapshot which is online, skipping immutable images reset\n"));
6686
6687 /* setup task object and thread to carry out the operation
6688 * asynchronously */
6689
6690#ifdef VBOX_WITH_EXTPACK
6691 mptrExtPackManager->dumpAllToReleaseLog();
6692#endif
6693
6694#ifdef RT_OS_SOLARIS
6695 /* setup host core dumper for the VM */
6696 Bstr value;
6697 HRESULT hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpEnabled").raw(), value.asOutParam());
6698 if (SUCCEEDED(hrc) && value == "1")
6699 {
6700 Bstr coreDumpDir, coreDumpReplaceSys, coreDumpLive;
6701 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpDir").raw(), coreDumpDir.asOutParam());
6702 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpReplaceSystemDump").raw(), coreDumpReplaceSys.asOutParam());
6703 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpLive").raw(), coreDumpLive.asOutParam());
6704
6705 uint32_t fCoreFlags = 0;
6706 if ( coreDumpReplaceSys.isEmpty() == false
6707 && Utf8Str(coreDumpReplaceSys).toUInt32() == 1)
6708 fCoreFlags |= RTCOREDUMPER_FLAGS_REPLACE_SYSTEM_DUMP;
6709
6710 if ( coreDumpLive.isEmpty() == false
6711 && Utf8Str(coreDumpLive).toUInt32() == 1)
6712 fCoreFlags |= RTCOREDUMPER_FLAGS_LIVE_CORE;
6713
6714 Utf8Str strDumpDir(coreDumpDir);
6715 const char *pszDumpDir = strDumpDir.c_str();
6716 if ( pszDumpDir
6717 && *pszDumpDir == '\0')
6718 pszDumpDir = NULL;
6719
6720 int vrc;
6721 if ( pszDumpDir
6722 && !RTDirExists(pszDumpDir))
6723 {
6724 /*
6725 * Try create the directory.
6726 */
6727 vrc = RTDirCreateFullPath(pszDumpDir, 0700);
6728 if (RT_FAILURE(vrc))
6729 throw setError(E_FAIL, "Failed to setup CoreDumper. Couldn't create dump directory '%s' (%Rrc)\n", pszDumpDir, vrc);
6730 }
6731
6732 vrc = RTCoreDumperSetup(pszDumpDir, fCoreFlags);
6733 if (RT_FAILURE(vrc))
6734 throw setError(E_FAIL, "Failed to setup CoreDumper (%Rrc)", vrc);
6735 else
6736 LogRel(("CoreDumper setup successful. pszDumpDir=%s fFlags=%#x\n", pszDumpDir ? pszDumpDir : ".", fCoreFlags));
6737 }
6738#endif
6739
6740
6741 // If there is immutable drive the process that.
6742 VMPowerUpTask::ProgressList progresses(task->hardDiskProgresses);
6743 if (aProgress && progresses.size() > 0){
6744
6745 for (VMPowerUpTask::ProgressList::const_iterator it = progresses.begin(); it != progresses.end(); ++it)
6746 {
6747 ++cOperations;
6748 ulTotalOperationsWeight += 1;
6749 }
6750 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
6751 progressDesc.raw(),
6752 TRUE, // Cancelable
6753 cOperations,
6754 ulTotalOperationsWeight,
6755 Bstr(tr("Starting Hard Disk operations")).raw(),
6756 1,
6757 NULL);
6758 AssertComRCReturnRC(rc);
6759 }
6760 else if ( mMachineState == MachineState_Saved
6761 || (!fTeleporterEnabled && !fFaultToleranceSyncEnabled))
6762 {
6763 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
6764 progressDesc.raw(),
6765 FALSE /* aCancelable */);
6766 }
6767 else if (fTeleporterEnabled)
6768 {
6769 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
6770 progressDesc.raw(),
6771 TRUE /* aCancelable */,
6772 3 /* cOperations */,
6773 10 /* ulTotalOperationsWeight */,
6774 Bstr(tr("Teleporting virtual machine")).raw(),
6775 1 /* ulFirstOperationWeight */,
6776 NULL);
6777 }
6778 else if (fFaultToleranceSyncEnabled)
6779 {
6780 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
6781 progressDesc.raw(),
6782 TRUE /* aCancelable */,
6783 3 /* cOperations */,
6784 10 /* ulTotalOperationsWeight */,
6785 Bstr(tr("Fault Tolerance syncing of remote virtual machine")).raw(),
6786 1 /* ulFirstOperationWeight */,
6787 NULL);
6788 }
6789
6790 if (FAILED(rc))
6791 throw rc;
6792
6793 /* Tell VBoxSVC and Machine about the progress object so they can
6794 combine/proxy it to any openRemoteSession caller. */
6795 LogFlowThisFunc(("Calling BeginPowerUp...\n"));
6796 rc = mControl->BeginPowerUp(pPowerupProgress);
6797 if (FAILED(rc))
6798 {
6799 LogFlowThisFunc(("BeginPowerUp failed\n"));
6800 throw rc;
6801 }
6802 fBeganPoweringUp = true;
6803
6804 LogFlowThisFunc(("Checking if canceled...\n"));
6805 BOOL fCanceled;
6806 rc = pPowerupProgress->COMGETTER(Canceled)(&fCanceled);
6807 if (FAILED(rc))
6808 throw rc;
6809
6810 if (fCanceled)
6811 {
6812 LogFlowThisFunc(("Canceled in BeginPowerUp\n"));
6813 throw setError(E_FAIL, tr("Powerup was canceled"));
6814 }
6815 LogFlowThisFunc(("Not canceled yet.\n"));
6816
6817 /** @todo this code prevents starting a VM with unavailable bridged
6818 * networking interface. The only benefit is a slightly better error
6819 * message, which should be moved to the driver code. This is the
6820 * only reason why I left the code in for now. The driver allows
6821 * unavailable bridged networking interfaces in certain circumstances,
6822 * and this is sabotaged by this check. The VM will initially have no
6823 * network connectivity, but the user can fix this at runtime. */
6824#if 0
6825 /* the network cards will undergo a quick consistency check */
6826 for (ULONG slot = 0;
6827 slot < maxNetworkAdapters;
6828 ++slot)
6829 {
6830 ComPtr<INetworkAdapter> pNetworkAdapter;
6831 mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
6832 BOOL enabled = FALSE;
6833 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
6834 if (!enabled)
6835 continue;
6836
6837 NetworkAttachmentType_T netattach;
6838 pNetworkAdapter->COMGETTER(AttachmentType)(&netattach);
6839 switch (netattach)
6840 {
6841 case NetworkAttachmentType_Bridged:
6842 {
6843 /* a valid host interface must have been set */
6844 Bstr hostif;
6845 pNetworkAdapter->COMGETTER(HostInterface)(hostif.asOutParam());
6846 if (hostif.isEmpty())
6847 {
6848 throw setError(VBOX_E_HOST_ERROR,
6849 tr("VM cannot start because host interface networking requires a host interface name to be set"));
6850 }
6851 ComPtr<IVirtualBox> pVirtualBox;
6852 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
6853 ComPtr<IHost> pHost;
6854 pVirtualBox->COMGETTER(Host)(pHost.asOutParam());
6855 ComPtr<IHostNetworkInterface> pHostInterface;
6856 if (!SUCCEEDED(pHost->FindHostNetworkInterfaceByName(hostif.raw(),
6857 pHostInterface.asOutParam())))
6858 {
6859 throw setError(VBOX_E_HOST_ERROR,
6860 tr("VM cannot start because the host interface '%ls' does not exist"),
6861 hostif.raw());
6862 }
6863 break;
6864 }
6865 default:
6866 break;
6867 }
6868 }
6869#endif // 0
6870
6871 /* Read console data stored in the saved state file (if not yet done) */
6872 rc = loadDataFromSavedState();
6873 if (FAILED(rc))
6874 throw rc;
6875
6876 /* setup task object and thread to carry out the operation
6877 * asynchronously */
6878 if (aProgress){
6879 rc = pPowerupProgress.queryInterfaceTo(aProgress);
6880 AssertComRCReturnRC(rc);
6881 }
6882
6883 int vrc = RTThreadCreate(NULL, Console::powerUpThread,
6884 (void *)task.get(), 0,
6885 RTTHREADTYPE_MAIN_WORKER, 0, "VMPwrUp");
6886 if (RT_FAILURE(vrc))
6887 throw setError(E_FAIL, "Could not create VMPowerUp thread (%Rrc)", vrc);
6888
6889 /* task is now owned by powerUpThread(), so release it */
6890 task.release();
6891
6892 /* finally, set the state: no right to fail in this method afterwards
6893 * since we've already started the thread and it is now responsible for
6894 * any error reporting and appropriate state change! */
6895 if (mMachineState == MachineState_Saved)
6896 setMachineState(MachineState_Restoring);
6897 else if (fTeleporterEnabled)
6898 setMachineState(MachineState_TeleportingIn);
6899 else if (enmFaultToleranceState == FaultToleranceState_Standby)
6900 setMachineState(MachineState_FaultTolerantSyncing);
6901 else
6902 setMachineState(MachineState_Starting);
6903 }
6904 catch (HRESULT aRC) { rc = aRC; }
6905
6906 if (FAILED(rc) && fBeganPoweringUp)
6907 {
6908
6909 /* The progress object will fetch the current error info */
6910 if (!pPowerupProgress.isNull())
6911 pPowerupProgress->notifyComplete(rc);
6912
6913 /* Save the error info across the IPC below. Can't be done before the
6914 * progress notification above, as saving the error info deletes it
6915 * from the current context, and thus the progress object wouldn't be
6916 * updated correctly. */
6917 ErrorInfoKeeper eik;
6918
6919 /* signal end of operation */
6920 mControl->EndPowerUp(rc);
6921 }
6922
6923 LogFlowThisFunc(("mMachineState=%d, rc=%Rhrc\n", mMachineState, rc));
6924 LogFlowThisFuncLeave();
6925 return rc;
6926}
6927
6928/**
6929 * Internal power off worker routine.
6930 *
6931 * This method may be called only at certain places with the following meaning
6932 * as shown below:
6933 *
6934 * - if the machine state is either Running or Paused, a normal
6935 * Console-initiated powerdown takes place (e.g. PowerDown());
6936 * - if the machine state is Saving, saveStateThread() has successfully done its
6937 * job;
6938 * - if the machine state is Starting or Restoring, powerUpThread() has failed
6939 * to start/load the VM;
6940 * - if the machine state is Stopping, the VM has powered itself off (i.e. not
6941 * as a result of the powerDown() call).
6942 *
6943 * Calling it in situations other than the above will cause unexpected behavior.
6944 *
6945 * Note that this method should be the only one that destroys mpUVM and sets it
6946 * to NULL.
6947 *
6948 * @param aProgress Progress object to run (may be NULL).
6949 *
6950 * @note Locks this object for writing.
6951 *
6952 * @note Never call this method from a thread that called addVMCaller() or
6953 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
6954 * release(). Otherwise it will deadlock.
6955 */
6956HRESULT Console::powerDown(IProgress *aProgress /*= NULL*/)
6957{
6958 LogFlowThisFuncEnter();
6959
6960 AutoCaller autoCaller(this);
6961 AssertComRCReturnRC(autoCaller.rc());
6962
6963 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6964
6965 /* Total # of steps for the progress object. Must correspond to the
6966 * number of "advance percent count" comments in this method! */
6967 enum { StepCount = 7 };
6968 /* current step */
6969 ULONG step = 0;
6970
6971 HRESULT rc = S_OK;
6972 int vrc = VINF_SUCCESS;
6973
6974 /* sanity */
6975 Assert(mVMDestroying == false);
6976
6977 PUVM pUVM = mpUVM; Assert(pUVM != NULL);
6978 uint32_t cRefs = VMR3RetainUVM(pUVM); Assert(cRefs != UINT32_MAX);
6979
6980 AssertMsg( mMachineState == MachineState_Running
6981 || mMachineState == MachineState_Paused
6982 || mMachineState == MachineState_Stuck
6983 || mMachineState == MachineState_Starting
6984 || mMachineState == MachineState_Stopping
6985 || mMachineState == MachineState_Saving
6986 || mMachineState == MachineState_Restoring
6987 || mMachineState == MachineState_TeleportingPausedVM
6988 || mMachineState == MachineState_FaultTolerantSyncing
6989 || mMachineState == MachineState_TeleportingIn
6990 , ("Invalid machine state: %s\n", Global::stringifyMachineState(mMachineState)));
6991
6992 LogRel(("Console::powerDown(): A request to power off the VM has been issued (mMachineState=%s, InUninit=%d)\n",
6993 Global::stringifyMachineState(mMachineState), autoCaller.state() == InUninit));
6994
6995 /* Check if we need to power off the VM. In case of mVMPoweredOff=true, the
6996 * VM has already powered itself off in vmstateChangeCallback() and is just
6997 * notifying Console about that. In case of Starting or Restoring,
6998 * powerUpThread() is calling us on failure, so the VM is already off at
6999 * that point. */
7000 if ( !mVMPoweredOff
7001 && ( mMachineState == MachineState_Starting
7002 || mMachineState == MachineState_Restoring
7003 || mMachineState == MachineState_FaultTolerantSyncing
7004 || mMachineState == MachineState_TeleportingIn)
7005 )
7006 mVMPoweredOff = true;
7007
7008 /*
7009 * Go to Stopping state if not already there.
7010 *
7011 * Note that we don't go from Saving/Restoring to Stopping because
7012 * vmstateChangeCallback() needs it to set the state to Saved on
7013 * VMSTATE_TERMINATED. In terms of protecting from inappropriate operations
7014 * while leaving the lock below, Saving or Restoring should be fine too.
7015 * Ditto for TeleportingPausedVM -> Teleported.
7016 */
7017 if ( mMachineState != MachineState_Saving
7018 && mMachineState != MachineState_Restoring
7019 && mMachineState != MachineState_Stopping
7020 && mMachineState != MachineState_TeleportingIn
7021 && mMachineState != MachineState_TeleportingPausedVM
7022 && mMachineState != MachineState_FaultTolerantSyncing
7023 )
7024 setMachineState(MachineState_Stopping);
7025
7026 /* ----------------------------------------------------------------------
7027 * DONE with necessary state changes, perform the power down actions (it's
7028 * safe to release the object lock now if needed)
7029 * ---------------------------------------------------------------------- */
7030
7031 /* Stop the VRDP server to prevent new clients connection while VM is being
7032 * powered off. */
7033 if (mConsoleVRDPServer)
7034 {
7035 LogFlowThisFunc(("Stopping VRDP server...\n"));
7036
7037 /* Leave the lock since EMT will call us back as addVMCaller()
7038 * in updateDisplayData(). */
7039 alock.release();
7040
7041 mConsoleVRDPServer->Stop();
7042
7043 alock.acquire();
7044 }
7045
7046 /* advance percent count */
7047 if (aProgress)
7048 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount );
7049
7050
7051 /* ----------------------------------------------------------------------
7052 * Now, wait for all mpUVM callers to finish their work if there are still
7053 * some on other threads. NO methods that need mpUVM (or initiate other calls
7054 * that need it) may be called after this point
7055 * ---------------------------------------------------------------------- */
7056
7057 /* go to the destroying state to prevent from adding new callers */
7058 mVMDestroying = true;
7059
7060 if (mVMCallers > 0)
7061 {
7062 /* lazy creation */
7063 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
7064 RTSemEventCreate(&mVMZeroCallersSem);
7065
7066 LogFlowThisFunc(("Waiting for mpUVM callers (%d) to drop to zero...\n", mVMCallers));
7067
7068 alock.release();
7069
7070 RTSemEventWait(mVMZeroCallersSem, RT_INDEFINITE_WAIT);
7071
7072 alock.acquire();
7073 }
7074
7075 /* advance percent count */
7076 if (aProgress)
7077 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount );
7078
7079 vrc = VINF_SUCCESS;
7080
7081 /*
7082 * Power off the VM if not already done that.
7083 * Leave the lock since EMT will call vmstateChangeCallback.
7084 *
7085 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
7086 * VM-(guest-)initiated power off happened in parallel a ms before this
7087 * call. So far, we let this error pop up on the user's side.
7088 */
7089 if (!mVMPoweredOff)
7090 {
7091 LogFlowThisFunc(("Powering off the VM...\n"));
7092 alock.release();
7093 vrc = VMR3PowerOff(pUVM);
7094#ifdef VBOX_WITH_EXTPACK
7095 mptrExtPackManager->callAllVmPowerOffHooks(this, VMR3GetVM(pUVM));
7096#endif
7097 alock.acquire();
7098 }
7099
7100 /* advance percent count */
7101 if (aProgress)
7102 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount );
7103
7104#ifdef VBOX_WITH_HGCM
7105 /* Shutdown HGCM services before destroying the VM. */
7106 if (m_pVMMDev)
7107 {
7108 LogFlowThisFunc(("Shutdown HGCM...\n"));
7109
7110 /* Leave the lock since EMT will call us back as addVMCaller() */
7111 alock.release();
7112
7113 m_pVMMDev->hgcmShutdown();
7114
7115 alock.acquire();
7116 }
7117
7118 /* advance percent count */
7119 if (aProgress)
7120 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount);
7121
7122#endif /* VBOX_WITH_HGCM */
7123
7124 LogFlowThisFunc(("Ready for VM destruction.\n"));
7125
7126 /* If we are called from Console::uninit(), then try to destroy the VM even
7127 * on failure (this will most likely fail too, but what to do?..) */
7128 if (RT_SUCCESS(vrc) || autoCaller.state() == InUninit)
7129 {
7130 /* If the machine has an USB controller, release all USB devices
7131 * (symmetric to the code in captureUSBDevices()) */
7132 bool fHasUSBController = false;
7133 {
7134 PPDMIBASE pBase;
7135 vrc = PDMR3QueryLun(pUVM, "usb-ohci", 0, 0, &pBase);
7136 if (RT_SUCCESS(vrc))
7137 {
7138 fHasUSBController = true;
7139 alock.release();
7140 detachAllUSBDevices(false /* aDone */);
7141 alock.acquire();
7142 }
7143 }
7144
7145 /* Now we've got to destroy the VM as well. (mpUVM is not valid beyond
7146 * this point). We release the lock before calling VMR3Destroy() because
7147 * it will result into calling destructors of drivers associated with
7148 * Console children which may in turn try to lock Console (e.g. by
7149 * instantiating SafeVMPtr to access mpUVM). It's safe here because
7150 * mVMDestroying is set which should prevent any activity. */
7151
7152 /* Set mpUVM to NULL early just in case if some old code is not using
7153 * addVMCaller()/releaseVMCaller(). (We have our own ref on pUVM.) */
7154 VMR3ReleaseUVM(mpUVM);
7155 mpUVM = NULL;
7156
7157 LogFlowThisFunc(("Destroying the VM...\n"));
7158
7159 alock.release();
7160
7161 vrc = VMR3Destroy(pUVM);
7162
7163 /* take the lock again */
7164 alock.acquire();
7165
7166 /* advance percent count */
7167 if (aProgress)
7168 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount);
7169
7170 if (RT_SUCCESS(vrc))
7171 {
7172 LogFlowThisFunc(("Machine has been destroyed (mMachineState=%d)\n",
7173 mMachineState));
7174 /* Note: the Console-level machine state change happens on the
7175 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
7176 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
7177 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
7178 * occurred yet. This is okay, because mMachineState is already
7179 * Stopping in this case, so any other attempt to call PowerDown()
7180 * will be rejected. */
7181 }
7182 else
7183 {
7184 /* bad bad bad, but what to do? (Give Console our UVM ref.) */
7185 mpUVM = pUVM;
7186 pUVM = NULL;
7187 rc = setError(VBOX_E_VM_ERROR,
7188 tr("Could not destroy the machine. (Error: %Rrc)"),
7189 vrc);
7190 }
7191
7192 /* Complete the detaching of the USB devices. */
7193 if (fHasUSBController)
7194 {
7195 alock.release();
7196 detachAllUSBDevices(true /* aDone */);
7197 alock.acquire();
7198 }
7199
7200 /* advance percent count */
7201 if (aProgress)
7202 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount);
7203 }
7204 else
7205 {
7206 rc = setError(VBOX_E_VM_ERROR,
7207 tr("Could not power off the machine. (Error: %Rrc)"),
7208 vrc);
7209 }
7210
7211 /*
7212 * Finished with the destruction.
7213 *
7214 * Note that if something impossible happened and we've failed to destroy
7215 * the VM, mVMDestroying will remain true and mMachineState will be
7216 * something like Stopping, so most Console methods will return an error
7217 * to the caller.
7218 */
7219 if (pUVM != NULL)
7220 VMR3ReleaseUVM(pUVM);
7221 else
7222 mVMDestroying = false;
7223
7224#ifdef CONSOLE_WITH_EVENT_CACHE
7225 if (SUCCEEDED(rc))
7226 mCallbackData.clear();
7227#endif
7228
7229 LogFlowThisFuncLeave();
7230 return rc;
7231}
7232
7233/**
7234 * @note Locks this object for writing.
7235 */
7236HRESULT Console::setMachineState(MachineState_T aMachineState,
7237 bool aUpdateServer /* = true */)
7238{
7239 AutoCaller autoCaller(this);
7240 AssertComRCReturnRC(autoCaller.rc());
7241
7242 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7243
7244 HRESULT rc = S_OK;
7245
7246 if (mMachineState != aMachineState)
7247 {
7248 LogThisFunc(("machineState=%s -> %s aUpdateServer=%RTbool\n",
7249 Global::stringifyMachineState(mMachineState), Global::stringifyMachineState(aMachineState), aUpdateServer));
7250 mMachineState = aMachineState;
7251
7252 /// @todo (dmik)
7253 // possibly, we need to redo onStateChange() using the dedicated
7254 // Event thread, like it is done in VirtualBox. This will make it
7255 // much safer (no deadlocks possible if someone tries to use the
7256 // console from the callback), however, listeners will lose the
7257 // ability to synchronously react to state changes (is it really
7258 // necessary??)
7259 LogFlowThisFunc(("Doing onStateChange()...\n"));
7260 onStateChange(aMachineState);
7261 LogFlowThisFunc(("Done onStateChange()\n"));
7262
7263 if (aUpdateServer)
7264 {
7265 /* Server notification MUST be done from under the lock; otherwise
7266 * the machine state here and on the server might go out of sync
7267 * which can lead to various unexpected results (like the machine
7268 * state being >= MachineState_Running on the server, while the
7269 * session state is already SessionState_Unlocked at the same time
7270 * there).
7271 *
7272 * Cross-lock conditions should be carefully watched out: calling
7273 * UpdateState we will require Machine and SessionMachine locks
7274 * (remember that here we're holding the Console lock here, and also
7275 * all locks that have been acquire by the thread before calling
7276 * this method).
7277 */
7278 LogFlowThisFunc(("Doing mControl->UpdateState()...\n"));
7279 rc = mControl->UpdateState(aMachineState);
7280 LogFlowThisFunc(("mControl->UpdateState()=%Rhrc\n", rc));
7281 }
7282 }
7283
7284 return rc;
7285}
7286
7287/**
7288 * Searches for a shared folder with the given logical name
7289 * in the collection of shared folders.
7290 *
7291 * @param aName logical name of the shared folder
7292 * @param aSharedFolder where to return the found object
7293 * @param aSetError whether to set the error info if the folder is
7294 * not found
7295 * @return
7296 * S_OK when found or E_INVALIDARG when not found
7297 *
7298 * @note The caller must lock this object for writing.
7299 */
7300HRESULT Console::findSharedFolder(const Utf8Str &strName,
7301 ComObjPtr<SharedFolder> &aSharedFolder,
7302 bool aSetError /* = false */)
7303{
7304 /* sanity check */
7305 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7306
7307 SharedFolderMap::const_iterator it = m_mapSharedFolders.find(strName);
7308 if (it != m_mapSharedFolders.end())
7309 {
7310 aSharedFolder = it->second;
7311 return S_OK;
7312 }
7313
7314 if (aSetError)
7315 setError(VBOX_E_FILE_ERROR,
7316 tr("Could not find a shared folder named '%s'."),
7317 strName.c_str());
7318
7319 return VBOX_E_FILE_ERROR;
7320}
7321
7322/**
7323 * Fetches the list of global or machine shared folders from the server.
7324 *
7325 * @param aGlobal true to fetch global folders.
7326 *
7327 * @note The caller must lock this object for writing.
7328 */
7329HRESULT Console::fetchSharedFolders(BOOL aGlobal)
7330{
7331 /* sanity check */
7332 AssertReturn(AutoCaller(this).state() == InInit ||
7333 isWriteLockOnCurrentThread(), E_FAIL);
7334
7335 LogFlowThisFunc(("Entering\n"));
7336
7337 /* Check if we're online and keep it that way. */
7338 SafeVMPtrQuiet ptrVM(this);
7339 AutoVMCallerQuietWeak autoVMCaller(this);
7340 bool const online = ptrVM.isOk()
7341 && m_pVMMDev
7342 && m_pVMMDev->isShFlActive();
7343
7344 HRESULT rc = S_OK;
7345
7346 try
7347 {
7348 if (aGlobal)
7349 {
7350 /// @todo grab & process global folders when they are done
7351 }
7352 else
7353 {
7354 SharedFolderDataMap oldFolders;
7355 if (online)
7356 oldFolders = m_mapMachineSharedFolders;
7357
7358 m_mapMachineSharedFolders.clear();
7359
7360 SafeIfaceArray<ISharedFolder> folders;
7361 rc = mMachine->COMGETTER(SharedFolders)(ComSafeArrayAsOutParam(folders));
7362 if (FAILED(rc)) throw rc;
7363
7364 for (size_t i = 0; i < folders.size(); ++i)
7365 {
7366 ComPtr<ISharedFolder> pSharedFolder = folders[i];
7367
7368 Bstr bstrName;
7369 Bstr bstrHostPath;
7370 BOOL writable;
7371 BOOL autoMount;
7372
7373 rc = pSharedFolder->COMGETTER(Name)(bstrName.asOutParam());
7374 if (FAILED(rc)) throw rc;
7375 Utf8Str strName(bstrName);
7376
7377 rc = pSharedFolder->COMGETTER(HostPath)(bstrHostPath.asOutParam());
7378 if (FAILED(rc)) throw rc;
7379 Utf8Str strHostPath(bstrHostPath);
7380
7381 rc = pSharedFolder->COMGETTER(Writable)(&writable);
7382 if (FAILED(rc)) throw rc;
7383
7384 rc = pSharedFolder->COMGETTER(AutoMount)(&autoMount);
7385 if (FAILED(rc)) throw rc;
7386
7387 m_mapMachineSharedFolders.insert(std::make_pair(strName,
7388 SharedFolderData(strHostPath, !!writable, !!autoMount)));
7389
7390 /* send changes to HGCM if the VM is running */
7391 if (online)
7392 {
7393 SharedFolderDataMap::iterator it = oldFolders.find(strName);
7394 if ( it == oldFolders.end()
7395 || it->second.m_strHostPath != strHostPath)
7396 {
7397 /* a new machine folder is added or
7398 * the existing machine folder is changed */
7399 if (m_mapSharedFolders.find(strName) != m_mapSharedFolders.end())
7400 ; /* the console folder exists, nothing to do */
7401 else
7402 {
7403 /* remove the old machine folder (when changed)
7404 * or the global folder if any (when new) */
7405 if ( it != oldFolders.end()
7406 || m_mapGlobalSharedFolders.find(strName) != m_mapGlobalSharedFolders.end()
7407 )
7408 {
7409 rc = removeSharedFolder(strName);
7410 if (FAILED(rc)) throw rc;
7411 }
7412
7413 /* create the new machine folder */
7414 rc = createSharedFolder(strName,
7415 SharedFolderData(strHostPath, !!writable, !!autoMount));
7416 if (FAILED(rc)) throw rc;
7417 }
7418 }
7419 /* forget the processed (or identical) folder */
7420 if (it != oldFolders.end())
7421 oldFolders.erase(it);
7422 }
7423 }
7424
7425 /* process outdated (removed) folders */
7426 if (online)
7427 {
7428 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
7429 it != oldFolders.end(); ++it)
7430 {
7431 if (m_mapSharedFolders.find(it->first) != m_mapSharedFolders.end())
7432 ; /* the console folder exists, nothing to do */
7433 else
7434 {
7435 /* remove the outdated machine folder */
7436 rc = removeSharedFolder(it->first);
7437 if (FAILED(rc)) throw rc;
7438
7439 /* create the global folder if there is any */
7440 SharedFolderDataMap::const_iterator git =
7441 m_mapGlobalSharedFolders.find(it->first);
7442 if (git != m_mapGlobalSharedFolders.end())
7443 {
7444 rc = createSharedFolder(git->first, git->second);
7445 if (FAILED(rc)) throw rc;
7446 }
7447 }
7448 }
7449 }
7450 }
7451 }
7452 catch (HRESULT rc2)
7453 {
7454 if (online)
7455 setVMRuntimeErrorCallbackF(0, "BrokenSharedFolder",
7456 N_("Broken shared folder!"));
7457 }
7458
7459 LogFlowThisFunc(("Leaving\n"));
7460
7461 return rc;
7462}
7463
7464/**
7465 * Searches for a shared folder with the given name in the list of machine
7466 * shared folders and then in the list of the global shared folders.
7467 *
7468 * @param aName Name of the folder to search for.
7469 * @param aIt Where to store the pointer to the found folder.
7470 * @return @c true if the folder was found and @c false otherwise.
7471 *
7472 * @note The caller must lock this object for reading.
7473 */
7474bool Console::findOtherSharedFolder(const Utf8Str &strName,
7475 SharedFolderDataMap::const_iterator &aIt)
7476{
7477 /* sanity check */
7478 AssertReturn(isWriteLockOnCurrentThread(), false);
7479
7480 /* first, search machine folders */
7481 aIt = m_mapMachineSharedFolders.find(strName);
7482 if (aIt != m_mapMachineSharedFolders.end())
7483 return true;
7484
7485 /* second, search machine folders */
7486 aIt = m_mapGlobalSharedFolders.find(strName);
7487 if (aIt != m_mapGlobalSharedFolders.end())
7488 return true;
7489
7490 return false;
7491}
7492
7493/**
7494 * Calls the HGCM service to add a shared folder definition.
7495 *
7496 * @param aName Shared folder name.
7497 * @param aHostPath Shared folder path.
7498 *
7499 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
7500 * @note Doesn't lock anything.
7501 */
7502HRESULT Console::createSharedFolder(const Utf8Str &strName, const SharedFolderData &aData)
7503{
7504 ComAssertRet(strName.isNotEmpty(), E_FAIL);
7505 ComAssertRet(aData.m_strHostPath.isNotEmpty(), E_FAIL);
7506
7507 /* sanity checks */
7508 AssertReturn(mpUVM, E_FAIL);
7509 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
7510
7511 VBOXHGCMSVCPARM parms[SHFL_CPARMS_ADD_MAPPING];
7512 SHFLSTRING *pFolderName, *pMapName;
7513 size_t cbString;
7514
7515 Bstr value;
7516 HRESULT hrc = mMachine->GetExtraData(BstrFmt("VBoxInternal2/SharedFoldersEnableSymlinksCreate/%s",
7517 strName.c_str()).raw(),
7518 value.asOutParam());
7519 bool fSymlinksCreate = hrc == S_OK && value == "1";
7520
7521 Log(("Adding shared folder '%s' -> '%s'\n", strName.c_str(), aData.m_strHostPath.c_str()));
7522
7523 // check whether the path is valid and exists
7524 char hostPathFull[RTPATH_MAX];
7525 int vrc = RTPathAbsEx(NULL,
7526 aData.m_strHostPath.c_str(),
7527 hostPathFull,
7528 sizeof(hostPathFull));
7529
7530 bool fMissing = false;
7531 if (RT_FAILURE(vrc))
7532 return setError(E_INVALIDARG,
7533 tr("Invalid shared folder path: '%s' (%Rrc)"),
7534 aData.m_strHostPath.c_str(), vrc);
7535 if (!RTPathExists(hostPathFull))
7536 fMissing = true;
7537
7538 /* Check whether the path is full (absolute) */
7539 if (RTPathCompare(aData.m_strHostPath.c_str(), hostPathFull) != 0)
7540 return setError(E_INVALIDARG,
7541 tr("Shared folder path '%s' is not absolute"),
7542 aData.m_strHostPath.c_str());
7543
7544 // now that we know the path is good, give it to HGCM
7545
7546 Bstr bstrName(strName);
7547 Bstr bstrHostPath(aData.m_strHostPath);
7548
7549 cbString = (bstrHostPath.length() + 1) * sizeof(RTUTF16);
7550 if (cbString >= UINT16_MAX)
7551 return setError(E_INVALIDARG, tr("The name is too long"));
7552 pFolderName = (SHFLSTRING*)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
7553 Assert(pFolderName);
7554 memcpy(pFolderName->String.ucs2, bstrHostPath.raw(), cbString);
7555
7556 pFolderName->u16Size = (uint16_t)cbString;
7557 pFolderName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
7558
7559 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
7560 parms[0].u.pointer.addr = pFolderName;
7561 parms[0].u.pointer.size = sizeof(SHFLSTRING) + (uint16_t)cbString;
7562
7563 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
7564 if (cbString >= UINT16_MAX)
7565 {
7566 RTMemFree(pFolderName);
7567 return setError(E_INVALIDARG, tr("The host path is too long"));
7568 }
7569 pMapName = (SHFLSTRING*)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
7570 Assert(pMapName);
7571 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
7572
7573 pMapName->u16Size = (uint16_t)cbString;
7574 pMapName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
7575
7576 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
7577 parms[1].u.pointer.addr = pMapName;
7578 parms[1].u.pointer.size = sizeof(SHFLSTRING) + (uint16_t)cbString;
7579
7580 parms[2].type = VBOX_HGCM_SVC_PARM_32BIT;
7581 parms[2].u.uint32 = (aData.m_fWritable ? SHFL_ADD_MAPPING_F_WRITABLE : 0)
7582 | (aData.m_fAutoMount ? SHFL_ADD_MAPPING_F_AUTOMOUNT : 0)
7583 | (fSymlinksCreate ? SHFL_ADD_MAPPING_F_CREATE_SYMLINKS : 0)
7584 | (fMissing ? SHFL_ADD_MAPPING_F_MISSING : 0)
7585 ;
7586
7587 vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders",
7588 SHFL_FN_ADD_MAPPING,
7589 SHFL_CPARMS_ADD_MAPPING, &parms[0]);
7590 RTMemFree(pFolderName);
7591 RTMemFree(pMapName);
7592
7593 if (RT_FAILURE(vrc))
7594 return setError(E_FAIL,
7595 tr("Could not create a shared folder '%s' mapped to '%s' (%Rrc)"),
7596 strName.c_str(), aData.m_strHostPath.c_str(), vrc);
7597
7598 if (fMissing)
7599 return setError(E_INVALIDARG,
7600 tr("Shared folder path '%s' does not exist on the host"),
7601 aData.m_strHostPath.c_str());
7602
7603 return S_OK;
7604}
7605
7606/**
7607 * Calls the HGCM service to remove the shared folder definition.
7608 *
7609 * @param aName Shared folder name.
7610 *
7611 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
7612 * @note Doesn't lock anything.
7613 */
7614HRESULT Console::removeSharedFolder(const Utf8Str &strName)
7615{
7616 ComAssertRet(strName.isNotEmpty(), E_FAIL);
7617
7618 /* sanity checks */
7619 AssertReturn(mpUVM, E_FAIL);
7620 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
7621
7622 VBOXHGCMSVCPARM parms;
7623 SHFLSTRING *pMapName;
7624 size_t cbString;
7625
7626 Log(("Removing shared folder '%s'\n", strName.c_str()));
7627
7628 Bstr bstrName(strName);
7629 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
7630 if (cbString >= UINT16_MAX)
7631 return setError(E_INVALIDARG, tr("The name is too long"));
7632 pMapName = (SHFLSTRING *) RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
7633 Assert(pMapName);
7634 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
7635
7636 pMapName->u16Size = (uint16_t)cbString;
7637 pMapName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
7638
7639 parms.type = VBOX_HGCM_SVC_PARM_PTR;
7640 parms.u.pointer.addr = pMapName;
7641 parms.u.pointer.size = sizeof(SHFLSTRING) + (uint16_t)cbString;
7642
7643 int vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders",
7644 SHFL_FN_REMOVE_MAPPING,
7645 1, &parms);
7646 RTMemFree(pMapName);
7647 if (RT_FAILURE(vrc))
7648 return setError(E_FAIL,
7649 tr("Could not remove the shared folder '%s' (%Rrc)"),
7650 strName.c_str(), vrc);
7651
7652 return S_OK;
7653}
7654
7655/** @callback_method_impl{FNVMATSTATE}
7656 *
7657 * @note Locks the Console object for writing.
7658 * @remarks The @a pUVM parameter can be NULL in one case where powerUpThread()
7659 * calls after the VM was destroyed.
7660 */
7661DECLCALLBACK(void) Console::vmstateChangeCallback(PUVM pUVM, VMSTATE enmState, VMSTATE enmOldState, void *pvUser)
7662{
7663 LogFlowFunc(("Changing state from %s to %s (pUVM=%p)\n",
7664 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState), pUVM));
7665
7666 Console *that = static_cast<Console *>(pvUser);
7667 AssertReturnVoid(that);
7668
7669 AutoCaller autoCaller(that);
7670
7671 /* Note that we must let this method proceed even if Console::uninit() has
7672 * been already called. In such case this VMSTATE change is a result of:
7673 * 1) powerDown() called from uninit() itself, or
7674 * 2) VM-(guest-)initiated power off. */
7675 AssertReturnVoid( autoCaller.isOk()
7676 || autoCaller.state() == InUninit);
7677
7678 switch (enmState)
7679 {
7680 /*
7681 * The VM has terminated
7682 */
7683 case VMSTATE_OFF:
7684 {
7685 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7686
7687 if (that->mVMStateChangeCallbackDisabled)
7688 break;
7689
7690 /* Do we still think that it is running? It may happen if this is a
7691 * VM-(guest-)initiated shutdown/poweroff.
7692 */
7693 if ( that->mMachineState != MachineState_Stopping
7694 && that->mMachineState != MachineState_Saving
7695 && that->mMachineState != MachineState_Restoring
7696 && that->mMachineState != MachineState_TeleportingIn
7697 && that->mMachineState != MachineState_FaultTolerantSyncing
7698 && that->mMachineState != MachineState_TeleportingPausedVM
7699 && !that->mVMIsAlreadyPoweringOff
7700 )
7701 {
7702 LogFlowFunc(("VM has powered itself off but Console still thinks it is running. Notifying.\n"));
7703
7704 /* prevent powerDown() from calling VMR3PowerOff() again */
7705 Assert(that->mVMPoweredOff == false);
7706 that->mVMPoweredOff = true;
7707
7708 /*
7709 * request a progress object from the server
7710 * (this will set the machine state to Stopping on the server
7711 * to block others from accessing this machine)
7712 */
7713 ComPtr<IProgress> pProgress;
7714 HRESULT rc = that->mControl->BeginPoweringDown(pProgress.asOutParam());
7715 AssertComRC(rc);
7716
7717 /* sync the state with the server */
7718 that->setMachineStateLocally(MachineState_Stopping);
7719
7720 /* Setup task object and thread to carry out the operation
7721 * asynchronously (if we call powerDown() right here but there
7722 * is one or more mpUVM callers (added with addVMCaller()) we'll
7723 * deadlock).
7724 */
7725 std::auto_ptr<VMPowerDownTask> task(new VMPowerDownTask(that, pProgress));
7726
7727 /* If creating a task failed, this can currently mean one of
7728 * two: either Console::uninit() has been called just a ms
7729 * before (so a powerDown() call is already on the way), or
7730 * powerDown() itself is being already executed. Just do
7731 * nothing.
7732 */
7733 if (!task->isOk())
7734 {
7735 LogFlowFunc(("Console is already being uninitialized.\n"));
7736 break;
7737 }
7738
7739 int vrc = RTThreadCreate(NULL, Console::powerDownThread,
7740 (void *)task.get(), 0,
7741 RTTHREADTYPE_MAIN_WORKER, 0,
7742 "VMPwrDwn");
7743 AssertMsgRCBreak(vrc, ("Could not create VMPowerDown thread (%Rrc)\n", vrc));
7744
7745 /* task is now owned by powerDownThread(), so release it */
7746 task.release();
7747 }
7748 break;
7749 }
7750
7751 /* The VM has been completely destroyed.
7752 *
7753 * Note: This state change can happen at two points:
7754 * 1) At the end of VMR3Destroy() if it was not called from EMT.
7755 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
7756 * called by EMT.
7757 */
7758 case VMSTATE_TERMINATED:
7759 {
7760 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7761
7762 if (that->mVMStateChangeCallbackDisabled)
7763 break;
7764
7765 /* Terminate host interface networking. If pUVM is NULL, we've been
7766 * manually called from powerUpThread() either before calling
7767 * VMR3Create() or after VMR3Create() failed, so no need to touch
7768 * networking.
7769 */
7770 if (pUVM)
7771 that->powerDownHostInterfaces();
7772
7773 /* From now on the machine is officially powered down or remains in
7774 * the Saved state.
7775 */
7776 switch (that->mMachineState)
7777 {
7778 default:
7779 AssertFailed();
7780 /* fall through */
7781 case MachineState_Stopping:
7782 /* successfully powered down */
7783 that->setMachineState(MachineState_PoweredOff);
7784 break;
7785 case MachineState_Saving:
7786 /* successfully saved */
7787 that->setMachineState(MachineState_Saved);
7788 break;
7789 case MachineState_Starting:
7790 /* failed to start, but be patient: set back to PoweredOff
7791 * (for similarity with the below) */
7792 that->setMachineState(MachineState_PoweredOff);
7793 break;
7794 case MachineState_Restoring:
7795 /* failed to load the saved state file, but be patient: set
7796 * back to Saved (to preserve the saved state file) */
7797 that->setMachineState(MachineState_Saved);
7798 break;
7799 case MachineState_TeleportingIn:
7800 /* Teleportation failed or was canceled. Back to powered off. */
7801 that->setMachineState(MachineState_PoweredOff);
7802 break;
7803 case MachineState_TeleportingPausedVM:
7804 /* Successfully teleported the VM. */
7805 that->setMachineState(MachineState_Teleported);
7806 break;
7807 case MachineState_FaultTolerantSyncing:
7808 /* Fault tolerant sync failed or was canceled. Back to powered off. */
7809 that->setMachineState(MachineState_PoweredOff);
7810 break;
7811 }
7812 break;
7813 }
7814
7815 case VMSTATE_RESETTING:
7816 {
7817#ifdef VBOX_WITH_GUEST_PROPS
7818 /* Do not take any read/write locks here! */
7819 that->guestPropertiesHandleVMReset();
7820#endif
7821 break;
7822 }
7823
7824 case VMSTATE_SUSPENDED:
7825 {
7826 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7827
7828 if (that->mVMStateChangeCallbackDisabled)
7829 break;
7830
7831 switch (that->mMachineState)
7832 {
7833 case MachineState_Teleporting:
7834 that->setMachineState(MachineState_TeleportingPausedVM);
7835 break;
7836
7837 case MachineState_LiveSnapshotting:
7838 that->setMachineState(MachineState_Saving);
7839 break;
7840
7841 case MachineState_TeleportingPausedVM:
7842 case MachineState_Saving:
7843 case MachineState_Restoring:
7844 case MachineState_Stopping:
7845 case MachineState_TeleportingIn:
7846 case MachineState_FaultTolerantSyncing:
7847 /* The worker thread handles the transition. */
7848 break;
7849
7850 default:
7851 AssertMsgFailed(("%s\n", Global::stringifyMachineState(that->mMachineState)));
7852 case MachineState_Running:
7853 that->setMachineState(MachineState_Paused);
7854 break;
7855
7856 case MachineState_Paused:
7857 /* Nothing to do. */
7858 break;
7859 }
7860 break;
7861 }
7862
7863 case VMSTATE_SUSPENDED_LS:
7864 case VMSTATE_SUSPENDED_EXT_LS:
7865 {
7866 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7867 if (that->mVMStateChangeCallbackDisabled)
7868 break;
7869 switch (that->mMachineState)
7870 {
7871 case MachineState_Teleporting:
7872 that->setMachineState(MachineState_TeleportingPausedVM);
7873 break;
7874
7875 case MachineState_LiveSnapshotting:
7876 that->setMachineState(MachineState_Saving);
7877 break;
7878
7879 case MachineState_TeleportingPausedVM:
7880 case MachineState_Saving:
7881 /* ignore */
7882 break;
7883
7884 default:
7885 AssertMsgFailed(("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState), VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
7886 that->setMachineState(MachineState_Paused);
7887 break;
7888 }
7889 break;
7890 }
7891
7892 case VMSTATE_RUNNING:
7893 {
7894 if ( enmOldState == VMSTATE_POWERING_ON
7895 || enmOldState == VMSTATE_RESUMING
7896 || enmOldState == VMSTATE_RUNNING_FT)
7897 {
7898 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7899
7900 if (that->mVMStateChangeCallbackDisabled)
7901 break;
7902
7903 Assert( ( ( that->mMachineState == MachineState_Starting
7904 || that->mMachineState == MachineState_Paused)
7905 && enmOldState == VMSTATE_POWERING_ON)
7906 || ( ( that->mMachineState == MachineState_Restoring
7907 || that->mMachineState == MachineState_TeleportingIn
7908 || that->mMachineState == MachineState_Paused
7909 || that->mMachineState == MachineState_Saving
7910 )
7911 && enmOldState == VMSTATE_RESUMING)
7912 || ( that->mMachineState == MachineState_FaultTolerantSyncing
7913 && enmOldState == VMSTATE_RUNNING_FT));
7914
7915 that->setMachineState(MachineState_Running);
7916 }
7917
7918 break;
7919 }
7920
7921 case VMSTATE_RUNNING_LS:
7922 AssertMsg( that->mMachineState == MachineState_LiveSnapshotting
7923 || that->mMachineState == MachineState_Teleporting,
7924 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState), VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
7925 break;
7926
7927 case VMSTATE_RUNNING_FT:
7928 AssertMsg(that->mMachineState == MachineState_FaultTolerantSyncing,
7929 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState), VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
7930 break;
7931
7932 case VMSTATE_FATAL_ERROR:
7933 {
7934 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7935
7936 if (that->mVMStateChangeCallbackDisabled)
7937 break;
7938
7939 /* Fatal errors are only for running VMs. */
7940 Assert(Global::IsOnline(that->mMachineState));
7941
7942 /* Note! 'Pause' is used here in want of something better. There
7943 * are currently only two places where fatal errors might be
7944 * raised, so it is not worth adding a new externally
7945 * visible state for this yet. */
7946 that->setMachineState(MachineState_Paused);
7947 break;
7948 }
7949
7950 case VMSTATE_GURU_MEDITATION:
7951 {
7952 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7953
7954 if (that->mVMStateChangeCallbackDisabled)
7955 break;
7956
7957 /* Guru are only for running VMs */
7958 Assert(Global::IsOnline(that->mMachineState));
7959
7960 that->setMachineState(MachineState_Stuck);
7961 break;
7962 }
7963
7964 default: /* shut up gcc */
7965 break;
7966 }
7967}
7968
7969/**
7970 * Changes the clipboard mode.
7971 *
7972 * @param aClipboardMode new clipboard mode.
7973 */
7974void Console::changeClipboardMode(ClipboardMode_T aClipboardMode)
7975{
7976 VMMDev *pVMMDev = m_pVMMDev;
7977 Assert(pVMMDev);
7978
7979 VBOXHGCMSVCPARM parm;
7980 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
7981
7982 switch (aClipboardMode)
7983 {
7984 default:
7985 case ClipboardMode_Disabled:
7986 LogRel(("Shared clipboard mode: Off\n"));
7987 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_OFF;
7988 break;
7989 case ClipboardMode_GuestToHost:
7990 LogRel(("Shared clipboard mode: Guest to Host\n"));
7991 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_GUEST_TO_HOST;
7992 break;
7993 case ClipboardMode_HostToGuest:
7994 LogRel(("Shared clipboard mode: Host to Guest\n"));
7995 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_HOST_TO_GUEST;
7996 break;
7997 case ClipboardMode_Bidirectional:
7998 LogRel(("Shared clipboard mode: Bidirectional\n"));
7999 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_BIDIRECTIONAL;
8000 break;
8001 }
8002
8003 pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE, 1, &parm);
8004}
8005
8006/**
8007 * Changes the drag'n_drop mode.
8008 *
8009 * @param aDragAndDropMode new drag'n'drop mode.
8010 */
8011void Console::changeDragAndDropMode(DragAndDropMode_T aDragAndDropMode)
8012{
8013 VMMDev *pVMMDev = m_pVMMDev;
8014 Assert(pVMMDev);
8015
8016 VBOXHGCMSVCPARM parm;
8017 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
8018
8019 switch (aDragAndDropMode)
8020 {
8021 default:
8022 case DragAndDropMode_Disabled:
8023 LogRel(("Drag'n'drop mode: Off\n"));
8024 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_OFF;
8025 break;
8026 case DragAndDropMode_GuestToHost:
8027 LogRel(("Drag'n'drop mode: Guest to Host\n"));
8028 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_GUEST_TO_HOST;
8029 break;
8030 case DragAndDropMode_HostToGuest:
8031 LogRel(("Drag'n'drop mode: Host to Guest\n"));
8032 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_HOST_TO_GUEST;
8033 break;
8034 case DragAndDropMode_Bidirectional:
8035 LogRel(("Drag'n'drop mode: Bidirectional\n"));
8036 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_BIDIRECTIONAL;
8037 break;
8038 }
8039
8040 pVMMDev->hgcmHostCall("VBoxDragAndDropSvc", DragAndDropSvc::HOST_DND_SET_MODE, 1, &parm);
8041}
8042
8043#ifdef VBOX_WITH_USB
8044/**
8045 * Sends a request to VMM to attach the given host device.
8046 * After this method succeeds, the attached device will appear in the
8047 * mUSBDevices collection.
8048 *
8049 * @param aHostDevice device to attach
8050 *
8051 * @note Synchronously calls EMT.
8052 */
8053HRESULT Console::attachUSBDevice(IUSBDevice *aHostDevice, ULONG aMaskedIfs)
8054{
8055 AssertReturn(aHostDevice, E_FAIL);
8056 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
8057
8058 HRESULT hrc;
8059
8060 /*
8061 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
8062 * method in EMT (using usbAttachCallback()).
8063 */
8064 Bstr BstrAddress;
8065 hrc = aHostDevice->COMGETTER(Address)(BstrAddress.asOutParam());
8066 ComAssertComRCRetRC(hrc);
8067
8068 Utf8Str Address(BstrAddress);
8069
8070 Bstr id;
8071 hrc = aHostDevice->COMGETTER(Id)(id.asOutParam());
8072 ComAssertComRCRetRC(hrc);
8073 Guid uuid(id);
8074
8075 BOOL fRemote = FALSE;
8076 hrc = aHostDevice->COMGETTER(Remote)(&fRemote);
8077 ComAssertComRCRetRC(hrc);
8078
8079 /* Get the VM handle. */
8080 SafeVMPtr ptrVM(this);
8081 if (!ptrVM.isOk())
8082 return ptrVM.rc();
8083
8084 LogFlowThisFunc(("Proxying USB device '%s' {%RTuuid}...\n",
8085 Address.c_str(), uuid.raw()));
8086
8087 void *pvRemoteBackend = NULL;
8088 if (fRemote)
8089 {
8090 RemoteUSBDevice *pRemoteUSBDevice = static_cast<RemoteUSBDevice *>(aHostDevice);
8091 pvRemoteBackend = consoleVRDPServer()->USBBackendRequestPointer(pRemoteUSBDevice->clientId(), &uuid);
8092 if (!pvRemoteBackend)
8093 return E_INVALIDARG; /* The clientId is invalid then. */
8094 }
8095
8096 USHORT portVersion = 1;
8097 hrc = aHostDevice->COMGETTER(PortVersion)(&portVersion);
8098 AssertComRCReturnRC(hrc);
8099 Assert(portVersion == 1 || portVersion == 2);
8100
8101 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
8102 (PFNRT)usbAttachCallback, 9,
8103 this, ptrVM.rawUVM(), aHostDevice, uuid.raw(), fRemote,
8104 Address.c_str(), pvRemoteBackend, portVersion, aMaskedIfs);
8105
8106 if (RT_SUCCESS(vrc))
8107 {
8108 /* Create a OUSBDevice and add it to the device list */
8109 ComObjPtr<OUSBDevice> pUSBDevice;
8110 pUSBDevice.createObject();
8111 hrc = pUSBDevice->init(aHostDevice);
8112 AssertComRC(hrc);
8113
8114 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8115 mUSBDevices.push_back(pUSBDevice);
8116 LogFlowFunc(("Attached device {%RTuuid}\n", pUSBDevice->id().raw()));
8117
8118 /* notify callbacks */
8119 alock.release();
8120 onUSBDeviceStateChange(pUSBDevice, true /* aAttached */, NULL);
8121 }
8122 else
8123 {
8124 LogWarningThisFunc(("Failed to create proxy device for '%s' {%RTuuid} (%Rrc)\n",
8125 Address.c_str(), uuid.raw(), vrc));
8126
8127 switch (vrc)
8128 {
8129 case VERR_VUSB_NO_PORTS:
8130 hrc = setError(E_FAIL, tr("Failed to attach the USB device. (No available ports on the USB controller)."));
8131 break;
8132 case VERR_VUSB_USBFS_PERMISSION:
8133 hrc = setError(E_FAIL, tr("Not permitted to open the USB device, check usbfs options"));
8134 break;
8135 default:
8136 hrc = setError(E_FAIL, tr("Failed to create a proxy device for the USB device. (Error: %Rrc)"), vrc);
8137 break;
8138 }
8139 }
8140
8141 return hrc;
8142}
8143
8144/**
8145 * USB device attach callback used by AttachUSBDevice().
8146 * Note that AttachUSBDevice() doesn't return until this callback is executed,
8147 * so we don't use AutoCaller and don't care about reference counters of
8148 * interface pointers passed in.
8149 *
8150 * @thread EMT
8151 * @note Locks the console object for writing.
8152 */
8153//static
8154DECLCALLBACK(int)
8155Console::usbAttachCallback(Console *that, PUVM pUVM, IUSBDevice *aHostDevice, PCRTUUID aUuid, bool aRemote,
8156 const char *aAddress, void *pvRemoteBackend, USHORT aPortVersion, ULONG aMaskedIfs)
8157{
8158 LogFlowFuncEnter();
8159 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
8160
8161 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
8162 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
8163
8164 int vrc = PDMR3UsbCreateProxyDevice(pUVM, aUuid, aRemote, aAddress, pvRemoteBackend,
8165 aPortVersion == 1 ? VUSB_STDVER_11 : VUSB_STDVER_20, aMaskedIfs);
8166 LogFlowFunc(("vrc=%Rrc\n", vrc));
8167 LogFlowFuncLeave();
8168 return vrc;
8169}
8170
8171/**
8172 * Sends a request to VMM to detach the given host device. After this method
8173 * succeeds, the detached device will disappear from the mUSBDevices
8174 * collection.
8175 *
8176 * @param aHostDevice device to attach
8177 *
8178 * @note Synchronously calls EMT.
8179 */
8180HRESULT Console::detachUSBDevice(const ComObjPtr<OUSBDevice> &aHostDevice)
8181{
8182 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
8183
8184 /* Get the VM handle. */
8185 SafeVMPtr ptrVM(this);
8186 if (!ptrVM.isOk())
8187 return ptrVM.rc();
8188
8189 /* if the device is attached, then there must at least one USB hub. */
8190 AssertReturn(PDMR3UsbHasHub(ptrVM.rawUVM()), E_FAIL);
8191
8192 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8193 LogFlowThisFunc(("Detaching USB proxy device {%RTuuid}...\n",
8194 aHostDevice->id().raw()));
8195
8196 /*
8197 * If this was a remote device, release the backend pointer.
8198 * The pointer was requested in usbAttachCallback.
8199 */
8200 BOOL fRemote = FALSE;
8201
8202 HRESULT hrc2 = aHostDevice->COMGETTER(Remote)(&fRemote);
8203 if (FAILED(hrc2))
8204 setErrorStatic(hrc2, "GetRemote() failed");
8205
8206 PCRTUUID pUuid = aHostDevice->id().raw();
8207 if (fRemote)
8208 {
8209 Guid guid(*pUuid);
8210 consoleVRDPServer()->USBBackendReleasePointer(&guid);
8211 }
8212
8213 alock.release();
8214 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
8215 (PFNRT)usbDetachCallback, 5,
8216 this, ptrVM.rawUVM(), pUuid);
8217 if (RT_SUCCESS(vrc))
8218 {
8219 LogFlowFunc(("Detached device {%RTuuid}\n", pUuid));
8220
8221 /* notify callbacks */
8222 onUSBDeviceStateChange(aHostDevice, false /* aAttached */, NULL);
8223 }
8224
8225 ComAssertRCRet(vrc, E_FAIL);
8226
8227 return S_OK;
8228}
8229
8230/**
8231 * USB device detach callback used by DetachUSBDevice().
8232 *
8233 * Note that DetachUSBDevice() doesn't return until this callback is executed,
8234 * so we don't use AutoCaller and don't care about reference counters of
8235 * interface pointers passed in.
8236 *
8237 * @thread EMT
8238 */
8239//static
8240DECLCALLBACK(int)
8241Console::usbDetachCallback(Console *that, PUVM pUVM, PCRTUUID aUuid)
8242{
8243 LogFlowFuncEnter();
8244 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
8245
8246 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
8247 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
8248
8249 int vrc = PDMR3UsbDetachDevice(pUVM, aUuid);
8250
8251 LogFlowFunc(("vrc=%Rrc\n", vrc));
8252 LogFlowFuncLeave();
8253 return vrc;
8254}
8255#endif /* VBOX_WITH_USB */
8256
8257/* Note: FreeBSD needs this whether netflt is used or not. */
8258#if ((defined(RT_OS_LINUX) && !defined(VBOX_WITH_NETFLT)) || defined(RT_OS_FREEBSD))
8259/**
8260 * Helper function to handle host interface device creation and attachment.
8261 *
8262 * @param networkAdapter the network adapter which attachment should be reset
8263 * @return COM status code
8264 *
8265 * @note The caller must lock this object for writing.
8266 *
8267 * @todo Move this back into the driver!
8268 */
8269HRESULT Console::attachToTapInterface(INetworkAdapter *networkAdapter)
8270{
8271 LogFlowThisFunc(("\n"));
8272 /* sanity check */
8273 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8274
8275# ifdef VBOX_STRICT
8276 /* paranoia */
8277 NetworkAttachmentType_T attachment;
8278 networkAdapter->COMGETTER(AttachmentType)(&attachment);
8279 Assert(attachment == NetworkAttachmentType_Bridged);
8280# endif /* VBOX_STRICT */
8281
8282 HRESULT rc = S_OK;
8283
8284 ULONG slot = 0;
8285 rc = networkAdapter->COMGETTER(Slot)(&slot);
8286 AssertComRC(rc);
8287
8288# ifdef RT_OS_LINUX
8289 /*
8290 * Allocate a host interface device
8291 */
8292 int rcVBox = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
8293 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
8294 if (RT_SUCCESS(rcVBox))
8295 {
8296 /*
8297 * Set/obtain the tap interface.
8298 */
8299 struct ifreq IfReq;
8300 RT_ZERO(IfReq);
8301 /* The name of the TAP interface we are using */
8302 Bstr tapDeviceName;
8303 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
8304 if (FAILED(rc))
8305 tapDeviceName.setNull(); /* Is this necessary? */
8306 if (tapDeviceName.isEmpty())
8307 {
8308 LogRel(("No TAP device name was supplied.\n"));
8309 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
8310 }
8311
8312 if (SUCCEEDED(rc))
8313 {
8314 /* If we are using a static TAP device then try to open it. */
8315 Utf8Str str(tapDeviceName);
8316 RTStrCopy(IfReq.ifr_name, sizeof(IfReq.ifr_name), str.c_str()); /** @todo bitch about names which are too long... */
8317 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
8318 rcVBox = ioctl(maTapFD[slot], TUNSETIFF, &IfReq);
8319 if (rcVBox != 0)
8320 {
8321 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
8322 rc = setError(E_FAIL,
8323 tr("Failed to open the host network interface %ls"),
8324 tapDeviceName.raw());
8325 }
8326 }
8327 if (SUCCEEDED(rc))
8328 {
8329 /*
8330 * Make it pollable.
8331 */
8332 if (fcntl(maTapFD[slot], F_SETFL, O_NONBLOCK) != -1)
8333 {
8334 Log(("attachToTapInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
8335 /*
8336 * Here is the right place to communicate the TAP file descriptor and
8337 * the host interface name to the server if/when it becomes really
8338 * necessary.
8339 */
8340 maTAPDeviceName[slot] = tapDeviceName;
8341 rcVBox = VINF_SUCCESS;
8342 }
8343 else
8344 {
8345 int iErr = errno;
8346
8347 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
8348 rcVBox = VERR_HOSTIF_BLOCKING;
8349 rc = setError(E_FAIL,
8350 tr("could not set up the host networking device for non blocking access: %s"),
8351 strerror(errno));
8352 }
8353 }
8354 }
8355 else
8356 {
8357 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Rrc\n", rcVBox));
8358 switch (rcVBox)
8359 {
8360 case VERR_ACCESS_DENIED:
8361 /* will be handled by our caller */
8362 rc = rcVBox;
8363 break;
8364 default:
8365 rc = setError(E_FAIL,
8366 tr("Could not set up the host networking device: %Rrc"),
8367 rcVBox);
8368 break;
8369 }
8370 }
8371
8372# elif defined(RT_OS_FREEBSD)
8373 /*
8374 * Set/obtain the tap interface.
8375 */
8376 /* The name of the TAP interface we are using */
8377 Bstr tapDeviceName;
8378 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
8379 if (FAILED(rc))
8380 tapDeviceName.setNull(); /* Is this necessary? */
8381 if (tapDeviceName.isEmpty())
8382 {
8383 LogRel(("No TAP device name was supplied.\n"));
8384 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
8385 }
8386 char szTapdev[1024] = "/dev/";
8387 /* If we are using a static TAP device then try to open it. */
8388 Utf8Str str(tapDeviceName);
8389 if (str.length() + strlen(szTapdev) <= sizeof(szTapdev))
8390 strcat(szTapdev, str.c_str());
8391 else
8392 memcpy(szTapdev + strlen(szTapdev), str.c_str(),
8393 sizeof(szTapdev) - strlen(szTapdev) - 1); /** @todo bitch about names which are too long... */
8394 int rcVBox = RTFileOpen(&maTapFD[slot], szTapdev,
8395 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT | RTFILE_O_NON_BLOCK);
8396
8397 if (RT_SUCCESS(rcVBox))
8398 maTAPDeviceName[slot] = tapDeviceName;
8399 else
8400 {
8401 switch (rcVBox)
8402 {
8403 case VERR_ACCESS_DENIED:
8404 /* will be handled by our caller */
8405 rc = rcVBox;
8406 break;
8407 default:
8408 rc = setError(E_FAIL,
8409 tr("Failed to open the host network interface %ls"),
8410 tapDeviceName.raw());
8411 break;
8412 }
8413 }
8414# else
8415# error "huh?"
8416# endif
8417 /* in case of failure, cleanup. */
8418 if (RT_FAILURE(rcVBox) && SUCCEEDED(rc))
8419 {
8420 LogRel(("General failure attaching to host interface\n"));
8421 rc = setError(E_FAIL,
8422 tr("General failure attaching to host interface"));
8423 }
8424 LogFlowThisFunc(("rc=%d\n", rc));
8425 return rc;
8426}
8427
8428
8429/**
8430 * Helper function to handle detachment from a host interface
8431 *
8432 * @param networkAdapter the network adapter which attachment should be reset
8433 * @return COM status code
8434 *
8435 * @note The caller must lock this object for writing.
8436 *
8437 * @todo Move this back into the driver!
8438 */
8439HRESULT Console::detachFromTapInterface(INetworkAdapter *networkAdapter)
8440{
8441 /* sanity check */
8442 LogFlowThisFunc(("\n"));
8443 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8444
8445 HRESULT rc = S_OK;
8446# ifdef VBOX_STRICT
8447 /* paranoia */
8448 NetworkAttachmentType_T attachment;
8449 networkAdapter->COMGETTER(AttachmentType)(&attachment);
8450 Assert(attachment == NetworkAttachmentType_Bridged);
8451# endif /* VBOX_STRICT */
8452
8453 ULONG slot = 0;
8454 rc = networkAdapter->COMGETTER(Slot)(&slot);
8455 AssertComRC(rc);
8456
8457 /* is there an open TAP device? */
8458 if (maTapFD[slot] != NIL_RTFILE)
8459 {
8460 /*
8461 * Close the file handle.
8462 */
8463 Bstr tapDeviceName, tapTerminateApplication;
8464 bool isStatic = true;
8465 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
8466 if (FAILED(rc) || tapDeviceName.isEmpty())
8467 {
8468 /* If the name is empty, this is a dynamic TAP device, so close it now,
8469 so that the termination script can remove the interface. Otherwise we still
8470 need the FD to pass to the termination script. */
8471 isStatic = false;
8472 int rcVBox = RTFileClose(maTapFD[slot]);
8473 AssertRC(rcVBox);
8474 maTapFD[slot] = NIL_RTFILE;
8475 }
8476 if (isStatic)
8477 {
8478 /* If we are using a static TAP device, we close it now, after having called the
8479 termination script. */
8480 int rcVBox = RTFileClose(maTapFD[slot]);
8481 AssertRC(rcVBox);
8482 }
8483 /* the TAP device name and handle are no longer valid */
8484 maTapFD[slot] = NIL_RTFILE;
8485 maTAPDeviceName[slot] = "";
8486 }
8487 LogFlowThisFunc(("returning %d\n", rc));
8488 return rc;
8489}
8490#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
8491
8492/**
8493 * Called at power down to terminate host interface networking.
8494 *
8495 * @note The caller must lock this object for writing.
8496 */
8497HRESULT Console::powerDownHostInterfaces()
8498{
8499 LogFlowThisFunc(("\n"));
8500
8501 /* sanity check */
8502 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8503
8504 /*
8505 * host interface termination handling
8506 */
8507 HRESULT rc = S_OK;
8508 ComPtr<IVirtualBox> pVirtualBox;
8509 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
8510 ComPtr<ISystemProperties> pSystemProperties;
8511 if (pVirtualBox)
8512 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
8513 ChipsetType_T chipsetType = ChipsetType_PIIX3;
8514 mMachine->COMGETTER(ChipsetType)(&chipsetType);
8515 ULONG maxNetworkAdapters = 0;
8516 if (pSystemProperties)
8517 pSystemProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
8518
8519 for (ULONG slot = 0; slot < maxNetworkAdapters; slot++)
8520 {
8521 ComPtr<INetworkAdapter> pNetworkAdapter;
8522 rc = mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
8523 if (FAILED(rc)) break;
8524
8525 BOOL enabled = FALSE;
8526 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
8527 if (!enabled)
8528 continue;
8529
8530 NetworkAttachmentType_T attachment;
8531 pNetworkAdapter->COMGETTER(AttachmentType)(&attachment);
8532 if (attachment == NetworkAttachmentType_Bridged)
8533 {
8534#if ((defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT))
8535 HRESULT rc2 = detachFromTapInterface(pNetworkAdapter);
8536 if (FAILED(rc2) && SUCCEEDED(rc))
8537 rc = rc2;
8538#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
8539 }
8540 }
8541
8542 return rc;
8543}
8544
8545
8546/**
8547 * Process callback handler for VMR3LoadFromFile, VMR3LoadFromStream, VMR3Save
8548 * and VMR3Teleport.
8549 *
8550 * @param pUVM The user mode VM handle.
8551 * @param uPercent Completion percentage (0-100).
8552 * @param pvUser Pointer to an IProgress instance.
8553 * @return VINF_SUCCESS.
8554 */
8555/*static*/
8556DECLCALLBACK(int) Console::stateProgressCallback(PUVM pUVM, unsigned uPercent, void *pvUser)
8557{
8558 IProgress *pProgress = static_cast<IProgress *>(pvUser);
8559
8560 /* update the progress object */
8561 if (pProgress)
8562 pProgress->SetCurrentOperationProgress(uPercent);
8563
8564 NOREF(pUVM);
8565 return VINF_SUCCESS;
8566}
8567
8568/**
8569 * @copydoc FNVMATERROR
8570 *
8571 * @remarks Might be some tiny serialization concerns with access to the string
8572 * object here...
8573 */
8574/*static*/ DECLCALLBACK(void)
8575Console::genericVMSetErrorCallback(PUVM pUVM, void *pvUser, int rc, RT_SRC_POS_DECL,
8576 const char *pszErrorFmt, va_list va)
8577{
8578 Utf8Str *pErrorText = (Utf8Str *)pvUser;
8579 AssertPtr(pErrorText);
8580
8581 /* We ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users. */
8582 va_list va2;
8583 va_copy(va2, va);
8584
8585 /* Append to any the existing error message. */
8586 if (pErrorText->length())
8587 *pErrorText = Utf8StrFmt("%s.\n%N (%Rrc)", pErrorText->c_str(),
8588 pszErrorFmt, &va2, rc, rc);
8589 else
8590 *pErrorText = Utf8StrFmt("%N (%Rrc)", pszErrorFmt, &va2, rc, rc);
8591
8592 va_end(va2);
8593
8594 NOREF(pUVM);
8595}
8596
8597/**
8598 * VM runtime error callback function.
8599 * See VMSetRuntimeError for the detailed description of parameters.
8600 *
8601 * @param pUVM The user mode VM handle. Ignored, so passing NULL
8602 * is fine.
8603 * @param pvUser The user argument, pointer to the Console instance.
8604 * @param fFlags The action flags. See VMSETRTERR_FLAGS_*.
8605 * @param pszErrorId Error ID string.
8606 * @param pszFormat Error message format string.
8607 * @param va Error message arguments.
8608 * @thread EMT.
8609 */
8610/* static */ DECLCALLBACK(void)
8611Console::setVMRuntimeErrorCallback(PUVM pUVM, void *pvUser, uint32_t fFlags,
8612 const char *pszErrorId,
8613 const char *pszFormat, va_list va)
8614{
8615 bool const fFatal = !!(fFlags & VMSETRTERR_FLAGS_FATAL);
8616 LogFlowFuncEnter();
8617
8618 Console *that = static_cast<Console *>(pvUser);
8619 AssertReturnVoid(that);
8620
8621 Utf8Str message(pszFormat, va);
8622
8623 LogRel(("Console: VM runtime error: fatal=%RTbool, errorID=%s message=\"%s\"\n",
8624 fFatal, pszErrorId, message.c_str()));
8625
8626 that->onRuntimeError(BOOL(fFatal), Bstr(pszErrorId).raw(), Bstr(message).raw());
8627
8628 LogFlowFuncLeave(); NOREF(pUVM);
8629}
8630
8631/**
8632 * Captures USB devices that match filters of the VM.
8633 * Called at VM startup.
8634 *
8635 * @param pUVM The VM handle.
8636 */
8637HRESULT Console::captureUSBDevices(PUVM pUVM)
8638{
8639 LogFlowThisFunc(("\n"));
8640
8641 /* sanity check */
8642 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
8643 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8644
8645 /* If the machine has an USB controller, ask the USB proxy service to
8646 * capture devices */
8647 PPDMIBASE pBase;
8648 int vrc = PDMR3QueryLun(pUVM, "usb-ohci", 0, 0, &pBase);
8649 if (RT_SUCCESS(vrc))
8650 {
8651 /* release the lock before calling Host in VBoxSVC since Host may call
8652 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
8653 * produce an inter-process dead-lock otherwise. */
8654 alock.release();
8655
8656 HRESULT hrc = mControl->AutoCaptureUSBDevices();
8657 ComAssertComRCRetRC(hrc);
8658 }
8659 else if ( vrc == VERR_PDM_DEVICE_NOT_FOUND
8660 || vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
8661 vrc = VINF_SUCCESS;
8662 else
8663 AssertRC(vrc);
8664
8665 return RT_SUCCESS(vrc) ? S_OK : E_FAIL;
8666}
8667
8668
8669/**
8670 * Detach all USB device which are attached to the VM for the
8671 * purpose of clean up and such like.
8672 */
8673void Console::detachAllUSBDevices(bool aDone)
8674{
8675 LogFlowThisFunc(("aDone=%RTbool\n", aDone));
8676
8677 /* sanity check */
8678 AssertReturnVoid(!isWriteLockOnCurrentThread());
8679 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8680
8681 mUSBDevices.clear();
8682
8683 /* release the lock before calling Host in VBoxSVC since Host may call
8684 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
8685 * produce an inter-process dead-lock otherwise. */
8686 alock.release();
8687
8688 mControl->DetachAllUSBDevices(aDone);
8689}
8690
8691/**
8692 * @note Locks this object for writing.
8693 */
8694void Console::processRemoteUSBDevices(uint32_t u32ClientId, VRDEUSBDEVICEDESC *pDevList, uint32_t cbDevList, bool fDescExt)
8695{
8696 LogFlowThisFuncEnter();
8697 LogFlowThisFunc(("u32ClientId = %d, pDevList=%p, cbDevList = %d, fDescExt = %d\n", u32ClientId, pDevList, cbDevList, fDescExt));
8698
8699 AutoCaller autoCaller(this);
8700 if (!autoCaller.isOk())
8701 {
8702 /* Console has been already uninitialized, deny request */
8703 AssertMsgFailed(("Console is already uninitialized\n"));
8704 LogFlowThisFunc(("Console is already uninitialized\n"));
8705 LogFlowThisFuncLeave();
8706 return;
8707 }
8708
8709 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8710
8711 /*
8712 * Mark all existing remote USB devices as dirty.
8713 */
8714 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
8715 it != mRemoteUSBDevices.end();
8716 ++it)
8717 {
8718 (*it)->dirty(true);
8719 }
8720
8721 /*
8722 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
8723 */
8724 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
8725 VRDEUSBDEVICEDESC *e = pDevList;
8726
8727 /* The cbDevList condition must be checked first, because the function can
8728 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
8729 */
8730 while (cbDevList >= 2 && e->oNext)
8731 {
8732 /* Sanitize incoming strings in case they aren't valid UTF-8. */
8733 if (e->oManufacturer)
8734 RTStrPurgeEncoding((char *)e + e->oManufacturer);
8735 if (e->oProduct)
8736 RTStrPurgeEncoding((char *)e + e->oProduct);
8737 if (e->oSerialNumber)
8738 RTStrPurgeEncoding((char *)e + e->oSerialNumber);
8739
8740 LogFlowThisFunc(("vendor %04X, product %04X, name = %s\n",
8741 e->idVendor, e->idProduct,
8742 e->oProduct? (char *)e + e->oProduct: ""));
8743
8744 bool fNewDevice = true;
8745
8746 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
8747 it != mRemoteUSBDevices.end();
8748 ++it)
8749 {
8750 if ((*it)->devId() == e->id
8751 && (*it)->clientId() == u32ClientId)
8752 {
8753 /* The device is already in the list. */
8754 (*it)->dirty(false);
8755 fNewDevice = false;
8756 break;
8757 }
8758 }
8759
8760 if (fNewDevice)
8761 {
8762 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
8763 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""));
8764
8765 /* Create the device object and add the new device to list. */
8766 ComObjPtr<RemoteUSBDevice> pUSBDevice;
8767 pUSBDevice.createObject();
8768 pUSBDevice->init(u32ClientId, e, fDescExt);
8769
8770 mRemoteUSBDevices.push_back(pUSBDevice);
8771
8772 /* Check if the device is ok for current USB filters. */
8773 BOOL fMatched = FALSE;
8774 ULONG fMaskedIfs = 0;
8775
8776 HRESULT hrc = mControl->RunUSBDeviceFilters(pUSBDevice, &fMatched, &fMaskedIfs);
8777
8778 AssertComRC(hrc);
8779
8780 LogFlowThisFunc(("USB filters return %d %#x\n", fMatched, fMaskedIfs));
8781
8782 if (fMatched)
8783 {
8784 alock.release();
8785 hrc = onUSBDeviceAttach(pUSBDevice, NULL, fMaskedIfs);
8786 alock.acquire();
8787
8788 /// @todo (r=dmik) warning reporting subsystem
8789
8790 if (hrc == S_OK)
8791 {
8792 LogFlowThisFunc(("Device attached\n"));
8793 pUSBDevice->captured(true);
8794 }
8795 }
8796 }
8797
8798 if (cbDevList < e->oNext)
8799 {
8800 LogWarningThisFunc(("cbDevList %d > oNext %d\n",
8801 cbDevList, e->oNext));
8802 break;
8803 }
8804
8805 cbDevList -= e->oNext;
8806
8807 e = (VRDEUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
8808 }
8809
8810 /*
8811 * Remove dirty devices, that is those which are not reported by the server anymore.
8812 */
8813 for (;;)
8814 {
8815 ComObjPtr<RemoteUSBDevice> pUSBDevice;
8816
8817 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
8818 while (it != mRemoteUSBDevices.end())
8819 {
8820 if ((*it)->dirty())
8821 {
8822 pUSBDevice = *it;
8823 break;
8824 }
8825
8826 ++it;
8827 }
8828
8829 if (!pUSBDevice)
8830 {
8831 break;
8832 }
8833
8834 USHORT vendorId = 0;
8835 pUSBDevice->COMGETTER(VendorId)(&vendorId);
8836
8837 USHORT productId = 0;
8838 pUSBDevice->COMGETTER(ProductId)(&productId);
8839
8840 Bstr product;
8841 pUSBDevice->COMGETTER(Product)(product.asOutParam());
8842
8843 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
8844 vendorId, productId, product.raw()));
8845
8846 /* Detach the device from VM. */
8847 if (pUSBDevice->captured())
8848 {
8849 Bstr uuid;
8850 pUSBDevice->COMGETTER(Id)(uuid.asOutParam());
8851 alock.release();
8852 onUSBDeviceDetach(uuid.raw(), NULL);
8853 alock.acquire();
8854 }
8855
8856 /* And remove it from the list. */
8857 mRemoteUSBDevices.erase(it);
8858 }
8859
8860 LogFlowThisFuncLeave();
8861}
8862
8863/**
8864 * Progress cancelation callback for fault tolerance VM poweron
8865 */
8866static void faultToleranceProgressCancelCallback(void *pvUser)
8867{
8868 PUVM pUVM = (PUVM)pvUser;
8869
8870 if (pUVM)
8871 FTMR3CancelStandby(pUVM);
8872}
8873
8874/**
8875 * Thread function which starts the VM (also from saved state) and
8876 * track progress.
8877 *
8878 * @param Thread The thread id.
8879 * @param pvUser Pointer to a VMPowerUpTask structure.
8880 * @return VINF_SUCCESS (ignored).
8881 *
8882 * @note Locks the Console object for writing.
8883 */
8884/*static*/
8885DECLCALLBACK(int) Console::powerUpThread(RTTHREAD Thread, void *pvUser)
8886{
8887 LogFlowFuncEnter();
8888
8889 std::auto_ptr<VMPowerUpTask> task(static_cast<VMPowerUpTask *>(pvUser));
8890 AssertReturn(task.get(), VERR_INVALID_PARAMETER);
8891
8892 AssertReturn(!task->mConsole.isNull(), VERR_INVALID_PARAMETER);
8893 AssertReturn(!task->mProgress.isNull(), VERR_INVALID_PARAMETER);
8894
8895 VirtualBoxBase::initializeComForThread();
8896
8897 HRESULT rc = S_OK;
8898 int vrc = VINF_SUCCESS;
8899
8900 /* Set up a build identifier so that it can be seen from core dumps what
8901 * exact build was used to produce the core. */
8902 static char saBuildID[40];
8903 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
8904 "BU", "IL", "DI", "D", RTBldCfgVersion(), RTBldCfgRevision(), "BU", "IL", "DI", "D");
8905
8906 ComObjPtr<Console> pConsole = task->mConsole;
8907
8908 /* Note: no need to use addCaller() because VMPowerUpTask does that */
8909
8910 /* The lock is also used as a signal from the task initiator (which
8911 * releases it only after RTThreadCreate()) that we can start the job */
8912 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
8913
8914 /* sanity */
8915 Assert(pConsole->mpUVM == NULL);
8916
8917 try
8918 {
8919 // Create the VMM device object, which starts the HGCM thread; do this only
8920 // once for the console, for the pathological case that the same console
8921 // object is used to power up a VM twice. VirtualBox 4.0: we now do that
8922 // here instead of the Console constructor (see Console::init())
8923 if (!pConsole->m_pVMMDev)
8924 {
8925 pConsole->m_pVMMDev = new VMMDev(pConsole);
8926 AssertReturn(pConsole->m_pVMMDev, E_FAIL);
8927 }
8928
8929 /* wait for auto reset ops to complete so that we can successfully lock
8930 * the attached hard disks by calling LockMedia() below */
8931 for (VMPowerUpTask::ProgressList::const_iterator
8932 it = task->hardDiskProgresses.begin();
8933 it != task->hardDiskProgresses.end(); ++it)
8934 {
8935 HRESULT rc2 = (*it)->WaitForCompletion(-1);
8936 AssertComRC(rc2);
8937
8938 rc = task->mProgress->SetNextOperation(BstrFmt(tr("Disk Image Reset Operation - Immutable Image")).raw(), 1);
8939 AssertComRCReturnRC(rc);
8940 }
8941
8942 /*
8943 * Lock attached media. This method will also check their accessibility.
8944 * If we're a teleporter, we'll have to postpone this action so we can
8945 * migrate between local processes.
8946 *
8947 * Note! The media will be unlocked automatically by
8948 * SessionMachine::setMachineState() when the VM is powered down.
8949 */
8950 if ( !task->mTeleporterEnabled
8951 && task->mEnmFaultToleranceState != FaultToleranceState_Standby)
8952 {
8953 rc = pConsole->mControl->LockMedia();
8954 if (FAILED(rc)) throw rc;
8955 }
8956
8957 /* Create the VRDP server. In case of headless operation, this will
8958 * also create the framebuffer, required at VM creation.
8959 */
8960 ConsoleVRDPServer *server = pConsole->consoleVRDPServer();
8961 Assert(server);
8962
8963 /* Does VRDP server call Console from the other thread?
8964 * Not sure (and can change), so release the lock just in case.
8965 */
8966 alock.release();
8967 vrc = server->Launch();
8968 alock.acquire();
8969
8970 if (vrc == VERR_NET_ADDRESS_IN_USE)
8971 {
8972 Utf8Str errMsg;
8973 Bstr bstr;
8974 pConsole->mVRDEServer->GetVRDEProperty(Bstr("TCP/Ports").raw(), bstr.asOutParam());
8975 Utf8Str ports = bstr;
8976 errMsg = Utf8StrFmt(tr("VirtualBox Remote Desktop Extension server can't bind to the port: %s"),
8977 ports.c_str());
8978 LogRel(("VRDE: Warning: failed to launch VRDE server (%Rrc): '%s'\n",
8979 vrc, errMsg.c_str()));
8980 }
8981 else if (vrc == VINF_NOT_SUPPORTED)
8982 {
8983 /* This means that the VRDE is not installed. */
8984 LogRel(("VRDE: VirtualBox Remote Desktop Extension is not available.\n"));
8985 }
8986 else if (RT_FAILURE(vrc))
8987 {
8988 /* Fail, if the server is installed but can't start. */
8989 Utf8Str errMsg;
8990 switch (vrc)
8991 {
8992 case VERR_FILE_NOT_FOUND:
8993 {
8994 /* VRDE library file is missing. */
8995 errMsg = Utf8StrFmt(tr("Could not find the VirtualBox Remote Desktop Extension library."));
8996 break;
8997 }
8998 default:
8999 errMsg = Utf8StrFmt(tr("Failed to launch Remote Desktop Extension server (%Rrc)"),
9000 vrc);
9001 }
9002 LogRel(("VRDE: Failed: (%Rrc), error message: '%s'\n",
9003 vrc, errMsg.c_str()));
9004 throw setErrorStatic(E_FAIL, errMsg.c_str());
9005 }
9006
9007 ComPtr<IMachine> pMachine = pConsole->machine();
9008 ULONG cCpus = 1;
9009 pMachine->COMGETTER(CPUCount)(&cCpus);
9010
9011 /*
9012 * Create the VM
9013 *
9014 * Note! Release the lock since EMT will call Console. It's safe because
9015 * mMachineState is either Starting or Restoring state here.
9016 */
9017 alock.release();
9018
9019 PVM pVM;
9020 vrc = VMR3Create(cCpus,
9021 pConsole->mpVmm2UserMethods,
9022 Console::genericVMSetErrorCallback,
9023 &task->mErrorMsg,
9024 task->mConfigConstructor,
9025 static_cast<Console *>(pConsole),
9026 &pVM, NULL);
9027
9028 alock.acquire();
9029
9030 /* Enable client connections to the server. */
9031 pConsole->consoleVRDPServer()->EnableConnections();
9032
9033 if (RT_SUCCESS(vrc))
9034 {
9035 do
9036 {
9037 /*
9038 * Register our load/save state file handlers
9039 */
9040 vrc = SSMR3RegisterExternal(pConsole->mpUVM, sSSMConsoleUnit, 0 /*iInstance*/, sSSMConsoleVer, 0 /* cbGuess */,
9041 NULL, NULL, NULL,
9042 NULL, saveStateFileExec, NULL,
9043 NULL, loadStateFileExec, NULL,
9044 static_cast<Console *>(pConsole));
9045 AssertRCBreak(vrc);
9046
9047 vrc = static_cast<Console *>(pConsole)->getDisplay()->registerSSM(pConsole->mpUVM);
9048 AssertRC(vrc);
9049 if (RT_FAILURE(vrc))
9050 break;
9051
9052 /*
9053 * Synchronize debugger settings
9054 */
9055 MachineDebugger *machineDebugger = pConsole->getMachineDebugger();
9056 if (machineDebugger)
9057 machineDebugger->flushQueuedSettings();
9058
9059 /*
9060 * Shared Folders
9061 */
9062 if (pConsole->m_pVMMDev->isShFlActive())
9063 {
9064 /* Does the code below call Console from the other thread?
9065 * Not sure, so release the lock just in case. */
9066 alock.release();
9067
9068 for (SharedFolderDataMap::const_iterator it = task->mSharedFolders.begin();
9069 it != task->mSharedFolders.end();
9070 ++it)
9071 {
9072 const SharedFolderData &d = it->second;
9073 rc = pConsole->createSharedFolder(it->first, d);
9074 if (FAILED(rc))
9075 {
9076 ErrorInfoKeeper eik;
9077 pConsole->setVMRuntimeErrorCallbackF(0, "BrokenSharedFolder",
9078 N_("The shared folder '%s' could not be set up: %ls.\n"
9079 "The shared folder setup will not be complete. It is recommended to power down the virtual "
9080 "machine and fix the shared folder settings while the machine is not running"),
9081 it->first.c_str(), eik.getText().raw());
9082 }
9083 }
9084 if (FAILED(rc))
9085 rc = S_OK; // do not fail with broken shared folders
9086
9087 /* acquire the lock again */
9088 alock.acquire();
9089 }
9090
9091 /* release the lock before a lengthy operation */
9092 alock.release();
9093
9094 /*
9095 * Capture USB devices.
9096 */
9097 rc = pConsole->captureUSBDevices(pConsole->mpUVM);
9098 if (FAILED(rc))
9099 break;
9100
9101 /* Load saved state? */
9102 if (task->mSavedStateFile.length())
9103 {
9104 LogFlowFunc(("Restoring saved state from '%s'...\n",
9105 task->mSavedStateFile.c_str()));
9106
9107 vrc = VMR3LoadFromFile(pConsole->mpUVM,
9108 task->mSavedStateFile.c_str(),
9109 Console::stateProgressCallback,
9110 static_cast<IProgress *>(task->mProgress));
9111
9112 if (RT_SUCCESS(vrc))
9113 {
9114 if (task->mStartPaused)
9115 /* done */
9116 pConsole->setMachineState(MachineState_Paused);
9117 else
9118 {
9119 /* Start/Resume the VM execution */
9120#ifdef VBOX_WITH_EXTPACK
9121 vrc = pConsole->mptrExtPackManager->callAllVmPowerOnHooks(pConsole, pVM);
9122#endif
9123 if (RT_SUCCESS(vrc))
9124 vrc = VMR3Resume(pConsole->mpUVM, VMRESUMEREASON_STATE_RESTORED);
9125 AssertLogRelRC(vrc);
9126 }
9127 }
9128
9129 /* Power off in case we failed loading or resuming the VM */
9130 if (RT_FAILURE(vrc))
9131 {
9132 int vrc2 = VMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
9133#ifdef VBOX_WITH_EXTPACK
9134 pConsole->mptrExtPackManager->callAllVmPowerOffHooks(pConsole, pVM);
9135#endif
9136 }
9137 }
9138 else if (task->mTeleporterEnabled)
9139 {
9140 /* -> ConsoleImplTeleporter.cpp */
9141 bool fPowerOffOnFailure;
9142 rc = pConsole->teleporterTrg(pConsole->mpUVM, pMachine, &task->mErrorMsg, task->mStartPaused,
9143 task->mProgress, &fPowerOffOnFailure);
9144 if (FAILED(rc) && fPowerOffOnFailure)
9145 {
9146 ErrorInfoKeeper eik;
9147 int vrc2 = VMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
9148#ifdef VBOX_WITH_EXTPACK
9149 pConsole->mptrExtPackManager->callAllVmPowerOffHooks(pConsole, pVM);
9150#endif
9151 }
9152 }
9153 else if (task->mEnmFaultToleranceState != FaultToleranceState_Inactive)
9154 {
9155 /*
9156 * Get the config.
9157 */
9158 ULONG uPort;
9159 ULONG uInterval;
9160 Bstr bstrAddress, bstrPassword;
9161
9162 rc = pMachine->COMGETTER(FaultTolerancePort)(&uPort);
9163 if (SUCCEEDED(rc))
9164 {
9165 rc = pMachine->COMGETTER(FaultToleranceSyncInterval)(&uInterval);
9166 if (SUCCEEDED(rc))
9167 rc = pMachine->COMGETTER(FaultToleranceAddress)(bstrAddress.asOutParam());
9168 if (SUCCEEDED(rc))
9169 rc = pMachine->COMGETTER(FaultTolerancePassword)(bstrPassword.asOutParam());
9170 }
9171 if (task->mProgress->setCancelCallback(faultToleranceProgressCancelCallback, pConsole->mpUVM))
9172 {
9173 if (SUCCEEDED(rc))
9174 {
9175 Utf8Str strAddress(bstrAddress);
9176 const char *pszAddress = strAddress.isEmpty() ? NULL : strAddress.c_str();
9177 Utf8Str strPassword(bstrPassword);
9178 const char *pszPassword = strPassword.isEmpty() ? NULL : strPassword.c_str();
9179
9180 /* Power on the FT enabled VM. */
9181#ifdef VBOX_WITH_EXTPACK
9182 vrc = pConsole->mptrExtPackManager->callAllVmPowerOnHooks(pConsole, pVM);
9183#endif
9184 if (RT_SUCCESS(vrc))
9185 vrc = FTMR3PowerOn(pConsole->mpUVM,
9186 task->mEnmFaultToleranceState == FaultToleranceState_Master /* fMaster */,
9187 uInterval,
9188 pszAddress,
9189 uPort,
9190 pszPassword);
9191 AssertLogRelRC(vrc);
9192 }
9193 task->mProgress->setCancelCallback(NULL, NULL);
9194 }
9195 else
9196 rc = E_FAIL;
9197 }
9198 else if (task->mStartPaused)
9199 /* done */
9200 pConsole->setMachineState(MachineState_Paused);
9201 else
9202 {
9203 /* Power on the VM (i.e. start executing) */
9204#ifdef VBOX_WITH_EXTPACK
9205 vrc = pConsole->mptrExtPackManager->callAllVmPowerOnHooks(pConsole, pVM);
9206#endif
9207 if (RT_SUCCESS(vrc))
9208 vrc = VMR3PowerOn(pConsole->mpUVM);
9209 AssertLogRelRC(vrc);
9210 }
9211
9212 /* acquire the lock again */
9213 alock.acquire();
9214 }
9215 while (0);
9216
9217 /* On failure, destroy the VM */
9218 if (FAILED(rc) || RT_FAILURE(vrc))
9219 {
9220 /* preserve existing error info */
9221 ErrorInfoKeeper eik;
9222
9223 /* powerDown() will call VMR3Destroy() and do all necessary
9224 * cleanup (VRDP, USB devices) */
9225 alock.release();
9226 HRESULT rc2 = pConsole->powerDown();
9227 alock.acquire();
9228 AssertComRC(rc2);
9229 }
9230 else
9231 {
9232 /*
9233 * Deregister the VMSetError callback. This is necessary as the
9234 * pfnVMAtError() function passed to VMR3Create() is supposed to
9235 * be sticky but our error callback isn't.
9236 */
9237 alock.release();
9238 VMR3AtErrorDeregister(pConsole->mpUVM, Console::genericVMSetErrorCallback, &task->mErrorMsg);
9239 /** @todo register another VMSetError callback? */
9240 alock.acquire();
9241 }
9242 }
9243 else
9244 {
9245 /*
9246 * If VMR3Create() failed it has released the VM memory.
9247 */
9248 VMR3ReleaseUVM(pConsole->mpUVM);
9249 pConsole->mpUVM = NULL;
9250 }
9251
9252 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
9253 {
9254 /* If VMR3Create() or one of the other calls in this function fail,
9255 * an appropriate error message has been set in task->mErrorMsg.
9256 * However since that happens via a callback, the rc status code in
9257 * this function is not updated.
9258 */
9259 if (!task->mErrorMsg.length())
9260 {
9261 /* If the error message is not set but we've got a failure,
9262 * convert the VBox status code into a meaningful error message.
9263 * This becomes unused once all the sources of errors set the
9264 * appropriate error message themselves.
9265 */
9266 AssertMsgFailed(("Missing error message during powerup for status code %Rrc\n", vrc));
9267 task->mErrorMsg = Utf8StrFmt(tr("Failed to start VM execution (%Rrc)"),
9268 vrc);
9269 }
9270
9271 /* Set the error message as the COM error.
9272 * Progress::notifyComplete() will pick it up later. */
9273 throw setErrorStatic(E_FAIL, task->mErrorMsg.c_str());
9274 }
9275 }
9276 catch (HRESULT aRC) { rc = aRC; }
9277
9278 if ( pConsole->mMachineState == MachineState_Starting
9279 || pConsole->mMachineState == MachineState_Restoring
9280 || pConsole->mMachineState == MachineState_TeleportingIn
9281 )
9282 {
9283 /* We are still in the Starting/Restoring state. This means one of:
9284 *
9285 * 1) we failed before VMR3Create() was called;
9286 * 2) VMR3Create() failed.
9287 *
9288 * In both cases, there is no need to call powerDown(), but we still
9289 * need to go back to the PoweredOff/Saved state. Reuse
9290 * vmstateChangeCallback() for that purpose.
9291 */
9292
9293 /* preserve existing error info */
9294 ErrorInfoKeeper eik;
9295
9296 Assert(pConsole->mpUVM == NULL);
9297 vmstateChangeCallback(NULL, VMSTATE_TERMINATED, VMSTATE_CREATING, pConsole);
9298 }
9299
9300 /*
9301 * Evaluate the final result. Note that the appropriate mMachineState value
9302 * is already set by vmstateChangeCallback() in all cases.
9303 */
9304
9305 /* release the lock, don't need it any more */
9306 alock.release();
9307
9308 if (SUCCEEDED(rc))
9309 {
9310 /* Notify the progress object of the success */
9311 task->mProgress->notifyComplete(S_OK);
9312 }
9313 else
9314 {
9315 /* The progress object will fetch the current error info */
9316 task->mProgress->notifyComplete(rc);
9317 LogRel(("Power up failed (vrc=%Rrc, rc=%Rhrc (%#08X))\n", vrc, rc, rc));
9318 }
9319
9320 /* Notify VBoxSVC and any waiting openRemoteSession progress object. */
9321 pConsole->mControl->EndPowerUp(rc);
9322
9323#if defined(RT_OS_WINDOWS)
9324 /* uninitialize COM */
9325 CoUninitialize();
9326#endif
9327
9328 LogFlowFuncLeave();
9329
9330 return VINF_SUCCESS;
9331}
9332
9333
9334/**
9335 * Reconfigures a medium attachment (part of taking or deleting an online snapshot).
9336 *
9337 * @param pConsole Reference to the console object.
9338 * @param pUVM The VM handle.
9339 * @param lInstance The instance of the controller.
9340 * @param pcszDevice The name of the controller type.
9341 * @param enmBus The storage bus type of the controller.
9342 * @param fSetupMerge Whether to set up a medium merge
9343 * @param uMergeSource Merge source image index
9344 * @param uMergeTarget Merge target image index
9345 * @param aMediumAtt The medium attachment.
9346 * @param aMachineState The current machine state.
9347 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
9348 * @return VBox status code.
9349 */
9350/* static */
9351DECLCALLBACK(int) Console::reconfigureMediumAttachment(Console *pConsole,
9352 PUVM pUVM,
9353 const char *pcszDevice,
9354 unsigned uInstance,
9355 StorageBus_T enmBus,
9356 bool fUseHostIOCache,
9357 bool fBuiltinIOCache,
9358 bool fSetupMerge,
9359 unsigned uMergeSource,
9360 unsigned uMergeTarget,
9361 IMediumAttachment *aMediumAtt,
9362 MachineState_T aMachineState,
9363 HRESULT *phrc)
9364{
9365 LogFlowFunc(("pUVM=%p aMediumAtt=%p phrc=%p\n", pUVM, aMediumAtt, phrc));
9366
9367 int rc;
9368 HRESULT hrc;
9369 Bstr bstr;
9370 *phrc = S_OK;
9371#define RC_CHECK() do { if (RT_FAILURE(rc)) { AssertMsgFailed(("rc=%Rrc\n", rc)); return rc; } } while (0)
9372#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
9373
9374 /* Ignore attachments other than hard disks, since at the moment they are
9375 * not subject to snapshotting in general. */
9376 DeviceType_T lType;
9377 hrc = aMediumAtt->COMGETTER(Type)(&lType); H();
9378 if (lType != DeviceType_HardDisk)
9379 return VINF_SUCCESS;
9380
9381 /* Determine the base path for the device instance. */
9382 PCFGMNODE pCtlInst;
9383 pCtlInst = CFGMR3GetChildF(CFGMR3GetRootU(pUVM), "Devices/%s/%u/", pcszDevice, uInstance);
9384 AssertReturn(pCtlInst, VERR_INTERNAL_ERROR);
9385
9386 /* Update the device instance configuration. */
9387 rc = pConsole->configMediumAttachment(pCtlInst,
9388 pcszDevice,
9389 uInstance,
9390 enmBus,
9391 fUseHostIOCache,
9392 fBuiltinIOCache,
9393 fSetupMerge,
9394 uMergeSource,
9395 uMergeTarget,
9396 aMediumAtt,
9397 aMachineState,
9398 phrc,
9399 true /* fAttachDetach */,
9400 false /* fForceUnmount */,
9401 false /* fHotplug */,
9402 pUVM,
9403 NULL /* paLedDevType */);
9404 /** @todo this dumps everything attached to this device instance, which
9405 * is more than necessary. Dumping the changed LUN would be enough. */
9406 CFGMR3Dump(pCtlInst);
9407 RC_CHECK();
9408
9409#undef RC_CHECK
9410#undef H
9411
9412 LogFlowFunc(("Returns success\n"));
9413 return VINF_SUCCESS;
9414}
9415
9416/**
9417 * Progress cancelation callback employed by Console::fntTakeSnapshotWorker.
9418 */
9419static void takesnapshotProgressCancelCallback(void *pvUser)
9420{
9421 PUVM pUVM = (PUVM)pvUser;
9422 SSMR3Cancel(pUVM);
9423}
9424
9425/**
9426 * Worker thread created by Console::TakeSnapshot.
9427 * @param Thread The current thread (ignored).
9428 * @param pvUser The task.
9429 * @return VINF_SUCCESS (ignored).
9430 */
9431/*static*/
9432DECLCALLBACK(int) Console::fntTakeSnapshotWorker(RTTHREAD Thread, void *pvUser)
9433{
9434 VMTakeSnapshotTask *pTask = (VMTakeSnapshotTask*)pvUser;
9435
9436 // taking a snapshot consists of the following:
9437
9438 // 1) creating a diff image for each virtual hard disk, into which write operations go after
9439 // the snapshot has been created (done in VBoxSVC, in SessionMachine::BeginTakingSnapshot)
9440 // 2) creating a Snapshot object with the state of the machine (hardware + storage,
9441 // done in VBoxSVC, also in SessionMachine::BeginTakingSnapshot)
9442 // 3) saving the state of the virtual machine (here, in the VM process, if the machine is online)
9443
9444 Console *that = pTask->mConsole;
9445 bool fBeganTakingSnapshot = false;
9446 bool fSuspenededBySave = false;
9447
9448 AutoCaller autoCaller(that);
9449 if (FAILED(autoCaller.rc()))
9450 {
9451 that->mptrCancelableProgress.setNull();
9452 return autoCaller.rc();
9453 }
9454
9455 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9456
9457 HRESULT rc = S_OK;
9458
9459 try
9460 {
9461 /* STEP 1 + 2:
9462 * request creating the diff images on the server and create the snapshot object
9463 * (this will set the machine state to Saving on the server to block
9464 * others from accessing this machine)
9465 */
9466 rc = that->mControl->BeginTakingSnapshot(that,
9467 pTask->bstrName.raw(),
9468 pTask->bstrDescription.raw(),
9469 pTask->mProgress,
9470 pTask->fTakingSnapshotOnline,
9471 pTask->bstrSavedStateFile.asOutParam());
9472 if (FAILED(rc))
9473 throw rc;
9474
9475 fBeganTakingSnapshot = true;
9476
9477 /* Check sanity: for offline snapshots there must not be a saved state
9478 * file name. All other combinations are valid (even though online
9479 * snapshots without saved state file seems inconsistent - there are
9480 * some exotic use cases, which need to be explicitly enabled, see the
9481 * code of SessionMachine::BeginTakingSnapshot. */
9482 if ( !pTask->fTakingSnapshotOnline
9483 && !pTask->bstrSavedStateFile.isEmpty())
9484 throw setErrorStatic(E_FAIL, "Invalid state of saved state file");
9485
9486 /* sync the state with the server */
9487 if (pTask->lastMachineState == MachineState_Running)
9488 that->setMachineStateLocally(MachineState_LiveSnapshotting);
9489 else
9490 that->setMachineStateLocally(MachineState_Saving);
9491
9492 // STEP 3: save the VM state (if online)
9493 if (pTask->fTakingSnapshotOnline)
9494 {
9495 int vrc;
9496 SafeVMPtr ptrVM(that);
9497 if (!ptrVM.isOk())
9498 throw ptrVM.rc();
9499
9500 pTask->mProgress->SetNextOperation(Bstr(tr("Saving the machine state")).raw(),
9501 pTask->ulMemSize); // operation weight, same as computed when setting up progress object
9502 if (!pTask->bstrSavedStateFile.isEmpty())
9503 {
9504 Utf8Str strSavedStateFile(pTask->bstrSavedStateFile);
9505
9506 pTask->mProgress->setCancelCallback(takesnapshotProgressCancelCallback, ptrVM.rawUVM());
9507
9508 alock.release();
9509 LogFlowFunc(("VMR3Save...\n"));
9510 vrc = VMR3Save(ptrVM.rawUVM(),
9511 strSavedStateFile.c_str(),
9512 true /*fContinueAfterwards*/,
9513 Console::stateProgressCallback,
9514 static_cast<IProgress *>(pTask->mProgress),
9515 &fSuspenededBySave);
9516 alock.acquire();
9517 if (RT_FAILURE(vrc))
9518 throw setErrorStatic(E_FAIL,
9519 tr("Failed to save the machine state to '%s' (%Rrc)"),
9520 strSavedStateFile.c_str(), vrc);
9521
9522 pTask->mProgress->setCancelCallback(NULL, NULL);
9523 }
9524 else
9525 LogRel(("Console: skipped saving state as part of online snapshot\n"));
9526
9527 if (!pTask->mProgress->notifyPointOfNoReturn())
9528 throw setErrorStatic(E_FAIL, tr("Canceled"));
9529 that->mptrCancelableProgress.setNull();
9530
9531 // STEP 4: reattach hard disks
9532 LogFlowFunc(("Reattaching new differencing hard disks...\n"));
9533
9534 pTask->mProgress->SetNextOperation(Bstr(tr("Reconfiguring medium attachments")).raw(),
9535 1); // operation weight, same as computed when setting up progress object
9536
9537 com::SafeIfaceArray<IMediumAttachment> atts;
9538 rc = that->mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
9539 if (FAILED(rc))
9540 throw rc;
9541
9542 for (size_t i = 0;
9543 i < atts.size();
9544 ++i)
9545 {
9546 ComPtr<IStorageController> pStorageController;
9547 Bstr controllerName;
9548 ULONG lInstance;
9549 StorageControllerType_T enmController;
9550 StorageBus_T enmBus;
9551 BOOL fUseHostIOCache;
9552
9553 /*
9554 * We can't pass a storage controller object directly
9555 * (g++ complains about not being able to pass non POD types through '...')
9556 * so we have to query needed values here and pass them.
9557 */
9558 rc = atts[i]->COMGETTER(Controller)(controllerName.asOutParam());
9559 if (FAILED(rc))
9560 throw rc;
9561
9562 rc = that->mMachine->GetStorageControllerByName(controllerName.raw(),
9563 pStorageController.asOutParam());
9564 if (FAILED(rc))
9565 throw rc;
9566
9567 rc = pStorageController->COMGETTER(ControllerType)(&enmController);
9568 if (FAILED(rc))
9569 throw rc;
9570 rc = pStorageController->COMGETTER(Instance)(&lInstance);
9571 if (FAILED(rc))
9572 throw rc;
9573 rc = pStorageController->COMGETTER(Bus)(&enmBus);
9574 if (FAILED(rc))
9575 throw rc;
9576 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
9577 if (FAILED(rc))
9578 throw rc;
9579
9580 const char *pcszDevice = Console::convertControllerTypeToDev(enmController);
9581
9582 BOOL fBuiltinIOCache;
9583 rc = that->mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
9584 if (FAILED(rc))
9585 throw rc;
9586
9587 /*
9588 * don't release the lock since reconfigureMediumAttachment
9589 * isn't going to need the Console lock.
9590 */
9591 vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(),
9592 VMCPUID_ANY,
9593 (PFNRT)reconfigureMediumAttachment,
9594 13,
9595 that,
9596 ptrVM.rawUVM(),
9597 pcszDevice,
9598 lInstance,
9599 enmBus,
9600 fUseHostIOCache,
9601 fBuiltinIOCache,
9602 false /* fSetupMerge */,
9603 0 /* uMergeSource */,
9604 0 /* uMergeTarget */,
9605 atts[i],
9606 that->mMachineState,
9607 &rc);
9608 if (RT_FAILURE(vrc))
9609 throw setErrorStatic(E_FAIL, Console::tr("%Rrc"), vrc);
9610 if (FAILED(rc))
9611 throw rc;
9612 }
9613 }
9614
9615 /*
9616 * finalize the requested snapshot object.
9617 * This will reset the machine state to the state it had right
9618 * before calling mControl->BeginTakingSnapshot().
9619 */
9620 rc = that->mControl->EndTakingSnapshot(TRUE /*aSuccess*/);
9621 // do not throw rc here because we can't call EndTakingSnapshot() twice
9622 LogFlowFunc(("EndTakingSnapshot -> %Rhrc [mMachineState=%s]\n", rc, Global::stringifyMachineState(that->mMachineState)));
9623 }
9624 catch (HRESULT rcThrown)
9625 {
9626 /* preserve existing error info */
9627 ErrorInfoKeeper eik;
9628
9629 if (fBeganTakingSnapshot)
9630 that->mControl->EndTakingSnapshot(FALSE /*aSuccess*/);
9631
9632 rc = rcThrown;
9633 LogFunc(("Caught %Rhrc [mMachineState=%s]\n", rc, Global::stringifyMachineState(that->mMachineState)));
9634 }
9635 Assert(alock.isWriteLockOnCurrentThread());
9636
9637 if (FAILED(rc)) /* Must come before calling setMachineState. */
9638 pTask->mProgress->notifyComplete(rc);
9639
9640 /*
9641 * Fix up the machine state.
9642 *
9643 * For live snapshots we do all the work, for the two other variations we
9644 * just update the local copy.
9645 */
9646 MachineState_T enmMachineState;
9647 that->mMachine->COMGETTER(State)(&enmMachineState);
9648 if ( that->mMachineState == MachineState_LiveSnapshotting
9649 || that->mMachineState == MachineState_Saving)
9650 {
9651
9652 if (!pTask->fTakingSnapshotOnline)
9653 that->setMachineStateLocally(pTask->lastMachineState);
9654 else if (SUCCEEDED(rc))
9655 {
9656 Assert( pTask->lastMachineState == MachineState_Running
9657 || pTask->lastMachineState == MachineState_Paused);
9658 Assert(that->mMachineState == MachineState_Saving);
9659 if (pTask->lastMachineState == MachineState_Running)
9660 {
9661 LogFlowFunc(("VMR3Resume...\n"));
9662 SafeVMPtr ptrVM(that);
9663 alock.release();
9664 int vrc = VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_STATE_SAVED);
9665 alock.acquire();
9666 if (RT_FAILURE(vrc))
9667 {
9668 rc = setErrorStatic(VBOX_E_VM_ERROR, tr("Could not resume the machine execution (%Rrc)"), vrc);
9669 pTask->mProgress->notifyComplete(rc);
9670 if (that->mMachineState == MachineState_Saving)
9671 that->setMachineStateLocally(MachineState_Paused);
9672 }
9673 }
9674 else
9675 that->setMachineStateLocally(MachineState_Paused);
9676 }
9677 else
9678 {
9679 /** @todo this could probably be made more generic and reused elsewhere. */
9680 /* paranoid cleanup on for a failed online snapshot. */
9681 VMSTATE enmVMState = VMR3GetStateU(that->mpUVM);
9682 switch (enmVMState)
9683 {
9684 case VMSTATE_RUNNING:
9685 case VMSTATE_RUNNING_LS:
9686 case VMSTATE_DEBUGGING:
9687 case VMSTATE_DEBUGGING_LS:
9688 case VMSTATE_POWERING_OFF:
9689 case VMSTATE_POWERING_OFF_LS:
9690 case VMSTATE_RESETTING:
9691 case VMSTATE_RESETTING_LS:
9692 Assert(!fSuspenededBySave);
9693 that->setMachineState(MachineState_Running);
9694 break;
9695
9696 case VMSTATE_GURU_MEDITATION:
9697 case VMSTATE_GURU_MEDITATION_LS:
9698 that->setMachineState(MachineState_Stuck);
9699 break;
9700
9701 case VMSTATE_FATAL_ERROR:
9702 case VMSTATE_FATAL_ERROR_LS:
9703 if (pTask->lastMachineState == MachineState_Paused)
9704 that->setMachineStateLocally(pTask->lastMachineState);
9705 else
9706 that->setMachineState(MachineState_Paused);
9707 break;
9708
9709 default:
9710 AssertMsgFailed(("%s\n", VMR3GetStateName(enmVMState)));
9711 case VMSTATE_SUSPENDED:
9712 case VMSTATE_SUSPENDED_LS:
9713 case VMSTATE_SUSPENDING:
9714 case VMSTATE_SUSPENDING_LS:
9715 case VMSTATE_SUSPENDING_EXT_LS:
9716 if (fSuspenededBySave)
9717 {
9718 Assert(pTask->lastMachineState == MachineState_Running);
9719 LogFlowFunc(("VMR3Resume (on failure)...\n"));
9720 SafeVMPtr ptrVM(that);
9721 alock.release();
9722 int vrc = VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_STATE_SAVED); AssertLogRelRC(vrc);
9723 alock.acquire();
9724 if (RT_FAILURE(vrc))
9725 that->setMachineState(MachineState_Paused);
9726 }
9727 else if (pTask->lastMachineState == MachineState_Paused)
9728 that->setMachineStateLocally(pTask->lastMachineState);
9729 else
9730 that->setMachineState(MachineState_Paused);
9731 break;
9732 }
9733
9734 }
9735 }
9736 /*else: somebody else has change the state... Leave it. */
9737
9738 /* check the remote state to see that we got it right. */
9739 that->mMachine->COMGETTER(State)(&enmMachineState);
9740 AssertLogRelMsg(that->mMachineState == enmMachineState,
9741 ("mMachineState=%s enmMachineState=%s\n", Global::stringifyMachineState(that->mMachineState),
9742 Global::stringifyMachineState(enmMachineState) ));
9743
9744
9745 if (SUCCEEDED(rc)) /* The failure cases are handled above. */
9746 pTask->mProgress->notifyComplete(rc);
9747
9748 delete pTask;
9749
9750 LogFlowFuncLeave();
9751 return VINF_SUCCESS;
9752}
9753
9754/**
9755 * Thread for executing the saved state operation.
9756 *
9757 * @param Thread The thread handle.
9758 * @param pvUser Pointer to a VMSaveTask structure.
9759 * @return VINF_SUCCESS (ignored).
9760 *
9761 * @note Locks the Console object for writing.
9762 */
9763/*static*/
9764DECLCALLBACK(int) Console::saveStateThread(RTTHREAD Thread, void *pvUser)
9765{
9766 LogFlowFuncEnter();
9767
9768 std::auto_ptr<VMSaveTask> task(static_cast<VMSaveTask*>(pvUser));
9769 AssertReturn(task.get(), VERR_INVALID_PARAMETER);
9770
9771 Assert(task->mSavedStateFile.length());
9772 Assert(task->mProgress.isNull());
9773 Assert(!task->mServerProgress.isNull());
9774
9775 const ComObjPtr<Console> &that = task->mConsole;
9776 Utf8Str errMsg;
9777 HRESULT rc = S_OK;
9778
9779 LogFlowFunc(("Saving the state to '%s'...\n", task->mSavedStateFile.c_str()));
9780
9781 bool fSuspenededBySave;
9782 int vrc = VMR3Save(task->mpUVM,
9783 task->mSavedStateFile.c_str(),
9784 false, /*fContinueAfterwards*/
9785 Console::stateProgressCallback,
9786 static_cast<IProgress *>(task->mServerProgress),
9787 &fSuspenededBySave);
9788 if (RT_FAILURE(vrc))
9789 {
9790 errMsg = Utf8StrFmt(Console::tr("Failed to save the machine state to '%s' (%Rrc)"),
9791 task->mSavedStateFile.c_str(), vrc);
9792 rc = E_FAIL;
9793 }
9794 Assert(!fSuspenededBySave);
9795
9796 /* lock the console once we're going to access it */
9797 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
9798
9799 /* synchronize the state with the server */
9800 if (SUCCEEDED(rc))
9801 {
9802 /*
9803 * The machine has been successfully saved, so power it down
9804 * (vmstateChangeCallback() will set state to Saved on success).
9805 * Note: we release the task's VM caller, otherwise it will
9806 * deadlock.
9807 */
9808 task->releaseVMCaller();
9809 thatLock.release();
9810 rc = that->powerDown();
9811 thatLock.acquire();
9812 }
9813
9814 /*
9815 * If we failed, reset the local machine state.
9816 */
9817 if (FAILED(rc))
9818 that->setMachineStateLocally(task->mMachineStateBefore);
9819
9820 /*
9821 * Finalize the requested save state procedure. In case of failure it will
9822 * reset the machine state to the state it had right before calling
9823 * mControl->BeginSavingState(). This must be the last thing because it
9824 * will set the progress to completed, and that means that the frontend
9825 * can immediately uninit the associated console object.
9826 */
9827 that->mControl->EndSavingState(rc, Bstr(errMsg).raw());
9828
9829 LogFlowFuncLeave();
9830 return VINF_SUCCESS;
9831}
9832
9833/**
9834 * Thread for powering down the Console.
9835 *
9836 * @param Thread The thread handle.
9837 * @param pvUser Pointer to the VMTask structure.
9838 * @return VINF_SUCCESS (ignored).
9839 *
9840 * @note Locks the Console object for writing.
9841 */
9842/*static*/
9843DECLCALLBACK(int) Console::powerDownThread(RTTHREAD Thread, void *pvUser)
9844{
9845 LogFlowFuncEnter();
9846
9847 std::auto_ptr<VMPowerDownTask> task(static_cast<VMPowerDownTask *>(pvUser));
9848 AssertReturn(task.get(), VERR_INVALID_PARAMETER);
9849
9850 AssertReturn(task->isOk(), VERR_GENERAL_FAILURE);
9851
9852 Assert(task->mProgress.isNull());
9853
9854 const ComObjPtr<Console> &that = task->mConsole;
9855
9856 /* Note: no need to use addCaller() to protect Console because VMTask does
9857 * that */
9858
9859 /* wait until the method tat started us returns */
9860 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
9861
9862 /* release VM caller to avoid the powerDown() deadlock */
9863 task->releaseVMCaller();
9864
9865 thatLock.release();
9866
9867 that->powerDown(task->mServerProgress);
9868
9869 /* complete the operation */
9870 that->mControl->EndPoweringDown(S_OK, Bstr().raw());
9871
9872 LogFlowFuncLeave();
9873 return VINF_SUCCESS;
9874}
9875
9876
9877/**
9878 * @interface_method_impl{VMM2USERMETHODS,pfnSaveState}
9879 */
9880/*static*/ DECLCALLBACK(int)
9881Console::vmm2User_SaveState(PCVMM2USERMETHODS pThis, PUVM pUVM)
9882{
9883 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
9884 NOREF(pUVM);
9885
9886 /*
9887 * For now, just call SaveState. We should probably try notify the GUI so
9888 * it can pop up a progress object and stuff.
9889 */
9890 HRESULT hrc = pConsole->SaveState(NULL);
9891 return SUCCEEDED(hrc) ? VINF_SUCCESS : Global::vboxStatusCodeFromCOM(hrc);
9892}
9893
9894/**
9895 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtInit}
9896 */
9897/*static*/ DECLCALLBACK(void)
9898Console::vmm2User_NotifyEmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
9899{
9900 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
9901 VirtualBoxBase::initializeComForThread();
9902}
9903
9904/**
9905 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtTerm}
9906 */
9907/*static*/ DECLCALLBACK(void)
9908Console::vmm2User_NotifyEmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
9909{
9910 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
9911 VirtualBoxBase::uninitializeComForThread();
9912}
9913
9914/**
9915 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtInit}
9916 */
9917/*static*/ DECLCALLBACK(void)
9918Console::vmm2User_NotifyPdmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM)
9919{
9920 NOREF(pThis); NOREF(pUVM);
9921 VirtualBoxBase::initializeComForThread();
9922}
9923
9924/**
9925 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtTerm}
9926 */
9927/*static*/ DECLCALLBACK(void)
9928Console::vmm2User_NotifyPdmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM)
9929{
9930 NOREF(pThis); NOREF(pUVM);
9931 VirtualBoxBase::uninitializeComForThread();
9932}
9933
9934
9935
9936
9937/**
9938 * The Main status driver instance data.
9939 */
9940typedef struct DRVMAINSTATUS
9941{
9942 /** The LED connectors. */
9943 PDMILEDCONNECTORS ILedConnectors;
9944 /** Pointer to the LED ports interface above us. */
9945 PPDMILEDPORTS pLedPorts;
9946 /** Pointer to the array of LED pointers. */
9947 PPDMLED *papLeds;
9948 /** The unit number corresponding to the first entry in the LED array. */
9949 RTUINT iFirstLUN;
9950 /** The unit number corresponding to the last entry in the LED array.
9951 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
9952 RTUINT iLastLUN;
9953 /** Pointer to the driver instance. */
9954 PPDMDRVINS pDrvIns;
9955 /** The Media Notify interface. */
9956 PDMIMEDIANOTIFY IMediaNotify;
9957 /** Map for translating PDM storage controller/LUN information to
9958 * IMediumAttachment references. */
9959 Console::MediumAttachmentMap *pmapMediumAttachments;
9960 /** Device name+instance for mapping */
9961 char *pszDeviceInstance;
9962 /** Pointer to the Console object, for driver triggered activities. */
9963 Console *pConsole;
9964} DRVMAINSTATUS, *PDRVMAINSTATUS;
9965
9966
9967/**
9968 * Notification about a unit which have been changed.
9969 *
9970 * The driver must discard any pointers to data owned by
9971 * the unit and requery it.
9972 *
9973 * @param pInterface Pointer to the interface structure containing the called function pointer.
9974 * @param iLUN The unit number.
9975 */
9976DECLCALLBACK(void) Console::drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
9977{
9978 PDRVMAINSTATUS pThis = (PDRVMAINSTATUS)((uintptr_t)pInterface - RT_OFFSETOF(DRVMAINSTATUS, ILedConnectors));
9979 if (iLUN >= pThis->iFirstLUN && iLUN <= pThis->iLastLUN)
9980 {
9981 PPDMLED pLed;
9982 int rc = pThis->pLedPorts->pfnQueryStatusLed(pThis->pLedPorts, iLUN, &pLed);
9983 if (RT_FAILURE(rc))
9984 pLed = NULL;
9985 ASMAtomicWritePtr(&pThis->papLeds[iLUN - pThis->iFirstLUN], pLed);
9986 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
9987 }
9988}
9989
9990
9991/**
9992 * Notification about a medium eject.
9993 *
9994 * @returns VBox status.
9995 * @param pInterface Pointer to the interface structure containing the called function pointer.
9996 * @param uLUN The unit number.
9997 */
9998DECLCALLBACK(int) Console::drvStatus_MediumEjected(PPDMIMEDIANOTIFY pInterface, unsigned uLUN)
9999{
10000 PDRVMAINSTATUS pThis = (PDRVMAINSTATUS)((uintptr_t)pInterface - RT_OFFSETOF(DRVMAINSTATUS, IMediaNotify));
10001 PPDMDRVINS pDrvIns = pThis->pDrvIns;
10002 LogFunc(("uLUN=%d\n", uLUN));
10003 if (pThis->pmapMediumAttachments)
10004 {
10005 AutoWriteLock alock(pThis->pConsole COMMA_LOCKVAL_SRC_POS);
10006
10007 ComPtr<IMediumAttachment> pMediumAtt;
10008 Utf8Str devicePath = Utf8StrFmt("%s/LUN#%u", pThis->pszDeviceInstance, uLUN);
10009 Console::MediumAttachmentMap::const_iterator end = pThis->pmapMediumAttachments->end();
10010 Console::MediumAttachmentMap::const_iterator it = pThis->pmapMediumAttachments->find(devicePath);
10011 if (it != end)
10012 pMediumAtt = it->second;
10013 Assert(!pMediumAtt.isNull());
10014 if (!pMediumAtt.isNull())
10015 {
10016 IMedium *pMedium = NULL;
10017 HRESULT rc = pMediumAtt->COMGETTER(Medium)(&pMedium);
10018 AssertComRC(rc);
10019 if (SUCCEEDED(rc) && pMedium)
10020 {
10021 BOOL fHostDrive = FALSE;
10022 rc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
10023 AssertComRC(rc);
10024 if (!fHostDrive)
10025 {
10026 alock.release();
10027
10028 ComPtr<IMediumAttachment> pNewMediumAtt;
10029 rc = pThis->pConsole->mControl->EjectMedium(pMediumAtt, pNewMediumAtt.asOutParam());
10030 if (SUCCEEDED(rc))
10031 fireMediumChangedEvent(pThis->pConsole->mEventSource, pNewMediumAtt);
10032
10033 alock.acquire();
10034 if (pNewMediumAtt != pMediumAtt)
10035 {
10036 pThis->pmapMediumAttachments->erase(devicePath);
10037 pThis->pmapMediumAttachments->insert(std::make_pair(devicePath, pNewMediumAtt));
10038 }
10039 }
10040 }
10041 }
10042 }
10043 return VINF_SUCCESS;
10044}
10045
10046
10047/**
10048 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
10049 */
10050DECLCALLBACK(void *) Console::drvStatus_QueryInterface(PPDMIBASE pInterface, const char *pszIID)
10051{
10052 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
10053 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10054 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
10055 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDCONNECTORS, &pThis->ILedConnectors);
10056 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIANOTIFY, &pThis->IMediaNotify);
10057 return NULL;
10058}
10059
10060
10061/**
10062 * Destruct a status driver instance.
10063 *
10064 * @returns VBox status.
10065 * @param pDrvIns The driver instance data.
10066 */
10067DECLCALLBACK(void) Console::drvStatus_Destruct(PPDMDRVINS pDrvIns)
10068{
10069 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
10070 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10071 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
10072
10073 if (pThis->papLeds)
10074 {
10075 unsigned iLed = pThis->iLastLUN - pThis->iFirstLUN + 1;
10076 while (iLed-- > 0)
10077 ASMAtomicWriteNullPtr(&pThis->papLeds[iLed]);
10078 }
10079}
10080
10081
10082/**
10083 * Construct a status driver instance.
10084 *
10085 * @copydoc FNPDMDRVCONSTRUCT
10086 */
10087DECLCALLBACK(int) Console::drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
10088{
10089 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
10090 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10091 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
10092
10093 /*
10094 * Validate configuration.
10095 */
10096 if (!CFGMR3AreValuesValid(pCfg, "papLeds\0pmapMediumAttachments\0DeviceInstance\0pConsole\0First\0Last\0"))
10097 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
10098 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
10099 ("Configuration error: Not possible to attach anything to this driver!\n"),
10100 VERR_PDM_DRVINS_NO_ATTACH);
10101
10102 /*
10103 * Data.
10104 */
10105 pDrvIns->IBase.pfnQueryInterface = Console::drvStatus_QueryInterface;
10106 pThis->ILedConnectors.pfnUnitChanged = Console::drvStatus_UnitChanged;
10107 pThis->IMediaNotify.pfnEjected = Console::drvStatus_MediumEjected;
10108 pThis->pDrvIns = pDrvIns;
10109 pThis->pszDeviceInstance = NULL;
10110
10111 /*
10112 * Read config.
10113 */
10114 int rc = CFGMR3QueryPtr(pCfg, "papLeds", (void **)&pThis->papLeds);
10115 if (RT_FAILURE(rc))
10116 {
10117 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Rrc\n", rc));
10118 return rc;
10119 }
10120
10121 rc = CFGMR3QueryPtrDef(pCfg, "pmapMediumAttachments", (void **)&pThis->pmapMediumAttachments, NULL);
10122 if (RT_FAILURE(rc))
10123 {
10124 AssertMsgFailed(("Configuration error: Failed to query the \"pmapMediumAttachments\" value! rc=%Rrc\n", rc));
10125 return rc;
10126 }
10127 if (pThis->pmapMediumAttachments)
10128 {
10129 rc = CFGMR3QueryStringAlloc(pCfg, "DeviceInstance", &pThis->pszDeviceInstance);
10130 if (RT_FAILURE(rc))
10131 {
10132 AssertMsgFailed(("Configuration error: Failed to query the \"DeviceInstance\" value! rc=%Rrc\n", rc));
10133 return rc;
10134 }
10135 rc = CFGMR3QueryPtr(pCfg, "pConsole", (void **)&pThis->pConsole);
10136 if (RT_FAILURE(rc))
10137 {
10138 AssertMsgFailed(("Configuration error: Failed to query the \"pConsole\" value! rc=%Rrc\n", rc));
10139 return rc;
10140 }
10141 }
10142
10143 rc = CFGMR3QueryU32(pCfg, "First", &pThis->iFirstLUN);
10144 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
10145 pThis->iFirstLUN = 0;
10146 else if (RT_FAILURE(rc))
10147 {
10148 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Rrc\n", rc));
10149 return rc;
10150 }
10151
10152 rc = CFGMR3QueryU32(pCfg, "Last", &pThis->iLastLUN);
10153 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
10154 pThis->iLastLUN = 0;
10155 else if (RT_FAILURE(rc))
10156 {
10157 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Rrc\n", rc));
10158 return rc;
10159 }
10160 if (pThis->iFirstLUN > pThis->iLastLUN)
10161 {
10162 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pThis->iFirstLUN, pThis->iLastLUN));
10163 return VERR_GENERAL_FAILURE;
10164 }
10165
10166 /*
10167 * Get the ILedPorts interface of the above driver/device and
10168 * query the LEDs we want.
10169 */
10170 pThis->pLedPorts = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMILEDPORTS);
10171 AssertMsgReturn(pThis->pLedPorts, ("Configuration error: No led ports interface above!\n"),
10172 VERR_PDM_MISSING_INTERFACE_ABOVE);
10173
10174 for (unsigned i = pThis->iFirstLUN; i <= pThis->iLastLUN; ++i)
10175 Console::drvStatus_UnitChanged(&pThis->ILedConnectors, i);
10176
10177 return VINF_SUCCESS;
10178}
10179
10180
10181/**
10182 * Console status driver (LED) registration record.
10183 */
10184const PDMDRVREG Console::DrvStatusReg =
10185{
10186 /* u32Version */
10187 PDM_DRVREG_VERSION,
10188 /* szName */
10189 "MainStatus",
10190 /* szRCMod */
10191 "",
10192 /* szR0Mod */
10193 "",
10194 /* pszDescription */
10195 "Main status driver (Main as in the API).",
10196 /* fFlags */
10197 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
10198 /* fClass. */
10199 PDM_DRVREG_CLASS_STATUS,
10200 /* cMaxInstances */
10201 ~0U,
10202 /* cbInstance */
10203 sizeof(DRVMAINSTATUS),
10204 /* pfnConstruct */
10205 Console::drvStatus_Construct,
10206 /* pfnDestruct */
10207 Console::drvStatus_Destruct,
10208 /* pfnRelocate */
10209 NULL,
10210 /* pfnIOCtl */
10211 NULL,
10212 /* pfnPowerOn */
10213 NULL,
10214 /* pfnReset */
10215 NULL,
10216 /* pfnSuspend */
10217 NULL,
10218 /* pfnResume */
10219 NULL,
10220 /* pfnAttach */
10221 NULL,
10222 /* pfnDetach */
10223 NULL,
10224 /* pfnPowerOff */
10225 NULL,
10226 /* pfnSoftReset */
10227 NULL,
10228 /* u32EndVersion */
10229 PDM_DRVREG_VERSION
10230};
10231
10232/* 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