VirtualBox

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

Last change on this file since 53534 was 53528, checked in by vboxsync, 10 years ago

Devices/Graphics, Devices/PC/DevACPI, Main: add support for sending video mode hints through the VGA device.

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