VirtualBox

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

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

Main: implement sharing saved state files between snapshots and machines in 'saved' state; this dramatically speeds up restoring snapshots as well as taking snapshots of 'saved' machines

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