VirtualBox

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

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

Main: use RT_FROM_MEMBER instead of RT_OFFSETOF; some Assert* cleanup

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

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