VirtualBox

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

Last change on this file since 28765 was 28765, checked in by vboxsync, 15 years ago

Main: Build fix

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

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