VirtualBox

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

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

Main,Frontends: Support for the USB storage controller

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

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