VirtualBox

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

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

Make the TurnResetIntoPowerOff setting configurable during runtime

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

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