VirtualBox

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

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

Main: Introduce "StorageMgmt/SilentReconfigureWhilePaused" extradata flag to allow attachment reconfiguration while the VM is paused

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