VirtualBox

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

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

Console,DrvVD: Clear the encryption keys on suspend

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

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