VirtualBox

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

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

Main/Console: another error code

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 337.9 KB
Line 
1/* $Id: ConsoleImpl.cpp 50737 2014-03-10 14:51:53Z vboxsync $ */
2/** @file
3 * VBox Console COM Class implementation
4 */
5
6/*
7 * Copyright (C) 2005-2014 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/** @todo Move the TAP mess back into the driver! */
19#if defined(RT_OS_WINDOWS)
20#elif defined(RT_OS_LINUX)
21# include <errno.h>
22# include <sys/ioctl.h>
23# include <sys/poll.h>
24# include <sys/fcntl.h>
25# include <sys/types.h>
26# include <sys/wait.h>
27# include <net/if.h>
28# include <linux/if_tun.h>
29# include <stdio.h>
30# include <stdlib.h>
31# include <string.h>
32#elif defined(RT_OS_FREEBSD)
33# include <errno.h>
34# include <sys/ioctl.h>
35# include <sys/poll.h>
36# include <sys/fcntl.h>
37# include <sys/types.h>
38# include <sys/wait.h>
39# include <stdio.h>
40# include <stdlib.h>
41# include <string.h>
42#elif defined(RT_OS_SOLARIS)
43# include <iprt/coredumper.h>
44#endif
45
46#include "ConsoleImpl.h"
47
48#include "Global.h"
49#include "VirtualBoxErrorInfoImpl.h"
50#include "GuestImpl.h"
51#include "KeyboardImpl.h"
52#include "MouseImpl.h"
53#include "DisplayImpl.h"
54#include "MachineDebuggerImpl.h"
55#include "USBDeviceImpl.h"
56#include "RemoteUSBDeviceImpl.h"
57#include "SharedFolderImpl.h"
58#ifdef VBOX_WITH_PDM_AUDIO_DRIVER
59#include "DrvAudioVRDE.h"
60#else
61#include "AudioSnifferInterface.h"
62#endif
63#include "Nvram.h"
64#ifdef VBOX_WITH_USB_CARDREADER
65# include "UsbCardReader.h"
66#endif
67#include "ProgressImpl.h"
68#include "ConsoleVRDPServer.h"
69#include "VMMDev.h"
70#ifdef VBOX_WITH_EXTPACK
71# include "ExtPackManagerImpl.h"
72#endif
73#include "BusAssignmentManager.h"
74#include "EmulatedUSBImpl.h"
75
76#include "VBoxEvents.h"
77#include "AutoCaller.h"
78#include "Logging.h"
79
80#include <VBox/com/array.h>
81#include "VBox/com/ErrorInfo.h"
82#include <VBox/com/listeners.h>
83
84#include <iprt/asm.h>
85#include <iprt/buildconfig.h>
86#include <iprt/cpp/utils.h>
87#include <iprt/dir.h>
88#include <iprt/file.h>
89#include <iprt/ldr.h>
90#include <iprt/path.h>
91#include <iprt/process.h>
92#include <iprt/string.h>
93#include <iprt/system.h>
94
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 if (RT_FAILURE(rc))
3565 return setErrorInternal(VBOX_E_INVALID_VM_STATE,
3566 COM_IIDOF(IConsole),
3567 getStaticComponentName(),
3568 Utf8StrFmt("Could suspend VM for medium change (%Rrc)", rc),
3569 false /*aWarning*/,
3570 true /*aLogIt*/);
3571 *pfResume = true;
3572 break;
3573 }
3574 case VMSTATE_SUSPENDED:
3575 break;
3576 default:
3577 return setErrorInternal(VBOX_E_INVALID_VM_STATE,
3578 COM_IIDOF(IConsole),
3579 getStaticComponentName(),
3580 Utf8StrFmt("Invalid state '%s' for changing medium",
3581 VMR3GetStateName(enmVMState)),
3582 false /*aWarning*/,
3583 true /*aLogIt*/);
3584 }
3585
3586 return S_OK;
3587}
3588
3589/**
3590 * Resume the VM after we did any medium or network attachment change.
3591 * This is the counterpart to Console::suspendBeforeConfigChange().
3592 *
3593 * @param pUVM Safe VM handle.
3594 */
3595void Console::resumeAfterConfigChange(PUVM pUVM)
3596{
3597 LogFlowFunc(("Resuming the VM...\n"));
3598 /* disable the callback to prevent Console-level state change */
3599 mVMStateChangeCallbackDisabled = true;
3600 int rc = VMR3Resume(pUVM, VMRESUMEREASON_RECONFIG);
3601 mVMStateChangeCallbackDisabled = false;
3602 AssertRC(rc);
3603 if (RT_FAILURE(rc))
3604 {
3605 VMSTATE enmVMState = VMR3GetStateU(pUVM);
3606 if (enmVMState == VMSTATE_SUSPENDED)
3607 {
3608 /* too bad, we failed. try to sync the console state with the VMM state */
3609 vmstateChangeCallback(pUVM, VMSTATE_SUSPENDED, enmVMState, this);
3610 }
3611 }
3612}
3613
3614/**
3615 * Process a medium change.
3616 *
3617 * @param aMediumAttachment The medium attachment with the new medium state.
3618 * @param fForce Force medium chance, if it is locked or not.
3619 * @param pUVM Safe VM handle.
3620 *
3621 * @note Locks this object for writing.
3622 */
3623HRESULT Console::doMediumChange(IMediumAttachment *aMediumAttachment, bool fForce, PUVM pUVM)
3624{
3625 AutoCaller autoCaller(this);
3626 AssertComRCReturnRC(autoCaller.rc());
3627
3628 /* We will need to release the write lock before calling EMT */
3629 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3630
3631 HRESULT rc = S_OK;
3632 const char *pszDevice = NULL;
3633
3634 SafeIfaceArray<IStorageController> ctrls;
3635 rc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
3636 AssertComRC(rc);
3637 IMedium *pMedium;
3638 rc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
3639 AssertComRC(rc);
3640 Bstr mediumLocation;
3641 if (pMedium)
3642 {
3643 rc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
3644 AssertComRC(rc);
3645 }
3646
3647 Bstr attCtrlName;
3648 rc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
3649 AssertComRC(rc);
3650 ComPtr<IStorageController> pStorageController;
3651 for (size_t i = 0; i < ctrls.size(); ++i)
3652 {
3653 Bstr ctrlName;
3654 rc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
3655 AssertComRC(rc);
3656 if (attCtrlName == ctrlName)
3657 {
3658 pStorageController = ctrls[i];
3659 break;
3660 }
3661 }
3662 if (pStorageController.isNull())
3663 return setError(E_FAIL,
3664 tr("Could not find storage controller '%ls'"), attCtrlName.raw());
3665
3666 StorageControllerType_T enmCtrlType;
3667 rc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
3668 AssertComRC(rc);
3669 pszDevice = convertControllerTypeToDev(enmCtrlType);
3670
3671 StorageBus_T enmBus;
3672 rc = pStorageController->COMGETTER(Bus)(&enmBus);
3673 AssertComRC(rc);
3674 ULONG uInstance;
3675 rc = pStorageController->COMGETTER(Instance)(&uInstance);
3676 AssertComRC(rc);
3677 BOOL fUseHostIOCache;
3678 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
3679 AssertComRC(rc);
3680
3681 /*
3682 * Suspend the VM first. The VM must not be running since it might have
3683 * pending I/O to the drive which is being changed.
3684 */
3685 bool fResume = false;
3686 rc = suspendBeforeConfigChange(pUVM, &alock, &fResume);
3687 if (FAILED(rc))
3688 return rc;
3689
3690 /*
3691 * Call worker in EMT, that's faster and safer than doing everything
3692 * using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
3693 * here to make requests from under the lock in order to serialize them.
3694 */
3695 PVMREQ pReq;
3696 int vrc = VMR3ReqCallU(pUVM, VMCPUID_ANY, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS,
3697 (PFNRT)changeRemovableMedium, 8,
3698 this, pUVM, pszDevice, uInstance, enmBus, fUseHostIOCache, aMediumAttachment, fForce);
3699
3700 /* release the lock before waiting for a result (EMT will call us back!) */
3701 alock.release();
3702
3703 if (vrc == VERR_TIMEOUT || RT_SUCCESS(vrc))
3704 {
3705 vrc = VMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
3706 AssertRC(vrc);
3707 if (RT_SUCCESS(vrc))
3708 vrc = pReq->iStatus;
3709 }
3710 VMR3ReqFree(pReq);
3711
3712 if (fResume)
3713 resumeAfterConfigChange(pUVM);
3714
3715 if (RT_SUCCESS(vrc))
3716 {
3717 LogFlowThisFunc(("Returns S_OK\n"));
3718 return S_OK;
3719 }
3720
3721 if (pMedium)
3722 return setError(E_FAIL,
3723 tr("Could not mount the media/drive '%ls' (%Rrc)"),
3724 mediumLocation.raw(), vrc);
3725
3726 return setError(E_FAIL,
3727 tr("Could not unmount the currently mounted media/drive (%Rrc)"),
3728 vrc);
3729}
3730
3731/**
3732 * Performs the medium change in EMT.
3733 *
3734 * @returns VBox status code.
3735 *
3736 * @param pThis Pointer to the Console object.
3737 * @param pUVM The VM handle.
3738 * @param pcszDevice The PDM device name.
3739 * @param uInstance The PDM device instance.
3740 * @param uLun The PDM LUN number of the drive.
3741 * @param fHostDrive True if this is a host drive attachment.
3742 * @param pszPath The path to the media / drive which is now being mounted / captured.
3743 * If NULL no media or drive is attached and the LUN will be configured with
3744 * the default block driver with no media. This will also be the state if
3745 * mounting / capturing the specified media / drive fails.
3746 * @param pszFormat Medium format string, usually "RAW".
3747 * @param fPassthrough Enables using passthrough mode of the host DVD drive if applicable.
3748 *
3749 * @thread EMT
3750 * @note The VM must not be running since it might have pending I/O to the drive which is being changed.
3751 */
3752DECLCALLBACK(int) Console::changeRemovableMedium(Console *pThis,
3753 PUVM pUVM,
3754 const char *pcszDevice,
3755 unsigned uInstance,
3756 StorageBus_T enmBus,
3757 bool fUseHostIOCache,
3758 IMediumAttachment *aMediumAtt,
3759 bool fForce)
3760{
3761 LogFlowFunc(("pThis=%p uInstance=%u pszDevice=%p:{%s} enmBus=%u, aMediumAtt=%p, fForce=%d\n",
3762 pThis, uInstance, pcszDevice, pcszDevice, enmBus, aMediumAtt, fForce));
3763
3764 AssertReturn(pThis, VERR_INVALID_PARAMETER);
3765
3766 AutoCaller autoCaller(pThis);
3767 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
3768
3769 /*
3770 * Check the VM for correct state.
3771 */
3772 VMSTATE enmVMState = VMR3GetStateU(pUVM);
3773 AssertReturn(enmVMState == VMSTATE_SUSPENDED, VERR_INVALID_STATE);
3774
3775 /* Determine the base path for the device instance. */
3776 PCFGMNODE pCtlInst;
3777 pCtlInst = CFGMR3GetChildF(CFGMR3GetRootU(pUVM), "Devices/%s/%u/", pcszDevice, uInstance);
3778 AssertReturn(pCtlInst, VERR_INTERNAL_ERROR);
3779
3780 PCFGMNODE pLunL0 = NULL;
3781 int rc = pThis->configMediumAttachment(pCtlInst,
3782 pcszDevice,
3783 uInstance,
3784 enmBus,
3785 fUseHostIOCache,
3786 false /* fSetupMerge */,
3787 false /* fBuiltinIOCache */,
3788 0 /* uMergeSource */,
3789 0 /* uMergeTarget */,
3790 aMediumAtt,
3791 pThis->mMachineState,
3792 NULL /* phrc */,
3793 true /* fAttachDetach */,
3794 fForce /* fForceUnmount */,
3795 false /* fHotplug */,
3796 pUVM,
3797 NULL /* paLedDevType */,
3798 &pLunL0);
3799 /* Dump the changed LUN if possible, dump the complete device otherwise */
3800 CFGMR3Dump(pLunL0 ? pLunL0 : pCtlInst);
3801
3802 LogFlowFunc(("Returning %Rrc\n", rc));
3803 return rc;
3804}
3805
3806
3807/**
3808 * Attach a new storage device to the VM.
3809 *
3810 * @param aMediumAttachment The medium attachment which is added.
3811 * @param pUVM Safe VM handle.
3812 * @param fSilent Flag whether to notify the guest about the attached device.
3813 *
3814 * @note Locks this object for writing.
3815 */
3816HRESULT Console::doStorageDeviceAttach(IMediumAttachment *aMediumAttachment, PUVM pUVM, bool fSilent)
3817{
3818 AutoCaller autoCaller(this);
3819 AssertComRCReturnRC(autoCaller.rc());
3820
3821 /* We will need to release the write lock before calling EMT */
3822 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3823
3824 HRESULT rc = S_OK;
3825 const char *pszDevice = NULL;
3826
3827 SafeIfaceArray<IStorageController> ctrls;
3828 rc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
3829 AssertComRC(rc);
3830 IMedium *pMedium;
3831 rc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
3832 AssertComRC(rc);
3833 Bstr mediumLocation;
3834 if (pMedium)
3835 {
3836 rc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
3837 AssertComRC(rc);
3838 }
3839
3840 Bstr attCtrlName;
3841 rc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
3842 AssertComRC(rc);
3843 ComPtr<IStorageController> pStorageController;
3844 for (size_t i = 0; i < ctrls.size(); ++i)
3845 {
3846 Bstr ctrlName;
3847 rc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
3848 AssertComRC(rc);
3849 if (attCtrlName == ctrlName)
3850 {
3851 pStorageController = ctrls[i];
3852 break;
3853 }
3854 }
3855 if (pStorageController.isNull())
3856 return setError(E_FAIL,
3857 tr("Could not find storage controller '%ls'"), attCtrlName.raw());
3858
3859 StorageControllerType_T enmCtrlType;
3860 rc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
3861 AssertComRC(rc);
3862 pszDevice = convertControllerTypeToDev(enmCtrlType);
3863
3864 StorageBus_T enmBus;
3865 rc = pStorageController->COMGETTER(Bus)(&enmBus);
3866 AssertComRC(rc);
3867 ULONG uInstance;
3868 rc = pStorageController->COMGETTER(Instance)(&uInstance);
3869 AssertComRC(rc);
3870 BOOL fUseHostIOCache;
3871 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
3872 AssertComRC(rc);
3873
3874 /*
3875 * Suspend the VM first. The VM must not be running since it might have
3876 * pending I/O to the drive which is being changed.
3877 */
3878 bool fResume = false;
3879 rc = suspendBeforeConfigChange(pUVM, &alock, &fResume);
3880 if (FAILED(rc))
3881 return rc;
3882
3883 /*
3884 * Call worker in EMT, that's faster and safer than doing everything
3885 * using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
3886 * here to make requests from under the lock in order to serialize them.
3887 */
3888 PVMREQ pReq;
3889 int vrc = VMR3ReqCallU(pUVM, VMCPUID_ANY, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS,
3890 (PFNRT)attachStorageDevice, 8,
3891 this, pUVM, pszDevice, uInstance, enmBus, fUseHostIOCache, aMediumAttachment, fSilent);
3892
3893 /* release the lock before waiting for a result (EMT will call us back!) */
3894 alock.release();
3895
3896 if (vrc == VERR_TIMEOUT || RT_SUCCESS(vrc))
3897 {
3898 vrc = VMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
3899 AssertRC(vrc);
3900 if (RT_SUCCESS(vrc))
3901 vrc = pReq->iStatus;
3902 }
3903 VMR3ReqFree(pReq);
3904
3905 if (fResume)
3906 resumeAfterConfigChange(pUVM);
3907
3908 if (RT_SUCCESS(vrc))
3909 {
3910 LogFlowThisFunc(("Returns S_OK\n"));
3911 return S_OK;
3912 }
3913
3914 if (!pMedium)
3915 return setError(E_FAIL,
3916 tr("Could not mount the media/drive '%ls' (%Rrc)"),
3917 mediumLocation.raw(), vrc);
3918
3919 return setError(E_FAIL,
3920 tr("Could not unmount the currently mounted media/drive (%Rrc)"),
3921 vrc);
3922}
3923
3924
3925/**
3926 * Performs the storage attach operation in EMT.
3927 *
3928 * @returns VBox status code.
3929 *
3930 * @param pThis Pointer to the Console object.
3931 * @param pUVM The VM handle.
3932 * @param pcszDevice The PDM device name.
3933 * @param uInstance The PDM device instance.
3934 * @param fSilent Flag whether to inform the guest about the attached device.
3935 *
3936 * @thread EMT
3937 * @note The VM must not be running since it might have pending I/O to the drive which is being changed.
3938 */
3939DECLCALLBACK(int) Console::attachStorageDevice(Console *pThis,
3940 PUVM pUVM,
3941 const char *pcszDevice,
3942 unsigned uInstance,
3943 StorageBus_T enmBus,
3944 bool fUseHostIOCache,
3945 IMediumAttachment *aMediumAtt,
3946 bool fSilent)
3947{
3948 LogFlowFunc(("pThis=%p uInstance=%u pszDevice=%p:{%s} enmBus=%u, aMediumAtt=%p\n",
3949 pThis, uInstance, pcszDevice, pcszDevice, enmBus, aMediumAtt));
3950
3951 AssertReturn(pThis, VERR_INVALID_PARAMETER);
3952
3953 AutoCaller autoCaller(pThis);
3954 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
3955
3956 /*
3957 * Check the VM for correct state.
3958 */
3959 VMSTATE enmVMState = VMR3GetStateU(pUVM);
3960 AssertReturn(enmVMState == VMSTATE_SUSPENDED, VERR_INVALID_STATE);
3961
3962 /*
3963 * Determine the base path for the device instance. USB Msd devices are handled different
3964 * because the PDM USB API requires a differnet CFGM tree when attaching a new USB device.
3965 */
3966 PCFGMNODE pCtlInst;
3967
3968 if (enmBus == StorageBus_USB)
3969 pCtlInst = CFGMR3CreateTree(pUVM);
3970 else
3971 pCtlInst = CFGMR3GetChildF(CFGMR3GetRootU(pUVM), "Devices/%s/%u/", pcszDevice, uInstance);
3972
3973 AssertReturn(pCtlInst, VERR_INTERNAL_ERROR);
3974
3975 PCFGMNODE pLunL0 = NULL;
3976 int rc = pThis->configMediumAttachment(pCtlInst,
3977 pcszDevice,
3978 uInstance,
3979 enmBus,
3980 fUseHostIOCache,
3981 false /* fSetupMerge */,
3982 false /* fBuiltinIOCache */,
3983 0 /* uMergeSource */,
3984 0 /* uMergeTarget */,
3985 aMediumAtt,
3986 pThis->mMachineState,
3987 NULL /* phrc */,
3988 true /* fAttachDetach */,
3989 false /* fForceUnmount */,
3990 !fSilent /* fHotplug */,
3991 pUVM,
3992 NULL /* paLedDevType */,
3993 &pLunL0);
3994 /* Dump the changed LUN if possible, dump the complete device otherwise */
3995 if (enmBus != StorageBus_USB)
3996 CFGMR3Dump(pLunL0 ? pLunL0 : pCtlInst);
3997
3998 LogFlowFunc(("Returning %Rrc\n", rc));
3999 return rc;
4000}
4001
4002/**
4003 * Attach a new storage device to the VM.
4004 *
4005 * @param aMediumAttachment The medium attachment which is added.
4006 * @param pUVM Safe VM handle.
4007 * @param fSilent Flag whether to notify the guest about the detached device.
4008 *
4009 * @note Locks this object for writing.
4010 */
4011HRESULT Console::doStorageDeviceDetach(IMediumAttachment *aMediumAttachment, PUVM pUVM, bool fSilent)
4012{
4013 AutoCaller autoCaller(this);
4014 AssertComRCReturnRC(autoCaller.rc());
4015
4016 /* We will need to release the write lock before calling EMT */
4017 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4018
4019 HRESULT rc = S_OK;
4020 const char *pszDevice = NULL;
4021
4022 SafeIfaceArray<IStorageController> ctrls;
4023 rc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
4024 AssertComRC(rc);
4025 IMedium *pMedium;
4026 rc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
4027 AssertComRC(rc);
4028 Bstr mediumLocation;
4029 if (pMedium)
4030 {
4031 rc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
4032 AssertComRC(rc);
4033 }
4034
4035 Bstr attCtrlName;
4036 rc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
4037 AssertComRC(rc);
4038 ComPtr<IStorageController> pStorageController;
4039 for (size_t i = 0; i < ctrls.size(); ++i)
4040 {
4041 Bstr ctrlName;
4042 rc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
4043 AssertComRC(rc);
4044 if (attCtrlName == ctrlName)
4045 {
4046 pStorageController = ctrls[i];
4047 break;
4048 }
4049 }
4050 if (pStorageController.isNull())
4051 return setError(E_FAIL,
4052 tr("Could not find storage controller '%ls'"), attCtrlName.raw());
4053
4054 StorageControllerType_T enmCtrlType;
4055 rc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
4056 AssertComRC(rc);
4057 pszDevice = convertControllerTypeToDev(enmCtrlType);
4058
4059 StorageBus_T enmBus;
4060 rc = pStorageController->COMGETTER(Bus)(&enmBus);
4061 AssertComRC(rc);
4062 ULONG uInstance;
4063 rc = pStorageController->COMGETTER(Instance)(&uInstance);
4064 AssertComRC(rc);
4065
4066 /*
4067 * Suspend the VM first. The VM must not be running since it might have
4068 * pending I/O to the drive which is being changed.
4069 */
4070 bool fResume = false;
4071 rc = suspendBeforeConfigChange(pUVM, &alock, &fResume);
4072 if (FAILED(rc))
4073 return rc;
4074
4075 /*
4076 * Call worker in EMT, that's faster and safer than doing everything
4077 * using VMR3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
4078 * here to make requests from under the lock in order to serialize them.
4079 */
4080 PVMREQ pReq;
4081 int vrc = VMR3ReqCallU(pUVM, VMCPUID_ANY, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS,
4082 (PFNRT)detachStorageDevice, 7,
4083 this, pUVM, pszDevice, uInstance, enmBus, aMediumAttachment, fSilent);
4084
4085 /* release the lock before waiting for a result (EMT will call us back!) */
4086 alock.release();
4087
4088 if (vrc == VERR_TIMEOUT || RT_SUCCESS(vrc))
4089 {
4090 vrc = VMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
4091 AssertRC(vrc);
4092 if (RT_SUCCESS(vrc))
4093 vrc = pReq->iStatus;
4094 }
4095 VMR3ReqFree(pReq);
4096
4097 if (fResume)
4098 resumeAfterConfigChange(pUVM);
4099
4100 if (RT_SUCCESS(vrc))
4101 {
4102 LogFlowThisFunc(("Returns S_OK\n"));
4103 return S_OK;
4104 }
4105
4106 if (!pMedium)
4107 return setError(E_FAIL,
4108 tr("Could not mount the media/drive '%ls' (%Rrc)"),
4109 mediumLocation.raw(), vrc);
4110
4111 return setError(E_FAIL,
4112 tr("Could not unmount the currently mounted media/drive (%Rrc)"),
4113 vrc);
4114}
4115
4116/**
4117 * Performs the storage detach operation in EMT.
4118 *
4119 * @returns VBox status code.
4120 *
4121 * @param pThis Pointer to the Console object.
4122 * @param pUVM The VM handle.
4123 * @param pcszDevice The PDM device name.
4124 * @param uInstance The PDM device instance.
4125 * @param fSilent Flag whether to notify the guest about the detached device.
4126 *
4127 * @thread EMT
4128 * @note The VM must not be running since it might have pending I/O to the drive which is being changed.
4129 */
4130DECLCALLBACK(int) Console::detachStorageDevice(Console *pThis,
4131 PUVM pUVM,
4132 const char *pcszDevice,
4133 unsigned uInstance,
4134 StorageBus_T enmBus,
4135 IMediumAttachment *pMediumAtt,
4136 bool fSilent)
4137{
4138 LogFlowFunc(("pThis=%p uInstance=%u pszDevice=%p:{%s} enmBus=%u, pMediumAtt=%p\n",
4139 pThis, uInstance, pcszDevice, pcszDevice, enmBus, pMediumAtt));
4140
4141 AssertReturn(pThis, VERR_INVALID_PARAMETER);
4142
4143 AutoCaller autoCaller(pThis);
4144 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
4145
4146 /*
4147 * Check the VM for correct state.
4148 */
4149 VMSTATE enmVMState = VMR3GetStateU(pUVM);
4150 AssertReturn(enmVMState == VMSTATE_SUSPENDED, VERR_INVALID_STATE);
4151
4152 /* Determine the base path for the device instance. */
4153 PCFGMNODE pCtlInst;
4154 pCtlInst = CFGMR3GetChildF(CFGMR3GetRootU(pUVM), "Devices/%s/%u/", pcszDevice, uInstance);
4155 AssertReturn(pCtlInst || enmBus == StorageBus_USB, VERR_INTERNAL_ERROR);
4156
4157#define H() AssertMsgReturn(!FAILED(hrc), ("hrc=%Rhrc\n", hrc), VERR_GENERAL_FAILURE)
4158
4159 HRESULT hrc;
4160 int rc = VINF_SUCCESS;
4161 int rcRet = VINF_SUCCESS;
4162 unsigned uLUN;
4163 LONG lDev;
4164 LONG lPort;
4165 DeviceType_T lType;
4166 PCFGMNODE pLunL0 = NULL;
4167 PCFGMNODE pCfg = NULL;
4168
4169 hrc = pMediumAtt->COMGETTER(Device)(&lDev); H();
4170 hrc = pMediumAtt->COMGETTER(Port)(&lPort); H();
4171 hrc = pMediumAtt->COMGETTER(Type)(&lType); H();
4172 hrc = Console::convertBusPortDeviceToLun(enmBus, lPort, lDev, uLUN); H();
4173
4174#undef H
4175
4176 if (enmBus != StorageBus_USB)
4177 {
4178 /* First check if the LUN really exists. */
4179 pLunL0 = CFGMR3GetChildF(pCtlInst, "LUN#%u", uLUN);
4180 if (pLunL0)
4181 {
4182 uint32_t fFlags = 0;
4183
4184 if (fSilent)
4185 fFlags |= PDM_TACH_FLAGS_NOT_HOT_PLUG;
4186
4187 rc = PDMR3DeviceDetach(pUVM, pcszDevice, uInstance, uLUN, fFlags);
4188 if (rc == VERR_PDM_NO_DRIVER_ATTACHED_TO_LUN)
4189 rc = VINF_SUCCESS;
4190 AssertRCReturn(rc, rc);
4191 CFGMR3RemoveNode(pLunL0);
4192
4193 Utf8Str devicePath = Utf8StrFmt("%s/%u/LUN#%u", pcszDevice, uInstance, uLUN);
4194 pThis->mapMediumAttachments.erase(devicePath);
4195
4196 }
4197 else
4198 AssertFailedReturn(VERR_INTERNAL_ERROR);
4199
4200 CFGMR3Dump(pCtlInst);
4201 }
4202 else
4203 {
4204 /* Find the correct USB device in the list. */
4205 USBStorageDeviceList::iterator it;
4206 for (it = pThis->mUSBStorageDevices.begin(); it != pThis->mUSBStorageDevices.end(); it++)
4207 {
4208 if (it->iPort == lPort)
4209 break;
4210 }
4211
4212 AssertReturn(it != pThis->mUSBStorageDevices.end(), VERR_INTERNAL_ERROR);
4213 rc = PDMR3UsbDetachDevice(pUVM, &it->mUuid);
4214 AssertRCReturn(rc, rc);
4215 pThis->mUSBStorageDevices.erase(it);
4216 }
4217
4218 LogFlowFunc(("Returning %Rrc\n", rcRet));
4219 return rcRet;
4220}
4221
4222/**
4223 * Called by IInternalSessionControl::OnNetworkAdapterChange().
4224 *
4225 * @note Locks this object for writing.
4226 */
4227HRESULT Console::onNetworkAdapterChange(INetworkAdapter *aNetworkAdapter, BOOL changeAdapter)
4228{
4229 LogFlowThisFunc(("\n"));
4230
4231 AutoCaller autoCaller(this);
4232 AssertComRCReturnRC(autoCaller.rc());
4233
4234 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4235
4236 HRESULT rc = S_OK;
4237
4238 /* don't trigger network changes if the VM isn't running */
4239 SafeVMPtrQuiet ptrVM(this);
4240 if (ptrVM.isOk())
4241 {
4242 /* Get the properties we need from the adapter */
4243 BOOL fCableConnected, fTraceEnabled;
4244 rc = aNetworkAdapter->COMGETTER(CableConnected)(&fCableConnected);
4245 AssertComRC(rc);
4246 if (SUCCEEDED(rc))
4247 {
4248 rc = aNetworkAdapter->COMGETTER(TraceEnabled)(&fTraceEnabled);
4249 AssertComRC(rc);
4250 }
4251 if (SUCCEEDED(rc))
4252 {
4253 ULONG ulInstance;
4254 rc = aNetworkAdapter->COMGETTER(Slot)(&ulInstance);
4255 AssertComRC(rc);
4256 if (SUCCEEDED(rc))
4257 {
4258 /*
4259 * Find the adapter instance, get the config interface and update
4260 * the link state.
4261 */
4262 NetworkAdapterType_T adapterType;
4263 rc = aNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
4264 AssertComRC(rc);
4265 const char *pszAdapterName = networkAdapterTypeToName(adapterType);
4266
4267 // prevent cross-thread deadlocks, don't need the lock any more
4268 alock.release();
4269
4270 PPDMIBASE pBase;
4271 int vrc = PDMR3QueryDeviceLun(ptrVM.rawUVM(), pszAdapterName, ulInstance, 0, &pBase);
4272 if (RT_SUCCESS(vrc))
4273 {
4274 Assert(pBase);
4275 PPDMINETWORKCONFIG pINetCfg;
4276 pINetCfg = PDMIBASE_QUERY_INTERFACE(pBase, PDMINETWORKCONFIG);
4277 if (pINetCfg)
4278 {
4279 Log(("Console::onNetworkAdapterChange: setting link state to %d\n",
4280 fCableConnected));
4281 vrc = pINetCfg->pfnSetLinkState(pINetCfg,
4282 fCableConnected ? PDMNETWORKLINKSTATE_UP
4283 : PDMNETWORKLINKSTATE_DOWN);
4284 ComAssertRC(vrc);
4285 }
4286 if (RT_SUCCESS(vrc) && changeAdapter)
4287 {
4288 VMSTATE enmVMState = VMR3GetStateU(ptrVM.rawUVM());
4289 if ( enmVMState == VMSTATE_RUNNING /** @todo LiveMigration: Forbid or deal correctly with the _LS variants */
4290 || enmVMState == VMSTATE_SUSPENDED)
4291 {
4292 if (fTraceEnabled && fCableConnected && pINetCfg)
4293 {
4294 vrc = pINetCfg->pfnSetLinkState(pINetCfg, PDMNETWORKLINKSTATE_DOWN);
4295 ComAssertRC(vrc);
4296 }
4297
4298 rc = doNetworkAdapterChange(ptrVM.rawUVM(), pszAdapterName, ulInstance, 0, aNetworkAdapter);
4299
4300 if (fTraceEnabled && fCableConnected && pINetCfg)
4301 {
4302 vrc = pINetCfg->pfnSetLinkState(pINetCfg, PDMNETWORKLINKSTATE_UP);
4303 ComAssertRC(vrc);
4304 }
4305 }
4306 }
4307 }
4308 else if (vrc == VERR_PDM_DEVICE_INSTANCE_NOT_FOUND)
4309 return setError(E_FAIL,
4310 tr("The network adapter #%u is not enabled"), ulInstance);
4311 else
4312 ComAssertRC(vrc);
4313
4314 if (RT_FAILURE(vrc))
4315 rc = E_FAIL;
4316
4317 alock.acquire();
4318 }
4319 }
4320 ptrVM.release();
4321 }
4322
4323 // definitely don't need the lock any more
4324 alock.release();
4325
4326 /* notify console callbacks on success */
4327 if (SUCCEEDED(rc))
4328 fireNetworkAdapterChangedEvent(mEventSource, aNetworkAdapter);
4329
4330 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4331 return rc;
4332}
4333
4334/**
4335 * Called by IInternalSessionControl::OnNATEngineChange().
4336 *
4337 * @note Locks this object for writing.
4338 */
4339HRESULT Console::onNATRedirectRuleChange(ULONG ulInstance, BOOL aNatRuleRemove,
4340 NATProtocol_T aProto, IN_BSTR aHostIP, LONG aHostPort, IN_BSTR aGuestIP, LONG aGuestPort)
4341{
4342 LogFlowThisFunc(("\n"));
4343
4344 AutoCaller autoCaller(this);
4345 AssertComRCReturnRC(autoCaller.rc());
4346
4347 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4348
4349 HRESULT rc = S_OK;
4350
4351 /* don't trigger NAT engine changes if the VM isn't running */
4352 SafeVMPtrQuiet ptrVM(this);
4353 if (ptrVM.isOk())
4354 {
4355 do
4356 {
4357 ComPtr<INetworkAdapter> pNetworkAdapter;
4358 rc = machine()->GetNetworkAdapter(ulInstance, pNetworkAdapter.asOutParam());
4359 if ( FAILED(rc)
4360 || pNetworkAdapter.isNull())
4361 break;
4362
4363 /*
4364 * Find the adapter instance, get the config interface and update
4365 * the link state.
4366 */
4367 NetworkAdapterType_T adapterType;
4368 rc = pNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
4369 if (FAILED(rc))
4370 {
4371 AssertComRC(rc);
4372 rc = E_FAIL;
4373 break;
4374 }
4375
4376 const char *pszAdapterName = networkAdapterTypeToName(adapterType);
4377 PPDMIBASE pBase;
4378 int vrc = PDMR3QueryLun(ptrVM.rawUVM(), pszAdapterName, ulInstance, 0, &pBase);
4379 if (RT_FAILURE(vrc))
4380 {
4381 ComAssertRC(vrc);
4382 rc = E_FAIL;
4383 break;
4384 }
4385
4386 NetworkAttachmentType_T attachmentType;
4387 rc = pNetworkAdapter->COMGETTER(AttachmentType)(&attachmentType);
4388 if ( FAILED(rc)
4389 || attachmentType != NetworkAttachmentType_NAT)
4390 {
4391 rc = E_FAIL;
4392 break;
4393 }
4394
4395 /* look down for PDMINETWORKNATCONFIG interface */
4396 PPDMINETWORKNATCONFIG pNetNatCfg = NULL;
4397 while (pBase)
4398 {
4399 pNetNatCfg = (PPDMINETWORKNATCONFIG)pBase->pfnQueryInterface(pBase, PDMINETWORKNATCONFIG_IID);
4400 if (pNetNatCfg)
4401 break;
4402 /** @todo r=bird: This stinks! */
4403 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pBase);
4404 pBase = pDrvIns->pDownBase;
4405 }
4406 if (!pNetNatCfg)
4407 break;
4408
4409 bool fUdp = aProto == NATProtocol_UDP;
4410 vrc = pNetNatCfg->pfnRedirectRuleCommand(pNetNatCfg, !!aNatRuleRemove, fUdp,
4411 Utf8Str(aHostIP).c_str(), (uint16_t)aHostPort, Utf8Str(aGuestIP).c_str(),
4412 (uint16_t)aGuestPort);
4413 if (RT_FAILURE(vrc))
4414 rc = E_FAIL;
4415 } while (0); /* break loop */
4416 ptrVM.release();
4417 }
4418
4419 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4420 return rc;
4421}
4422
4423VMMDevMouseInterface *Console::getVMMDevMouseInterface()
4424{
4425 return m_pVMMDev;
4426}
4427
4428DisplayMouseInterface *Console::getDisplayMouseInterface()
4429{
4430 return mDisplay;
4431}
4432
4433/**
4434 * Process a network adaptor change.
4435 *
4436 * @returns COM status code.
4437 *
4438 * @parma pUVM The VM handle (caller hold this safely).
4439 * @param pszDevice The PDM device name.
4440 * @param uInstance The PDM device instance.
4441 * @param uLun The PDM LUN number of the drive.
4442 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
4443 */
4444HRESULT Console::doNetworkAdapterChange(PUVM pUVM,
4445 const char *pszDevice,
4446 unsigned uInstance,
4447 unsigned uLun,
4448 INetworkAdapter *aNetworkAdapter)
4449{
4450 LogFlowThisFunc(("pszDevice=%p:{%s} uInstance=%u uLun=%u aNetworkAdapter=%p\n",
4451 pszDevice, pszDevice, uInstance, uLun, aNetworkAdapter));
4452
4453 AutoCaller autoCaller(this);
4454 AssertComRCReturnRC(autoCaller.rc());
4455
4456 /*
4457 * Suspend the VM first.
4458 */
4459 bool fResume = false;
4460 int rc = suspendBeforeConfigChange(pUVM, NULL, &fResume);
4461 if (FAILED(rc))
4462 return rc;
4463
4464 /*
4465 * Call worker in EMT, that's faster and safer than doing everything
4466 * using VM3ReqCall. Note that we separate VMR3ReqCall from VMR3ReqWait
4467 * here to make requests from under the lock in order to serialize them.
4468 */
4469 PVMREQ pReq;
4470 int vrc = VMR3ReqCallU(pUVM, 0 /*idDstCpu*/, &pReq, 0 /* no wait! */, VMREQFLAGS_VBOX_STATUS,
4471 (PFNRT)changeNetworkAttachment, 6,
4472 this, pUVM, pszDevice, uInstance, uLun, aNetworkAdapter);
4473
4474 if (vrc == VERR_TIMEOUT || RT_SUCCESS(vrc))
4475 {
4476 vrc = VMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
4477 AssertRC(vrc);
4478 if (RT_SUCCESS(vrc))
4479 vrc = pReq->iStatus;
4480 }
4481 VMR3ReqFree(pReq);
4482
4483 if (fResume)
4484 resumeAfterConfigChange(pUVM);
4485
4486 if (RT_SUCCESS(vrc))
4487 {
4488 LogFlowThisFunc(("Returns S_OK\n"));
4489 return S_OK;
4490 }
4491
4492 return setError(E_FAIL,
4493 tr("Could not change the network adaptor attachement type (%Rrc)"),
4494 vrc);
4495}
4496
4497
4498/**
4499 * Performs the Network Adaptor change in EMT.
4500 *
4501 * @returns VBox status code.
4502 *
4503 * @param pThis Pointer to the Console object.
4504 * @param pUVM The VM handle.
4505 * @param pszDevice The PDM device name.
4506 * @param uInstance The PDM device instance.
4507 * @param uLun The PDM LUN number of the drive.
4508 * @param aNetworkAdapter The network adapter whose attachment needs to be changed
4509 *
4510 * @thread EMT
4511 * @note Locks the Console object for writing.
4512 * @note The VM must not be running.
4513 */
4514DECLCALLBACK(int) Console::changeNetworkAttachment(Console *pThis,
4515 PUVM pUVM,
4516 const char *pszDevice,
4517 unsigned uInstance,
4518 unsigned uLun,
4519 INetworkAdapter *aNetworkAdapter)
4520{
4521 LogFlowFunc(("pThis=%p pszDevice=%p:{%s} uInstance=%u uLun=%u aNetworkAdapter=%p\n",
4522 pThis, pszDevice, pszDevice, uInstance, uLun, aNetworkAdapter));
4523
4524 AssertReturn(pThis, VERR_INVALID_PARAMETER);
4525
4526 AutoCaller autoCaller(pThis);
4527 AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);
4528
4529 ComPtr<IVirtualBox> pVirtualBox;
4530 pThis->mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
4531 ComPtr<ISystemProperties> pSystemProperties;
4532 if (pVirtualBox)
4533 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
4534 ChipsetType_T chipsetType = ChipsetType_PIIX3;
4535 pThis->mMachine->COMGETTER(ChipsetType)(&chipsetType);
4536 ULONG maxNetworkAdapters = 0;
4537 if (pSystemProperties)
4538 pSystemProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
4539 AssertMsg( ( !strcmp(pszDevice, "pcnet")
4540 || !strcmp(pszDevice, "e1000")
4541 || !strcmp(pszDevice, "virtio-net"))
4542 && uLun == 0
4543 && uInstance < maxNetworkAdapters,
4544 ("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
4545 Log(("pszDevice=%s uLun=%d uInstance=%d\n", pszDevice, uLun, uInstance));
4546
4547 /*
4548 * Check the VM for correct state.
4549 */
4550 VMSTATE enmVMState = VMR3GetStateU(pUVM);
4551 AssertReturn(enmVMState == VMSTATE_SUSPENDED, VERR_INVALID_STATE);
4552
4553 PCFGMNODE pCfg = NULL; /* /Devices/Dev/.../Config/ */
4554 PCFGMNODE pLunL0 = NULL; /* /Devices/Dev/0/LUN#0/ */
4555 PCFGMNODE pInst = CFGMR3GetChildF(CFGMR3GetRootU(pUVM), "Devices/%s/%d/", pszDevice, uInstance);
4556 AssertRelease(pInst);
4557
4558 int rc = pThis->configNetwork(pszDevice, uInstance, uLun, aNetworkAdapter, pCfg, pLunL0, pInst,
4559 true /*fAttachDetach*/, false /*fIgnoreConnectFailure*/);
4560
4561 LogFlowFunc(("Returning %Rrc\n", rc));
4562 return rc;
4563}
4564
4565
4566/**
4567 * Called by IInternalSessionControl::OnSerialPortChange().
4568 */
4569HRESULT Console::onSerialPortChange(ISerialPort *aSerialPort)
4570{
4571 LogFlowThisFunc(("\n"));
4572
4573 AutoCaller autoCaller(this);
4574 AssertComRCReturnRC(autoCaller.rc());
4575
4576 fireSerialPortChangedEvent(mEventSource, aSerialPort);
4577
4578 LogFlowThisFunc(("Leaving rc=%#x\n", S_OK));
4579 return S_OK;
4580}
4581
4582/**
4583 * Called by IInternalSessionControl::OnParallelPortChange().
4584 */
4585HRESULT Console::onParallelPortChange(IParallelPort *aParallelPort)
4586{
4587 LogFlowThisFunc(("\n"));
4588
4589 AutoCaller autoCaller(this);
4590 AssertComRCReturnRC(autoCaller.rc());
4591
4592 fireParallelPortChangedEvent(mEventSource, aParallelPort);
4593
4594 LogFlowThisFunc(("Leaving rc=%#x\n", S_OK));
4595 return S_OK;
4596}
4597
4598/**
4599 * Called by IInternalSessionControl::OnStorageControllerChange().
4600 */
4601HRESULT Console::onStorageControllerChange()
4602{
4603 LogFlowThisFunc(("\n"));
4604
4605 AutoCaller autoCaller(this);
4606 AssertComRCReturnRC(autoCaller.rc());
4607
4608 fireStorageControllerChangedEvent(mEventSource);
4609
4610 LogFlowThisFunc(("Leaving rc=%#x\n", S_OK));
4611 return S_OK;
4612}
4613
4614/**
4615 * Called by IInternalSessionControl::OnMediumChange().
4616 */
4617HRESULT Console::onMediumChange(IMediumAttachment *aMediumAttachment, BOOL aForce)
4618{
4619 LogFlowThisFunc(("\n"));
4620
4621 AutoCaller autoCaller(this);
4622 AssertComRCReturnRC(autoCaller.rc());
4623
4624 HRESULT rc = S_OK;
4625
4626 /* don't trigger medium changes if the VM isn't running */
4627 SafeVMPtrQuiet ptrVM(this);
4628 if (ptrVM.isOk())
4629 {
4630 rc = doMediumChange(aMediumAttachment, !!aForce, ptrVM.rawUVM());
4631 ptrVM.release();
4632 }
4633
4634 /* notify console callbacks on success */
4635 if (SUCCEEDED(rc))
4636 fireMediumChangedEvent(mEventSource, aMediumAttachment);
4637
4638 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4639 return rc;
4640}
4641
4642/**
4643 * Called by IInternalSessionControl::OnCPUChange().
4644 *
4645 * @note Locks this object for writing.
4646 */
4647HRESULT Console::onCPUChange(ULONG aCPU, BOOL aRemove)
4648{
4649 LogFlowThisFunc(("\n"));
4650
4651 AutoCaller autoCaller(this);
4652 AssertComRCReturnRC(autoCaller.rc());
4653
4654 HRESULT rc = S_OK;
4655
4656 /* don't trigger CPU changes if the VM isn't running */
4657 SafeVMPtrQuiet ptrVM(this);
4658 if (ptrVM.isOk())
4659 {
4660 if (aRemove)
4661 rc = doCPURemove(aCPU, ptrVM.rawUVM());
4662 else
4663 rc = doCPUAdd(aCPU, ptrVM.rawUVM());
4664 ptrVM.release();
4665 }
4666
4667 /* notify console callbacks on success */
4668 if (SUCCEEDED(rc))
4669 fireCPUChangedEvent(mEventSource, aCPU, aRemove);
4670
4671 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4672 return rc;
4673}
4674
4675/**
4676 * Called by IInternalSessionControl::OnCpuExecutionCapChange().
4677 *
4678 * @note Locks this object for writing.
4679 */
4680HRESULT Console::onCPUExecutionCapChange(ULONG aExecutionCap)
4681{
4682 LogFlowThisFunc(("\n"));
4683
4684 AutoCaller autoCaller(this);
4685 AssertComRCReturnRC(autoCaller.rc());
4686
4687 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4688
4689 HRESULT rc = S_OK;
4690
4691 /* don't trigger the CPU priority change if the VM isn't running */
4692 SafeVMPtrQuiet ptrVM(this);
4693 if (ptrVM.isOk())
4694 {
4695 if ( mMachineState == MachineState_Running
4696 || mMachineState == MachineState_Teleporting
4697 || mMachineState == MachineState_LiveSnapshotting
4698 )
4699 {
4700 /* No need to call in the EMT thread. */
4701 rc = VMR3SetCpuExecutionCap(ptrVM.rawUVM(), aExecutionCap);
4702 }
4703 else
4704 rc = setInvalidMachineStateError();
4705 ptrVM.release();
4706 }
4707
4708 /* notify console callbacks on success */
4709 if (SUCCEEDED(rc))
4710 {
4711 alock.release();
4712 fireCPUExecutionCapChangedEvent(mEventSource, aExecutionCap);
4713 }
4714
4715 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4716 return rc;
4717}
4718
4719/**
4720 * Called by IInternalSessionControl::OnClipboardModeChange().
4721 *
4722 * @note Locks this object for writing.
4723 */
4724HRESULT Console::onClipboardModeChange(ClipboardMode_T aClipboardMode)
4725{
4726 LogFlowThisFunc(("\n"));
4727
4728 AutoCaller autoCaller(this);
4729 AssertComRCReturnRC(autoCaller.rc());
4730
4731 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4732
4733 HRESULT rc = S_OK;
4734
4735 /* don't trigger the clipboard mode change if the VM isn't running */
4736 SafeVMPtrQuiet ptrVM(this);
4737 if (ptrVM.isOk())
4738 {
4739 if ( mMachineState == MachineState_Running
4740 || mMachineState == MachineState_Teleporting
4741 || mMachineState == MachineState_LiveSnapshotting)
4742 changeClipboardMode(aClipboardMode);
4743 else
4744 rc = setInvalidMachineStateError();
4745 ptrVM.release();
4746 }
4747
4748 /* notify console callbacks on success */
4749 if (SUCCEEDED(rc))
4750 {
4751 alock.release();
4752 fireClipboardModeChangedEvent(mEventSource, aClipboardMode);
4753 }
4754
4755 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4756 return rc;
4757}
4758
4759/**
4760 * Called by IInternalSessionControl::OnDragAndDropModeChange().
4761 *
4762 * @note Locks this object for writing.
4763 */
4764HRESULT Console::onDragAndDropModeChange(DragAndDropMode_T aDragAndDropMode)
4765{
4766 LogFlowThisFunc(("\n"));
4767
4768 AutoCaller autoCaller(this);
4769 AssertComRCReturnRC(autoCaller.rc());
4770
4771 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4772
4773 HRESULT rc = S_OK;
4774
4775 /* don't trigger the drag'n'drop mode change if the VM isn't running */
4776 SafeVMPtrQuiet ptrVM(this);
4777 if (ptrVM.isOk())
4778 {
4779 if ( mMachineState == MachineState_Running
4780 || mMachineState == MachineState_Teleporting
4781 || mMachineState == MachineState_LiveSnapshotting)
4782 changeDragAndDropMode(aDragAndDropMode);
4783 else
4784 rc = setInvalidMachineStateError();
4785 ptrVM.release();
4786 }
4787
4788 /* notify console callbacks on success */
4789 if (SUCCEEDED(rc))
4790 {
4791 alock.release();
4792 fireDragAndDropModeChangedEvent(mEventSource, aDragAndDropMode);
4793 }
4794
4795 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
4796 return rc;
4797}
4798
4799/**
4800 * Called by IInternalSessionControl::OnVRDEServerChange().
4801 *
4802 * @note Locks this object for writing.
4803 */
4804HRESULT Console::onVRDEServerChange(BOOL aRestart)
4805{
4806 AutoCaller autoCaller(this);
4807 AssertComRCReturnRC(autoCaller.rc());
4808
4809 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4810
4811 HRESULT rc = S_OK;
4812
4813 /* don't trigger VRDE server changes if the VM isn't running */
4814 SafeVMPtrQuiet ptrVM(this);
4815 if (ptrVM.isOk())
4816 {
4817 /* Serialize. */
4818 if (mfVRDEChangeInProcess)
4819 mfVRDEChangePending = true;
4820 else
4821 {
4822 do {
4823 mfVRDEChangeInProcess = true;
4824 mfVRDEChangePending = false;
4825
4826 if ( mVRDEServer
4827 && ( mMachineState == MachineState_Running
4828 || mMachineState == MachineState_Teleporting
4829 || mMachineState == MachineState_LiveSnapshotting
4830 || mMachineState == MachineState_Paused
4831 )
4832 )
4833 {
4834 BOOL vrdpEnabled = FALSE;
4835
4836 rc = mVRDEServer->COMGETTER(Enabled)(&vrdpEnabled);
4837 ComAssertComRCRetRC(rc);
4838
4839 if (aRestart)
4840 {
4841 /* VRDP server may call this Console object back from other threads (VRDP INPUT or OUTPUT). */
4842 alock.release();
4843
4844 if (vrdpEnabled)
4845 {
4846 // If there was no VRDP server started the 'stop' will do nothing.
4847 // However if a server was started and this notification was called,
4848 // we have to restart the server.
4849 mConsoleVRDPServer->Stop();
4850
4851 if (RT_FAILURE(mConsoleVRDPServer->Launch()))
4852 rc = E_FAIL;
4853 else
4854 mConsoleVRDPServer->EnableConnections();
4855 }
4856 else
4857 mConsoleVRDPServer->Stop();
4858
4859 alock.acquire();
4860 }
4861 }
4862 else
4863 rc = setInvalidMachineStateError();
4864
4865 mfVRDEChangeInProcess = false;
4866 } while (mfVRDEChangePending && SUCCEEDED(rc));
4867 }
4868
4869 ptrVM.release();
4870 }
4871
4872 /* notify console callbacks on success */
4873 if (SUCCEEDED(rc))
4874 {
4875 alock.release();
4876 fireVRDEServerChangedEvent(mEventSource);
4877 }
4878
4879 return rc;
4880}
4881
4882void Console::onVRDEServerInfoChange()
4883{
4884 AutoCaller autoCaller(this);
4885 AssertComRCReturnVoid(autoCaller.rc());
4886
4887 fireVRDEServerInfoChangedEvent(mEventSource);
4888}
4889
4890HRESULT Console::onVideoCaptureChange()
4891{
4892 AutoCaller autoCaller(this);
4893 AssertComRCReturnRC(autoCaller.rc());
4894
4895 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4896
4897 HRESULT rc = S_OK;
4898
4899 /* don't trigger video capture changes if the VM isn't running */
4900 SafeVMPtrQuiet ptrVM(this);
4901 if (ptrVM.isOk())
4902 {
4903 BOOL fEnabled;
4904 rc = mMachine->COMGETTER(VideoCaptureEnabled)(&fEnabled);
4905 SafeArray<BOOL> screens;
4906 if (SUCCEEDED(rc))
4907 rc = mMachine->COMGETTER(VideoCaptureScreens)(ComSafeArrayAsOutParam(screens));
4908 if (mDisplay)
4909 {
4910 int vrc = VINF_SUCCESS;
4911 if (SUCCEEDED(rc))
4912 vrc = mDisplay->VideoCaptureEnableScreens(ComSafeArrayAsInParam(screens));
4913 if (RT_SUCCESS(vrc))
4914 {
4915 if (fEnabled)
4916 {
4917 vrc = mDisplay->VideoCaptureStart();
4918 if (RT_FAILURE(vrc))
4919 rc = setError(E_FAIL, tr("Unable to start video capturing (%Rrc)"), vrc);
4920 }
4921 else
4922 mDisplay->VideoCaptureStop();
4923 }
4924 else
4925 rc = setError(E_FAIL, tr("Unable to set screens for capturing (%Rrc)"), vrc);
4926 }
4927 ptrVM.release();
4928 }
4929
4930 /* notify console callbacks on success */
4931 if (SUCCEEDED(rc))
4932 {
4933 alock.release();
4934 fireVideoCaptureChangedEvent(mEventSource);
4935 }
4936
4937 return rc;
4938}
4939
4940/**
4941 * Called by IInternalSessionControl::OnUSBControllerChange().
4942 */
4943HRESULT Console::onUSBControllerChange()
4944{
4945 LogFlowThisFunc(("\n"));
4946
4947 AutoCaller autoCaller(this);
4948 AssertComRCReturnRC(autoCaller.rc());
4949
4950 fireUSBControllerChangedEvent(mEventSource);
4951
4952 return S_OK;
4953}
4954
4955/**
4956 * Called by IInternalSessionControl::OnSharedFolderChange().
4957 *
4958 * @note Locks this object for writing.
4959 */
4960HRESULT Console::onSharedFolderChange(BOOL aGlobal)
4961{
4962 LogFlowThisFunc(("aGlobal=%RTbool\n", aGlobal));
4963
4964 AutoCaller autoCaller(this);
4965 AssertComRCReturnRC(autoCaller.rc());
4966
4967 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4968
4969 HRESULT rc = fetchSharedFolders(aGlobal);
4970
4971 /* notify console callbacks on success */
4972 if (SUCCEEDED(rc))
4973 {
4974 alock.release();
4975 fireSharedFolderChangedEvent(mEventSource, aGlobal ? (Scope_T)Scope_Global : (Scope_T)Scope_Machine);
4976 }
4977
4978 return rc;
4979}
4980
4981/**
4982 * Called by IInternalSessionControl::OnUSBDeviceAttach() or locally by
4983 * processRemoteUSBDevices() after IInternalMachineControl::RunUSBDeviceFilters()
4984 * returns TRUE for a given remote USB device.
4985 *
4986 * @return S_OK if the device was attached to the VM.
4987 * @return failure if not attached.
4988 *
4989 * @param aDevice
4990 * The device in question.
4991 * @param aMaskedIfs
4992 * The interfaces to hide from the guest.
4993 *
4994 * @note Locks this object for writing.
4995 */
4996HRESULT Console::onUSBDeviceAttach(IUSBDevice *aDevice, IVirtualBoxErrorInfo *aError, ULONG aMaskedIfs)
4997{
4998#ifdef VBOX_WITH_USB
4999 LogFlowThisFunc(("aDevice=%p aError=%p\n", aDevice, aError));
5000
5001 AutoCaller autoCaller(this);
5002 ComAssertComRCRetRC(autoCaller.rc());
5003
5004 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5005
5006 /* Get the VM pointer (we don't need error info, since it's a callback). */
5007 SafeVMPtrQuiet ptrVM(this);
5008 if (!ptrVM.isOk())
5009 {
5010 /* The VM may be no more operational when this message arrives
5011 * (e.g. it may be Saving or Stopping or just PoweredOff) --
5012 * autoVMCaller.rc() will return a failure in this case. */
5013 LogFlowThisFunc(("Attach request ignored (mMachineState=%d).\n",
5014 mMachineState));
5015 return ptrVM.rc();
5016 }
5017
5018 if (aError != NULL)
5019 {
5020 /* notify callbacks about the error */
5021 alock.release();
5022 onUSBDeviceStateChange(aDevice, true /* aAttached */, aError);
5023 return S_OK;
5024 }
5025
5026 /* Don't proceed unless there's at least one USB hub. */
5027 if (!PDMR3UsbHasHub(ptrVM.rawUVM()))
5028 {
5029 LogFlowThisFunc(("Attach request ignored (no USB controller).\n"));
5030 return E_FAIL;
5031 }
5032
5033 alock.release();
5034 HRESULT rc = attachUSBDevice(aDevice, aMaskedIfs);
5035 if (FAILED(rc))
5036 {
5037 /* take the current error info */
5038 com::ErrorInfoKeeper eik;
5039 /* the error must be a VirtualBoxErrorInfo instance */
5040 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
5041 Assert(!pError.isNull());
5042 if (!pError.isNull())
5043 {
5044 /* notify callbacks about the error */
5045 onUSBDeviceStateChange(aDevice, true /* aAttached */, pError);
5046 }
5047 }
5048
5049 return rc;
5050
5051#else /* !VBOX_WITH_USB */
5052 return E_FAIL;
5053#endif /* !VBOX_WITH_USB */
5054}
5055
5056/**
5057 * Called by IInternalSessionControl::OnUSBDeviceDetach() and locally by
5058 * processRemoteUSBDevices().
5059 *
5060 * @note Locks this object for writing.
5061 */
5062HRESULT Console::onUSBDeviceDetach(IN_BSTR aId,
5063 IVirtualBoxErrorInfo *aError)
5064{
5065#ifdef VBOX_WITH_USB
5066 Guid Uuid(aId);
5067 LogFlowThisFunc(("aId={%RTuuid} aError=%p\n", Uuid.raw(), aError));
5068
5069 AutoCaller autoCaller(this);
5070 AssertComRCReturnRC(autoCaller.rc());
5071
5072 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5073
5074 /* Find the device. */
5075 ComObjPtr<OUSBDevice> pUSBDevice;
5076 USBDeviceList::iterator it = mUSBDevices.begin();
5077 while (it != mUSBDevices.end())
5078 {
5079 LogFlowThisFunc(("it={%RTuuid}\n", (*it)->i_id().raw()));
5080 if ((*it)->i_id() == Uuid)
5081 {
5082 pUSBDevice = *it;
5083 break;
5084 }
5085 ++it;
5086 }
5087
5088
5089 if (pUSBDevice.isNull())
5090 {
5091 LogFlowThisFunc(("USB device not found.\n"));
5092
5093 /* The VM may be no more operational when this message arrives
5094 * (e.g. it may be Saving or Stopping or just PoweredOff). Use
5095 * AutoVMCaller to detect it -- AutoVMCaller::rc() will return a
5096 * failure in this case. */
5097
5098 AutoVMCallerQuiet autoVMCaller(this);
5099 if (FAILED(autoVMCaller.rc()))
5100 {
5101 LogFlowThisFunc(("Detach request ignored (mMachineState=%d).\n",
5102 mMachineState));
5103 return autoVMCaller.rc();
5104 }
5105
5106 /* the device must be in the list otherwise */
5107 AssertFailedReturn(E_FAIL);
5108 }
5109
5110 if (aError != NULL)
5111 {
5112 /* notify callback about an error */
5113 alock.release();
5114 onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, aError);
5115 return S_OK;
5116 }
5117
5118 /* Remove the device from the collection, it is re-added below for failures */
5119 mUSBDevices.erase(it);
5120
5121 alock.release();
5122 HRESULT rc = detachUSBDevice(pUSBDevice);
5123 if (FAILED(rc))
5124 {
5125 /* Re-add the device to the collection */
5126 alock.acquire();
5127 mUSBDevices.push_back(pUSBDevice);
5128 alock.release();
5129 /* take the current error info */
5130 com::ErrorInfoKeeper eik;
5131 /* the error must be a VirtualBoxErrorInfo instance */
5132 ComPtr<IVirtualBoxErrorInfo> pError = eik.takeError();
5133 Assert(!pError.isNull());
5134 if (!pError.isNull())
5135 {
5136 /* notify callbacks about the error */
5137 onUSBDeviceStateChange(pUSBDevice, false /* aAttached */, pError);
5138 }
5139 }
5140
5141 return rc;
5142
5143#else /* !VBOX_WITH_USB */
5144 return E_FAIL;
5145#endif /* !VBOX_WITH_USB */
5146}
5147
5148/**
5149 * Called by IInternalSessionControl::OnBandwidthGroupChange().
5150 *
5151 * @note Locks this object for writing.
5152 */
5153HRESULT Console::onBandwidthGroupChange(IBandwidthGroup *aBandwidthGroup)
5154{
5155 LogFlowThisFunc(("\n"));
5156
5157 AutoCaller autoCaller(this);
5158 AssertComRCReturnRC(autoCaller.rc());
5159
5160 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5161
5162 HRESULT rc = S_OK;
5163
5164 /* don't trigger bandwidth group changes if the VM isn't running */
5165 SafeVMPtrQuiet ptrVM(this);
5166 if (ptrVM.isOk())
5167 {
5168 if ( mMachineState == MachineState_Running
5169 || mMachineState == MachineState_Teleporting
5170 || mMachineState == MachineState_LiveSnapshotting
5171 )
5172 {
5173 /* No need to call in the EMT thread. */
5174 LONG64 cMax;
5175 Bstr strName;
5176 BandwidthGroupType_T enmType;
5177 rc = aBandwidthGroup->COMGETTER(Name)(strName.asOutParam());
5178 if (SUCCEEDED(rc))
5179 rc = aBandwidthGroup->COMGETTER(MaxBytesPerSec)(&cMax);
5180 if (SUCCEEDED(rc))
5181 rc = aBandwidthGroup->COMGETTER(Type)(&enmType);
5182
5183 if (SUCCEEDED(rc))
5184 {
5185 int vrc = VINF_SUCCESS;
5186 if (enmType == BandwidthGroupType_Disk)
5187 vrc = PDMR3AsyncCompletionBwMgrSetMaxForFile(ptrVM.rawUVM(), Utf8Str(strName).c_str(), (uint32_t)cMax);
5188#ifdef VBOX_WITH_NETSHAPER
5189 else if (enmType == BandwidthGroupType_Network)
5190 vrc = PDMR3NsBwGroupSetLimit(ptrVM.rawUVM(), Utf8Str(strName).c_str(), cMax);
5191 else
5192 rc = E_NOTIMPL;
5193#endif /* VBOX_WITH_NETSHAPER */
5194 AssertRC(vrc);
5195 }
5196 }
5197 else
5198 rc = setInvalidMachineStateError();
5199 ptrVM.release();
5200 }
5201
5202 /* notify console callbacks on success */
5203 if (SUCCEEDED(rc))
5204 {
5205 alock.release();
5206 fireBandwidthGroupChangedEvent(mEventSource, aBandwidthGroup);
5207 }
5208
5209 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
5210 return rc;
5211}
5212
5213/**
5214 * Called by IInternalSessionControl::OnStorageDeviceChange().
5215 *
5216 * @note Locks this object for writing.
5217 */
5218HRESULT Console::onStorageDeviceChange(IMediumAttachment *aMediumAttachment, BOOL aRemove, BOOL aSilent)
5219{
5220 LogFlowThisFunc(("\n"));
5221
5222 AutoCaller autoCaller(this);
5223 AssertComRCReturnRC(autoCaller.rc());
5224
5225 HRESULT rc = S_OK;
5226
5227 /* don't trigger medium changes if the VM isn't running */
5228 SafeVMPtrQuiet ptrVM(this);
5229 if (ptrVM.isOk())
5230 {
5231 if (aRemove)
5232 rc = doStorageDeviceDetach(aMediumAttachment, ptrVM.rawUVM(), RT_BOOL(aSilent));
5233 else
5234 rc = doStorageDeviceAttach(aMediumAttachment, ptrVM.rawUVM(), RT_BOOL(aSilent));
5235 ptrVM.release();
5236 }
5237
5238 /* notify console callbacks on success */
5239 if (SUCCEEDED(rc))
5240 fireStorageDeviceChangedEvent(mEventSource, aMediumAttachment, aRemove, aSilent);
5241
5242 LogFlowThisFunc(("Leaving rc=%#x\n", rc));
5243 return rc;
5244}
5245
5246HRESULT Console::onExtraDataChange(IN_BSTR aMachineId, IN_BSTR aKey, IN_BSTR aVal)
5247{
5248 LogFlowThisFunc(("\n"));
5249
5250 AutoCaller autoCaller(this);
5251 if (FAILED(autoCaller.rc()))
5252 return autoCaller.rc();
5253
5254 if (!aMachineId)
5255 return S_OK;
5256
5257 HRESULT hrc = S_OK;
5258 Bstr idMachine(aMachineId);
5259 Bstr idSelf;
5260 hrc = mMachine->COMGETTER(Id)(idSelf.asOutParam());
5261 if ( FAILED(hrc)
5262 || idMachine != idSelf)
5263 return hrc;
5264
5265 /* don't do anything if the VM isn't running */
5266 SafeVMPtrQuiet ptrVM(this);
5267 if (ptrVM.isOk())
5268 {
5269 Bstr strKey(aKey);
5270 Bstr strVal(aVal);
5271
5272 if (strKey == "VBoxInternal2/TurnResetIntoPowerOff")
5273 {
5274 int vrc = VMR3SetPowerOffInsteadOfReset(ptrVM.rawUVM(), strVal == "1");
5275 AssertRC(vrc);
5276 }
5277
5278 ptrVM.release();
5279 }
5280
5281 /* notify console callbacks on success */
5282 if (SUCCEEDED(hrc))
5283 fireExtraDataChangedEvent(mEventSource, aMachineId, aKey, aVal);
5284
5285 LogFlowThisFunc(("Leaving hrc=%#x\n", hrc));
5286 return hrc;
5287}
5288
5289/**
5290 * @note Temporarily locks this object for writing.
5291 */
5292HRESULT Console::getGuestProperty(IN_BSTR aName, BSTR *aValue,
5293 LONG64 *aTimestamp, BSTR *aFlags)
5294{
5295#ifndef VBOX_WITH_GUEST_PROPS
5296 ReturnComNotImplemented();
5297#else /* VBOX_WITH_GUEST_PROPS */
5298 if (!VALID_PTR(aName))
5299 return E_INVALIDARG;
5300 if (!VALID_PTR(aValue))
5301 return E_POINTER;
5302 if ((aTimestamp != NULL) && !VALID_PTR(aTimestamp))
5303 return E_POINTER;
5304 if ((aFlags != NULL) && !VALID_PTR(aFlags))
5305 return E_POINTER;
5306
5307 AutoCaller autoCaller(this);
5308 AssertComRCReturnRC(autoCaller.rc());
5309
5310 /* protect mpUVM (if not NULL) */
5311 SafeVMPtrQuiet ptrVM(this);
5312 if (FAILED(ptrVM.rc()))
5313 return ptrVM.rc();
5314
5315 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
5316 * ptrVM, so there is no need to hold a lock of this */
5317
5318 HRESULT rc = E_UNEXPECTED;
5319 using namespace guestProp;
5320
5321 try
5322 {
5323 VBOXHGCMSVCPARM parm[4];
5324 Utf8Str Utf8Name = aName;
5325 char szBuffer[MAX_VALUE_LEN + MAX_FLAGS_LEN];
5326
5327 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
5328 parm[0].u.pointer.addr = (void*)Utf8Name.c_str();
5329 /* The + 1 is the null terminator */
5330 parm[0].u.pointer.size = (uint32_t)Utf8Name.length() + 1;
5331 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
5332 parm[1].u.pointer.addr = szBuffer;
5333 parm[1].u.pointer.size = sizeof(szBuffer);
5334 int vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", GET_PROP_HOST,
5335 4, &parm[0]);
5336 /* The returned string should never be able to be greater than our buffer */
5337 AssertLogRel(vrc != VERR_BUFFER_OVERFLOW);
5338 AssertLogRel(RT_FAILURE(vrc) || VBOX_HGCM_SVC_PARM_64BIT == parm[2].type);
5339 if (RT_SUCCESS(vrc) || (VERR_NOT_FOUND == vrc))
5340 {
5341 rc = S_OK;
5342 if (vrc != VERR_NOT_FOUND)
5343 {
5344 Utf8Str strBuffer(szBuffer);
5345 strBuffer.cloneTo(aValue);
5346
5347 if (aTimestamp)
5348 *aTimestamp = parm[2].u.uint64;
5349
5350 if (aFlags)
5351 {
5352 size_t iFlags = strBuffer.length() + 1;
5353 Utf8Str(szBuffer + iFlags).cloneTo(aFlags);
5354 }
5355 }
5356 else
5357 aValue = NULL;
5358 }
5359 else
5360 rc = setError(E_UNEXPECTED,
5361 tr("The service call failed with the error %Rrc"),
5362 vrc);
5363 }
5364 catch(std::bad_alloc & /*e*/)
5365 {
5366 rc = E_OUTOFMEMORY;
5367 }
5368 return rc;
5369#endif /* VBOX_WITH_GUEST_PROPS */
5370}
5371
5372/**
5373 * @note Temporarily locks this object for writing.
5374 */
5375HRESULT Console::setGuestProperty(IN_BSTR aName, IN_BSTR aValue, IN_BSTR aFlags)
5376{
5377#ifndef VBOX_WITH_GUEST_PROPS
5378 ReturnComNotImplemented();
5379#else /* VBOX_WITH_GUEST_PROPS */
5380 if (!RT_VALID_PTR(aName))
5381 return setError(E_INVALIDARG, tr("Name cannot be NULL or an invalid pointer"));
5382 if (aValue != NULL && !RT_VALID_PTR(aValue))
5383 return setError(E_INVALIDARG, tr("Invalid value pointer"));
5384 if (aFlags != NULL && !RT_VALID_PTR(aFlags))
5385 return setError(E_INVALIDARG, tr("Invalid flags pointer"));
5386
5387 AutoCaller autoCaller(this);
5388 AssertComRCReturnRC(autoCaller.rc());
5389
5390 /* protect mpUVM (if not NULL) */
5391 SafeVMPtrQuiet ptrVM(this);
5392 if (FAILED(ptrVM.rc()))
5393 return ptrVM.rc();
5394
5395 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
5396 * ptrVM, so there is no need to hold a lock of this */
5397
5398 using namespace guestProp;
5399
5400 VBOXHGCMSVCPARM parm[3];
5401
5402 Utf8Str Utf8Name = aName;
5403 parm[0].type = VBOX_HGCM_SVC_PARM_PTR;
5404 parm[0].u.pointer.addr = (void*)Utf8Name.c_str();
5405 /* The + 1 is the null terminator */
5406 parm[0].u.pointer.size = (uint32_t)Utf8Name.length() + 1;
5407
5408 Utf8Str Utf8Value;
5409 if (aValue != NULL)
5410 {
5411 Utf8Value = aValue;
5412 parm[1].type = VBOX_HGCM_SVC_PARM_PTR;
5413 parm[1].u.pointer.addr = (void *)Utf8Value.c_str();
5414 /* The + 1 is the null terminator */
5415 parm[1].u.pointer.size = (uint32_t)Utf8Value.length() + 1;
5416 }
5417
5418 Utf8Str Utf8Flags;
5419 if (aFlags != NULL)
5420 {
5421 Utf8Flags = aFlags;
5422 parm[2].type = VBOX_HGCM_SVC_PARM_PTR;
5423 parm[2].u.pointer.addr = (void*)Utf8Flags.c_str();
5424 /* The + 1 is the null terminator */
5425 parm[2].u.pointer.size = (uint32_t)Utf8Flags.length() + 1;
5426 }
5427
5428 int vrc;
5429 if (aValue != NULL && aFlags != NULL)
5430 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", SET_PROP_HOST,
5431 3, &parm[0]);
5432 else if (aValue != NULL)
5433 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", SET_PROP_VALUE_HOST,
5434 2, &parm[0]);
5435 else
5436 vrc = m_pVMMDev->hgcmHostCall("VBoxGuestPropSvc", DEL_PROP_HOST,
5437 1, &parm[0]);
5438 HRESULT hrc;
5439 if (RT_SUCCESS(vrc))
5440 hrc = S_OK;
5441 else
5442 hrc = setError(E_UNEXPECTED, tr("The service call failed with the error %Rrc"), vrc);
5443 return hrc;
5444#endif /* VBOX_WITH_GUEST_PROPS */
5445}
5446
5447
5448/**
5449 * @note Temporarily locks this object for writing.
5450 */
5451HRESULT Console::enumerateGuestProperties(IN_BSTR aPatterns,
5452 ComSafeArrayOut(BSTR, aNames),
5453 ComSafeArrayOut(BSTR, aValues),
5454 ComSafeArrayOut(LONG64, aTimestamps),
5455 ComSafeArrayOut(BSTR, aFlags))
5456{
5457#ifndef VBOX_WITH_GUEST_PROPS
5458 ReturnComNotImplemented();
5459#else /* VBOX_WITH_GUEST_PROPS */
5460 if (!VALID_PTR(aPatterns) && (aPatterns != NULL))
5461 return E_POINTER;
5462 if (ComSafeArrayOutIsNull(aNames))
5463 return E_POINTER;
5464 if (ComSafeArrayOutIsNull(aValues))
5465 return E_POINTER;
5466 if (ComSafeArrayOutIsNull(aTimestamps))
5467 return E_POINTER;
5468 if (ComSafeArrayOutIsNull(aFlags))
5469 return E_POINTER;
5470
5471 AutoCaller autoCaller(this);
5472 AssertComRCReturnRC(autoCaller.rc());
5473
5474 /* protect mpUVM (if not NULL) */
5475 AutoVMCallerWeak autoVMCaller(this);
5476 if (FAILED(autoVMCaller.rc()))
5477 return autoVMCaller.rc();
5478
5479 /* Note: validity of mVMMDev which is bound to uninit() is guaranteed by
5480 * autoVMCaller, so there is no need to hold a lock of this */
5481
5482 return doEnumerateGuestProperties(aPatterns, ComSafeArrayOutArg(aNames),
5483 ComSafeArrayOutArg(aValues),
5484 ComSafeArrayOutArg(aTimestamps),
5485 ComSafeArrayOutArg(aFlags));
5486#endif /* VBOX_WITH_GUEST_PROPS */
5487}
5488
5489
5490/*
5491 * Internal: helper function for connecting progress reporting
5492 */
5493static int onlineMergeMediumProgress(void *pvUser, unsigned uPercentage)
5494{
5495 HRESULT rc = S_OK;
5496 IProgress *pProgress = static_cast<IProgress *>(pvUser);
5497 if (pProgress)
5498 rc = pProgress->SetCurrentOperationProgress(uPercentage);
5499 return SUCCEEDED(rc) ? VINF_SUCCESS : VERR_GENERAL_FAILURE;
5500}
5501
5502/**
5503 * @note Temporarily locks this object for writing. bird: And/or reading?
5504 */
5505HRESULT Console::onlineMergeMedium(IMediumAttachment *aMediumAttachment,
5506 ULONG aSourceIdx, ULONG aTargetIdx,
5507 IProgress *aProgress)
5508{
5509 AutoCaller autoCaller(this);
5510 AssertComRCReturnRC(autoCaller.rc());
5511
5512 HRESULT rc = S_OK;
5513 int vrc = VINF_SUCCESS;
5514
5515 /* Get the VM - must be done before the read-locking. */
5516 SafeVMPtr ptrVM(this);
5517 if (!ptrVM.isOk())
5518 return ptrVM.rc();
5519
5520 /* We will need to release the lock before doing the actual merge */
5521 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5522
5523 /* paranoia - we don't want merges to happen while teleporting etc. */
5524 switch (mMachineState)
5525 {
5526 case MachineState_DeletingSnapshotOnline:
5527 case MachineState_DeletingSnapshotPaused:
5528 break;
5529
5530 default:
5531 return setInvalidMachineStateError();
5532 }
5533
5534 /** @todo AssertComRC -> AssertComRCReturn! Could potentially end up
5535 * using uninitialized variables here. */
5536 BOOL fBuiltinIOCache;
5537 rc = mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
5538 AssertComRC(rc);
5539 SafeIfaceArray<IStorageController> ctrls;
5540 rc = mMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));
5541 AssertComRC(rc);
5542 LONG lDev;
5543 rc = aMediumAttachment->COMGETTER(Device)(&lDev);
5544 AssertComRC(rc);
5545 LONG lPort;
5546 rc = aMediumAttachment->COMGETTER(Port)(&lPort);
5547 AssertComRC(rc);
5548 IMedium *pMedium;
5549 rc = aMediumAttachment->COMGETTER(Medium)(&pMedium);
5550 AssertComRC(rc);
5551 Bstr mediumLocation;
5552 if (pMedium)
5553 {
5554 rc = pMedium->COMGETTER(Location)(mediumLocation.asOutParam());
5555 AssertComRC(rc);
5556 }
5557
5558 Bstr attCtrlName;
5559 rc = aMediumAttachment->COMGETTER(Controller)(attCtrlName.asOutParam());
5560 AssertComRC(rc);
5561 ComPtr<IStorageController> pStorageController;
5562 for (size_t i = 0; i < ctrls.size(); ++i)
5563 {
5564 Bstr ctrlName;
5565 rc = ctrls[i]->COMGETTER(Name)(ctrlName.asOutParam());
5566 AssertComRC(rc);
5567 if (attCtrlName == ctrlName)
5568 {
5569 pStorageController = ctrls[i];
5570 break;
5571 }
5572 }
5573 if (pStorageController.isNull())
5574 return setError(E_FAIL,
5575 tr("Could not find storage controller '%ls'"),
5576 attCtrlName.raw());
5577
5578 StorageControllerType_T enmCtrlType;
5579 rc = pStorageController->COMGETTER(ControllerType)(&enmCtrlType);
5580 AssertComRC(rc);
5581 const char *pcszDevice = convertControllerTypeToDev(enmCtrlType);
5582
5583 StorageBus_T enmBus;
5584 rc = pStorageController->COMGETTER(Bus)(&enmBus);
5585 AssertComRC(rc);
5586 ULONG uInstance;
5587 rc = pStorageController->COMGETTER(Instance)(&uInstance);
5588 AssertComRC(rc);
5589 BOOL fUseHostIOCache;
5590 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
5591 AssertComRC(rc);
5592
5593 unsigned uLUN;
5594 rc = Console::convertBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);
5595 AssertComRCReturnRC(rc);
5596
5597 alock.release();
5598
5599 /* Pause the VM, as it might have pending IO on this drive */
5600 VMSTATE enmVMState = VMR3GetStateU(ptrVM.rawUVM());
5601 if (mMachineState == MachineState_DeletingSnapshotOnline)
5602 {
5603 LogFlowFunc(("Suspending the VM...\n"));
5604 /* disable the callback to prevent Console-level state change */
5605 mVMStateChangeCallbackDisabled = true;
5606 int vrc2 = VMR3Suspend(ptrVM.rawUVM(), VMSUSPENDREASON_RECONFIG);
5607 mVMStateChangeCallbackDisabled = false;
5608 AssertRCReturn(vrc2, E_FAIL);
5609 }
5610
5611 vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
5612 (PFNRT)reconfigureMediumAttachment, 13,
5613 this, ptrVM.rawUVM(), pcszDevice, uInstance, enmBus, fUseHostIOCache,
5614 fBuiltinIOCache, true /* fSetupMerge */, aSourceIdx, aTargetIdx,
5615 aMediumAttachment, mMachineState, &rc);
5616 /* error handling is after resuming the VM */
5617
5618 if (mMachineState == MachineState_DeletingSnapshotOnline)
5619 {
5620 LogFlowFunc(("Resuming the VM...\n"));
5621 /* disable the callback to prevent Console-level state change */
5622 mVMStateChangeCallbackDisabled = true;
5623 int vrc2 = VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_RECONFIG);
5624 mVMStateChangeCallbackDisabled = false;
5625 if (RT_FAILURE(vrc2))
5626 {
5627 /* too bad, we failed. try to sync the console state with the VMM state */
5628 AssertLogRelRC(vrc2);
5629 vmstateChangeCallback(ptrVM.rawUVM(), VMSTATE_SUSPENDED, enmVMState, this);
5630 }
5631 }
5632
5633 if (RT_FAILURE(vrc))
5634 return setError(E_FAIL, tr("%Rrc"), vrc);
5635 if (FAILED(rc))
5636 return rc;
5637
5638 PPDMIBASE pIBase = NULL;
5639 PPDMIMEDIA pIMedium = NULL;
5640 vrc = PDMR3QueryDriverOnLun(ptrVM.rawUVM(), pcszDevice, uInstance, uLUN, "VD", &pIBase);
5641 if (RT_SUCCESS(vrc))
5642 {
5643 if (pIBase)
5644 {
5645 pIMedium = (PPDMIMEDIA)pIBase->pfnQueryInterface(pIBase, PDMIMEDIA_IID);
5646 if (!pIMedium)
5647 return setError(E_FAIL, tr("could not query medium interface of controller"));
5648 }
5649 else
5650 return setError(E_FAIL, tr("could not query base interface of controller"));
5651 }
5652
5653 /* Finally trigger the merge. */
5654 vrc = pIMedium->pfnMerge(pIMedium, onlineMergeMediumProgress, aProgress);
5655 if (RT_FAILURE(vrc))
5656 return setError(E_FAIL, tr("Failed to perform an online medium merge (%Rrc)"), vrc);
5657
5658 /* Pause the VM, as it might have pending IO on this drive */
5659 enmVMState = VMR3GetStateU(ptrVM.rawUVM());
5660 if (mMachineState == MachineState_DeletingSnapshotOnline)
5661 {
5662 LogFlowFunc(("Suspending the VM...\n"));
5663 /* disable the callback to prevent Console-level state change */
5664 mVMStateChangeCallbackDisabled = true;
5665 int vrc2 = VMR3Suspend(ptrVM.rawUVM(), VMSUSPENDREASON_RECONFIG);
5666 mVMStateChangeCallbackDisabled = false;
5667 AssertRCReturn(vrc2, E_FAIL);
5668 }
5669
5670 /* Update medium chain and state now, so that the VM can continue. */
5671 rc = mControl->FinishOnlineMergeMedium();
5672
5673 vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
5674 (PFNRT)reconfigureMediumAttachment, 13,
5675 this, ptrVM.rawUVM(), pcszDevice, uInstance, enmBus, fUseHostIOCache,
5676 fBuiltinIOCache, false /* fSetupMerge */, 0 /* uMergeSource */,
5677 0 /* uMergeTarget */, aMediumAttachment, mMachineState, &rc);
5678 /* error handling is after resuming the VM */
5679
5680 if (mMachineState == MachineState_DeletingSnapshotOnline)
5681 {
5682 LogFlowFunc(("Resuming the VM...\n"));
5683 /* disable the callback to prevent Console-level state change */
5684 mVMStateChangeCallbackDisabled = true;
5685 int vrc2 = VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_RECONFIG);
5686 mVMStateChangeCallbackDisabled = false;
5687 AssertRC(vrc2);
5688 if (RT_FAILURE(vrc2))
5689 {
5690 /* too bad, we failed. try to sync the console state with the VMM state */
5691 vmstateChangeCallback(ptrVM.rawUVM(), VMSTATE_SUSPENDED, enmVMState, this);
5692 }
5693 }
5694
5695 if (RT_FAILURE(vrc))
5696 return setError(E_FAIL, tr("%Rrc"), vrc);
5697 if (FAILED(rc))
5698 return rc;
5699
5700 return rc;
5701}
5702
5703
5704/**
5705 * Load an HGCM service.
5706 *
5707 * Main purpose of this method is to allow extension packs to load HGCM
5708 * service modules, which they can't, because the HGCM functionality lives
5709 * in module VBoxC (and ConsoleImpl.cpp is part of it and thus can call it).
5710 * Extension modules must not link directly against VBoxC, (XP)COM is
5711 * handling this.
5712 */
5713int Console::hgcmLoadService(const char *pszServiceLibrary, const char *pszServiceName)
5714{
5715 /* Everyone seems to delegate all HGCM calls to VMMDev, so stick to this
5716 * convention. Adds one level of indirection for no obvious reason. */
5717 AssertPtrReturn(m_pVMMDev, VERR_INVALID_STATE);
5718 return m_pVMMDev->hgcmLoadService(pszServiceLibrary, pszServiceName);
5719}
5720
5721/**
5722 * Merely passes the call to Guest::enableVMMStatistics().
5723 */
5724void Console::enableVMMStatistics(BOOL aEnable)
5725{
5726 if (mGuest)
5727 mGuest->enableVMMStatistics(aEnable);
5728}
5729
5730/**
5731 * Worker for Console::Pause and internal entry point for pausing a VM for
5732 * a specific reason.
5733 */
5734HRESULT Console::pause(Reason_T aReason)
5735{
5736 LogFlowThisFuncEnter();
5737
5738 AutoCaller autoCaller(this);
5739 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5740
5741 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5742
5743 switch (mMachineState)
5744 {
5745 case MachineState_Running:
5746 case MachineState_Teleporting:
5747 case MachineState_LiveSnapshotting:
5748 break;
5749
5750 case MachineState_Paused:
5751 case MachineState_TeleportingPausedVM:
5752 case MachineState_Saving:
5753 return setError(VBOX_E_INVALID_VM_STATE, tr("Already paused"));
5754
5755 default:
5756 return setInvalidMachineStateError();
5757 }
5758
5759 /* get the VM handle. */
5760 SafeVMPtr ptrVM(this);
5761 if (!ptrVM.isOk())
5762 return ptrVM.rc();
5763
5764 /* release the lock before a VMR3* call (EMT will call us back)! */
5765 alock.release();
5766
5767 LogFlowThisFunc(("Sending PAUSE request...\n"));
5768 if (aReason != Reason_Unspecified)
5769 LogRel(("Pausing VM execution, reason \"%s\"\n", Global::stringifyReason(aReason)));
5770
5771 /** @todo r=klaus make use of aReason */
5772 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
5773 if (aReason == Reason_HostSuspend)
5774 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
5775 else if (aReason == Reason_HostBatteryLow)
5776 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
5777 int vrc = VMR3Suspend(ptrVM.rawUVM(), enmReason);
5778
5779 HRESULT hrc = S_OK;
5780 if (RT_FAILURE(vrc))
5781 hrc = setError(VBOX_E_VM_ERROR, tr("Could not suspend the machine execution (%Rrc)"), vrc);
5782
5783 LogFlowThisFunc(("hrc=%Rhrc\n", hrc));
5784 LogFlowThisFuncLeave();
5785 return hrc;
5786}
5787
5788/**
5789 * Worker for Console::Resume and internal entry point for resuming a VM for
5790 * a specific reason.
5791 */
5792HRESULT Console::resume(Reason_T aReason)
5793{
5794 LogFlowThisFuncEnter();
5795
5796 AutoCaller autoCaller(this);
5797 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5798
5799 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5800
5801 if (mMachineState != MachineState_Paused)
5802 return setError(VBOX_E_INVALID_VM_STATE,
5803 tr("Cannot resume the machine as it is not paused (machine state: %s)"),
5804 Global::stringifyMachineState(mMachineState));
5805
5806 /* get the VM handle. */
5807 SafeVMPtr ptrVM(this);
5808 if (!ptrVM.isOk())
5809 return ptrVM.rc();
5810
5811 /* release the lock before a VMR3* call (EMT will call us back)! */
5812 alock.release();
5813
5814 LogFlowThisFunc(("Sending RESUME request...\n"));
5815 if (aReason != Reason_Unspecified)
5816 LogRel(("Resuming VM execution, reason \"%s\"\n", Global::stringifyReason(aReason)));
5817
5818 int vrc;
5819 if (VMR3GetStateU(ptrVM.rawUVM()) == VMSTATE_CREATED)
5820 {
5821#ifdef VBOX_WITH_EXTPACK
5822 vrc = mptrExtPackManager->callAllVmPowerOnHooks(this, VMR3GetVM(ptrVM.rawUVM()));
5823#else
5824 vrc = VINF_SUCCESS;
5825#endif
5826 if (RT_SUCCESS(vrc))
5827 vrc = VMR3PowerOn(ptrVM.rawUVM()); /* (PowerUpPaused) */
5828 }
5829 else
5830 {
5831 VMRESUMEREASON enmReason = VMRESUMEREASON_USER;
5832 if (aReason == Reason_HostResume)
5833 enmReason = VMRESUMEREASON_HOST_RESUME;
5834 vrc = VMR3Resume(ptrVM.rawUVM(), enmReason);
5835 }
5836
5837 HRESULT rc = RT_SUCCESS(vrc) ? S_OK :
5838 setError(VBOX_E_VM_ERROR,
5839 tr("Could not resume the machine execution (%Rrc)"),
5840 vrc);
5841
5842 LogFlowThisFunc(("rc=%Rhrc\n", rc));
5843 LogFlowThisFuncLeave();
5844 return rc;
5845}
5846
5847/**
5848 * Worker for Console::SaveState and internal entry point for saving state of
5849 * a VM for a specific reason.
5850 */
5851HRESULT Console::saveState(Reason_T aReason, IProgress **aProgress)
5852{
5853 LogFlowThisFuncEnter();
5854
5855 CheckComArgOutPointerValid(aProgress);
5856
5857 AutoCaller autoCaller(this);
5858 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5859
5860 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5861
5862 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
5863 if ( mMachineState != MachineState_Running
5864 && mMachineState != MachineState_Paused)
5865 {
5866 return setError(VBOX_E_INVALID_VM_STATE,
5867 tr("Cannot save the execution state as the machine is not running or paused (machine state: %s)"),
5868 Global::stringifyMachineState(mMachineState));
5869 }
5870
5871 if (aReason != Reason_Unspecified)
5872 LogRel(("Saving state of VM, reason \"%s\"\n", Global::stringifyReason(aReason)));
5873
5874 /* memorize the current machine state */
5875 MachineState_T lastMachineState = mMachineState;
5876
5877 if (mMachineState == MachineState_Running)
5878 {
5879 /* get the VM handle. */
5880 SafeVMPtr ptrVM(this);
5881 if (!ptrVM.isOk())
5882 return ptrVM.rc();
5883
5884 /* release the lock before a VMR3* call (EMT will call us back)! */
5885 alock.release();
5886 VMSUSPENDREASON enmReason = VMSUSPENDREASON_USER;
5887 if (aReason == Reason_HostSuspend)
5888 enmReason = VMSUSPENDREASON_HOST_SUSPEND;
5889 else if (aReason == Reason_HostBatteryLow)
5890 enmReason = VMSUSPENDREASON_HOST_BATTERY_LOW;
5891 int vrc = VMR3Suspend(ptrVM.rawUVM(), enmReason);
5892 alock.acquire();
5893
5894 HRESULT hrc = S_OK;
5895 if (RT_FAILURE(vrc))
5896 hrc = setError(VBOX_E_VM_ERROR, tr("Could not suspend the machine execution (%Rrc)"), vrc);
5897 if (FAILED(hrc))
5898 return hrc;
5899 }
5900
5901 HRESULT rc = S_OK;
5902 bool fBeganSavingState = false;
5903 bool fTaskCreationFailed = false;
5904
5905 do
5906 {
5907 ComPtr<IProgress> pProgress;
5908 Bstr stateFilePath;
5909
5910 /*
5911 * request a saved state file path from the server
5912 * (this will set the machine state to Saving on the server to block
5913 * others from accessing this machine)
5914 */
5915 rc = mControl->BeginSavingState(pProgress.asOutParam(),
5916 stateFilePath.asOutParam());
5917 if (FAILED(rc))
5918 break;
5919
5920 fBeganSavingState = true;
5921
5922 /* sync the state with the server */
5923 setMachineStateLocally(MachineState_Saving);
5924
5925 /* ensure the directory for the saved state file exists */
5926 {
5927 Utf8Str dir = stateFilePath;
5928 dir.stripFilename();
5929 if (!RTDirExists(dir.c_str()))
5930 {
5931 int vrc = RTDirCreateFullPath(dir.c_str(), 0700);
5932 if (RT_FAILURE(vrc))
5933 {
5934 rc = setError(VBOX_E_FILE_ERROR,
5935 tr("Could not create a directory '%s' to save the state to (%Rrc)"),
5936 dir.c_str(), vrc);
5937 break;
5938 }
5939 }
5940 }
5941
5942 /* Create a task object early to ensure mpUVM protection is successful. */
5943 std::auto_ptr<VMSaveTask> task(new VMSaveTask(this, pProgress,
5944 stateFilePath,
5945 lastMachineState,
5946 aReason));
5947 rc = task->rc();
5948 /*
5949 * If we fail here it means a PowerDown() call happened on another
5950 * thread while we were doing Pause() (which releases the Console lock).
5951 * We assign PowerDown() a higher precedence than SaveState(),
5952 * therefore just return the error to the caller.
5953 */
5954 if (FAILED(rc))
5955 {
5956 fTaskCreationFailed = true;
5957 break;
5958 }
5959
5960 /* create a thread to wait until the VM state is saved */
5961 int vrc = RTThreadCreate(NULL, Console::saveStateThread, (void *)task.get(),
5962 0, RTTHREADTYPE_MAIN_WORKER, 0, "VMSave");
5963 if (RT_FAILURE(vrc))
5964 {
5965 rc = setError(E_FAIL, "Could not create VMSave thread (%Rrc)", vrc);
5966 break;
5967 }
5968
5969 /* task is now owned by saveStateThread(), so release it */
5970 task.release();
5971
5972 /* return the progress to the caller */
5973 pProgress.queryInterfaceTo(aProgress);
5974 } while (0);
5975
5976 if (FAILED(rc) && !fTaskCreationFailed)
5977 {
5978 /* preserve existing error info */
5979 ErrorInfoKeeper eik;
5980
5981 if (fBeganSavingState)
5982 {
5983 /*
5984 * cancel the requested save state procedure.
5985 * This will reset the machine state to the state it had right
5986 * before calling mControl->BeginSavingState().
5987 */
5988 mControl->EndSavingState(eik.getResultCode(), eik.getText().raw());
5989 }
5990
5991 if (lastMachineState == MachineState_Running)
5992 {
5993 /* restore the paused state if appropriate */
5994 setMachineStateLocally(MachineState_Paused);
5995 /* restore the running state if appropriate */
5996 SafeVMPtr ptrVM(this);
5997 if (ptrVM.isOk())
5998 {
5999 alock.release();
6000 VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_STATE_RESTORED);
6001 alock.acquire();
6002 }
6003 }
6004 else
6005 setMachineStateLocally(lastMachineState);
6006 }
6007
6008 LogFlowThisFunc(("rc=%Rhrc\n", rc));
6009 LogFlowThisFuncLeave();
6010 return rc;
6011}
6012
6013/**
6014 * Gets called by Session::UpdateMachineState()
6015 * (IInternalSessionControl::updateMachineState()).
6016 *
6017 * Must be called only in certain cases (see the implementation).
6018 *
6019 * @note Locks this object for writing.
6020 */
6021HRESULT Console::updateMachineState(MachineState_T aMachineState)
6022{
6023 AutoCaller autoCaller(this);
6024 AssertComRCReturnRC(autoCaller.rc());
6025
6026 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6027
6028 AssertReturn( mMachineState == MachineState_Saving
6029 || mMachineState == MachineState_LiveSnapshotting
6030 || mMachineState == MachineState_RestoringSnapshot
6031 || mMachineState == MachineState_DeletingSnapshot
6032 || mMachineState == MachineState_DeletingSnapshotOnline
6033 || mMachineState == MachineState_DeletingSnapshotPaused
6034 , E_FAIL);
6035
6036 return setMachineStateLocally(aMachineState);
6037}
6038
6039#ifdef CONSOLE_WITH_EVENT_CACHE
6040/**
6041 * @note Locks this object for writing.
6042 */
6043#endif
6044void Console::onMousePointerShapeChange(bool fVisible, bool fAlpha,
6045 uint32_t xHot, uint32_t yHot,
6046 uint32_t width, uint32_t height,
6047 ComSafeArrayIn(BYTE,pShape))
6048{
6049#if 0
6050 LogFlowThisFuncEnter();
6051 LogFlowThisFunc(("fVisible=%d, fAlpha=%d, xHot = %d, yHot = %d, width=%d, height=%d, shape=%p\n",
6052 fVisible, fAlpha, xHot, yHot, width, height, pShape));
6053#endif
6054
6055 AutoCaller autoCaller(this);
6056 AssertComRCReturnVoid(autoCaller.rc());
6057
6058#ifdef CONSOLE_WITH_EVENT_CACHE
6059 {
6060 /* We need a write lock because we alter the cached callback data */
6061 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6062
6063 /* Save the callback arguments */
6064 mCallbackData.mpsc.visible = fVisible;
6065 mCallbackData.mpsc.alpha = fAlpha;
6066 mCallbackData.mpsc.xHot = xHot;
6067 mCallbackData.mpsc.yHot = yHot;
6068 mCallbackData.mpsc.width = width;
6069 mCallbackData.mpsc.height = height;
6070
6071 /* start with not valid */
6072 bool wasValid = mCallbackData.mpsc.valid;
6073 mCallbackData.mpsc.valid = false;
6074
6075 com::SafeArray<BYTE> aShape(ComSafeArrayInArg(pShape));
6076 if (aShape.size() != 0)
6077 mCallbackData.mpsc.shape.initFrom(aShape);
6078 else
6079 mCallbackData.mpsc.shape.resize(0);
6080 mCallbackData.mpsc.valid = true;
6081 }
6082#endif
6083
6084 fireMousePointerShapeChangedEvent(mEventSource, fVisible, fAlpha, xHot, yHot, width, height, ComSafeArrayInArg(pShape));
6085
6086#if 0
6087 LogFlowThisFuncLeave();
6088#endif
6089}
6090
6091#ifdef CONSOLE_WITH_EVENT_CACHE
6092/**
6093 * @note Locks this object for writing.
6094 */
6095#endif
6096void Console::onMouseCapabilityChange(BOOL supportsAbsolute, BOOL supportsRelative,
6097 BOOL supportsMT, BOOL needsHostCursor)
6098{
6099 LogFlowThisFunc(("supportsAbsolute=%d supportsRelative=%d needsHostCursor=%d\n",
6100 supportsAbsolute, supportsRelative, needsHostCursor));
6101
6102 AutoCaller autoCaller(this);
6103 AssertComRCReturnVoid(autoCaller.rc());
6104
6105#ifdef CONSOLE_WITH_EVENT_CACHE
6106 {
6107 /* We need a write lock because we alter the cached callback data */
6108 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6109
6110 /* save the callback arguments */
6111 mCallbackData.mcc.supportsAbsolute = supportsAbsolute;
6112 mCallbackData.mcc.supportsRelative = supportsRelative;
6113 mCallbackData.mcc.needsHostCursor = needsHostCursor;
6114 mCallbackData.mcc.valid = true;
6115 }
6116#endif
6117
6118 fireMouseCapabilityChangedEvent(mEventSource, supportsAbsolute, supportsRelative, supportsMT, needsHostCursor);
6119}
6120
6121void Console::onStateChange(MachineState_T machineState)
6122{
6123 AutoCaller autoCaller(this);
6124 AssertComRCReturnVoid(autoCaller.rc());
6125 fireStateChangedEvent(mEventSource, machineState);
6126}
6127
6128void Console::onAdditionsStateChange()
6129{
6130 AutoCaller autoCaller(this);
6131 AssertComRCReturnVoid(autoCaller.rc());
6132
6133 fireAdditionsStateChangedEvent(mEventSource);
6134}
6135
6136/**
6137 * @remarks This notification only is for reporting an incompatible
6138 * Guest Additions interface, *not* the Guest Additions version!
6139 *
6140 * The user will be notified inside the guest if new Guest
6141 * Additions are available (via VBoxTray/VBoxClient).
6142 */
6143void Console::onAdditionsOutdated()
6144{
6145 AutoCaller autoCaller(this);
6146 AssertComRCReturnVoid(autoCaller.rc());
6147
6148 /** @todo implement this */
6149}
6150
6151#ifdef CONSOLE_WITH_EVENT_CACHE
6152/**
6153 * @note Locks this object for writing.
6154 */
6155#endif
6156void Console::onKeyboardLedsChange(bool fNumLock, bool fCapsLock, bool fScrollLock)
6157{
6158 AutoCaller autoCaller(this);
6159 AssertComRCReturnVoid(autoCaller.rc());
6160
6161#ifdef CONSOLE_WITH_EVENT_CACHE
6162 {
6163 /* We need a write lock because we alter the cached callback data */
6164 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6165
6166 /* save the callback arguments */
6167 mCallbackData.klc.numLock = fNumLock;
6168 mCallbackData.klc.capsLock = fCapsLock;
6169 mCallbackData.klc.scrollLock = fScrollLock;
6170 mCallbackData.klc.valid = true;
6171 }
6172#endif
6173
6174 fireKeyboardLedsChangedEvent(mEventSource, fNumLock, fCapsLock, fScrollLock);
6175}
6176
6177void Console::onUSBDeviceStateChange(IUSBDevice *aDevice, bool aAttached,
6178 IVirtualBoxErrorInfo *aError)
6179{
6180 AutoCaller autoCaller(this);
6181 AssertComRCReturnVoid(autoCaller.rc());
6182
6183 fireUSBDeviceStateChangedEvent(mEventSource, aDevice, aAttached, aError);
6184}
6185
6186void Console::onRuntimeError(BOOL aFatal, IN_BSTR aErrorID, IN_BSTR aMessage)
6187{
6188 AutoCaller autoCaller(this);
6189 AssertComRCReturnVoid(autoCaller.rc());
6190
6191 fireRuntimeErrorEvent(mEventSource, aFatal, aErrorID, aMessage);
6192}
6193
6194HRESULT Console::onShowWindow(BOOL aCheck, BOOL *aCanShow, LONG64 *aWinId)
6195{
6196 AssertReturn(aCanShow, E_POINTER);
6197 AssertReturn(aWinId, E_POINTER);
6198
6199 *aCanShow = FALSE;
6200 *aWinId = 0;
6201
6202 AutoCaller autoCaller(this);
6203 AssertComRCReturnRC(autoCaller.rc());
6204
6205 VBoxEventDesc evDesc;
6206 if (aCheck)
6207 {
6208 evDesc.init(mEventSource, VBoxEventType_OnCanShowWindow);
6209 BOOL fDelivered = evDesc.fire(5000); /* Wait up to 5 secs for delivery */
6210 //Assert(fDelivered);
6211 if (fDelivered)
6212 {
6213 ComPtr<IEvent> pEvent;
6214 evDesc.getEvent(pEvent.asOutParam());
6215 // bit clumsy
6216 ComPtr<ICanShowWindowEvent> pCanShowEvent = pEvent;
6217 if (pCanShowEvent)
6218 {
6219 BOOL fVetoed = FALSE;
6220 pCanShowEvent->IsVetoed(&fVetoed);
6221 *aCanShow = !fVetoed;
6222 }
6223 else
6224 {
6225 AssertFailed();
6226 *aCanShow = TRUE;
6227 }
6228 }
6229 else
6230 *aCanShow = TRUE;
6231 }
6232 else
6233 {
6234 evDesc.init(mEventSource, VBoxEventType_OnShowWindow, INT64_C(0));
6235 BOOL fDelivered = evDesc.fire(5000); /* Wait up to 5 secs for delivery */
6236 //Assert(fDelivered);
6237 if (fDelivered)
6238 {
6239 ComPtr<IEvent> pEvent;
6240 evDesc.getEvent(pEvent.asOutParam());
6241 ComPtr<IShowWindowEvent> pShowEvent = pEvent;
6242 if (pShowEvent)
6243 {
6244 LONG64 iEvWinId = 0;
6245 pShowEvent->COMGETTER(WinId)(&iEvWinId);
6246 if (iEvWinId != 0 && *aWinId == 0)
6247 *aWinId = iEvWinId;
6248 }
6249 else
6250 AssertFailed();
6251 }
6252 }
6253
6254 return S_OK;
6255}
6256
6257// private methods
6258////////////////////////////////////////////////////////////////////////////////
6259
6260/**
6261 * Increases the usage counter of the mpUVM pointer.
6262 *
6263 * Guarantees that VMR3Destroy() will not be called on it at least until
6264 * releaseVMCaller() is called.
6265 *
6266 * If this method returns a failure, the caller is not allowed to use mpUVM and
6267 * may return the failed result code to the upper level. This method sets the
6268 * extended error info on failure if \a aQuiet is false.
6269 *
6270 * Setting \a aQuiet to true is useful for methods that don't want to return
6271 * the failed result code to the caller when this method fails (e.g. need to
6272 * silently check for the mpUVM availability).
6273 *
6274 * When mpUVM is NULL but \a aAllowNullVM is true, a corresponding error will be
6275 * returned instead of asserting. Having it false is intended as a sanity check
6276 * for methods that have checked mMachineState and expect mpUVM *NOT* to be
6277 * NULL.
6278 *
6279 * @param aQuiet true to suppress setting error info
6280 * @param aAllowNullVM true to accept mpUVM being NULL and return a failure
6281 * (otherwise this method will assert if mpUVM is NULL)
6282 *
6283 * @note Locks this object for writing.
6284 */
6285HRESULT Console::addVMCaller(bool aQuiet /* = false */,
6286 bool aAllowNullVM /* = false */)
6287{
6288 AutoCaller autoCaller(this);
6289 /** @todo Fix race during console/VM reference destruction, refer @bugref{6318}
6290 * comment 25. */
6291 if (FAILED(autoCaller.rc()))
6292 return autoCaller.rc();
6293
6294 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6295
6296 if (mVMDestroying)
6297 {
6298 /* powerDown() is waiting for all callers to finish */
6299 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED,
6300 tr("The virtual machine is being powered down"));
6301 }
6302
6303 if (mpUVM == NULL)
6304 {
6305 Assert(aAllowNullVM == true);
6306
6307 /* The machine is not powered up */
6308 return aQuiet ? E_ACCESSDENIED : setError(E_ACCESSDENIED,
6309 tr("The virtual machine is not powered up"));
6310 }
6311
6312 ++mVMCallers;
6313
6314 return S_OK;
6315}
6316
6317/**
6318 * Decreases the usage counter of the mpUVM pointer.
6319 *
6320 * Must always complete the addVMCaller() call after the mpUVM pointer is no
6321 * more necessary.
6322 *
6323 * @note Locks this object for writing.
6324 */
6325void Console::releaseVMCaller()
6326{
6327 AutoCaller autoCaller(this);
6328 AssertComRCReturnVoid(autoCaller.rc());
6329
6330 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6331
6332 AssertReturnVoid(mpUVM != NULL);
6333
6334 Assert(mVMCallers > 0);
6335 --mVMCallers;
6336
6337 if (mVMCallers == 0 && mVMDestroying)
6338 {
6339 /* inform powerDown() there are no more callers */
6340 RTSemEventSignal(mVMZeroCallersSem);
6341 }
6342}
6343
6344
6345HRESULT Console::safeVMPtrRetainer(PUVM *a_ppUVM, bool a_Quiet)
6346{
6347 *a_ppUVM = NULL;
6348
6349 AutoCaller autoCaller(this);
6350 AssertComRCReturnRC(autoCaller.rc());
6351 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6352
6353 /*
6354 * Repeat the checks done by addVMCaller.
6355 */
6356 if (mVMDestroying) /* powerDown() is waiting for all callers to finish */
6357 return a_Quiet
6358 ? E_ACCESSDENIED
6359 : setError(E_ACCESSDENIED, tr("The virtual machine is being powered down"));
6360 PUVM pUVM = mpUVM;
6361 if (!pUVM)
6362 return a_Quiet
6363 ? E_ACCESSDENIED
6364 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
6365
6366 /*
6367 * Retain a reference to the user mode VM handle and get the global handle.
6368 */
6369 uint32_t cRefs = VMR3RetainUVM(pUVM);
6370 if (cRefs == UINT32_MAX)
6371 return a_Quiet
6372 ? E_ACCESSDENIED
6373 : setError(E_ACCESSDENIED, tr("The virtual machine is powered off"));
6374
6375 /* done */
6376 *a_ppUVM = pUVM;
6377 return S_OK;
6378}
6379
6380void Console::safeVMPtrReleaser(PUVM *a_ppUVM)
6381{
6382 if (*a_ppUVM)
6383 VMR3ReleaseUVM(*a_ppUVM);
6384 *a_ppUVM = NULL;
6385}
6386
6387
6388/**
6389 * Initialize the release logging facility. In case something
6390 * goes wrong, there will be no release logging. Maybe in the future
6391 * we can add some logic to use different file names in this case.
6392 * Note that the logic must be in sync with Machine::DeleteSettings().
6393 */
6394HRESULT Console::consoleInitReleaseLog(const ComPtr<IMachine> aMachine)
6395{
6396 HRESULT hrc = S_OK;
6397
6398 Bstr logFolder;
6399 hrc = aMachine->COMGETTER(LogFolder)(logFolder.asOutParam());
6400 if (FAILED(hrc))
6401 return hrc;
6402
6403 Utf8Str logDir = logFolder;
6404
6405 /* make sure the Logs folder exists */
6406 Assert(logDir.length());
6407 if (!RTDirExists(logDir.c_str()))
6408 RTDirCreateFullPath(logDir.c_str(), 0700);
6409
6410 Utf8Str logFile = Utf8StrFmt("%s%cVBox.log",
6411 logDir.c_str(), RTPATH_DELIMITER);
6412 Utf8Str pngFile = Utf8StrFmt("%s%cVBox.png",
6413 logDir.c_str(), RTPATH_DELIMITER);
6414
6415 /*
6416 * Age the old log files
6417 * Rename .(n-1) to .(n), .(n-2) to .(n-1), ..., and the last log file to .1
6418 * Overwrite target files in case they exist.
6419 */
6420 ComPtr<IVirtualBox> pVirtualBox;
6421 aMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
6422 ComPtr<ISystemProperties> pSystemProperties;
6423 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
6424 ULONG cHistoryFiles = 3;
6425 pSystemProperties->COMGETTER(LogHistoryCount)(&cHistoryFiles);
6426 if (cHistoryFiles)
6427 {
6428 for (int i = cHistoryFiles-1; i >= 0; i--)
6429 {
6430 Utf8Str *files[] = { &logFile, &pngFile };
6431 Utf8Str oldName, newName;
6432
6433 for (unsigned int j = 0; j < RT_ELEMENTS(files); ++j)
6434 {
6435 if (i > 0)
6436 oldName = Utf8StrFmt("%s.%d", files[j]->c_str(), i);
6437 else
6438 oldName = *files[j];
6439 newName = Utf8StrFmt("%s.%d", files[j]->c_str(), i + 1);
6440 /* If the old file doesn't exist, delete the new file (if it
6441 * exists) to provide correct rotation even if the sequence is
6442 * broken */
6443 if ( RTFileRename(oldName.c_str(), newName.c_str(), RTFILEMOVE_FLAGS_REPLACE)
6444 == VERR_FILE_NOT_FOUND)
6445 RTFileDelete(newName.c_str());
6446 }
6447 }
6448 }
6449
6450 char szError[RTPATH_MAX + 128];
6451 int vrc = com::VBoxLogRelCreate("VM", logFile.c_str(),
6452 RTLOGFLAGS_PREFIX_TIME_PROG | RTLOGFLAGS_RESTRICT_GROUPS,
6453 "all all.restrict -default.restrict",
6454 "VBOX_RELEASE_LOG", RTLOGDEST_FILE,
6455 32768 /* cMaxEntriesPerGroup */,
6456 0 /* cHistory */, 0 /* uHistoryFileTime */,
6457 0 /* uHistoryFileSize */, szError, sizeof(szError));
6458 if (RT_FAILURE(vrc))
6459 hrc = setError(E_FAIL, tr("Failed to open release log (%s, %Rrc)"),
6460 szError, vrc);
6461
6462 /* If we've made any directory changes, flush the directory to increase
6463 the likelihood that the log file will be usable after a system panic.
6464
6465 Tip: Try 'export VBOX_RELEASE_LOG_FLAGS=flush' if the last bits of the log
6466 is missing. Just don't have too high hopes for this to help. */
6467 if (SUCCEEDED(hrc) || cHistoryFiles)
6468 RTDirFlush(logDir.c_str());
6469
6470 return hrc;
6471}
6472
6473/**
6474 * Common worker for PowerUp and PowerUpPaused.
6475 *
6476 * @returns COM status code.
6477 *
6478 * @param aProgress Where to return the progress object.
6479 * @param aPaused true if PowerUpPaused called.
6480 */
6481HRESULT Console::powerUp(IProgress **aProgress, bool aPaused)
6482{
6483
6484 LogFlowThisFuncEnter();
6485
6486 CheckComArgOutPointerValid(aProgress);
6487
6488 AutoCaller autoCaller(this);
6489 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6490
6491 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6492
6493 LogFlowThisFunc(("mMachineState=%d\n", mMachineState));
6494 HRESULT rc = S_OK;
6495 ComObjPtr<Progress> pPowerupProgress;
6496 bool fBeganPoweringUp = false;
6497
6498 LONG cOperations = 1;
6499 LONG ulTotalOperationsWeight = 1;
6500
6501 try
6502 {
6503
6504 if (Global::IsOnlineOrTransient(mMachineState))
6505 throw setError(VBOX_E_INVALID_VM_STATE,
6506 tr("The virtual machine is already running or busy (machine state: %s)"),
6507 Global::stringifyMachineState(mMachineState));
6508
6509 /* Set up release logging as early as possible after the check if
6510 * there is already a running VM which we shouldn't disturb. */
6511 rc = consoleInitReleaseLog(mMachine);
6512 if (FAILED(rc))
6513 throw rc;
6514
6515 /* test and clear the TeleporterEnabled property */
6516 BOOL fTeleporterEnabled;
6517 rc = mMachine->COMGETTER(TeleporterEnabled)(&fTeleporterEnabled);
6518 if (FAILED(rc))
6519 throw rc;
6520
6521#if 0 /** @todo we should save it afterwards, but that isn't necessarily a good idea. Find a better place for this (VBoxSVC). */
6522 if (fTeleporterEnabled)
6523 {
6524 rc = mMachine->COMSETTER(TeleporterEnabled)(FALSE);
6525 if (FAILED(rc))
6526 throw rc;
6527 }
6528#endif
6529
6530 /* test the FaultToleranceState property */
6531 FaultToleranceState_T enmFaultToleranceState;
6532 rc = mMachine->COMGETTER(FaultToleranceState)(&enmFaultToleranceState);
6533 if (FAILED(rc))
6534 throw rc;
6535 BOOL fFaultToleranceSyncEnabled = (enmFaultToleranceState == FaultToleranceState_Standby);
6536
6537 /* Create a progress object to track progress of this operation. Must
6538 * be done as early as possible (together with BeginPowerUp()) as this
6539 * is vital for communicating as much as possible early powerup
6540 * failure information to the API caller */
6541 pPowerupProgress.createObject();
6542 Bstr progressDesc;
6543 if (mMachineState == MachineState_Saved)
6544 progressDesc = tr("Restoring virtual machine");
6545 else if (fTeleporterEnabled)
6546 progressDesc = tr("Teleporting virtual machine");
6547 else if (fFaultToleranceSyncEnabled)
6548 progressDesc = tr("Fault Tolerance syncing of remote virtual machine");
6549 else
6550 progressDesc = tr("Starting virtual machine");
6551
6552 Bstr savedStateFile;
6553
6554 /*
6555 * Saved VMs will have to prove that their saved states seem kosher.
6556 */
6557 if (mMachineState == MachineState_Saved)
6558 {
6559 rc = mMachine->COMGETTER(StateFilePath)(savedStateFile.asOutParam());
6560 if (FAILED(rc))
6561 throw rc;
6562 ComAssertRet(!savedStateFile.isEmpty(), E_FAIL);
6563 int vrc = SSMR3ValidateFile(Utf8Str(savedStateFile).c_str(), false /* fChecksumIt */);
6564 if (RT_FAILURE(vrc))
6565 throw setError(VBOX_E_FILE_ERROR,
6566 tr("VM cannot start because the saved state file '%ls' is invalid (%Rrc). Delete the saved state prior to starting the VM"),
6567 savedStateFile.raw(), vrc);
6568 }
6569
6570 /* Read console data, including console shared folders, stored in the
6571 * saved state file (if not yet done).
6572 */
6573 rc = loadDataFromSavedState();
6574 if (FAILED(rc))
6575 throw rc;
6576
6577 /* Check all types of shared folders and compose a single list */
6578 SharedFolderDataMap sharedFolders;
6579 {
6580 /* first, insert global folders */
6581 for (SharedFolderDataMap::const_iterator it = m_mapGlobalSharedFolders.begin();
6582 it != m_mapGlobalSharedFolders.end();
6583 ++it)
6584 {
6585 const SharedFolderData &d = it->second;
6586 sharedFolders[it->first] = d;
6587 }
6588
6589 /* second, insert machine folders */
6590 for (SharedFolderDataMap::const_iterator it = m_mapMachineSharedFolders.begin();
6591 it != m_mapMachineSharedFolders.end();
6592 ++it)
6593 {
6594 const SharedFolderData &d = it->second;
6595 sharedFolders[it->first] = d;
6596 }
6597
6598 /* third, insert console folders */
6599 for (SharedFolderMap::const_iterator it = m_mapSharedFolders.begin();
6600 it != m_mapSharedFolders.end();
6601 ++it)
6602 {
6603 SharedFolder *pSF = it->second;
6604 AutoCaller sfCaller(pSF);
6605 AutoReadLock sfLock(pSF COMMA_LOCKVAL_SRC_POS);
6606 sharedFolders[it->first] = SharedFolderData(pSF->getHostPath(),
6607 pSF->isWritable(),
6608 pSF->isAutoMounted());
6609 }
6610 }
6611
6612 /* Setup task object and thread to carry out the operaton
6613 * Asycnhronously */
6614 std::auto_ptr<VMPowerUpTask> task(new VMPowerUpTask(this, pPowerupProgress));
6615 ComAssertComRCRetRC(task->rc());
6616
6617 task->mConfigConstructor = configConstructor;
6618 task->mSharedFolders = sharedFolders;
6619 task->mStartPaused = aPaused;
6620 if (mMachineState == MachineState_Saved)
6621 task->mSavedStateFile = savedStateFile;
6622 task->mTeleporterEnabled = fTeleporterEnabled;
6623 task->mEnmFaultToleranceState = enmFaultToleranceState;
6624
6625 /* Reset differencing hard disks for which autoReset is true,
6626 * but only if the machine has no snapshots OR the current snapshot
6627 * is an OFFLINE snapshot; otherwise we would reset the current
6628 * differencing image of an ONLINE snapshot which contains the disk
6629 * state of the machine while it was previously running, but without
6630 * the corresponding machine state, which is equivalent to powering
6631 * off a running machine and not good idea
6632 */
6633 ComPtr<ISnapshot> pCurrentSnapshot;
6634 rc = mMachine->COMGETTER(CurrentSnapshot)(pCurrentSnapshot.asOutParam());
6635 if (FAILED(rc))
6636 throw rc;
6637
6638 BOOL fCurrentSnapshotIsOnline = false;
6639 if (pCurrentSnapshot)
6640 {
6641 rc = pCurrentSnapshot->COMGETTER(Online)(&fCurrentSnapshotIsOnline);
6642 if (FAILED(rc))
6643 throw rc;
6644 }
6645
6646 if (!fCurrentSnapshotIsOnline)
6647 {
6648 LogFlowThisFunc(("Looking for immutable images to reset\n"));
6649
6650 com::SafeIfaceArray<IMediumAttachment> atts;
6651 rc = mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
6652 if (FAILED(rc))
6653 throw rc;
6654
6655 for (size_t i = 0;
6656 i < atts.size();
6657 ++i)
6658 {
6659 DeviceType_T devType;
6660 rc = atts[i]->COMGETTER(Type)(&devType);
6661 /** @todo later applies to floppies as well */
6662 if (devType == DeviceType_HardDisk)
6663 {
6664 ComPtr<IMedium> pMedium;
6665 rc = atts[i]->COMGETTER(Medium)(pMedium.asOutParam());
6666 if (FAILED(rc))
6667 throw rc;
6668
6669 /* needs autoreset? */
6670 BOOL autoReset = FALSE;
6671 rc = pMedium->COMGETTER(AutoReset)(&autoReset);
6672 if (FAILED(rc))
6673 throw rc;
6674
6675 if (autoReset)
6676 {
6677 ComPtr<IProgress> pResetProgress;
6678 rc = pMedium->Reset(pResetProgress.asOutParam());
6679 if (FAILED(rc))
6680 throw rc;
6681
6682 /* save for later use on the powerup thread */
6683 task->hardDiskProgresses.push_back(pResetProgress);
6684 }
6685 }
6686 }
6687 }
6688 else
6689 LogFlowThisFunc(("Machine has a current snapshot which is online, skipping immutable images reset\n"));
6690
6691 /* setup task object and thread to carry out the operation
6692 * asynchronously */
6693
6694#ifdef VBOX_WITH_EXTPACK
6695 mptrExtPackManager->dumpAllToReleaseLog();
6696#endif
6697
6698#ifdef RT_OS_SOLARIS
6699 /* setup host core dumper for the VM */
6700 Bstr value;
6701 HRESULT hrc = mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpEnabled").raw(), value.asOutParam());
6702 if (SUCCEEDED(hrc) && value == "1")
6703 {
6704 Bstr coreDumpDir, coreDumpReplaceSys, coreDumpLive;
6705 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpDir").raw(), coreDumpDir.asOutParam());
6706 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpReplaceSystemDump").raw(), coreDumpReplaceSys.asOutParam());
6707 mMachine->GetExtraData(Bstr("VBoxInternal2/CoreDumpLive").raw(), coreDumpLive.asOutParam());
6708
6709 uint32_t fCoreFlags = 0;
6710 if ( coreDumpReplaceSys.isEmpty() == false
6711 && Utf8Str(coreDumpReplaceSys).toUInt32() == 1)
6712 fCoreFlags |= RTCOREDUMPER_FLAGS_REPLACE_SYSTEM_DUMP;
6713
6714 if ( coreDumpLive.isEmpty() == false
6715 && Utf8Str(coreDumpLive).toUInt32() == 1)
6716 fCoreFlags |= RTCOREDUMPER_FLAGS_LIVE_CORE;
6717
6718 Utf8Str strDumpDir(coreDumpDir);
6719 const char *pszDumpDir = strDumpDir.c_str();
6720 if ( pszDumpDir
6721 && *pszDumpDir == '\0')
6722 pszDumpDir = NULL;
6723
6724 int vrc;
6725 if ( pszDumpDir
6726 && !RTDirExists(pszDumpDir))
6727 {
6728 /*
6729 * Try create the directory.
6730 */
6731 vrc = RTDirCreateFullPath(pszDumpDir, 0700);
6732 if (RT_FAILURE(vrc))
6733 throw setError(E_FAIL, "Failed to setup CoreDumper. Couldn't create dump directory '%s' (%Rrc)\n", pszDumpDir, vrc);
6734 }
6735
6736 vrc = RTCoreDumperSetup(pszDumpDir, fCoreFlags);
6737 if (RT_FAILURE(vrc))
6738 throw setError(E_FAIL, "Failed to setup CoreDumper (%Rrc)", vrc);
6739 else
6740 LogRel(("CoreDumper setup successful. pszDumpDir=%s fFlags=%#x\n", pszDumpDir ? pszDumpDir : ".", fCoreFlags));
6741 }
6742#endif
6743
6744
6745 // If there is immutable drive the process that.
6746 VMPowerUpTask::ProgressList progresses(task->hardDiskProgresses);
6747 if (aProgress && progresses.size() > 0){
6748
6749 for (VMPowerUpTask::ProgressList::const_iterator it = progresses.begin(); it != progresses.end(); ++it)
6750 {
6751 ++cOperations;
6752 ulTotalOperationsWeight += 1;
6753 }
6754 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
6755 progressDesc.raw(),
6756 TRUE, // Cancelable
6757 cOperations,
6758 ulTotalOperationsWeight,
6759 Bstr(tr("Starting Hard Disk operations")).raw(),
6760 1,
6761 NULL);
6762 AssertComRCReturnRC(rc);
6763 }
6764 else if ( mMachineState == MachineState_Saved
6765 || (!fTeleporterEnabled && !fFaultToleranceSyncEnabled))
6766 {
6767 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
6768 progressDesc.raw(),
6769 FALSE /* aCancelable */);
6770 }
6771 else if (fTeleporterEnabled)
6772 {
6773 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
6774 progressDesc.raw(),
6775 TRUE /* aCancelable */,
6776 3 /* cOperations */,
6777 10 /* ulTotalOperationsWeight */,
6778 Bstr(tr("Teleporting virtual machine")).raw(),
6779 1 /* ulFirstOperationWeight */,
6780 NULL);
6781 }
6782 else if (fFaultToleranceSyncEnabled)
6783 {
6784 rc = pPowerupProgress->init(static_cast<IConsole *>(this),
6785 progressDesc.raw(),
6786 TRUE /* aCancelable */,
6787 3 /* cOperations */,
6788 10 /* ulTotalOperationsWeight */,
6789 Bstr(tr("Fault Tolerance syncing of remote virtual machine")).raw(),
6790 1 /* ulFirstOperationWeight */,
6791 NULL);
6792 }
6793
6794 if (FAILED(rc))
6795 throw rc;
6796
6797 /* Tell VBoxSVC and Machine about the progress object so they can
6798 combine/proxy it to any openRemoteSession caller. */
6799 LogFlowThisFunc(("Calling BeginPowerUp...\n"));
6800 rc = mControl->BeginPowerUp(pPowerupProgress);
6801 if (FAILED(rc))
6802 {
6803 LogFlowThisFunc(("BeginPowerUp failed\n"));
6804 throw rc;
6805 }
6806 fBeganPoweringUp = true;
6807
6808 LogFlowThisFunc(("Checking if canceled...\n"));
6809 BOOL fCanceled;
6810 rc = pPowerupProgress->COMGETTER(Canceled)(&fCanceled);
6811 if (FAILED(rc))
6812 throw rc;
6813
6814 if (fCanceled)
6815 {
6816 LogFlowThisFunc(("Canceled in BeginPowerUp\n"));
6817 throw setError(E_FAIL, tr("Powerup was canceled"));
6818 }
6819 LogFlowThisFunc(("Not canceled yet.\n"));
6820
6821 /** @todo this code prevents starting a VM with unavailable bridged
6822 * networking interface. The only benefit is a slightly better error
6823 * message, which should be moved to the driver code. This is the
6824 * only reason why I left the code in for now. The driver allows
6825 * unavailable bridged networking interfaces in certain circumstances,
6826 * and this is sabotaged by this check. The VM will initially have no
6827 * network connectivity, but the user can fix this at runtime. */
6828#if 0
6829 /* the network cards will undergo a quick consistency check */
6830 for (ULONG slot = 0;
6831 slot < maxNetworkAdapters;
6832 ++slot)
6833 {
6834 ComPtr<INetworkAdapter> pNetworkAdapter;
6835 mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
6836 BOOL enabled = FALSE;
6837 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
6838 if (!enabled)
6839 continue;
6840
6841 NetworkAttachmentType_T netattach;
6842 pNetworkAdapter->COMGETTER(AttachmentType)(&netattach);
6843 switch (netattach)
6844 {
6845 case NetworkAttachmentType_Bridged:
6846 {
6847 /* a valid host interface must have been set */
6848 Bstr hostif;
6849 pNetworkAdapter->COMGETTER(HostInterface)(hostif.asOutParam());
6850 if (hostif.isEmpty())
6851 {
6852 throw setError(VBOX_E_HOST_ERROR,
6853 tr("VM cannot start because host interface networking requires a host interface name to be set"));
6854 }
6855 ComPtr<IVirtualBox> pVirtualBox;
6856 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
6857 ComPtr<IHost> pHost;
6858 pVirtualBox->COMGETTER(Host)(pHost.asOutParam());
6859 ComPtr<IHostNetworkInterface> pHostInterface;
6860 if (!SUCCEEDED(pHost->FindHostNetworkInterfaceByName(hostif.raw(),
6861 pHostInterface.asOutParam())))
6862 {
6863 throw setError(VBOX_E_HOST_ERROR,
6864 tr("VM cannot start because the host interface '%ls' does not exist"),
6865 hostif.raw());
6866 }
6867 break;
6868 }
6869 default:
6870 break;
6871 }
6872 }
6873#endif // 0
6874
6875 /* setup task object and thread to carry out the operation
6876 * asynchronously */
6877 if (aProgress){
6878 rc = pPowerupProgress.queryInterfaceTo(aProgress);
6879 AssertComRCReturnRC(rc);
6880 }
6881
6882 int vrc = RTThreadCreate(NULL, Console::powerUpThread,
6883 (void *)task.get(), 0,
6884 RTTHREADTYPE_MAIN_WORKER, 0, "VMPwrUp");
6885 if (RT_FAILURE(vrc))
6886 throw setError(E_FAIL, "Could not create VMPowerUp thread (%Rrc)", vrc);
6887
6888 /* task is now owned by powerUpThread(), so release it */
6889 task.release();
6890
6891 /* finally, set the state: no right to fail in this method afterwards
6892 * since we've already started the thread and it is now responsible for
6893 * any error reporting and appropriate state change! */
6894 if (mMachineState == MachineState_Saved)
6895 setMachineState(MachineState_Restoring);
6896 else if (fTeleporterEnabled)
6897 setMachineState(MachineState_TeleportingIn);
6898 else if (enmFaultToleranceState == FaultToleranceState_Standby)
6899 setMachineState(MachineState_FaultTolerantSyncing);
6900 else
6901 setMachineState(MachineState_Starting);
6902 }
6903 catch (HRESULT aRC) { rc = aRC; }
6904
6905 if (FAILED(rc) && fBeganPoweringUp)
6906 {
6907
6908 /* The progress object will fetch the current error info */
6909 if (!pPowerupProgress.isNull())
6910 pPowerupProgress->notifyComplete(rc);
6911
6912 /* Save the error info across the IPC below. Can't be done before the
6913 * progress notification above, as saving the error info deletes it
6914 * from the current context, and thus the progress object wouldn't be
6915 * updated correctly. */
6916 ErrorInfoKeeper eik;
6917
6918 /* signal end of operation */
6919 mControl->EndPowerUp(rc);
6920 }
6921
6922 LogFlowThisFunc(("mMachineState=%d, rc=%Rhrc\n", mMachineState, rc));
6923 LogFlowThisFuncLeave();
6924 return rc;
6925}
6926
6927/**
6928 * Internal power off worker routine.
6929 *
6930 * This method may be called only at certain places with the following meaning
6931 * as shown below:
6932 *
6933 * - if the machine state is either Running or Paused, a normal
6934 * Console-initiated powerdown takes place (e.g. PowerDown());
6935 * - if the machine state is Saving, saveStateThread() has successfully done its
6936 * job;
6937 * - if the machine state is Starting or Restoring, powerUpThread() has failed
6938 * to start/load the VM;
6939 * - if the machine state is Stopping, the VM has powered itself off (i.e. not
6940 * as a result of the powerDown() call).
6941 *
6942 * Calling it in situations other than the above will cause unexpected behavior.
6943 *
6944 * Note that this method should be the only one that destroys mpUVM and sets it
6945 * to NULL.
6946 *
6947 * @param aProgress Progress object to run (may be NULL).
6948 *
6949 * @note Locks this object for writing.
6950 *
6951 * @note Never call this method from a thread that called addVMCaller() or
6952 * instantiated an AutoVMCaller object; first call releaseVMCaller() or
6953 * release(). Otherwise it will deadlock.
6954 */
6955HRESULT Console::powerDown(IProgress *aProgress /*= NULL*/)
6956{
6957 LogFlowThisFuncEnter();
6958
6959 AutoCaller autoCaller(this);
6960 AssertComRCReturnRC(autoCaller.rc());
6961
6962 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6963
6964 /* Total # of steps for the progress object. Must correspond to the
6965 * number of "advance percent count" comments in this method! */
6966 enum { StepCount = 7 };
6967 /* current step */
6968 ULONG step = 0;
6969
6970 HRESULT rc = S_OK;
6971 int vrc = VINF_SUCCESS;
6972
6973 /* sanity */
6974 Assert(mVMDestroying == false);
6975
6976 PUVM pUVM = mpUVM; Assert(pUVM != NULL);
6977 uint32_t cRefs = VMR3RetainUVM(pUVM); Assert(cRefs != UINT32_MAX);
6978
6979 AssertMsg( mMachineState == MachineState_Running
6980 || mMachineState == MachineState_Paused
6981 || mMachineState == MachineState_Stuck
6982 || mMachineState == MachineState_Starting
6983 || mMachineState == MachineState_Stopping
6984 || mMachineState == MachineState_Saving
6985 || mMachineState == MachineState_Restoring
6986 || mMachineState == MachineState_TeleportingPausedVM
6987 || mMachineState == MachineState_FaultTolerantSyncing
6988 || mMachineState == MachineState_TeleportingIn
6989 , ("Invalid machine state: %s\n", Global::stringifyMachineState(mMachineState)));
6990
6991 LogRel(("Console::powerDown(): A request to power off the VM has been issued (mMachineState=%s, InUninit=%d)\n",
6992 Global::stringifyMachineState(mMachineState), autoCaller.state() == InUninit));
6993
6994 /* Check if we need to power off the VM. In case of mVMPoweredOff=true, the
6995 * VM has already powered itself off in vmstateChangeCallback() and is just
6996 * notifying Console about that. In case of Starting or Restoring,
6997 * powerUpThread() is calling us on failure, so the VM is already off at
6998 * that point. */
6999 if ( !mVMPoweredOff
7000 && ( mMachineState == MachineState_Starting
7001 || mMachineState == MachineState_Restoring
7002 || mMachineState == MachineState_FaultTolerantSyncing
7003 || mMachineState == MachineState_TeleportingIn)
7004 )
7005 mVMPoweredOff = true;
7006
7007 /*
7008 * Go to Stopping state if not already there.
7009 *
7010 * Note that we don't go from Saving/Restoring to Stopping because
7011 * vmstateChangeCallback() needs it to set the state to Saved on
7012 * VMSTATE_TERMINATED. In terms of protecting from inappropriate operations
7013 * while leaving the lock below, Saving or Restoring should be fine too.
7014 * Ditto for TeleportingPausedVM -> Teleported.
7015 */
7016 if ( mMachineState != MachineState_Saving
7017 && mMachineState != MachineState_Restoring
7018 && mMachineState != MachineState_Stopping
7019 && mMachineState != MachineState_TeleportingIn
7020 && mMachineState != MachineState_TeleportingPausedVM
7021 && mMachineState != MachineState_FaultTolerantSyncing
7022 )
7023 setMachineState(MachineState_Stopping);
7024
7025 /* ----------------------------------------------------------------------
7026 * DONE with necessary state changes, perform the power down actions (it's
7027 * safe to release the object lock now if needed)
7028 * ---------------------------------------------------------------------- */
7029
7030 /* Stop the VRDP server to prevent new clients connection while VM is being
7031 * powered off. */
7032 if (mConsoleVRDPServer)
7033 {
7034 LogFlowThisFunc(("Stopping VRDP server...\n"));
7035
7036 /* Leave the lock since EMT will call us back as addVMCaller()
7037 * in updateDisplayData(). */
7038 alock.release();
7039
7040 mConsoleVRDPServer->Stop();
7041
7042 alock.acquire();
7043 }
7044
7045 /* advance percent count */
7046 if (aProgress)
7047 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount );
7048
7049
7050 /* ----------------------------------------------------------------------
7051 * Now, wait for all mpUVM callers to finish their work if there are still
7052 * some on other threads. NO methods that need mpUVM (or initiate other calls
7053 * that need it) may be called after this point
7054 * ---------------------------------------------------------------------- */
7055
7056 /* go to the destroying state to prevent from adding new callers */
7057 mVMDestroying = true;
7058
7059 if (mVMCallers > 0)
7060 {
7061 /* lazy creation */
7062 if (mVMZeroCallersSem == NIL_RTSEMEVENT)
7063 RTSemEventCreate(&mVMZeroCallersSem);
7064
7065 LogFlowThisFunc(("Waiting for mpUVM callers (%d) to drop to zero...\n", mVMCallers));
7066
7067 alock.release();
7068
7069 RTSemEventWait(mVMZeroCallersSem, RT_INDEFINITE_WAIT);
7070
7071 alock.acquire();
7072 }
7073
7074 /* advance percent count */
7075 if (aProgress)
7076 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount );
7077
7078 vrc = VINF_SUCCESS;
7079
7080 /*
7081 * Power off the VM if not already done that.
7082 * Leave the lock since EMT will call vmstateChangeCallback.
7083 *
7084 * Note that VMR3PowerOff() may fail here (invalid VMSTATE) if the
7085 * VM-(guest-)initiated power off happened in parallel a ms before this
7086 * call. So far, we let this error pop up on the user's side.
7087 */
7088 if (!mVMPoweredOff)
7089 {
7090 LogFlowThisFunc(("Powering off the VM...\n"));
7091 alock.release();
7092 vrc = VMR3PowerOff(pUVM);
7093#ifdef VBOX_WITH_EXTPACK
7094 mptrExtPackManager->callAllVmPowerOffHooks(this, VMR3GetVM(pUVM));
7095#endif
7096 alock.acquire();
7097 }
7098
7099 /* advance percent count */
7100 if (aProgress)
7101 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount );
7102
7103#ifdef VBOX_WITH_HGCM
7104 /* Shutdown HGCM services before destroying the VM. */
7105 if (m_pVMMDev)
7106 {
7107 LogFlowThisFunc(("Shutdown HGCM...\n"));
7108
7109 /* Leave the lock since EMT will call us back as addVMCaller() */
7110 alock.release();
7111
7112 m_pVMMDev->hgcmShutdown();
7113
7114 alock.acquire();
7115 }
7116
7117 /* advance percent count */
7118 if (aProgress)
7119 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount);
7120
7121#endif /* VBOX_WITH_HGCM */
7122
7123 LogFlowThisFunc(("Ready for VM destruction.\n"));
7124
7125 /* If we are called from Console::uninit(), then try to destroy the VM even
7126 * on failure (this will most likely fail too, but what to do?..) */
7127 if (RT_SUCCESS(vrc) || autoCaller.state() == InUninit)
7128 {
7129 /* If the machine has a USB controller, release all USB devices
7130 * (symmetric to the code in captureUSBDevices()) */
7131 if (mfVMHasUsbController)
7132 {
7133 alock.release();
7134 detachAllUSBDevices(false /* aDone */);
7135 alock.acquire();
7136 }
7137
7138 /* Now we've got to destroy the VM as well. (mpUVM is not valid beyond
7139 * this point). We release the lock before calling VMR3Destroy() because
7140 * it will result into calling destructors of drivers associated with
7141 * Console children which may in turn try to lock Console (e.g. by
7142 * instantiating SafeVMPtr to access mpUVM). It's safe here because
7143 * mVMDestroying is set which should prevent any activity. */
7144
7145 /* Set mpUVM to NULL early just in case if some old code is not using
7146 * addVMCaller()/releaseVMCaller(). (We have our own ref on pUVM.) */
7147 VMR3ReleaseUVM(mpUVM);
7148 mpUVM = NULL;
7149
7150 LogFlowThisFunc(("Destroying the VM...\n"));
7151
7152 alock.release();
7153
7154 vrc = VMR3Destroy(pUVM);
7155
7156 /* take the lock again */
7157 alock.acquire();
7158
7159 /* advance percent count */
7160 if (aProgress)
7161 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount);
7162
7163 if (RT_SUCCESS(vrc))
7164 {
7165 LogFlowThisFunc(("Machine has been destroyed (mMachineState=%d)\n",
7166 mMachineState));
7167 /* Note: the Console-level machine state change happens on the
7168 * VMSTATE_TERMINATE state change in vmstateChangeCallback(). If
7169 * powerDown() is called from EMT (i.e. from vmstateChangeCallback()
7170 * on receiving VM-initiated VMSTATE_OFF), VMSTATE_TERMINATE hasn't
7171 * occurred yet. This is okay, because mMachineState is already
7172 * Stopping in this case, so any other attempt to call PowerDown()
7173 * will be rejected. */
7174 }
7175 else
7176 {
7177 /* bad bad bad, but what to do? (Give Console our UVM ref.) */
7178 mpUVM = pUVM;
7179 pUVM = NULL;
7180 rc = setError(VBOX_E_VM_ERROR,
7181 tr("Could not destroy the machine. (Error: %Rrc)"),
7182 vrc);
7183 }
7184
7185 /* Complete the detaching of the USB devices. */
7186 if (mfVMHasUsbController)
7187 {
7188 alock.release();
7189 detachAllUSBDevices(true /* aDone */);
7190 alock.acquire();
7191 }
7192
7193 /* advance percent count */
7194 if (aProgress)
7195 aProgress->SetCurrentOperationProgress(99 * (++step) / StepCount);
7196 }
7197 else
7198 {
7199 rc = setError(VBOX_E_VM_ERROR,
7200 tr("Could not power off the machine. (Error: %Rrc)"),
7201 vrc);
7202 }
7203
7204 /*
7205 * Finished with the destruction.
7206 *
7207 * Note that if something impossible happened and we've failed to destroy
7208 * the VM, mVMDestroying will remain true and mMachineState will be
7209 * something like Stopping, so most Console methods will return an error
7210 * to the caller.
7211 */
7212 if (pUVM != NULL)
7213 VMR3ReleaseUVM(pUVM);
7214 else
7215 mVMDestroying = false;
7216
7217#ifdef CONSOLE_WITH_EVENT_CACHE
7218 if (SUCCEEDED(rc))
7219 mCallbackData.clear();
7220#endif
7221
7222 LogFlowThisFuncLeave();
7223 return rc;
7224}
7225
7226/**
7227 * @note Locks this object for writing.
7228 */
7229HRESULT Console::setMachineState(MachineState_T aMachineState,
7230 bool aUpdateServer /* = true */)
7231{
7232 AutoCaller autoCaller(this);
7233 AssertComRCReturnRC(autoCaller.rc());
7234
7235 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
7236
7237 HRESULT rc = S_OK;
7238
7239 if (mMachineState != aMachineState)
7240 {
7241 LogThisFunc(("machineState=%s -> %s aUpdateServer=%RTbool\n",
7242 Global::stringifyMachineState(mMachineState), Global::stringifyMachineState(aMachineState), aUpdateServer));
7243 mMachineState = aMachineState;
7244
7245 /// @todo (dmik)
7246 // possibly, we need to redo onStateChange() using the dedicated
7247 // Event thread, like it is done in VirtualBox. This will make it
7248 // much safer (no deadlocks possible if someone tries to use the
7249 // console from the callback), however, listeners will lose the
7250 // ability to synchronously react to state changes (is it really
7251 // necessary??)
7252 LogFlowThisFunc(("Doing onStateChange()...\n"));
7253 onStateChange(aMachineState);
7254 LogFlowThisFunc(("Done onStateChange()\n"));
7255
7256 if (aUpdateServer)
7257 {
7258 /* Server notification MUST be done from under the lock; otherwise
7259 * the machine state here and on the server might go out of sync
7260 * which can lead to various unexpected results (like the machine
7261 * state being >= MachineState_Running on the server, while the
7262 * session state is already SessionState_Unlocked at the same time
7263 * there).
7264 *
7265 * Cross-lock conditions should be carefully watched out: calling
7266 * UpdateState we will require Machine and SessionMachine locks
7267 * (remember that here we're holding the Console lock here, and also
7268 * all locks that have been acquire by the thread before calling
7269 * this method).
7270 */
7271 LogFlowThisFunc(("Doing mControl->UpdateState()...\n"));
7272 rc = mControl->UpdateState(aMachineState);
7273 LogFlowThisFunc(("mControl->UpdateState()=%Rhrc\n", rc));
7274 }
7275 }
7276
7277 return rc;
7278}
7279
7280/**
7281 * Searches for a shared folder with the given logical name
7282 * in the collection of shared folders.
7283 *
7284 * @param aName logical name of the shared folder
7285 * @param aSharedFolder where to return the found object
7286 * @param aSetError whether to set the error info if the folder is
7287 * not found
7288 * @return
7289 * S_OK when found or E_INVALIDARG when not found
7290 *
7291 * @note The caller must lock this object for writing.
7292 */
7293HRESULT Console::findSharedFolder(const Utf8Str &strName,
7294 ComObjPtr<SharedFolder> &aSharedFolder,
7295 bool aSetError /* = false */)
7296{
7297 /* sanity check */
7298 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
7299
7300 SharedFolderMap::const_iterator it = m_mapSharedFolders.find(strName);
7301 if (it != m_mapSharedFolders.end())
7302 {
7303 aSharedFolder = it->second;
7304 return S_OK;
7305 }
7306
7307 if (aSetError)
7308 setError(VBOX_E_FILE_ERROR,
7309 tr("Could not find a shared folder named '%s'."),
7310 strName.c_str());
7311
7312 return VBOX_E_FILE_ERROR;
7313}
7314
7315/**
7316 * Fetches the list of global or machine shared folders from the server.
7317 *
7318 * @param aGlobal true to fetch global folders.
7319 *
7320 * @note The caller must lock this object for writing.
7321 */
7322HRESULT Console::fetchSharedFolders(BOOL aGlobal)
7323{
7324 /* sanity check */
7325 AssertReturn(AutoCaller(this).state() == InInit ||
7326 isWriteLockOnCurrentThread(), E_FAIL);
7327
7328 LogFlowThisFunc(("Entering\n"));
7329
7330 /* Check if we're online and keep it that way. */
7331 SafeVMPtrQuiet ptrVM(this);
7332 AutoVMCallerQuietWeak autoVMCaller(this);
7333 bool const online = ptrVM.isOk()
7334 && m_pVMMDev
7335 && m_pVMMDev->isShFlActive();
7336
7337 HRESULT rc = S_OK;
7338
7339 try
7340 {
7341 if (aGlobal)
7342 {
7343 /// @todo grab & process global folders when they are done
7344 }
7345 else
7346 {
7347 SharedFolderDataMap oldFolders;
7348 if (online)
7349 oldFolders = m_mapMachineSharedFolders;
7350
7351 m_mapMachineSharedFolders.clear();
7352
7353 SafeIfaceArray<ISharedFolder> folders;
7354 rc = mMachine->COMGETTER(SharedFolders)(ComSafeArrayAsOutParam(folders));
7355 if (FAILED(rc)) throw rc;
7356
7357 for (size_t i = 0; i < folders.size(); ++i)
7358 {
7359 ComPtr<ISharedFolder> pSharedFolder = folders[i];
7360
7361 Bstr bstrName;
7362 Bstr bstrHostPath;
7363 BOOL writable;
7364 BOOL autoMount;
7365
7366 rc = pSharedFolder->COMGETTER(Name)(bstrName.asOutParam());
7367 if (FAILED(rc)) throw rc;
7368 Utf8Str strName(bstrName);
7369
7370 rc = pSharedFolder->COMGETTER(HostPath)(bstrHostPath.asOutParam());
7371 if (FAILED(rc)) throw rc;
7372 Utf8Str strHostPath(bstrHostPath);
7373
7374 rc = pSharedFolder->COMGETTER(Writable)(&writable);
7375 if (FAILED(rc)) throw rc;
7376
7377 rc = pSharedFolder->COMGETTER(AutoMount)(&autoMount);
7378 if (FAILED(rc)) throw rc;
7379
7380 m_mapMachineSharedFolders.insert(std::make_pair(strName,
7381 SharedFolderData(strHostPath, !!writable, !!autoMount)));
7382
7383 /* send changes to HGCM if the VM is running */
7384 if (online)
7385 {
7386 SharedFolderDataMap::iterator it = oldFolders.find(strName);
7387 if ( it == oldFolders.end()
7388 || it->second.m_strHostPath != strHostPath)
7389 {
7390 /* a new machine folder is added or
7391 * the existing machine folder is changed */
7392 if (m_mapSharedFolders.find(strName) != m_mapSharedFolders.end())
7393 ; /* the console folder exists, nothing to do */
7394 else
7395 {
7396 /* remove the old machine folder (when changed)
7397 * or the global folder if any (when new) */
7398 if ( it != oldFolders.end()
7399 || m_mapGlobalSharedFolders.find(strName) != m_mapGlobalSharedFolders.end()
7400 )
7401 {
7402 rc = removeSharedFolder(strName);
7403 if (FAILED(rc)) throw rc;
7404 }
7405
7406 /* create the new machine folder */
7407 rc = createSharedFolder(strName,
7408 SharedFolderData(strHostPath, !!writable, !!autoMount));
7409 if (FAILED(rc)) throw rc;
7410 }
7411 }
7412 /* forget the processed (or identical) folder */
7413 if (it != oldFolders.end())
7414 oldFolders.erase(it);
7415 }
7416 }
7417
7418 /* process outdated (removed) folders */
7419 if (online)
7420 {
7421 for (SharedFolderDataMap::const_iterator it = oldFolders.begin();
7422 it != oldFolders.end(); ++it)
7423 {
7424 if (m_mapSharedFolders.find(it->first) != m_mapSharedFolders.end())
7425 ; /* the console folder exists, nothing to do */
7426 else
7427 {
7428 /* remove the outdated machine folder */
7429 rc = removeSharedFolder(it->first);
7430 if (FAILED(rc)) throw rc;
7431
7432 /* create the global folder if there is any */
7433 SharedFolderDataMap::const_iterator git =
7434 m_mapGlobalSharedFolders.find(it->first);
7435 if (git != m_mapGlobalSharedFolders.end())
7436 {
7437 rc = createSharedFolder(git->first, git->second);
7438 if (FAILED(rc)) throw rc;
7439 }
7440 }
7441 }
7442 }
7443 }
7444 }
7445 catch (HRESULT rc2)
7446 {
7447 rc = rc2;
7448 if (online)
7449 setVMRuntimeErrorCallbackF(0, "BrokenSharedFolder",
7450 N_("Broken shared folder!"));
7451 }
7452
7453 LogFlowThisFunc(("Leaving\n"));
7454
7455 return rc;
7456}
7457
7458/**
7459 * Searches for a shared folder with the given name in the list of machine
7460 * shared folders and then in the list of the global shared folders.
7461 *
7462 * @param aName Name of the folder to search for.
7463 * @param aIt Where to store the pointer to the found folder.
7464 * @return @c true if the folder was found and @c false otherwise.
7465 *
7466 * @note The caller must lock this object for reading.
7467 */
7468bool Console::findOtherSharedFolder(const Utf8Str &strName,
7469 SharedFolderDataMap::const_iterator &aIt)
7470{
7471 /* sanity check */
7472 AssertReturn(isWriteLockOnCurrentThread(), false);
7473
7474 /* first, search machine folders */
7475 aIt = m_mapMachineSharedFolders.find(strName);
7476 if (aIt != m_mapMachineSharedFolders.end())
7477 return true;
7478
7479 /* second, search machine folders */
7480 aIt = m_mapGlobalSharedFolders.find(strName);
7481 if (aIt != m_mapGlobalSharedFolders.end())
7482 return true;
7483
7484 return false;
7485}
7486
7487/**
7488 * Calls the HGCM service to add a shared folder definition.
7489 *
7490 * @param aName Shared folder name.
7491 * @param aHostPath Shared folder path.
7492 *
7493 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
7494 * @note Doesn't lock anything.
7495 */
7496HRESULT Console::createSharedFolder(const Utf8Str &strName, const SharedFolderData &aData)
7497{
7498 ComAssertRet(strName.isNotEmpty(), E_FAIL);
7499 ComAssertRet(aData.m_strHostPath.isNotEmpty(), E_FAIL);
7500
7501 /* sanity checks */
7502 AssertReturn(mpUVM, E_FAIL);
7503 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
7504
7505 VBOXHGCMSVCPARM parms[SHFL_CPARMS_ADD_MAPPING];
7506 SHFLSTRING *pFolderName, *pMapName;
7507 size_t cbString;
7508
7509 Bstr value;
7510 HRESULT hrc = mMachine->GetExtraData(BstrFmt("VBoxInternal2/SharedFoldersEnableSymlinksCreate/%s",
7511 strName.c_str()).raw(),
7512 value.asOutParam());
7513 bool fSymlinksCreate = hrc == S_OK && value == "1";
7514
7515 Log(("Adding shared folder '%s' -> '%s'\n", strName.c_str(), aData.m_strHostPath.c_str()));
7516
7517 // check whether the path is valid and exists
7518 char hostPathFull[RTPATH_MAX];
7519 int vrc = RTPathAbsEx(NULL,
7520 aData.m_strHostPath.c_str(),
7521 hostPathFull,
7522 sizeof(hostPathFull));
7523
7524 bool fMissing = false;
7525 if (RT_FAILURE(vrc))
7526 return setError(E_INVALIDARG,
7527 tr("Invalid shared folder path: '%s' (%Rrc)"),
7528 aData.m_strHostPath.c_str(), vrc);
7529 if (!RTPathExists(hostPathFull))
7530 fMissing = true;
7531
7532 /* Check whether the path is full (absolute) */
7533 if (RTPathCompare(aData.m_strHostPath.c_str(), hostPathFull) != 0)
7534 return setError(E_INVALIDARG,
7535 tr("Shared folder path '%s' is not absolute"),
7536 aData.m_strHostPath.c_str());
7537
7538 // now that we know the path is good, give it to HGCM
7539
7540 Bstr bstrName(strName);
7541 Bstr bstrHostPath(aData.m_strHostPath);
7542
7543 cbString = (bstrHostPath.length() + 1) * sizeof(RTUTF16);
7544 if (cbString >= UINT16_MAX)
7545 return setError(E_INVALIDARG, tr("The name is too long"));
7546 pFolderName = (SHFLSTRING*)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
7547 Assert(pFolderName);
7548 memcpy(pFolderName->String.ucs2, bstrHostPath.raw(), cbString);
7549
7550 pFolderName->u16Size = (uint16_t)cbString;
7551 pFolderName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
7552
7553 parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
7554 parms[0].u.pointer.addr = pFolderName;
7555 parms[0].u.pointer.size = sizeof(SHFLSTRING) + (uint16_t)cbString;
7556
7557 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
7558 if (cbString >= UINT16_MAX)
7559 {
7560 RTMemFree(pFolderName);
7561 return setError(E_INVALIDARG, tr("The host path is too long"));
7562 }
7563 pMapName = (SHFLSTRING*)RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
7564 Assert(pMapName);
7565 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
7566
7567 pMapName->u16Size = (uint16_t)cbString;
7568 pMapName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
7569
7570 parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
7571 parms[1].u.pointer.addr = pMapName;
7572 parms[1].u.pointer.size = sizeof(SHFLSTRING) + (uint16_t)cbString;
7573
7574 parms[2].type = VBOX_HGCM_SVC_PARM_32BIT;
7575 parms[2].u.uint32 = (aData.m_fWritable ? SHFL_ADD_MAPPING_F_WRITABLE : 0)
7576 | (aData.m_fAutoMount ? SHFL_ADD_MAPPING_F_AUTOMOUNT : 0)
7577 | (fSymlinksCreate ? SHFL_ADD_MAPPING_F_CREATE_SYMLINKS : 0)
7578 | (fMissing ? SHFL_ADD_MAPPING_F_MISSING : 0)
7579 ;
7580
7581 vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders",
7582 SHFL_FN_ADD_MAPPING,
7583 SHFL_CPARMS_ADD_MAPPING, &parms[0]);
7584 RTMemFree(pFolderName);
7585 RTMemFree(pMapName);
7586
7587 if (RT_FAILURE(vrc))
7588 return setError(E_FAIL,
7589 tr("Could not create a shared folder '%s' mapped to '%s' (%Rrc)"),
7590 strName.c_str(), aData.m_strHostPath.c_str(), vrc);
7591
7592 if (fMissing)
7593 return setError(E_INVALIDARG,
7594 tr("Shared folder path '%s' does not exist on the host"),
7595 aData.m_strHostPath.c_str());
7596
7597 return S_OK;
7598}
7599
7600/**
7601 * Calls the HGCM service to remove the shared folder definition.
7602 *
7603 * @param aName Shared folder name.
7604 *
7605 * @note Must be called from under AutoVMCaller and when mpUVM != NULL!
7606 * @note Doesn't lock anything.
7607 */
7608HRESULT Console::removeSharedFolder(const Utf8Str &strName)
7609{
7610 ComAssertRet(strName.isNotEmpty(), E_FAIL);
7611
7612 /* sanity checks */
7613 AssertReturn(mpUVM, E_FAIL);
7614 AssertReturn(m_pVMMDev && m_pVMMDev->isShFlActive(), E_FAIL);
7615
7616 VBOXHGCMSVCPARM parms;
7617 SHFLSTRING *pMapName;
7618 size_t cbString;
7619
7620 Log(("Removing shared folder '%s'\n", strName.c_str()));
7621
7622 Bstr bstrName(strName);
7623 cbString = (bstrName.length() + 1) * sizeof(RTUTF16);
7624 if (cbString >= UINT16_MAX)
7625 return setError(E_INVALIDARG, tr("The name is too long"));
7626 pMapName = (SHFLSTRING *) RTMemAllocZ(sizeof(SHFLSTRING) + cbString);
7627 Assert(pMapName);
7628 memcpy(pMapName->String.ucs2, bstrName.raw(), cbString);
7629
7630 pMapName->u16Size = (uint16_t)cbString;
7631 pMapName->u16Length = (uint16_t)cbString - sizeof(RTUTF16);
7632
7633 parms.type = VBOX_HGCM_SVC_PARM_PTR;
7634 parms.u.pointer.addr = pMapName;
7635 parms.u.pointer.size = sizeof(SHFLSTRING) + (uint16_t)cbString;
7636
7637 int vrc = m_pVMMDev->hgcmHostCall("VBoxSharedFolders",
7638 SHFL_FN_REMOVE_MAPPING,
7639 1, &parms);
7640 RTMemFree(pMapName);
7641 if (RT_FAILURE(vrc))
7642 return setError(E_FAIL,
7643 tr("Could not remove the shared folder '%s' (%Rrc)"),
7644 strName.c_str(), vrc);
7645
7646 return S_OK;
7647}
7648
7649/** @callback_method_impl{FNVMATSTATE}
7650 *
7651 * @note Locks the Console object for writing.
7652 * @remarks The @a pUVM parameter can be NULL in one case where powerUpThread()
7653 * calls after the VM was destroyed.
7654 */
7655DECLCALLBACK(void) Console::vmstateChangeCallback(PUVM pUVM, VMSTATE enmState, VMSTATE enmOldState, void *pvUser)
7656{
7657 LogFlowFunc(("Changing state from %s to %s (pUVM=%p)\n",
7658 VMR3GetStateName(enmOldState), VMR3GetStateName(enmState), pUVM));
7659
7660 Console *that = static_cast<Console *>(pvUser);
7661 AssertReturnVoid(that);
7662
7663 AutoCaller autoCaller(that);
7664
7665 /* Note that we must let this method proceed even if Console::uninit() has
7666 * been already called. In such case this VMSTATE change is a result of:
7667 * 1) powerDown() called from uninit() itself, or
7668 * 2) VM-(guest-)initiated power off. */
7669 AssertReturnVoid( autoCaller.isOk()
7670 || autoCaller.state() == InUninit);
7671
7672 switch (enmState)
7673 {
7674 /*
7675 * The VM has terminated
7676 */
7677 case VMSTATE_OFF:
7678 {
7679#ifdef VBOX_WITH_GUEST_PROPS
7680 if (that->isResetTurnedIntoPowerOff())
7681 {
7682 Bstr strPowerOffReason;
7683
7684 if (that->mfPowerOffCausedByReset)
7685 strPowerOffReason = Bstr("Reset");
7686 else
7687 strPowerOffReason = Bstr("PowerOff");
7688
7689 that->mMachine->DeleteGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw());
7690 that->mMachine->SetGuestProperty(Bstr("/VirtualBox/HostInfo/VMPowerOffReason").raw(),
7691 strPowerOffReason.raw(), Bstr("RDONLYGUEST").raw());
7692 that->mMachine->SaveSettings();
7693 }
7694#endif
7695
7696 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7697
7698 if (that->mVMStateChangeCallbackDisabled)
7699 return;
7700
7701 /* Do we still think that it is running? It may happen if this is a
7702 * VM-(guest-)initiated shutdown/poweroff.
7703 */
7704 if ( that->mMachineState != MachineState_Stopping
7705 && that->mMachineState != MachineState_Saving
7706 && that->mMachineState != MachineState_Restoring
7707 && that->mMachineState != MachineState_TeleportingIn
7708 && that->mMachineState != MachineState_FaultTolerantSyncing
7709 && that->mMachineState != MachineState_TeleportingPausedVM
7710 && !that->mVMIsAlreadyPoweringOff
7711 )
7712 {
7713 LogFlowFunc(("VM has powered itself off but Console still thinks it is running. Notifying.\n"));
7714
7715 /*
7716 * Prevent powerDown() from calling VMR3PowerOff() again if this was called from
7717 * the power off state change.
7718 * When called from the Reset state make sure to call VMR3PowerOff() first.
7719 */
7720 Assert(that->mVMPoweredOff == false);
7721 that->mVMPoweredOff = true;
7722
7723 /*
7724 * request a progress object from the server
7725 * (this will set the machine state to Stopping on the server
7726 * to block others from accessing this machine)
7727 */
7728 ComPtr<IProgress> pProgress;
7729 HRESULT rc = that->mControl->BeginPoweringDown(pProgress.asOutParam());
7730 AssertComRC(rc);
7731
7732 /* sync the state with the server */
7733 that->setMachineStateLocally(MachineState_Stopping);
7734
7735 /* Setup task object and thread to carry out the operation
7736 * asynchronously (if we call powerDown() right here but there
7737 * is one or more mpUVM callers (added with addVMCaller()) we'll
7738 * deadlock).
7739 */
7740 std::auto_ptr<VMPowerDownTask> task(new VMPowerDownTask(that, pProgress));
7741
7742 /* If creating a task failed, this can currently mean one of
7743 * two: either Console::uninit() has been called just a ms
7744 * before (so a powerDown() call is already on the way), or
7745 * powerDown() itself is being already executed. Just do
7746 * nothing.
7747 */
7748 if (!task->isOk())
7749 {
7750 LogFlowFunc(("Console is already being uninitialized.\n"));
7751 return;
7752 }
7753
7754 int vrc = RTThreadCreate(NULL, Console::powerDownThread,
7755 (void *)task.get(), 0,
7756 RTTHREADTYPE_MAIN_WORKER, 0,
7757 "VMPwrDwn");
7758 AssertMsgRCReturnVoid(vrc, ("Could not create VMPowerDown thread (%Rrc)\n", vrc));
7759
7760 /* task is now owned by powerDownThread(), so release it */
7761 task.release();
7762 }
7763 break;
7764 }
7765
7766 /* The VM has been completely destroyed.
7767 *
7768 * Note: This state change can happen at two points:
7769 * 1) At the end of VMR3Destroy() if it was not called from EMT.
7770 * 2) At the end of vmR3EmulationThread if VMR3Destroy() was
7771 * called by EMT.
7772 */
7773 case VMSTATE_TERMINATED:
7774 {
7775 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7776
7777 if (that->mVMStateChangeCallbackDisabled)
7778 break;
7779
7780 /* Terminate host interface networking. If pUVM is NULL, we've been
7781 * manually called from powerUpThread() either before calling
7782 * VMR3Create() or after VMR3Create() failed, so no need to touch
7783 * networking.
7784 */
7785 if (pUVM)
7786 that->powerDownHostInterfaces();
7787
7788 /* From now on the machine is officially powered down or remains in
7789 * the Saved state.
7790 */
7791 switch (that->mMachineState)
7792 {
7793 default:
7794 AssertFailed();
7795 /* fall through */
7796 case MachineState_Stopping:
7797 /* successfully powered down */
7798 that->setMachineState(MachineState_PoweredOff);
7799 break;
7800 case MachineState_Saving:
7801 /* successfully saved */
7802 that->setMachineState(MachineState_Saved);
7803 break;
7804 case MachineState_Starting:
7805 /* failed to start, but be patient: set back to PoweredOff
7806 * (for similarity with the below) */
7807 that->setMachineState(MachineState_PoweredOff);
7808 break;
7809 case MachineState_Restoring:
7810 /* failed to load the saved state file, but be patient: set
7811 * back to Saved (to preserve the saved state file) */
7812 that->setMachineState(MachineState_Saved);
7813 break;
7814 case MachineState_TeleportingIn:
7815 /* Teleportation failed or was canceled. Back to powered off. */
7816 that->setMachineState(MachineState_PoweredOff);
7817 break;
7818 case MachineState_TeleportingPausedVM:
7819 /* Successfully teleported the VM. */
7820 that->setMachineState(MachineState_Teleported);
7821 break;
7822 case MachineState_FaultTolerantSyncing:
7823 /* Fault tolerant sync failed or was canceled. Back to powered off. */
7824 that->setMachineState(MachineState_PoweredOff);
7825 break;
7826 }
7827 break;
7828 }
7829
7830 case VMSTATE_RESETTING:
7831 {
7832#ifdef VBOX_WITH_GUEST_PROPS
7833 /* Do not take any read/write locks here! */
7834 that->guestPropertiesHandleVMReset();
7835#endif
7836 break;
7837 }
7838
7839 case VMSTATE_SUSPENDED:
7840 {
7841 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7842
7843 if (that->mVMStateChangeCallbackDisabled)
7844 break;
7845
7846 switch (that->mMachineState)
7847 {
7848 case MachineState_Teleporting:
7849 that->setMachineState(MachineState_TeleportingPausedVM);
7850 break;
7851
7852 case MachineState_LiveSnapshotting:
7853 that->setMachineState(MachineState_Saving);
7854 break;
7855
7856 case MachineState_TeleportingPausedVM:
7857 case MachineState_Saving:
7858 case MachineState_Restoring:
7859 case MachineState_Stopping:
7860 case MachineState_TeleportingIn:
7861 case MachineState_FaultTolerantSyncing:
7862 /* The worker thread handles the transition. */
7863 break;
7864
7865 default:
7866 AssertMsgFailed(("%s\n", Global::stringifyMachineState(that->mMachineState)));
7867 case MachineState_Running:
7868 that->setMachineState(MachineState_Paused);
7869 break;
7870
7871 case MachineState_Paused:
7872 /* Nothing to do. */
7873 break;
7874 }
7875 break;
7876 }
7877
7878 case VMSTATE_SUSPENDED_LS:
7879 case VMSTATE_SUSPENDED_EXT_LS:
7880 {
7881 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7882 if (that->mVMStateChangeCallbackDisabled)
7883 break;
7884 switch (that->mMachineState)
7885 {
7886 case MachineState_Teleporting:
7887 that->setMachineState(MachineState_TeleportingPausedVM);
7888 break;
7889
7890 case MachineState_LiveSnapshotting:
7891 that->setMachineState(MachineState_Saving);
7892 break;
7893
7894 case MachineState_TeleportingPausedVM:
7895 case MachineState_Saving:
7896 /* ignore */
7897 break;
7898
7899 default:
7900 AssertMsgFailed(("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState), VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
7901 that->setMachineState(MachineState_Paused);
7902 break;
7903 }
7904 break;
7905 }
7906
7907 case VMSTATE_RUNNING:
7908 {
7909 if ( enmOldState == VMSTATE_POWERING_ON
7910 || enmOldState == VMSTATE_RESUMING
7911 || enmOldState == VMSTATE_RUNNING_FT)
7912 {
7913 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7914
7915 if (that->mVMStateChangeCallbackDisabled)
7916 break;
7917
7918 Assert( ( ( that->mMachineState == MachineState_Starting
7919 || that->mMachineState == MachineState_Paused)
7920 && enmOldState == VMSTATE_POWERING_ON)
7921 || ( ( that->mMachineState == MachineState_Restoring
7922 || that->mMachineState == MachineState_TeleportingIn
7923 || that->mMachineState == MachineState_Paused
7924 || that->mMachineState == MachineState_Saving
7925 )
7926 && enmOldState == VMSTATE_RESUMING)
7927 || ( that->mMachineState == MachineState_FaultTolerantSyncing
7928 && enmOldState == VMSTATE_RUNNING_FT));
7929
7930 that->setMachineState(MachineState_Running);
7931 }
7932
7933 break;
7934 }
7935
7936 case VMSTATE_RUNNING_LS:
7937 AssertMsg( that->mMachineState == MachineState_LiveSnapshotting
7938 || that->mMachineState == MachineState_Teleporting,
7939 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState), VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
7940 break;
7941
7942 case VMSTATE_RUNNING_FT:
7943 AssertMsg(that->mMachineState == MachineState_FaultTolerantSyncing,
7944 ("%s/%s -> %s\n", Global::stringifyMachineState(that->mMachineState), VMR3GetStateName(enmOldState), VMR3GetStateName(enmState) ));
7945 break;
7946
7947 case VMSTATE_FATAL_ERROR:
7948 {
7949 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7950
7951 if (that->mVMStateChangeCallbackDisabled)
7952 break;
7953
7954 /* Fatal errors are only for running VMs. */
7955 Assert(Global::IsOnline(that->mMachineState));
7956
7957 /* Note! 'Pause' is used here in want of something better. There
7958 * are currently only two places where fatal errors might be
7959 * raised, so it is not worth adding a new externally
7960 * visible state for this yet. */
7961 that->setMachineState(MachineState_Paused);
7962 break;
7963 }
7964
7965 case VMSTATE_GURU_MEDITATION:
7966 {
7967 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
7968
7969 if (that->mVMStateChangeCallbackDisabled)
7970 break;
7971
7972 /* Guru are only for running VMs */
7973 Assert(Global::IsOnline(that->mMachineState));
7974
7975 that->setMachineState(MachineState_Stuck);
7976 break;
7977 }
7978
7979 default: /* shut up gcc */
7980 break;
7981 }
7982}
7983
7984/**
7985 * Changes the clipboard mode.
7986 *
7987 * @param aClipboardMode new clipboard mode.
7988 */
7989void Console::changeClipboardMode(ClipboardMode_T aClipboardMode)
7990{
7991 VMMDev *pVMMDev = m_pVMMDev;
7992 Assert(pVMMDev);
7993
7994 VBOXHGCMSVCPARM parm;
7995 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
7996
7997 switch (aClipboardMode)
7998 {
7999 default:
8000 case ClipboardMode_Disabled:
8001 LogRel(("Shared clipboard mode: Off\n"));
8002 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_OFF;
8003 break;
8004 case ClipboardMode_GuestToHost:
8005 LogRel(("Shared clipboard mode: Guest to Host\n"));
8006 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_GUEST_TO_HOST;
8007 break;
8008 case ClipboardMode_HostToGuest:
8009 LogRel(("Shared clipboard mode: Host to Guest\n"));
8010 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_HOST_TO_GUEST;
8011 break;
8012 case ClipboardMode_Bidirectional:
8013 LogRel(("Shared clipboard mode: Bidirectional\n"));
8014 parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_BIDIRECTIONAL;
8015 break;
8016 }
8017
8018 pVMMDev->hgcmHostCall("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE, 1, &parm);
8019}
8020
8021/**
8022 * Changes the drag'n_drop mode.
8023 *
8024 * @param aDragAndDropMode new drag'n'drop mode.
8025 */
8026void Console::changeDragAndDropMode(DragAndDropMode_T aDragAndDropMode)
8027{
8028 VMMDev *pVMMDev = m_pVMMDev;
8029 Assert(pVMMDev);
8030
8031 VBOXHGCMSVCPARM parm;
8032 parm.type = VBOX_HGCM_SVC_PARM_32BIT;
8033
8034 switch (aDragAndDropMode)
8035 {
8036 default:
8037 case DragAndDropMode_Disabled:
8038 LogRel(("Drag'n'drop mode: Off\n"));
8039 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_OFF;
8040 break;
8041 case DragAndDropMode_GuestToHost:
8042 LogRel(("Drag'n'drop mode: Guest to Host\n"));
8043 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_GUEST_TO_HOST;
8044 break;
8045 case DragAndDropMode_HostToGuest:
8046 LogRel(("Drag'n'drop mode: Host to Guest\n"));
8047 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_HOST_TO_GUEST;
8048 break;
8049 case DragAndDropMode_Bidirectional:
8050 LogRel(("Drag'n'drop mode: Bidirectional\n"));
8051 parm.u.uint32 = VBOX_DRAG_AND_DROP_MODE_BIDIRECTIONAL;
8052 break;
8053 }
8054
8055 pVMMDev->hgcmHostCall("VBoxDragAndDropSvc", DragAndDropSvc::HOST_DND_SET_MODE, 1, &parm);
8056}
8057
8058#ifdef VBOX_WITH_USB
8059/**
8060 * Sends a request to VMM to attach the given host device.
8061 * After this method succeeds, the attached device will appear in the
8062 * mUSBDevices collection.
8063 *
8064 * @param aHostDevice device to attach
8065 *
8066 * @note Synchronously calls EMT.
8067 */
8068HRESULT Console::attachUSBDevice(IUSBDevice *aHostDevice, ULONG aMaskedIfs)
8069{
8070 AssertReturn(aHostDevice, E_FAIL);
8071 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
8072
8073 HRESULT hrc;
8074
8075 /*
8076 * Get the address and the Uuid, and call the pfnCreateProxyDevice roothub
8077 * method in EMT (using usbAttachCallback()).
8078 */
8079 Bstr BstrAddress;
8080 hrc = aHostDevice->COMGETTER(Address)(BstrAddress.asOutParam());
8081 ComAssertComRCRetRC(hrc);
8082
8083 Utf8Str Address(BstrAddress);
8084
8085 Bstr id;
8086 hrc = aHostDevice->COMGETTER(Id)(id.asOutParam());
8087 ComAssertComRCRetRC(hrc);
8088 Guid uuid(id);
8089
8090 BOOL fRemote = FALSE;
8091 hrc = aHostDevice->COMGETTER(Remote)(&fRemote);
8092 ComAssertComRCRetRC(hrc);
8093
8094 /* Get the VM handle. */
8095 SafeVMPtr ptrVM(this);
8096 if (!ptrVM.isOk())
8097 return ptrVM.rc();
8098
8099 LogFlowThisFunc(("Proxying USB device '%s' {%RTuuid}...\n",
8100 Address.c_str(), uuid.raw()));
8101
8102 void *pvRemoteBackend = NULL;
8103 if (fRemote)
8104 {
8105 RemoteUSBDevice *pRemoteUSBDevice = static_cast<RemoteUSBDevice *>(aHostDevice);
8106 pvRemoteBackend = consoleVRDPServer()->USBBackendRequestPointer(pRemoteUSBDevice->clientId(), &uuid);
8107 if (!pvRemoteBackend)
8108 return E_INVALIDARG; /* The clientId is invalid then. */
8109 }
8110
8111 USHORT portVersion = 1;
8112 hrc = aHostDevice->COMGETTER(PortVersion)(&portVersion);
8113 AssertComRCReturnRC(hrc);
8114 Assert(portVersion == 1 || portVersion == 2);
8115
8116 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
8117 (PFNRT)usbAttachCallback, 9,
8118 this, ptrVM.rawUVM(), aHostDevice, uuid.raw(), fRemote,
8119 Address.c_str(), pvRemoteBackend, portVersion, aMaskedIfs);
8120 if (RT_SUCCESS(vrc))
8121 {
8122 /* Create a OUSBDevice and add it to the device list */
8123 ComObjPtr<OUSBDevice> pUSBDevice;
8124 pUSBDevice.createObject();
8125 hrc = pUSBDevice->init(aHostDevice);
8126 AssertComRC(hrc);
8127
8128 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8129 mUSBDevices.push_back(pUSBDevice);
8130 LogFlowFunc(("Attached device {%RTuuid}\n", pUSBDevice->i_id().raw()));
8131
8132 /* notify callbacks */
8133 alock.release();
8134 onUSBDeviceStateChange(pUSBDevice, true /* aAttached */, NULL);
8135 }
8136 else
8137 {
8138 LogWarningThisFunc(("Failed to create proxy device for '%s' {%RTuuid} (%Rrc)\n",
8139 Address.c_str(), uuid.raw(), vrc));
8140
8141 switch (vrc)
8142 {
8143 case VERR_VUSB_NO_PORTS:
8144 hrc = setError(E_FAIL, tr("Failed to attach the USB device. (No available ports on the USB controller)."));
8145 break;
8146 case VERR_VUSB_USBFS_PERMISSION:
8147 hrc = setError(E_FAIL, tr("Not permitted to open the USB device, check usbfs options"));
8148 break;
8149 default:
8150 hrc = setError(E_FAIL, tr("Failed to create a proxy device for the USB device. (Error: %Rrc)"), vrc);
8151 break;
8152 }
8153 }
8154
8155 return hrc;
8156}
8157
8158/**
8159 * USB device attach callback used by AttachUSBDevice().
8160 * Note that AttachUSBDevice() doesn't return until this callback is executed,
8161 * so we don't use AutoCaller and don't care about reference counters of
8162 * interface pointers passed in.
8163 *
8164 * @thread EMT
8165 * @note Locks the console object for writing.
8166 */
8167//static
8168DECLCALLBACK(int)
8169Console::usbAttachCallback(Console *that, PUVM pUVM, IUSBDevice *aHostDevice, PCRTUUID aUuid, bool aRemote,
8170 const char *aAddress, void *pvRemoteBackend, USHORT aPortVersion, ULONG aMaskedIfs)
8171{
8172 LogFlowFuncEnter();
8173 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
8174
8175 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
8176 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
8177
8178 int vrc = PDMR3UsbCreateProxyDevice(pUVM, aUuid, aRemote, aAddress, pvRemoteBackend,
8179 aPortVersion == 1 ? VUSB_STDVER_11 : VUSB_STDVER_20, aMaskedIfs);
8180 LogFlowFunc(("vrc=%Rrc\n", vrc));
8181 LogFlowFuncLeave();
8182 return vrc;
8183}
8184
8185/**
8186 * Sends a request to VMM to detach the given host device. After this method
8187 * succeeds, the detached device will disappear from the mUSBDevices
8188 * collection.
8189 *
8190 * @param aHostDevice device to attach
8191 *
8192 * @note Synchronously calls EMT.
8193 */
8194HRESULT Console::detachUSBDevice(const ComObjPtr<OUSBDevice> &aHostDevice)
8195{
8196 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
8197
8198 /* Get the VM handle. */
8199 SafeVMPtr ptrVM(this);
8200 if (!ptrVM.isOk())
8201 return ptrVM.rc();
8202
8203 /* if the device is attached, then there must at least one USB hub. */
8204 AssertReturn(PDMR3UsbHasHub(ptrVM.rawUVM()), E_FAIL);
8205
8206 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8207 LogFlowThisFunc(("Detaching USB proxy device {%RTuuid}...\n",
8208 aHostDevice->i_id().raw()));
8209
8210 /*
8211 * If this was a remote device, release the backend pointer.
8212 * The pointer was requested in usbAttachCallback.
8213 */
8214 BOOL fRemote = FALSE;
8215
8216 HRESULT hrc2 = aHostDevice->COMGETTER(Remote)(&fRemote);
8217 if (FAILED(hrc2))
8218 setErrorStatic(hrc2, "GetRemote() failed");
8219
8220 PCRTUUID pUuid = aHostDevice->i_id().raw();
8221 if (fRemote)
8222 {
8223 Guid guid(*pUuid);
8224 consoleVRDPServer()->USBBackendReleasePointer(&guid);
8225 }
8226
8227 alock.release();
8228 int vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), 0 /* idDstCpu (saved state, see #6232) */,
8229 (PFNRT)usbDetachCallback, 5,
8230 this, ptrVM.rawUVM(), pUuid);
8231 if (RT_SUCCESS(vrc))
8232 {
8233 LogFlowFunc(("Detached device {%RTuuid}\n", pUuid));
8234
8235 /* notify callbacks */
8236 onUSBDeviceStateChange(aHostDevice, false /* aAttached */, NULL);
8237 }
8238
8239 ComAssertRCRet(vrc, E_FAIL);
8240
8241 return S_OK;
8242}
8243
8244/**
8245 * USB device detach callback used by DetachUSBDevice().
8246 *
8247 * Note that DetachUSBDevice() doesn't return until this callback is executed,
8248 * so we don't use AutoCaller and don't care about reference counters of
8249 * interface pointers passed in.
8250 *
8251 * @thread EMT
8252 */
8253//static
8254DECLCALLBACK(int)
8255Console::usbDetachCallback(Console *that, PUVM pUVM, PCRTUUID aUuid)
8256{
8257 LogFlowFuncEnter();
8258 LogFlowFunc(("that={%p} aUuid={%RTuuid}\n", that, aUuid));
8259
8260 AssertReturn(that && aUuid, VERR_INVALID_PARAMETER);
8261 AssertReturn(!that->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
8262
8263 int vrc = PDMR3UsbDetachDevice(pUVM, aUuid);
8264
8265 LogFlowFunc(("vrc=%Rrc\n", vrc));
8266 LogFlowFuncLeave();
8267 return vrc;
8268}
8269#endif /* VBOX_WITH_USB */
8270
8271/* Note: FreeBSD needs this whether netflt is used or not. */
8272#if ((defined(RT_OS_LINUX) && !defined(VBOX_WITH_NETFLT)) || defined(RT_OS_FREEBSD))
8273/**
8274 * Helper function to handle host interface device creation and attachment.
8275 *
8276 * @param networkAdapter the network adapter which attachment should be reset
8277 * @return COM status code
8278 *
8279 * @note The caller must lock this object for writing.
8280 *
8281 * @todo Move this back into the driver!
8282 */
8283HRESULT Console::attachToTapInterface(INetworkAdapter *networkAdapter)
8284{
8285 LogFlowThisFunc(("\n"));
8286 /* sanity check */
8287 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8288
8289# ifdef VBOX_STRICT
8290 /* paranoia */
8291 NetworkAttachmentType_T attachment;
8292 networkAdapter->COMGETTER(AttachmentType)(&attachment);
8293 Assert(attachment == NetworkAttachmentType_Bridged);
8294# endif /* VBOX_STRICT */
8295
8296 HRESULT rc = S_OK;
8297
8298 ULONG slot = 0;
8299 rc = networkAdapter->COMGETTER(Slot)(&slot);
8300 AssertComRC(rc);
8301
8302# ifdef RT_OS_LINUX
8303 /*
8304 * Allocate a host interface device
8305 */
8306 int rcVBox = RTFileOpen(&maTapFD[slot], "/dev/net/tun",
8307 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT);
8308 if (RT_SUCCESS(rcVBox))
8309 {
8310 /*
8311 * Set/obtain the tap interface.
8312 */
8313 struct ifreq IfReq;
8314 RT_ZERO(IfReq);
8315 /* The name of the TAP interface we are using */
8316 Bstr tapDeviceName;
8317 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
8318 if (FAILED(rc))
8319 tapDeviceName.setNull(); /* Is this necessary? */
8320 if (tapDeviceName.isEmpty())
8321 {
8322 LogRel(("No TAP device name was supplied.\n"));
8323 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
8324 }
8325
8326 if (SUCCEEDED(rc))
8327 {
8328 /* If we are using a static TAP device then try to open it. */
8329 Utf8Str str(tapDeviceName);
8330 RTStrCopy(IfReq.ifr_name, sizeof(IfReq.ifr_name), str.c_str()); /** @todo bitch about names which are too long... */
8331 IfReq.ifr_flags = IFF_TAP | IFF_NO_PI;
8332 rcVBox = ioctl(RTFileToNative(maTapFD[slot]), TUNSETIFF, &IfReq);
8333 if (rcVBox != 0)
8334 {
8335 LogRel(("Failed to open the host network interface %ls\n", tapDeviceName.raw()));
8336 rc = setError(E_FAIL,
8337 tr("Failed to open the host network interface %ls"),
8338 tapDeviceName.raw());
8339 }
8340 }
8341 if (SUCCEEDED(rc))
8342 {
8343 /*
8344 * Make it pollable.
8345 */
8346 if (fcntl(RTFileToNative(maTapFD[slot]), F_SETFL, O_NONBLOCK) != -1)
8347 {
8348 Log(("attachToTapInterface: %RTfile %ls\n", maTapFD[slot], tapDeviceName.raw()));
8349 /*
8350 * Here is the right place to communicate the TAP file descriptor and
8351 * the host interface name to the server if/when it becomes really
8352 * necessary.
8353 */
8354 maTAPDeviceName[slot] = tapDeviceName;
8355 rcVBox = VINF_SUCCESS;
8356 }
8357 else
8358 {
8359 int iErr = errno;
8360
8361 LogRel(("Configuration error: Failed to configure /dev/net/tun non blocking. Error: %s\n", strerror(iErr)));
8362 rcVBox = VERR_HOSTIF_BLOCKING;
8363 rc = setError(E_FAIL,
8364 tr("could not set up the host networking device for non blocking access: %s"),
8365 strerror(errno));
8366 }
8367 }
8368 }
8369 else
8370 {
8371 LogRel(("Configuration error: Failed to open /dev/net/tun rc=%Rrc\n", rcVBox));
8372 switch (rcVBox)
8373 {
8374 case VERR_ACCESS_DENIED:
8375 /* will be handled by our caller */
8376 rc = rcVBox;
8377 break;
8378 default:
8379 rc = setError(E_FAIL,
8380 tr("Could not set up the host networking device: %Rrc"),
8381 rcVBox);
8382 break;
8383 }
8384 }
8385
8386# elif defined(RT_OS_FREEBSD)
8387 /*
8388 * Set/obtain the tap interface.
8389 */
8390 /* The name of the TAP interface we are using */
8391 Bstr tapDeviceName;
8392 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
8393 if (FAILED(rc))
8394 tapDeviceName.setNull(); /* Is this necessary? */
8395 if (tapDeviceName.isEmpty())
8396 {
8397 LogRel(("No TAP device name was supplied.\n"));
8398 rc = setError(E_FAIL, tr("No TAP device name was supplied for the host networking interface"));
8399 }
8400 char szTapdev[1024] = "/dev/";
8401 /* If we are using a static TAP device then try to open it. */
8402 Utf8Str str(tapDeviceName);
8403 if (str.length() + strlen(szTapdev) <= sizeof(szTapdev))
8404 strcat(szTapdev, str.c_str());
8405 else
8406 memcpy(szTapdev + strlen(szTapdev), str.c_str(),
8407 sizeof(szTapdev) - strlen(szTapdev) - 1); /** @todo bitch about names which are too long... */
8408 int rcVBox = RTFileOpen(&maTapFD[slot], szTapdev,
8409 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_INHERIT | RTFILE_O_NON_BLOCK);
8410
8411 if (RT_SUCCESS(rcVBox))
8412 maTAPDeviceName[slot] = tapDeviceName;
8413 else
8414 {
8415 switch (rcVBox)
8416 {
8417 case VERR_ACCESS_DENIED:
8418 /* will be handled by our caller */
8419 rc = rcVBox;
8420 break;
8421 default:
8422 rc = setError(E_FAIL,
8423 tr("Failed to open the host network interface %ls"),
8424 tapDeviceName.raw());
8425 break;
8426 }
8427 }
8428# else
8429# error "huh?"
8430# endif
8431 /* in case of failure, cleanup. */
8432 if (RT_FAILURE(rcVBox) && SUCCEEDED(rc))
8433 {
8434 LogRel(("General failure attaching to host interface\n"));
8435 rc = setError(E_FAIL,
8436 tr("General failure attaching to host interface"));
8437 }
8438 LogFlowThisFunc(("rc=%d\n", rc));
8439 return rc;
8440}
8441
8442
8443/**
8444 * Helper function to handle detachment from a host interface
8445 *
8446 * @param networkAdapter the network adapter which attachment should be reset
8447 * @return COM status code
8448 *
8449 * @note The caller must lock this object for writing.
8450 *
8451 * @todo Move this back into the driver!
8452 */
8453HRESULT Console::detachFromTapInterface(INetworkAdapter *networkAdapter)
8454{
8455 /* sanity check */
8456 LogFlowThisFunc(("\n"));
8457 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8458
8459 HRESULT rc = S_OK;
8460# ifdef VBOX_STRICT
8461 /* paranoia */
8462 NetworkAttachmentType_T attachment;
8463 networkAdapter->COMGETTER(AttachmentType)(&attachment);
8464 Assert(attachment == NetworkAttachmentType_Bridged);
8465# endif /* VBOX_STRICT */
8466
8467 ULONG slot = 0;
8468 rc = networkAdapter->COMGETTER(Slot)(&slot);
8469 AssertComRC(rc);
8470
8471 /* is there an open TAP device? */
8472 if (maTapFD[slot] != NIL_RTFILE)
8473 {
8474 /*
8475 * Close the file handle.
8476 */
8477 Bstr tapDeviceName, tapTerminateApplication;
8478 bool isStatic = true;
8479 rc = networkAdapter->COMGETTER(BridgedInterface)(tapDeviceName.asOutParam());
8480 if (FAILED(rc) || tapDeviceName.isEmpty())
8481 {
8482 /* If the name is empty, this is a dynamic TAP device, so close it now,
8483 so that the termination script can remove the interface. Otherwise we still
8484 need the FD to pass to the termination script. */
8485 isStatic = false;
8486 int rcVBox = RTFileClose(maTapFD[slot]);
8487 AssertRC(rcVBox);
8488 maTapFD[slot] = NIL_RTFILE;
8489 }
8490 if (isStatic)
8491 {
8492 /* If we are using a static TAP device, we close it now, after having called the
8493 termination script. */
8494 int rcVBox = RTFileClose(maTapFD[slot]);
8495 AssertRC(rcVBox);
8496 }
8497 /* the TAP device name and handle are no longer valid */
8498 maTapFD[slot] = NIL_RTFILE;
8499 maTAPDeviceName[slot] = "";
8500 }
8501 LogFlowThisFunc(("returning %d\n", rc));
8502 return rc;
8503}
8504#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
8505
8506/**
8507 * Called at power down to terminate host interface networking.
8508 *
8509 * @note The caller must lock this object for writing.
8510 */
8511HRESULT Console::powerDownHostInterfaces()
8512{
8513 LogFlowThisFunc(("\n"));
8514
8515 /* sanity check */
8516 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
8517
8518 /*
8519 * host interface termination handling
8520 */
8521 HRESULT rc = S_OK;
8522 ComPtr<IVirtualBox> pVirtualBox;
8523 mMachine->COMGETTER(Parent)(pVirtualBox.asOutParam());
8524 ComPtr<ISystemProperties> pSystemProperties;
8525 if (pVirtualBox)
8526 pVirtualBox->COMGETTER(SystemProperties)(pSystemProperties.asOutParam());
8527 ChipsetType_T chipsetType = ChipsetType_PIIX3;
8528 mMachine->COMGETTER(ChipsetType)(&chipsetType);
8529 ULONG maxNetworkAdapters = 0;
8530 if (pSystemProperties)
8531 pSystemProperties->GetMaxNetworkAdapters(chipsetType, &maxNetworkAdapters);
8532
8533 for (ULONG slot = 0; slot < maxNetworkAdapters; slot++)
8534 {
8535 ComPtr<INetworkAdapter> pNetworkAdapter;
8536 rc = mMachine->GetNetworkAdapter(slot, pNetworkAdapter.asOutParam());
8537 if (FAILED(rc)) break;
8538
8539 BOOL enabled = FALSE;
8540 pNetworkAdapter->COMGETTER(Enabled)(&enabled);
8541 if (!enabled)
8542 continue;
8543
8544 NetworkAttachmentType_T attachment;
8545 pNetworkAdapter->COMGETTER(AttachmentType)(&attachment);
8546 if (attachment == NetworkAttachmentType_Bridged)
8547 {
8548#if ((defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT))
8549 HRESULT rc2 = detachFromTapInterface(pNetworkAdapter);
8550 if (FAILED(rc2) && SUCCEEDED(rc))
8551 rc = rc2;
8552#endif /* (RT_OS_LINUX || RT_OS_FREEBSD) && !VBOX_WITH_NETFLT */
8553 }
8554 }
8555
8556 return rc;
8557}
8558
8559
8560/**
8561 * Process callback handler for VMR3LoadFromFile, VMR3LoadFromStream, VMR3Save
8562 * and VMR3Teleport.
8563 *
8564 * @param pUVM The user mode VM handle.
8565 * @param uPercent Completion percentage (0-100).
8566 * @param pvUser Pointer to an IProgress instance.
8567 * @return VINF_SUCCESS.
8568 */
8569/*static*/
8570DECLCALLBACK(int) Console::stateProgressCallback(PUVM pUVM, unsigned uPercent, void *pvUser)
8571{
8572 IProgress *pProgress = static_cast<IProgress *>(pvUser);
8573
8574 /* update the progress object */
8575 if (pProgress)
8576 pProgress->SetCurrentOperationProgress(uPercent);
8577
8578 NOREF(pUVM);
8579 return VINF_SUCCESS;
8580}
8581
8582/**
8583 * @copydoc FNVMATERROR
8584 *
8585 * @remarks Might be some tiny serialization concerns with access to the string
8586 * object here...
8587 */
8588/*static*/ DECLCALLBACK(void)
8589Console::genericVMSetErrorCallback(PUVM pUVM, void *pvUser, int rc, RT_SRC_POS_DECL,
8590 const char *pszErrorFmt, va_list va)
8591{
8592 Utf8Str *pErrorText = (Utf8Str *)pvUser;
8593 AssertPtr(pErrorText);
8594
8595 /* We ignore RT_SRC_POS_DECL arguments to avoid confusion of end-users. */
8596 va_list va2;
8597 va_copy(va2, va);
8598
8599 /* Append to any the existing error message. */
8600 if (pErrorText->length())
8601 *pErrorText = Utf8StrFmt("%s.\n%N (%Rrc)", pErrorText->c_str(),
8602 pszErrorFmt, &va2, rc, rc);
8603 else
8604 *pErrorText = Utf8StrFmt("%N (%Rrc)", pszErrorFmt, &va2, rc, rc);
8605
8606 va_end(va2);
8607
8608 NOREF(pUVM);
8609}
8610
8611/**
8612 * VM runtime error callback function.
8613 * See VMSetRuntimeError for the detailed description of parameters.
8614 *
8615 * @param pUVM The user mode VM handle. Ignored, so passing NULL
8616 * is fine.
8617 * @param pvUser The user argument, pointer to the Console instance.
8618 * @param fFlags The action flags. See VMSETRTERR_FLAGS_*.
8619 * @param pszErrorId Error ID string.
8620 * @param pszFormat Error message format string.
8621 * @param va Error message arguments.
8622 * @thread EMT.
8623 */
8624/* static */ DECLCALLBACK(void)
8625Console::setVMRuntimeErrorCallback(PUVM pUVM, void *pvUser, uint32_t fFlags,
8626 const char *pszErrorId,
8627 const char *pszFormat, va_list va)
8628{
8629 bool const fFatal = !!(fFlags & VMSETRTERR_FLAGS_FATAL);
8630 LogFlowFuncEnter();
8631
8632 Console *that = static_cast<Console *>(pvUser);
8633 AssertReturnVoid(that);
8634
8635 Utf8Str message(pszFormat, va);
8636
8637 LogRel(("Console: VM runtime error: fatal=%RTbool, errorID=%s message=\"%s\"\n",
8638 fFatal, pszErrorId, message.c_str()));
8639
8640 that->onRuntimeError(BOOL(fFatal), Bstr(pszErrorId).raw(), Bstr(message).raw());
8641
8642 LogFlowFuncLeave(); NOREF(pUVM);
8643}
8644
8645/**
8646 * Captures USB devices that match filters of the VM.
8647 * Called at VM startup.
8648 *
8649 * @param pUVM The VM handle.
8650 */
8651HRESULT Console::captureUSBDevices(PUVM pUVM)
8652{
8653 LogFlowThisFunc(("\n"));
8654
8655 /* sanity check */
8656 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
8657 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8658
8659 /* If the machine has a USB controller, ask the USB proxy service to
8660 * capture devices */
8661 if (mfVMHasUsbController)
8662 {
8663 /* release the lock before calling Host in VBoxSVC since Host may call
8664 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
8665 * produce an inter-process dead-lock otherwise. */
8666 alock.release();
8667
8668 HRESULT hrc = mControl->AutoCaptureUSBDevices();
8669 ComAssertComRCRetRC(hrc);
8670 }
8671
8672 return S_OK;
8673}
8674
8675
8676/**
8677 * Detach all USB device which are attached to the VM for the
8678 * purpose of clean up and such like.
8679 */
8680void Console::detachAllUSBDevices(bool aDone)
8681{
8682 LogFlowThisFunc(("aDone=%RTbool\n", aDone));
8683
8684 /* sanity check */
8685 AssertReturnVoid(!isWriteLockOnCurrentThread());
8686 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8687
8688 mUSBDevices.clear();
8689
8690 /* release the lock before calling Host in VBoxSVC since Host may call
8691 * us back from under its lock (e.g. onUSBDeviceAttach()) which would
8692 * produce an inter-process dead-lock otherwise. */
8693 alock.release();
8694
8695 mControl->DetachAllUSBDevices(aDone);
8696}
8697
8698/**
8699 * @note Locks this object for writing.
8700 */
8701void Console::processRemoteUSBDevices(uint32_t u32ClientId, VRDEUSBDEVICEDESC *pDevList, uint32_t cbDevList, bool fDescExt)
8702{
8703 LogFlowThisFuncEnter();
8704 LogFlowThisFunc(("u32ClientId = %d, pDevList=%p, cbDevList = %d, fDescExt = %d\n", u32ClientId, pDevList, cbDevList, fDescExt));
8705
8706 AutoCaller autoCaller(this);
8707 if (!autoCaller.isOk())
8708 {
8709 /* Console has been already uninitialized, deny request */
8710 AssertMsgFailed(("Console is already uninitialized\n"));
8711 LogFlowThisFunc(("Console is already uninitialized\n"));
8712 LogFlowThisFuncLeave();
8713 return;
8714 }
8715
8716 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
8717
8718 /*
8719 * Mark all existing remote USB devices as dirty.
8720 */
8721 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
8722 it != mRemoteUSBDevices.end();
8723 ++it)
8724 {
8725 (*it)->dirty(true);
8726 }
8727
8728 /*
8729 * Process the pDevList and add devices those are not already in the mRemoteUSBDevices list.
8730 */
8731 /** @todo (sunlover) REMOTE_USB Strict validation of the pDevList. */
8732 VRDEUSBDEVICEDESC *e = pDevList;
8733
8734 /* The cbDevList condition must be checked first, because the function can
8735 * receive pDevList = NULL and cbDevList = 0 on client disconnect.
8736 */
8737 while (cbDevList >= 2 && e->oNext)
8738 {
8739 /* Sanitize incoming strings in case they aren't valid UTF-8. */
8740 if (e->oManufacturer)
8741 RTStrPurgeEncoding((char *)e + e->oManufacturer);
8742 if (e->oProduct)
8743 RTStrPurgeEncoding((char *)e + e->oProduct);
8744 if (e->oSerialNumber)
8745 RTStrPurgeEncoding((char *)e + e->oSerialNumber);
8746
8747 LogFlowThisFunc(("vendor %04X, product %04X, name = %s\n",
8748 e->idVendor, e->idProduct,
8749 e->oProduct? (char *)e + e->oProduct: ""));
8750
8751 bool fNewDevice = true;
8752
8753 for (RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
8754 it != mRemoteUSBDevices.end();
8755 ++it)
8756 {
8757 if ((*it)->devId() == e->id
8758 && (*it)->clientId() == u32ClientId)
8759 {
8760 /* The device is already in the list. */
8761 (*it)->dirty(false);
8762 fNewDevice = false;
8763 break;
8764 }
8765 }
8766
8767 if (fNewDevice)
8768 {
8769 LogRel(("Remote USB: ++++ Vendor %04X. Product %04X. Name = [%s].\n",
8770 e->idVendor, e->idProduct, e->oProduct? (char *)e + e->oProduct: ""));
8771
8772 /* Create the device object and add the new device to list. */
8773 ComObjPtr<RemoteUSBDevice> pUSBDevice;
8774 pUSBDevice.createObject();
8775 pUSBDevice->init(u32ClientId, e, fDescExt);
8776
8777 mRemoteUSBDevices.push_back(pUSBDevice);
8778
8779 /* Check if the device is ok for current USB filters. */
8780 BOOL fMatched = FALSE;
8781 ULONG fMaskedIfs = 0;
8782
8783 HRESULT hrc = mControl->RunUSBDeviceFilters(pUSBDevice, &fMatched, &fMaskedIfs);
8784
8785 AssertComRC(hrc);
8786
8787 LogFlowThisFunc(("USB filters return %d %#x\n", fMatched, fMaskedIfs));
8788
8789 if (fMatched)
8790 {
8791 alock.release();
8792 hrc = onUSBDeviceAttach(pUSBDevice, NULL, fMaskedIfs);
8793 alock.acquire();
8794
8795 /// @todo (r=dmik) warning reporting subsystem
8796
8797 if (hrc == S_OK)
8798 {
8799 LogFlowThisFunc(("Device attached\n"));
8800 pUSBDevice->captured(true);
8801 }
8802 }
8803 }
8804
8805 if (cbDevList < e->oNext)
8806 {
8807 LogWarningThisFunc(("cbDevList %d > oNext %d\n",
8808 cbDevList, e->oNext));
8809 break;
8810 }
8811
8812 cbDevList -= e->oNext;
8813
8814 e = (VRDEUSBDEVICEDESC *)((uint8_t *)e + e->oNext);
8815 }
8816
8817 /*
8818 * Remove dirty devices, that is those which are not reported by the server anymore.
8819 */
8820 for (;;)
8821 {
8822 ComObjPtr<RemoteUSBDevice> pUSBDevice;
8823
8824 RemoteUSBDeviceList::iterator it = mRemoteUSBDevices.begin();
8825 while (it != mRemoteUSBDevices.end())
8826 {
8827 if ((*it)->dirty())
8828 {
8829 pUSBDevice = *it;
8830 break;
8831 }
8832
8833 ++it;
8834 }
8835
8836 if (!pUSBDevice)
8837 {
8838 break;
8839 }
8840
8841 USHORT vendorId = 0;
8842 pUSBDevice->COMGETTER(VendorId)(&vendorId);
8843
8844 USHORT productId = 0;
8845 pUSBDevice->COMGETTER(ProductId)(&productId);
8846
8847 Bstr product;
8848 pUSBDevice->COMGETTER(Product)(product.asOutParam());
8849
8850 LogRel(("Remote USB: ---- Vendor %04X. Product %04X. Name = [%ls].\n",
8851 vendorId, productId, product.raw()));
8852
8853 /* Detach the device from VM. */
8854 if (pUSBDevice->captured())
8855 {
8856 Bstr uuid;
8857 pUSBDevice->COMGETTER(Id)(uuid.asOutParam());
8858 alock.release();
8859 onUSBDeviceDetach(uuid.raw(), NULL);
8860 alock.acquire();
8861 }
8862
8863 /* And remove it from the list. */
8864 mRemoteUSBDevices.erase(it);
8865 }
8866
8867 LogFlowThisFuncLeave();
8868}
8869
8870/**
8871 * Progress cancelation callback for fault tolerance VM poweron
8872 */
8873static void faultToleranceProgressCancelCallback(void *pvUser)
8874{
8875 PUVM pUVM = (PUVM)pvUser;
8876
8877 if (pUVM)
8878 FTMR3CancelStandby(pUVM);
8879}
8880
8881/**
8882 * Thread function which starts the VM (also from saved state) and
8883 * track progress.
8884 *
8885 * @param Thread The thread id.
8886 * @param pvUser Pointer to a VMPowerUpTask structure.
8887 * @return VINF_SUCCESS (ignored).
8888 *
8889 * @note Locks the Console object for writing.
8890 */
8891/*static*/
8892DECLCALLBACK(int) Console::powerUpThread(RTTHREAD Thread, void *pvUser)
8893{
8894 LogFlowFuncEnter();
8895
8896 std::auto_ptr<VMPowerUpTask> task(static_cast<VMPowerUpTask *>(pvUser));
8897 AssertReturn(task.get(), VERR_INVALID_PARAMETER);
8898
8899 AssertReturn(!task->mConsole.isNull(), VERR_INVALID_PARAMETER);
8900 AssertReturn(!task->mProgress.isNull(), VERR_INVALID_PARAMETER);
8901
8902 VirtualBoxBase::initializeComForThread();
8903
8904 HRESULT rc = S_OK;
8905 int vrc = VINF_SUCCESS;
8906
8907 /* Set up a build identifier so that it can be seen from core dumps what
8908 * exact build was used to produce the core. */
8909 static char saBuildID[40];
8910 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
8911 "BU", "IL", "DI", "D", RTBldCfgVersion(), RTBldCfgRevision(), "BU", "IL", "DI", "D");
8912
8913 ComObjPtr<Console> pConsole = task->mConsole;
8914
8915 /* Note: no need to use addCaller() because VMPowerUpTask does that */
8916
8917 /* The lock is also used as a signal from the task initiator (which
8918 * releases it only after RTThreadCreate()) that we can start the job */
8919 AutoWriteLock alock(pConsole COMMA_LOCKVAL_SRC_POS);
8920
8921 /* sanity */
8922 Assert(pConsole->mpUVM == NULL);
8923
8924 try
8925 {
8926 // Create the VMM device object, which starts the HGCM thread; do this only
8927 // once for the console, for the pathological case that the same console
8928 // object is used to power up a VM twice. VirtualBox 4.0: we now do that
8929 // here instead of the Console constructor (see Console::init())
8930 if (!pConsole->m_pVMMDev)
8931 {
8932 pConsole->m_pVMMDev = new VMMDev(pConsole);
8933 AssertReturn(pConsole->m_pVMMDev, E_FAIL);
8934 }
8935
8936 /* wait for auto reset ops to complete so that we can successfully lock
8937 * the attached hard disks by calling LockMedia() below */
8938 for (VMPowerUpTask::ProgressList::const_iterator
8939 it = task->hardDiskProgresses.begin();
8940 it != task->hardDiskProgresses.end(); ++it)
8941 {
8942 HRESULT rc2 = (*it)->WaitForCompletion(-1);
8943 AssertComRC(rc2);
8944
8945 rc = task->mProgress->SetNextOperation(BstrFmt(tr("Disk Image Reset Operation - Immutable Image")).raw(), 1);
8946 AssertComRCReturnRC(rc);
8947 }
8948
8949 /*
8950 * Lock attached media. This method will also check their accessibility.
8951 * If we're a teleporter, we'll have to postpone this action so we can
8952 * migrate between local processes.
8953 *
8954 * Note! The media will be unlocked automatically by
8955 * SessionMachine::setMachineState() when the VM is powered down.
8956 */
8957 if ( !task->mTeleporterEnabled
8958 && task->mEnmFaultToleranceState != FaultToleranceState_Standby)
8959 {
8960 rc = pConsole->mControl->LockMedia();
8961 if (FAILED(rc)) throw rc;
8962 }
8963
8964 /* Create the VRDP server. In case of headless operation, this will
8965 * also create the framebuffer, required at VM creation.
8966 */
8967 ConsoleVRDPServer *server = pConsole->consoleVRDPServer();
8968 Assert(server);
8969
8970 /* Does VRDP server call Console from the other thread?
8971 * Not sure (and can change), so release the lock just in case.
8972 */
8973 alock.release();
8974 vrc = server->Launch();
8975 alock.acquire();
8976
8977 if (vrc == VERR_NET_ADDRESS_IN_USE)
8978 {
8979 Utf8Str errMsg;
8980 Bstr bstr;
8981 pConsole->mVRDEServer->GetVRDEProperty(Bstr("TCP/Ports").raw(), bstr.asOutParam());
8982 Utf8Str ports = bstr;
8983 errMsg = Utf8StrFmt(tr("VirtualBox Remote Desktop Extension server can't bind to the port: %s"),
8984 ports.c_str());
8985 LogRel(("VRDE: Warning: failed to launch VRDE server (%Rrc): '%s'\n",
8986 vrc, errMsg.c_str()));
8987 }
8988 else if (vrc == VINF_NOT_SUPPORTED)
8989 {
8990 /* This means that the VRDE is not installed. */
8991 LogRel(("VRDE: VirtualBox Remote Desktop Extension is not available.\n"));
8992 }
8993 else if (RT_FAILURE(vrc))
8994 {
8995 /* Fail, if the server is installed but can't start. */
8996 Utf8Str errMsg;
8997 switch (vrc)
8998 {
8999 case VERR_FILE_NOT_FOUND:
9000 {
9001 /* VRDE library file is missing. */
9002 errMsg = Utf8StrFmt(tr("Could not find the VirtualBox Remote Desktop Extension library."));
9003 break;
9004 }
9005 default:
9006 errMsg = Utf8StrFmt(tr("Failed to launch Remote Desktop Extension server (%Rrc)"),
9007 vrc);
9008 }
9009 LogRel(("VRDE: Failed: (%Rrc), error message: '%s'\n",
9010 vrc, errMsg.c_str()));
9011 throw setErrorStatic(E_FAIL, errMsg.c_str());
9012 }
9013
9014 ComPtr<IMachine> pMachine = pConsole->machine();
9015 ULONG cCpus = 1;
9016 pMachine->COMGETTER(CPUCount)(&cCpus);
9017
9018 /*
9019 * Create the VM
9020 *
9021 * Note! Release the lock since EMT will call Console. It's safe because
9022 * mMachineState is either Starting or Restoring state here.
9023 */
9024 alock.release();
9025
9026 PVM pVM;
9027 vrc = VMR3Create(cCpus,
9028 pConsole->mpVmm2UserMethods,
9029 Console::genericVMSetErrorCallback,
9030 &task->mErrorMsg,
9031 task->mConfigConstructor,
9032 static_cast<Console *>(pConsole),
9033 &pVM, NULL);
9034
9035 alock.acquire();
9036
9037 /* Enable client connections to the server. */
9038 pConsole->consoleVRDPServer()->EnableConnections();
9039
9040 if (RT_SUCCESS(vrc))
9041 {
9042 do
9043 {
9044 /*
9045 * Register our load/save state file handlers
9046 */
9047 vrc = SSMR3RegisterExternal(pConsole->mpUVM, sSSMConsoleUnit, 0 /*iInstance*/, sSSMConsoleVer, 0 /* cbGuess */,
9048 NULL, NULL, NULL,
9049 NULL, saveStateFileExec, NULL,
9050 NULL, loadStateFileExec, NULL,
9051 static_cast<Console *>(pConsole));
9052 AssertRCBreak(vrc);
9053
9054 vrc = static_cast<Console *>(pConsole)->getDisplay()->registerSSM(pConsole->mpUVM);
9055 AssertRC(vrc);
9056 if (RT_FAILURE(vrc))
9057 break;
9058
9059 /*
9060 * Synchronize debugger settings
9061 */
9062 MachineDebugger *machineDebugger = pConsole->getMachineDebugger();
9063 if (machineDebugger)
9064 machineDebugger->flushQueuedSettings();
9065
9066 /*
9067 * Shared Folders
9068 */
9069 if (pConsole->m_pVMMDev->isShFlActive())
9070 {
9071 /* Does the code below call Console from the other thread?
9072 * Not sure, so release the lock just in case. */
9073 alock.release();
9074
9075 for (SharedFolderDataMap::const_iterator it = task->mSharedFolders.begin();
9076 it != task->mSharedFolders.end();
9077 ++it)
9078 {
9079 const SharedFolderData &d = it->second;
9080 rc = pConsole->createSharedFolder(it->first, d);
9081 if (FAILED(rc))
9082 {
9083 ErrorInfoKeeper eik;
9084 pConsole->setVMRuntimeErrorCallbackF(0, "BrokenSharedFolder",
9085 N_("The shared folder '%s' could not be set up: %ls.\n"
9086 "The shared folder setup will not be complete. It is recommended to power down the virtual "
9087 "machine and fix the shared folder settings while the machine is not running"),
9088 it->first.c_str(), eik.getText().raw());
9089 }
9090 }
9091 if (FAILED(rc))
9092 rc = S_OK; // do not fail with broken shared folders
9093
9094 /* acquire the lock again */
9095 alock.acquire();
9096 }
9097
9098 /* release the lock before a lengthy operation */
9099 alock.release();
9100
9101 /*
9102 * Capture USB devices.
9103 */
9104 rc = pConsole->captureUSBDevices(pConsole->mpUVM);
9105 if (FAILED(rc))
9106 break;
9107
9108 /* Load saved state? */
9109 if (task->mSavedStateFile.length())
9110 {
9111 LogFlowFunc(("Restoring saved state from '%s'...\n",
9112 task->mSavedStateFile.c_str()));
9113
9114 vrc = VMR3LoadFromFile(pConsole->mpUVM,
9115 task->mSavedStateFile.c_str(),
9116 Console::stateProgressCallback,
9117 static_cast<IProgress *>(task->mProgress));
9118
9119 if (RT_SUCCESS(vrc))
9120 {
9121 if (task->mStartPaused)
9122 /* done */
9123 pConsole->setMachineState(MachineState_Paused);
9124 else
9125 {
9126 /* Start/Resume the VM execution */
9127#ifdef VBOX_WITH_EXTPACK
9128 vrc = pConsole->mptrExtPackManager->callAllVmPowerOnHooks(pConsole, pVM);
9129#endif
9130 if (RT_SUCCESS(vrc))
9131 vrc = VMR3Resume(pConsole->mpUVM, VMRESUMEREASON_STATE_RESTORED);
9132 AssertLogRelRC(vrc);
9133 }
9134 }
9135
9136 /* Power off in case we failed loading or resuming the VM */
9137 if (RT_FAILURE(vrc))
9138 {
9139 int vrc2 = VMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
9140#ifdef VBOX_WITH_EXTPACK
9141 pConsole->mptrExtPackManager->callAllVmPowerOffHooks(pConsole, pVM);
9142#endif
9143 }
9144 }
9145 else if (task->mTeleporterEnabled)
9146 {
9147 /* -> ConsoleImplTeleporter.cpp */
9148 bool fPowerOffOnFailure;
9149 rc = pConsole->teleporterTrg(pConsole->mpUVM, pMachine, &task->mErrorMsg, task->mStartPaused,
9150 task->mProgress, &fPowerOffOnFailure);
9151 if (FAILED(rc) && fPowerOffOnFailure)
9152 {
9153 ErrorInfoKeeper eik;
9154 int vrc2 = VMR3PowerOff(pConsole->mpUVM); AssertLogRelRC(vrc2);
9155#ifdef VBOX_WITH_EXTPACK
9156 pConsole->mptrExtPackManager->callAllVmPowerOffHooks(pConsole, pVM);
9157#endif
9158 }
9159 }
9160 else if (task->mEnmFaultToleranceState != FaultToleranceState_Inactive)
9161 {
9162 /*
9163 * Get the config.
9164 */
9165 ULONG uPort;
9166 ULONG uInterval;
9167 Bstr bstrAddress, bstrPassword;
9168
9169 rc = pMachine->COMGETTER(FaultTolerancePort)(&uPort);
9170 if (SUCCEEDED(rc))
9171 {
9172 rc = pMachine->COMGETTER(FaultToleranceSyncInterval)(&uInterval);
9173 if (SUCCEEDED(rc))
9174 rc = pMachine->COMGETTER(FaultToleranceAddress)(bstrAddress.asOutParam());
9175 if (SUCCEEDED(rc))
9176 rc = pMachine->COMGETTER(FaultTolerancePassword)(bstrPassword.asOutParam());
9177 }
9178 if (task->mProgress->setCancelCallback(faultToleranceProgressCancelCallback, pConsole->mpUVM))
9179 {
9180 if (SUCCEEDED(rc))
9181 {
9182 Utf8Str strAddress(bstrAddress);
9183 const char *pszAddress = strAddress.isEmpty() ? NULL : strAddress.c_str();
9184 Utf8Str strPassword(bstrPassword);
9185 const char *pszPassword = strPassword.isEmpty() ? NULL : strPassword.c_str();
9186
9187 /* Power on the FT enabled VM. */
9188#ifdef VBOX_WITH_EXTPACK
9189 vrc = pConsole->mptrExtPackManager->callAllVmPowerOnHooks(pConsole, pVM);
9190#endif
9191 if (RT_SUCCESS(vrc))
9192 vrc = FTMR3PowerOn(pConsole->mpUVM,
9193 task->mEnmFaultToleranceState == FaultToleranceState_Master /* fMaster */,
9194 uInterval,
9195 pszAddress,
9196 uPort,
9197 pszPassword);
9198 AssertLogRelRC(vrc);
9199 }
9200 task->mProgress->setCancelCallback(NULL, NULL);
9201 }
9202 else
9203 rc = E_FAIL;
9204 }
9205 else if (task->mStartPaused)
9206 /* done */
9207 pConsole->setMachineState(MachineState_Paused);
9208 else
9209 {
9210 /* Power on the VM (i.e. start executing) */
9211#ifdef VBOX_WITH_EXTPACK
9212 vrc = pConsole->mptrExtPackManager->callAllVmPowerOnHooks(pConsole, pVM);
9213#endif
9214 if (RT_SUCCESS(vrc))
9215 vrc = VMR3PowerOn(pConsole->mpUVM);
9216 AssertLogRelRC(vrc);
9217 }
9218
9219 /* acquire the lock again */
9220 alock.acquire();
9221 }
9222 while (0);
9223
9224 /* On failure, destroy the VM */
9225 if (FAILED(rc) || RT_FAILURE(vrc))
9226 {
9227 /* preserve existing error info */
9228 ErrorInfoKeeper eik;
9229
9230 /* powerDown() will call VMR3Destroy() and do all necessary
9231 * cleanup (VRDP, USB devices) */
9232 alock.release();
9233 HRESULT rc2 = pConsole->powerDown();
9234 alock.acquire();
9235 AssertComRC(rc2);
9236 }
9237 else
9238 {
9239 /*
9240 * Deregister the VMSetError callback. This is necessary as the
9241 * pfnVMAtError() function passed to VMR3Create() is supposed to
9242 * be sticky but our error callback isn't.
9243 */
9244 alock.release();
9245 VMR3AtErrorDeregister(pConsole->mpUVM, Console::genericVMSetErrorCallback, &task->mErrorMsg);
9246 /** @todo register another VMSetError callback? */
9247 alock.acquire();
9248 }
9249 }
9250 else
9251 {
9252 /*
9253 * If VMR3Create() failed it has released the VM memory.
9254 */
9255 VMR3ReleaseUVM(pConsole->mpUVM);
9256 pConsole->mpUVM = NULL;
9257 }
9258
9259 if (SUCCEEDED(rc) && RT_FAILURE(vrc))
9260 {
9261 /* If VMR3Create() or one of the other calls in this function fail,
9262 * an appropriate error message has been set in task->mErrorMsg.
9263 * However since that happens via a callback, the rc status code in
9264 * this function is not updated.
9265 */
9266 if (!task->mErrorMsg.length())
9267 {
9268 /* If the error message is not set but we've got a failure,
9269 * convert the VBox status code into a meaningful error message.
9270 * This becomes unused once all the sources of errors set the
9271 * appropriate error message themselves.
9272 */
9273 AssertMsgFailed(("Missing error message during powerup for status code %Rrc\n", vrc));
9274 task->mErrorMsg = Utf8StrFmt(tr("Failed to start VM execution (%Rrc)"),
9275 vrc);
9276 }
9277
9278 /* Set the error message as the COM error.
9279 * Progress::notifyComplete() will pick it up later. */
9280 throw setErrorStatic(E_FAIL, task->mErrorMsg.c_str());
9281 }
9282 }
9283 catch (HRESULT aRC) { rc = aRC; }
9284
9285 if ( pConsole->mMachineState == MachineState_Starting
9286 || pConsole->mMachineState == MachineState_Restoring
9287 || pConsole->mMachineState == MachineState_TeleportingIn
9288 )
9289 {
9290 /* We are still in the Starting/Restoring state. This means one of:
9291 *
9292 * 1) we failed before VMR3Create() was called;
9293 * 2) VMR3Create() failed.
9294 *
9295 * In both cases, there is no need to call powerDown(), but we still
9296 * need to go back to the PoweredOff/Saved state. Reuse
9297 * vmstateChangeCallback() for that purpose.
9298 */
9299
9300 /* preserve existing error info */
9301 ErrorInfoKeeper eik;
9302
9303 Assert(pConsole->mpUVM == NULL);
9304 vmstateChangeCallback(NULL, VMSTATE_TERMINATED, VMSTATE_CREATING, pConsole);
9305 }
9306
9307 /*
9308 * Evaluate the final result. Note that the appropriate mMachineState value
9309 * is already set by vmstateChangeCallback() in all cases.
9310 */
9311
9312 /* release the lock, don't need it any more */
9313 alock.release();
9314
9315 if (SUCCEEDED(rc))
9316 {
9317 /* Notify the progress object of the success */
9318 task->mProgress->notifyComplete(S_OK);
9319 }
9320 else
9321 {
9322 /* The progress object will fetch the current error info */
9323 task->mProgress->notifyComplete(rc);
9324 LogRel(("Power up failed (vrc=%Rrc, rc=%Rhrc (%#08X))\n", vrc, rc, rc));
9325 }
9326
9327 /* Notify VBoxSVC and any waiting openRemoteSession progress object. */
9328 pConsole->mControl->EndPowerUp(rc);
9329
9330#if defined(RT_OS_WINDOWS)
9331 /* uninitialize COM */
9332 CoUninitialize();
9333#endif
9334
9335 LogFlowFuncLeave();
9336
9337 return VINF_SUCCESS;
9338}
9339
9340
9341/**
9342 * Reconfigures a medium attachment (part of taking or deleting an online snapshot).
9343 *
9344 * @param pThis Reference to the console object.
9345 * @param pUVM The VM handle.
9346 * @param lInstance The instance of the controller.
9347 * @param pcszDevice The name of the controller type.
9348 * @param enmBus The storage bus type of the controller.
9349 * @param fSetupMerge Whether to set up a medium merge
9350 * @param uMergeSource Merge source image index
9351 * @param uMergeTarget Merge target image index
9352 * @param aMediumAtt The medium attachment.
9353 * @param aMachineState The current machine state.
9354 * @param phrc Where to store com error - only valid if we return VERR_GENERAL_FAILURE.
9355 * @return VBox status code.
9356 */
9357/* static */
9358DECLCALLBACK(int) Console::reconfigureMediumAttachment(Console *pThis,
9359 PUVM pUVM,
9360 const char *pcszDevice,
9361 unsigned uInstance,
9362 StorageBus_T enmBus,
9363 bool fUseHostIOCache,
9364 bool fBuiltinIOCache,
9365 bool fSetupMerge,
9366 unsigned uMergeSource,
9367 unsigned uMergeTarget,
9368 IMediumAttachment *aMediumAtt,
9369 MachineState_T aMachineState,
9370 HRESULT *phrc)
9371{
9372 LogFlowFunc(("pUVM=%p aMediumAtt=%p phrc=%p\n", pUVM, aMediumAtt, phrc));
9373
9374 HRESULT hrc;
9375 Bstr bstr;
9376 *phrc = S_OK;
9377#define H() do { if (FAILED(hrc)) { AssertMsgFailed(("hrc=%Rhrc (%#x)\n", hrc, hrc)); *phrc = hrc; return VERR_GENERAL_FAILURE; } } while (0)
9378
9379 /* Ignore attachments other than hard disks, since at the moment they are
9380 * not subject to snapshotting in general. */
9381 DeviceType_T lType;
9382 hrc = aMediumAtt->COMGETTER(Type)(&lType); H();
9383 if (lType != DeviceType_HardDisk)
9384 return VINF_SUCCESS;
9385
9386 /* Determine the base path for the device instance. */
9387 PCFGMNODE pCtlInst;
9388
9389 if (enmBus == StorageBus_USB)
9390 pCtlInst = CFGMR3GetChildF(CFGMR3GetRootU(pUVM), "USB/%s/", pcszDevice);
9391 else
9392 pCtlInst = CFGMR3GetChildF(CFGMR3GetRootU(pUVM), "Devices/%s/%u/", pcszDevice, uInstance);
9393
9394 AssertReturn(pCtlInst, VERR_INTERNAL_ERROR);
9395
9396 /* Update the device instance configuration. */
9397 PCFGMNODE pLunL0 = NULL;
9398 int rc = pThis->configMediumAttachment(pCtlInst,
9399 pcszDevice,
9400 uInstance,
9401 enmBus,
9402 fUseHostIOCache,
9403 fBuiltinIOCache,
9404 fSetupMerge,
9405 uMergeSource,
9406 uMergeTarget,
9407 aMediumAtt,
9408 aMachineState,
9409 phrc,
9410 true /* fAttachDetach */,
9411 false /* fForceUnmount */,
9412 false /* fHotplug */,
9413 pUVM,
9414 NULL /* paLedDevType */,
9415 &pLunL0);
9416 /* Dump the changed LUN if possible, dump the complete device otherwise */
9417 CFGMR3Dump(pLunL0 ? pLunL0 : pCtlInst);
9418 if (RT_FAILURE(rc))
9419 {
9420 AssertMsgFailed(("rc=%Rrc\n", rc));
9421 return rc;
9422 }
9423
9424#undef H
9425
9426 LogFlowFunc(("Returns success\n"));
9427 return VINF_SUCCESS;
9428}
9429
9430/**
9431 * Progress cancelation callback employed by Console::fntTakeSnapshotWorker.
9432 */
9433static void takesnapshotProgressCancelCallback(void *pvUser)
9434{
9435 PUVM pUVM = (PUVM)pvUser;
9436 SSMR3Cancel(pUVM);
9437}
9438
9439/**
9440 * Worker thread created by Console::TakeSnapshot.
9441 * @param Thread The current thread (ignored).
9442 * @param pvUser The task.
9443 * @return VINF_SUCCESS (ignored).
9444 */
9445/*static*/
9446DECLCALLBACK(int) Console::fntTakeSnapshotWorker(RTTHREAD Thread, void *pvUser)
9447{
9448 VMTakeSnapshotTask *pTask = (VMTakeSnapshotTask*)pvUser;
9449
9450 // taking a snapshot consists of the following:
9451
9452 // 1) creating a diff image for each virtual hard disk, into which write operations go after
9453 // the snapshot has been created (done in VBoxSVC, in SessionMachine::BeginTakingSnapshot)
9454 // 2) creating a Snapshot object with the state of the machine (hardware + storage,
9455 // done in VBoxSVC, also in SessionMachine::BeginTakingSnapshot)
9456 // 3) saving the state of the virtual machine (here, in the VM process, if the machine is online)
9457
9458 Console *that = pTask->mConsole;
9459 bool fBeganTakingSnapshot = false;
9460 bool fSuspenededBySave = false;
9461
9462 AutoCaller autoCaller(that);
9463 if (FAILED(autoCaller.rc()))
9464 {
9465 that->mptrCancelableProgress.setNull();
9466 return autoCaller.rc();
9467 }
9468
9469 AutoWriteLock alock(that COMMA_LOCKVAL_SRC_POS);
9470
9471 HRESULT rc = S_OK;
9472
9473 try
9474 {
9475 /* STEP 1 + 2:
9476 * request creating the diff images on the server and create the snapshot object
9477 * (this will set the machine state to Saving on the server to block
9478 * others from accessing this machine)
9479 */
9480 rc = that->mControl->BeginTakingSnapshot(that,
9481 pTask->bstrName.raw(),
9482 pTask->bstrDescription.raw(),
9483 pTask->mProgress,
9484 pTask->fTakingSnapshotOnline,
9485 pTask->bstrSavedStateFile.asOutParam());
9486 if (FAILED(rc))
9487 throw rc;
9488
9489 fBeganTakingSnapshot = true;
9490
9491 /* Check sanity: for offline snapshots there must not be a saved state
9492 * file name. All other combinations are valid (even though online
9493 * snapshots without saved state file seems inconsistent - there are
9494 * some exotic use cases, which need to be explicitly enabled, see the
9495 * code of SessionMachine::BeginTakingSnapshot. */
9496 if ( !pTask->fTakingSnapshotOnline
9497 && !pTask->bstrSavedStateFile.isEmpty())
9498 throw setErrorStatic(E_FAIL, "Invalid state of saved state file");
9499
9500 /* sync the state with the server */
9501 if (pTask->lastMachineState == MachineState_Running)
9502 that->setMachineStateLocally(MachineState_LiveSnapshotting);
9503 else
9504 that->setMachineStateLocally(MachineState_Saving);
9505
9506 // STEP 3: save the VM state (if online)
9507 if (pTask->fTakingSnapshotOnline)
9508 {
9509 int vrc;
9510 SafeVMPtr ptrVM(that);
9511 if (!ptrVM.isOk())
9512 throw ptrVM.rc();
9513
9514 pTask->mProgress->SetNextOperation(Bstr(tr("Saving the machine state")).raw(),
9515 pTask->ulMemSize); // operation weight, same as computed when setting up progress object
9516 if (!pTask->bstrSavedStateFile.isEmpty())
9517 {
9518 Utf8Str strSavedStateFile(pTask->bstrSavedStateFile);
9519
9520 pTask->mProgress->setCancelCallback(takesnapshotProgressCancelCallback, ptrVM.rawUVM());
9521
9522 alock.release();
9523 LogFlowFunc(("VMR3Save...\n"));
9524 vrc = VMR3Save(ptrVM.rawUVM(),
9525 strSavedStateFile.c_str(),
9526 true /*fContinueAfterwards*/,
9527 Console::stateProgressCallback,
9528 static_cast<IProgress *>(pTask->mProgress),
9529 &fSuspenededBySave);
9530 alock.acquire();
9531 if (RT_FAILURE(vrc))
9532 throw setErrorStatic(E_FAIL,
9533 tr("Failed to save the machine state to '%s' (%Rrc)"),
9534 strSavedStateFile.c_str(), vrc);
9535
9536 pTask->mProgress->setCancelCallback(NULL, NULL);
9537 }
9538 else
9539 LogRel(("Console: skipped saving state as part of online snapshot\n"));
9540
9541 if (!pTask->mProgress->notifyPointOfNoReturn())
9542 throw setErrorStatic(E_FAIL, tr("Canceled"));
9543 that->mptrCancelableProgress.setNull();
9544
9545 // STEP 4: reattach hard disks
9546 LogFlowFunc(("Reattaching new differencing hard disks...\n"));
9547
9548 pTask->mProgress->SetNextOperation(Bstr(tr("Reconfiguring medium attachments")).raw(),
9549 1); // operation weight, same as computed when setting up progress object
9550
9551 com::SafeIfaceArray<IMediumAttachment> atts;
9552 rc = that->mMachine->COMGETTER(MediumAttachments)(ComSafeArrayAsOutParam(atts));
9553 if (FAILED(rc))
9554 throw rc;
9555
9556 for (size_t i = 0;
9557 i < atts.size();
9558 ++i)
9559 {
9560 ComPtr<IStorageController> pStorageController;
9561 Bstr controllerName;
9562 ULONG lInstance;
9563 StorageControllerType_T enmController;
9564 StorageBus_T enmBus;
9565 BOOL fUseHostIOCache;
9566
9567 /*
9568 * We can't pass a storage controller object directly
9569 * (g++ complains about not being able to pass non POD types through '...')
9570 * so we have to query needed values here and pass them.
9571 */
9572 rc = atts[i]->COMGETTER(Controller)(controllerName.asOutParam());
9573 if (FAILED(rc))
9574 throw rc;
9575
9576 rc = that->mMachine->GetStorageControllerByName(controllerName.raw(),
9577 pStorageController.asOutParam());
9578 if (FAILED(rc))
9579 throw rc;
9580
9581 rc = pStorageController->COMGETTER(ControllerType)(&enmController);
9582 if (FAILED(rc))
9583 throw rc;
9584 rc = pStorageController->COMGETTER(Instance)(&lInstance);
9585 if (FAILED(rc))
9586 throw rc;
9587 rc = pStorageController->COMGETTER(Bus)(&enmBus);
9588 if (FAILED(rc))
9589 throw rc;
9590 rc = pStorageController->COMGETTER(UseHostIOCache)(&fUseHostIOCache);
9591 if (FAILED(rc))
9592 throw rc;
9593
9594 const char *pcszDevice = Console::convertControllerTypeToDev(enmController);
9595
9596 BOOL fBuiltinIOCache;
9597 rc = that->mMachine->COMGETTER(IOCacheEnabled)(&fBuiltinIOCache);
9598 if (FAILED(rc))
9599 throw rc;
9600
9601 /*
9602 * don't release the lock since reconfigureMediumAttachment
9603 * isn't going to need the Console lock.
9604 */
9605 vrc = VMR3ReqCallWaitU(ptrVM.rawUVM(), VMCPUID_ANY,
9606 (PFNRT)reconfigureMediumAttachment, 13,
9607 that, ptrVM.rawUVM(), pcszDevice, lInstance, enmBus, fUseHostIOCache,
9608 fBuiltinIOCache, false /* fSetupMerge */, 0 /* uMergeSource */,
9609 0 /* uMergeTarget */, atts[i], that->mMachineState, &rc);
9610 if (RT_FAILURE(vrc))
9611 throw setErrorStatic(E_FAIL, Console::tr("%Rrc"), vrc);
9612 if (FAILED(rc))
9613 throw rc;
9614 }
9615 }
9616
9617 /*
9618 * finalize the requested snapshot object.
9619 * This will reset the machine state to the state it had right
9620 * before calling mControl->BeginTakingSnapshot().
9621 */
9622 rc = that->mControl->EndTakingSnapshot(TRUE /*aSuccess*/);
9623 // do not throw rc here because we can't call EndTakingSnapshot() twice
9624 LogFlowFunc(("EndTakingSnapshot -> %Rhrc [mMachineState=%s]\n", rc, Global::stringifyMachineState(that->mMachineState)));
9625 }
9626 catch (HRESULT rcThrown)
9627 {
9628 /* preserve existing error info */
9629 ErrorInfoKeeper eik;
9630
9631 if (fBeganTakingSnapshot)
9632 that->mControl->EndTakingSnapshot(FALSE /*aSuccess*/);
9633
9634 rc = rcThrown;
9635 LogFunc(("Caught %Rhrc [mMachineState=%s]\n", rc, Global::stringifyMachineState(that->mMachineState)));
9636 }
9637 Assert(alock.isWriteLockOnCurrentThread());
9638
9639 if (FAILED(rc)) /* Must come before calling setMachineState. */
9640 pTask->mProgress->notifyComplete(rc);
9641
9642 /*
9643 * Fix up the machine state.
9644 *
9645 * For live snapshots we do all the work, for the two other variations we
9646 * just update the local copy.
9647 */
9648 MachineState_T enmMachineState;
9649 that->mMachine->COMGETTER(State)(&enmMachineState);
9650 if ( that->mMachineState == MachineState_LiveSnapshotting
9651 || that->mMachineState == MachineState_Saving)
9652 {
9653
9654 if (!pTask->fTakingSnapshotOnline)
9655 that->setMachineStateLocally(pTask->lastMachineState);
9656 else if (SUCCEEDED(rc))
9657 {
9658 Assert( pTask->lastMachineState == MachineState_Running
9659 || pTask->lastMachineState == MachineState_Paused);
9660 Assert(that->mMachineState == MachineState_Saving);
9661 if (pTask->lastMachineState == MachineState_Running)
9662 {
9663 LogFlowFunc(("VMR3Resume...\n"));
9664 SafeVMPtr ptrVM(that);
9665 alock.release();
9666 int vrc = VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_STATE_SAVED);
9667 alock.acquire();
9668 if (RT_FAILURE(vrc))
9669 {
9670 rc = setErrorStatic(VBOX_E_VM_ERROR, tr("Could not resume the machine execution (%Rrc)"), vrc);
9671 pTask->mProgress->notifyComplete(rc);
9672 if (that->mMachineState == MachineState_Saving)
9673 that->setMachineStateLocally(MachineState_Paused);
9674 }
9675 }
9676 else
9677 that->setMachineStateLocally(MachineState_Paused);
9678 }
9679 else
9680 {
9681 /** @todo this could probably be made more generic and reused elsewhere. */
9682 /* paranoid cleanup on for a failed online snapshot. */
9683 VMSTATE enmVMState = VMR3GetStateU(that->mpUVM);
9684 switch (enmVMState)
9685 {
9686 case VMSTATE_RUNNING:
9687 case VMSTATE_RUNNING_LS:
9688 case VMSTATE_DEBUGGING:
9689 case VMSTATE_DEBUGGING_LS:
9690 case VMSTATE_POWERING_OFF:
9691 case VMSTATE_POWERING_OFF_LS:
9692 case VMSTATE_RESETTING:
9693 case VMSTATE_RESETTING_LS:
9694 Assert(!fSuspenededBySave);
9695 that->setMachineState(MachineState_Running);
9696 break;
9697
9698 case VMSTATE_GURU_MEDITATION:
9699 case VMSTATE_GURU_MEDITATION_LS:
9700 that->setMachineState(MachineState_Stuck);
9701 break;
9702
9703 case VMSTATE_FATAL_ERROR:
9704 case VMSTATE_FATAL_ERROR_LS:
9705 if (pTask->lastMachineState == MachineState_Paused)
9706 that->setMachineStateLocally(pTask->lastMachineState);
9707 else
9708 that->setMachineState(MachineState_Paused);
9709 break;
9710
9711 default:
9712 AssertMsgFailed(("%s\n", VMR3GetStateName(enmVMState)));
9713 case VMSTATE_SUSPENDED:
9714 case VMSTATE_SUSPENDED_LS:
9715 case VMSTATE_SUSPENDING:
9716 case VMSTATE_SUSPENDING_LS:
9717 case VMSTATE_SUSPENDING_EXT_LS:
9718 if (fSuspenededBySave)
9719 {
9720 Assert(pTask->lastMachineState == MachineState_Running);
9721 LogFlowFunc(("VMR3Resume (on failure)...\n"));
9722 SafeVMPtr ptrVM(that);
9723 alock.release();
9724 int vrc = VMR3Resume(ptrVM.rawUVM(), VMRESUMEREASON_STATE_SAVED); AssertLogRelRC(vrc);
9725 alock.acquire();
9726 if (RT_FAILURE(vrc))
9727 that->setMachineState(MachineState_Paused);
9728 }
9729 else if (pTask->lastMachineState == MachineState_Paused)
9730 that->setMachineStateLocally(pTask->lastMachineState);
9731 else
9732 that->setMachineState(MachineState_Paused);
9733 break;
9734 }
9735
9736 }
9737 }
9738 /*else: somebody else has change the state... Leave it. */
9739
9740 /* check the remote state to see that we got it right. */
9741 that->mMachine->COMGETTER(State)(&enmMachineState);
9742 AssertLogRelMsg(that->mMachineState == enmMachineState,
9743 ("mMachineState=%s enmMachineState=%s\n", Global::stringifyMachineState(that->mMachineState),
9744 Global::stringifyMachineState(enmMachineState) ));
9745
9746
9747 if (SUCCEEDED(rc)) /* The failure cases are handled above. */
9748 pTask->mProgress->notifyComplete(rc);
9749
9750 delete pTask;
9751
9752 LogFlowFuncLeave();
9753 return VINF_SUCCESS;
9754}
9755
9756/**
9757 * Thread for executing the saved state operation.
9758 *
9759 * @param Thread The thread handle.
9760 * @param pvUser Pointer to a VMSaveTask structure.
9761 * @return VINF_SUCCESS (ignored).
9762 *
9763 * @note Locks the Console object for writing.
9764 */
9765/*static*/
9766DECLCALLBACK(int) Console::saveStateThread(RTTHREAD Thread, void *pvUser)
9767{
9768 LogFlowFuncEnter();
9769
9770 std::auto_ptr<VMSaveTask> task(static_cast<VMSaveTask*>(pvUser));
9771 AssertReturn(task.get(), VERR_INVALID_PARAMETER);
9772
9773 Assert(task->mSavedStateFile.length());
9774 Assert(task->mProgress.isNull());
9775 Assert(!task->mServerProgress.isNull());
9776
9777 const ComObjPtr<Console> &that = task->mConsole;
9778 Utf8Str errMsg;
9779 HRESULT rc = S_OK;
9780
9781 LogFlowFunc(("Saving the state to '%s'...\n", task->mSavedStateFile.c_str()));
9782
9783 bool fSuspenededBySave;
9784 int vrc = VMR3Save(task->mpUVM,
9785 task->mSavedStateFile.c_str(),
9786 false, /*fContinueAfterwards*/
9787 Console::stateProgressCallback,
9788 static_cast<IProgress *>(task->mServerProgress),
9789 &fSuspenededBySave);
9790 if (RT_FAILURE(vrc))
9791 {
9792 errMsg = Utf8StrFmt(Console::tr("Failed to save the machine state to '%s' (%Rrc)"),
9793 task->mSavedStateFile.c_str(), vrc);
9794 rc = E_FAIL;
9795 }
9796 Assert(!fSuspenededBySave);
9797
9798 /* lock the console once we're going to access it */
9799 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
9800
9801 /* synchronize the state with the server */
9802 if (SUCCEEDED(rc))
9803 {
9804 /*
9805 * The machine has been successfully saved, so power it down
9806 * (vmstateChangeCallback() will set state to Saved on success).
9807 * Note: we release the task's VM caller, otherwise it will
9808 * deadlock.
9809 */
9810 task->releaseVMCaller();
9811 thatLock.release();
9812 rc = that->powerDown();
9813 thatLock.acquire();
9814 }
9815
9816 /*
9817 * If we failed, reset the local machine state.
9818 */
9819 if (FAILED(rc))
9820 that->setMachineStateLocally(task->mMachineStateBefore);
9821
9822 /*
9823 * Finalize the requested save state procedure. In case of failure it will
9824 * reset the machine state to the state it had right before calling
9825 * mControl->BeginSavingState(). This must be the last thing because it
9826 * will set the progress to completed, and that means that the frontend
9827 * can immediately uninit the associated console object.
9828 */
9829 that->mControl->EndSavingState(rc, Bstr(errMsg).raw());
9830
9831 LogFlowFuncLeave();
9832 return VINF_SUCCESS;
9833}
9834
9835/**
9836 * Thread for powering down the Console.
9837 *
9838 * @param Thread The thread handle.
9839 * @param pvUser Pointer to the VMTask structure.
9840 * @return VINF_SUCCESS (ignored).
9841 *
9842 * @note Locks the Console object for writing.
9843 */
9844/*static*/
9845DECLCALLBACK(int) Console::powerDownThread(RTTHREAD Thread, void *pvUser)
9846{
9847 LogFlowFuncEnter();
9848
9849 std::auto_ptr<VMPowerDownTask> task(static_cast<VMPowerDownTask *>(pvUser));
9850 AssertReturn(task.get(), VERR_INVALID_PARAMETER);
9851
9852 AssertReturn(task->isOk(), VERR_GENERAL_FAILURE);
9853
9854 Assert(task->mProgress.isNull());
9855
9856 const ComObjPtr<Console> &that = task->mConsole;
9857
9858 /* Note: no need to use addCaller() to protect Console because VMTask does
9859 * that */
9860
9861 /* wait until the method tat started us returns */
9862 AutoWriteLock thatLock(that COMMA_LOCKVAL_SRC_POS);
9863
9864 /* release VM caller to avoid the powerDown() deadlock */
9865 task->releaseVMCaller();
9866
9867 thatLock.release();
9868
9869 that->powerDown(task->mServerProgress);
9870
9871 /* complete the operation */
9872 that->mControl->EndPoweringDown(S_OK, Bstr().raw());
9873
9874 LogFlowFuncLeave();
9875 return VINF_SUCCESS;
9876}
9877
9878
9879/**
9880 * @interface_method_impl{VMM2USERMETHODS,pfnSaveState}
9881 */
9882/*static*/ DECLCALLBACK(int)
9883Console::vmm2User_SaveState(PCVMM2USERMETHODS pThis, PUVM pUVM)
9884{
9885 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
9886 NOREF(pUVM);
9887
9888 /*
9889 * For now, just call SaveState. We should probably try notify the GUI so
9890 * it can pop up a progress object and stuff.
9891 */
9892 HRESULT hrc = pConsole->SaveState(NULL);
9893 return SUCCEEDED(hrc) ? VINF_SUCCESS : Global::vboxStatusCodeFromCOM(hrc);
9894}
9895
9896/**
9897 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtInit}
9898 */
9899/*static*/ DECLCALLBACK(void)
9900Console::vmm2User_NotifyEmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
9901{
9902 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
9903 VirtualBoxBase::initializeComForThread();
9904}
9905
9906/**
9907 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyEmtTerm}
9908 */
9909/*static*/ DECLCALLBACK(void)
9910Console::vmm2User_NotifyEmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM, PUVMCPU pUVCpu)
9911{
9912 NOREF(pThis); NOREF(pUVM); NOREF(pUVCpu);
9913 VirtualBoxBase::uninitializeComForThread();
9914}
9915
9916/**
9917 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtInit}
9918 */
9919/*static*/ DECLCALLBACK(void)
9920Console::vmm2User_NotifyPdmtInit(PCVMM2USERMETHODS pThis, PUVM pUVM)
9921{
9922 NOREF(pThis); NOREF(pUVM);
9923 VirtualBoxBase::initializeComForThread();
9924}
9925
9926/**
9927 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyPdmtTerm}
9928 */
9929/*static*/ DECLCALLBACK(void)
9930Console::vmm2User_NotifyPdmtTerm(PCVMM2USERMETHODS pThis, PUVM pUVM)
9931{
9932 NOREF(pThis); NOREF(pUVM);
9933 VirtualBoxBase::uninitializeComForThread();
9934}
9935
9936/**
9937 * @interface_method_impl{VMM2USERMETHODS,pfnNotifyResetTurnedIntoPowerOff}
9938 */
9939/*static*/ DECLCALLBACK(void)
9940Console::vmm2User_NotifyResetTurnedIntoPowerOff(PCVMM2USERMETHODS pThis, PUVM pUVM)
9941{
9942 Console *pConsole = ((MYVMM2USERMETHODS *)pThis)->pConsole;
9943 NOREF(pUVM);
9944
9945 pConsole->mfPowerOffCausedByReset = true;
9946}
9947
9948
9949
9950
9951/**
9952 * The Main status driver instance data.
9953 */
9954typedef struct DRVMAINSTATUS
9955{
9956 /** The LED connectors. */
9957 PDMILEDCONNECTORS ILedConnectors;
9958 /** Pointer to the LED ports interface above us. */
9959 PPDMILEDPORTS pLedPorts;
9960 /** Pointer to the array of LED pointers. */
9961 PPDMLED *papLeds;
9962 /** The unit number corresponding to the first entry in the LED array. */
9963 RTUINT iFirstLUN;
9964 /** The unit number corresponding to the last entry in the LED array.
9965 * (The size of the LED array is iLastLUN - iFirstLUN + 1.) */
9966 RTUINT iLastLUN;
9967 /** Pointer to the driver instance. */
9968 PPDMDRVINS pDrvIns;
9969 /** The Media Notify interface. */
9970 PDMIMEDIANOTIFY IMediaNotify;
9971 /** Map for translating PDM storage controller/LUN information to
9972 * IMediumAttachment references. */
9973 Console::MediumAttachmentMap *pmapMediumAttachments;
9974 /** Device name+instance for mapping */
9975 char *pszDeviceInstance;
9976 /** Pointer to the Console object, for driver triggered activities. */
9977 Console *pConsole;
9978} DRVMAINSTATUS, *PDRVMAINSTATUS;
9979
9980
9981/**
9982 * Notification about a unit which have been changed.
9983 *
9984 * The driver must discard any pointers to data owned by
9985 * the unit and requery it.
9986 *
9987 * @param pInterface Pointer to the interface structure containing the called function pointer.
9988 * @param iLUN The unit number.
9989 */
9990DECLCALLBACK(void) Console::drvStatus_UnitChanged(PPDMILEDCONNECTORS pInterface, unsigned iLUN)
9991{
9992 PDRVMAINSTATUS pThis = (PDRVMAINSTATUS)((uintptr_t)pInterface - RT_OFFSETOF(DRVMAINSTATUS, ILedConnectors));
9993 if (iLUN >= pThis->iFirstLUN && iLUN <= pThis->iLastLUN)
9994 {
9995 PPDMLED pLed;
9996 int rc = pThis->pLedPorts->pfnQueryStatusLed(pThis->pLedPorts, iLUN, &pLed);
9997 if (RT_FAILURE(rc))
9998 pLed = NULL;
9999 ASMAtomicWritePtr(&pThis->papLeds[iLUN - pThis->iFirstLUN], pLed);
10000 Log(("drvStatus_UnitChanged: iLUN=%d pLed=%p\n", iLUN, pLed));
10001 }
10002}
10003
10004
10005/**
10006 * Notification about a medium eject.
10007 *
10008 * @returns VBox status.
10009 * @param pInterface Pointer to the interface structure containing the called function pointer.
10010 * @param uLUN The unit number.
10011 */
10012DECLCALLBACK(int) Console::drvStatus_MediumEjected(PPDMIMEDIANOTIFY pInterface, unsigned uLUN)
10013{
10014 PDRVMAINSTATUS pThis = (PDRVMAINSTATUS)((uintptr_t)pInterface - RT_OFFSETOF(DRVMAINSTATUS, IMediaNotify));
10015 PPDMDRVINS pDrvIns = pThis->pDrvIns;
10016 LogFunc(("uLUN=%d\n", uLUN));
10017 if (pThis->pmapMediumAttachments)
10018 {
10019 AutoWriteLock alock(pThis->pConsole COMMA_LOCKVAL_SRC_POS);
10020
10021 ComPtr<IMediumAttachment> pMediumAtt;
10022 Utf8Str devicePath = Utf8StrFmt("%s/LUN#%u", pThis->pszDeviceInstance, uLUN);
10023 Console::MediumAttachmentMap::const_iterator end = pThis->pmapMediumAttachments->end();
10024 Console::MediumAttachmentMap::const_iterator it = pThis->pmapMediumAttachments->find(devicePath);
10025 if (it != end)
10026 pMediumAtt = it->second;
10027 Assert(!pMediumAtt.isNull());
10028 if (!pMediumAtt.isNull())
10029 {
10030 IMedium *pMedium = NULL;
10031 HRESULT rc = pMediumAtt->COMGETTER(Medium)(&pMedium);
10032 AssertComRC(rc);
10033 if (SUCCEEDED(rc) && pMedium)
10034 {
10035 BOOL fHostDrive = FALSE;
10036 rc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
10037 AssertComRC(rc);
10038 if (!fHostDrive)
10039 {
10040 alock.release();
10041
10042 ComPtr<IMediumAttachment> pNewMediumAtt;
10043 rc = pThis->pConsole->mControl->EjectMedium(pMediumAtt, pNewMediumAtt.asOutParam());
10044 if (SUCCEEDED(rc))
10045 fireMediumChangedEvent(pThis->pConsole->mEventSource, pNewMediumAtt);
10046
10047 alock.acquire();
10048 if (pNewMediumAtt != pMediumAtt)
10049 {
10050 pThis->pmapMediumAttachments->erase(devicePath);
10051 pThis->pmapMediumAttachments->insert(std::make_pair(devicePath, pNewMediumAtt));
10052 }
10053 }
10054 }
10055 }
10056 }
10057 return VINF_SUCCESS;
10058}
10059
10060
10061/**
10062 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
10063 */
10064DECLCALLBACK(void *) Console::drvStatus_QueryInterface(PPDMIBASE pInterface, const char *pszIID)
10065{
10066 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
10067 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10068 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
10069 PDMIBASE_RETURN_INTERFACE(pszIID, PDMILEDCONNECTORS, &pThis->ILedConnectors);
10070 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIANOTIFY, &pThis->IMediaNotify);
10071 return NULL;
10072}
10073
10074
10075/**
10076 * Destruct a status driver instance.
10077 *
10078 * @returns VBox status.
10079 * @param pDrvIns The driver instance data.
10080 */
10081DECLCALLBACK(void) Console::drvStatus_Destruct(PPDMDRVINS pDrvIns)
10082{
10083 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
10084 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10085 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
10086
10087 if (pThis->papLeds)
10088 {
10089 unsigned iLed = pThis->iLastLUN - pThis->iFirstLUN + 1;
10090 while (iLed-- > 0)
10091 ASMAtomicWriteNullPtr(&pThis->papLeds[iLed]);
10092 }
10093}
10094
10095
10096/**
10097 * Construct a status driver instance.
10098 *
10099 * @copydoc FNPDMDRVCONSTRUCT
10100 */
10101DECLCALLBACK(int) Console::drvStatus_Construct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
10102{
10103 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
10104 PDRVMAINSTATUS pThis = PDMINS_2_DATA(pDrvIns, PDRVMAINSTATUS);
10105 LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
10106
10107 /*
10108 * Validate configuration.
10109 */
10110 if (!CFGMR3AreValuesValid(pCfg, "papLeds\0pmapMediumAttachments\0DeviceInstance\0pConsole\0First\0Last\0"))
10111 return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;
10112 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
10113 ("Configuration error: Not possible to attach anything to this driver!\n"),
10114 VERR_PDM_DRVINS_NO_ATTACH);
10115
10116 /*
10117 * Data.
10118 */
10119 pDrvIns->IBase.pfnQueryInterface = Console::drvStatus_QueryInterface;
10120 pThis->ILedConnectors.pfnUnitChanged = Console::drvStatus_UnitChanged;
10121 pThis->IMediaNotify.pfnEjected = Console::drvStatus_MediumEjected;
10122 pThis->pDrvIns = pDrvIns;
10123 pThis->pszDeviceInstance = NULL;
10124
10125 /*
10126 * Read config.
10127 */
10128 int rc = CFGMR3QueryPtr(pCfg, "papLeds", (void **)&pThis->papLeds);
10129 if (RT_FAILURE(rc))
10130 {
10131 AssertMsgFailed(("Configuration error: Failed to query the \"papLeds\" value! rc=%Rrc\n", rc));
10132 return rc;
10133 }
10134
10135 rc = CFGMR3QueryPtrDef(pCfg, "pmapMediumAttachments", (void **)&pThis->pmapMediumAttachments, NULL);
10136 if (RT_FAILURE(rc))
10137 {
10138 AssertMsgFailed(("Configuration error: Failed to query the \"pmapMediumAttachments\" value! rc=%Rrc\n", rc));
10139 return rc;
10140 }
10141 if (pThis->pmapMediumAttachments)
10142 {
10143 rc = CFGMR3QueryStringAlloc(pCfg, "DeviceInstance", &pThis->pszDeviceInstance);
10144 if (RT_FAILURE(rc))
10145 {
10146 AssertMsgFailed(("Configuration error: Failed to query the \"DeviceInstance\" value! rc=%Rrc\n", rc));
10147 return rc;
10148 }
10149 rc = CFGMR3QueryPtr(pCfg, "pConsole", (void **)&pThis->pConsole);
10150 if (RT_FAILURE(rc))
10151 {
10152 AssertMsgFailed(("Configuration error: Failed to query the \"pConsole\" value! rc=%Rrc\n", rc));
10153 return rc;
10154 }
10155 }
10156
10157 rc = CFGMR3QueryU32(pCfg, "First", &pThis->iFirstLUN);
10158 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
10159 pThis->iFirstLUN = 0;
10160 else if (RT_FAILURE(rc))
10161 {
10162 AssertMsgFailed(("Configuration error: Failed to query the \"First\" value! rc=%Rrc\n", rc));
10163 return rc;
10164 }
10165
10166 rc = CFGMR3QueryU32(pCfg, "Last", &pThis->iLastLUN);
10167 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
10168 pThis->iLastLUN = 0;
10169 else if (RT_FAILURE(rc))
10170 {
10171 AssertMsgFailed(("Configuration error: Failed to query the \"Last\" value! rc=%Rrc\n", rc));
10172 return rc;
10173 }
10174 if (pThis->iFirstLUN > pThis->iLastLUN)
10175 {
10176 AssertMsgFailed(("Configuration error: Invalid unit range %u-%u\n", pThis->iFirstLUN, pThis->iLastLUN));
10177 return VERR_GENERAL_FAILURE;
10178 }
10179
10180 /*
10181 * Get the ILedPorts interface of the above driver/device and
10182 * query the LEDs we want.
10183 */
10184 pThis->pLedPorts = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMILEDPORTS);
10185 AssertMsgReturn(pThis->pLedPorts, ("Configuration error: No led ports interface above!\n"),
10186 VERR_PDM_MISSING_INTERFACE_ABOVE);
10187
10188 for (unsigned i = pThis->iFirstLUN; i <= pThis->iLastLUN; ++i)
10189 Console::drvStatus_UnitChanged(&pThis->ILedConnectors, i);
10190
10191 return VINF_SUCCESS;
10192}
10193
10194
10195/**
10196 * Console status driver (LED) registration record.
10197 */
10198const PDMDRVREG Console::DrvStatusReg =
10199{
10200 /* u32Version */
10201 PDM_DRVREG_VERSION,
10202 /* szName */
10203 "MainStatus",
10204 /* szRCMod */
10205 "",
10206 /* szR0Mod */
10207 "",
10208 /* pszDescription */
10209 "Main status driver (Main as in the API).",
10210 /* fFlags */
10211 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
10212 /* fClass. */
10213 PDM_DRVREG_CLASS_STATUS,
10214 /* cMaxInstances */
10215 ~0U,
10216 /* cbInstance */
10217 sizeof(DRVMAINSTATUS),
10218 /* pfnConstruct */
10219 Console::drvStatus_Construct,
10220 /* pfnDestruct */
10221 Console::drvStatus_Destruct,
10222 /* pfnRelocate */
10223 NULL,
10224 /* pfnIOCtl */
10225 NULL,
10226 /* pfnPowerOn */
10227 NULL,
10228 /* pfnReset */
10229 NULL,
10230 /* pfnSuspend */
10231 NULL,
10232 /* pfnResume */
10233 NULL,
10234 /* pfnAttach */
10235 NULL,
10236 /* pfnDetach */
10237 NULL,
10238 /* pfnPowerOff */
10239 NULL,
10240 /* pfnSoftReset */
10241 NULL,
10242 /* u32EndVersion */
10243 PDM_DRVREG_VERSION
10244};
10245
10246/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

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