VirtualBox

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

Last change on this file since 35650 was 35638, checked in by vboxsync, 14 years ago

Main. QT/FE: fix long standing COM issue

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