VirtualBox

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

Last change on this file since 49139 was 49120, checked in by vboxsync, 11 years ago

Main: emulated webcam updates.

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

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