VirtualBox

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

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

Change implementation for turning a reset into a power off to prevent the VM from executing while the power down thread is not running

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