VirtualBox

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

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

Main/Console: fixed error code if changing a medium / network attachment doesn't work for invalid VM state

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

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