VirtualBox

source: vbox/trunk/src/VBox/Main/ConsoleImpl.cpp@ 28800

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

Automated rebranding to Oracle copyright/license strings via filemuncher

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

© 2023 Oracle
ContactPrivacy policyTerms of Use