VirtualBox

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

Last change on this file since 51797 was 51765, checked in by vboxsync, 10 years ago

Main/src-client: fix SEGFAULT when returning USB devices and Shared Folders lists.

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

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