VirtualBox

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

Last change on this file since 47106 was 47106, checked in by vboxsync, 12 years ago

ConsoleImpl: serialize onVRDEServerChange

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

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