VirtualBox

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

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

Comments.

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

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