VirtualBox

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

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

Main/Console+Machine: move PowerDown progress object to VBoxSVC, plus VMTask cleanup

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

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