VirtualBox

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

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

IMouse::PointerShape

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