VirtualBox

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

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

6813 Use of server side API wrapper code - ConsoleImpl.cpp

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